text:
Q: Asp.net SQL Server user impersonation I wonder if somebody could point me in the right direction. We're currently looking to update an ASP.NET application that uses SQL Server 2005 for its db. We need to provide robust and consistent functionality that prevents certain users creating, updating, deleting certain records from the database.
Unfortunately, the application isn't written using OO concepts, instead favouring many data access stored procedures called directly from the web page code behind files. Due to the sheer amount of stored procedures we'd prefer to investigate database triggers to implement our security.
The question is; is it possible for the db trigger to be aware of the specific application user (managed using custom user account tables in the db) which executed the sp? All we'd need is an id. The connection string used to connect to the db is identical for all users (taken from the web.config), is there a way for the connection to some how either impersonate a user, or set a specific variable accessible to the trigger?

A: If the application uses a SqlConnection to 'login' the user and then performs the data access/updates using the very same SqlConnection then you can use  CONTEXT_INFO(). Set the context in the 'login' procedure, then check it in the data access/update procedure(s). See Using Session Context Information.
But if the application uses a SqlConnection to 'login', caches the result (perhaps in a cookie or in the ASP session state), and then uses a different SqlConnection to access data then there is no way access the needed login information w/o application support. If you can locate all the places where SqlConnection objects are created and refactor it to use the factory pattern then you can augment each connection open with a call to set the context info before returning it to the caller for use and that would also work, with minimal application changes.


text:
Q: Angularjs structure for reusable data visualization? I would like to build a reusable SVG chart with Angularjs and I have a number of directive-controller related questions.
In a first instance I'd like to be able to have mark-up like this that renders a chart with form elements that affect the internal state and hence the data visualization:
<scatterChart></scatterChart>

=>
<div class="scatterChart">
 <div> [Form elements] </div>
 <svg>
   [Data visualization]
 </svg>
</div>

Question 1: Controller, Directive, Module
Does it make sense to build this as a single Directive with a separate Controller? Or would you embed the Controller in the Directive or perhaps create a Module?
Question 2: Model/State to SVG render
Let's say the chart controller has a an internal state like this:
scope.model = {
  xAxis : "xyz",
  yAxis : "abc"
}

A change in the model should trigger a rerendering of the chart.
What would be a DRY/proper way of sharing all of the charts user-controlled attributes between the controller and the directive?
(At the same time the directive should be able to have some dependent/private attributes.)
Question 3: API
How would I pass an initial state to the chart? Attributes? And if it is a 20 parameter state?
<scatterChart xAxis="abc"></scatterChart>

A: Answer 1
Embed the controller in directive, unless you want to reuse the same controller in other directive.
Answer 2
You may create a service to store the user-controlled attributes which are shared among all charts.
Answer 3
When there are many parameters, creating a service to store the data and inject it into your directive and controller would be a good idea.
The general idea is to decouple your data from controller and directive by creating a service.

redpajama_set_name: RedPajamaStackExchange


text:
Q: CSS: IE11 not applying style At this page there is a graphic in the sidebar:

I have in the <head>:
<!--[if IE]>

    <link rel="stylesheet" href="<?php echo get_stylesheet_directory_uri(); ?>/css/ie.css" media="screen" />

<![endif]-->

The ie.css file contains .textwidget {display: inline-block;} however this CSS rule is not being applied when I select the <div class="textwidget"> while inspecting the graphic in IE11.

A: IE11 doesn't support conditional comments such as <!--[if IE]>.
From MSDN:

Important As of Internet Explorer 10, conditional comments are no longer supported by standards mode. Use feature detection to provide effective fallback strategies for website features that aren't supported by the browser.

A: You have missed type of the link you are adding. It should be
<!--[if IE]>

    <link rel="stylesheet" href="<?php echo get_stylesheet_directory_uri(); ?>/css/ie.css" media="screen" type="text/css" />

<![endif]-->


text:
Q: Start/stop background function I'm trying to develop a WPF application that runs other process in background when a button is pressed (and stop it when the same button is pressed again).
Well, the point here is that the process that I'm calling it's going to be monitorizing a folder, so, it doesn't ends at any point.
I tried with Threads, but when I create a new thread object when I press the button, I can't access to it when I press it again because there're in different codeblocks.
I rode that the better way to do this is using BackgroundWorker, but I don't understand how to use it.
This is the code that I have right now. mon is the object created that have the function that I want to run in background (mon.MonitoriceDirectory)
if (this.monitoring)
{
    var dialog = new System.Windows.Forms.FolderBrowserDialog();
    dialog.ShowNewFolderButton = false;
    System.Windows.Forms.DialogResult result = dialog.ShowDialog();
    if (dialog.SelectedPath != "")
    {
         monitorizeButton.Content = "Stop";
         textBlockMonitorize.Text = "Monitoring...";
         this.monitorizando = false;
         mon.monitorizePath = dialog.SelectedPath;
         Thread newThread = new Thread(mon.MonitorizeDirectory);
         newThread.Start();
    }
}
else
{
    newThread.Abort(); // Here is the problem, I can't access to that cuz
                      // it's in another codeblock.
    monitorizeButton.Content = "Monitorice";
    textBlockMonitorize.Text = "Ready";
    this.monitorizando = true;
}

A: By declaring newThread out side the if block help you to extend is scope to the else part also; so You can try this,
  Thread newThread;
  if (this.monitorizing)
  {
    var dialog = new System.Windows.Forms.FolderBrowserDialog();
    //rest of code here
    newThread = new Thread(mon.MonitorizeDirectory);
    //Rest of code
  }
 else
  {
    newThread.Abort();
    //Rest of code here
  }


text:
Q: Git shows wrong push author but correct commit author My dev team is banging our heads against the wall trying to figure this out.  Two of my team members show activity under our old CTO/Developer when pushing, but correct author on the commit level.
Example (censored)
OLD_CTO_USERNAME pushed to integration at charitybuzz/charitybuzz
OLD_CTO_FULLNAME
 CORRECT_COMMIT_AUTHOR 3d5e7d3 getting rid of duplicate slim gem

A: I have solved the mystery of the rouge pusher.    Turns out our old CTO had actually added those keys to his own account, instead of letting our new devs add them to their own.   Not really sure why he did so, but this is the reason.
We couldn't get in touch with him and ask him to remove the keys so we created a new key JUST for github, added a ssh config that set key by domain.
Host github.com
  IdentityFile ~/.ssh/just_for_github.key
Host *
  IdentityFile ~/.ssh/id_rsa


text:
Q: Create elements dynamically in XSLT I want to create as many <Group> elements as they are in the Main xml dynamically using XSLT as <Group folder ="Group1"> in the new Xml. Also, the <Data> element added as the last child should be added only once inside.
Main Xml
<Root>
    <ClassA>
    <Groups>
    <Group1>
        <Group2>
            <Group3>
             ............
            </Group3>
        </Group2>
    </Group1>
    </Groups>
    <Data>
        <Name>George</Name>
        <Class>A</Class>
    </Data>
    </ClassA>
</Root>

I need an Xml like this
<Data>
    <ClassA>
    <Group folder = "Group1">
        <Group folder = "Group2">
            <Group folder = "Group3">
             ............

            <Data>
                <Name>George</Name>
                <Class>A</Class>
            </Data>
            </Group>
        </Group>
    </Group>

    </ClassA>
</Data>

A: Actually, you need the following templates:

*

*Matching Root. Generate <Data> element and inside it
apply templates to the whole own content.

*Matching ClassA. Copy the own element and inside if
apply templates to the content of the child Groups element.

*Matching elements with name containing Group and then a digit.
Create Group element with proper folder attribute.
Apply templates to its content (if any).
If this element does not contain any child element, copy
Data element from ancestor ClassA.

*The identity template.
So the whole script can look like below:
<?xml version="1.0" encoding="UTF-8" ?>
<xsl:transform version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  <xsl:output method="xml" encoding="UTF-8" indent="yes"/>
  <xsl:strip-space elements="*"/>

  <xsl:template match="Root">
     <Data><xsl:apply-templates select="@*|node()"/></Data>
  </xsl:template>

  <xsl:template match="ClassA">
    <xsl:copy><xsl:apply-templates select="Groups/*"/></xsl:copy>
  </xsl:template>

  <xsl:template match="*[matches(name(), 'Group\d')]">
    <xsl:element name='Group'>
      <xsl:attribute name="folder" select="name()"/>
      <xsl:apply-templates select="@*|node()"/>
      <xsl:if test="count(*) = 0">
        <xsl:copy-of select="ancestor::ClassA/Data"/>
      </xsl:if>
    </xsl:element>
  </xsl:template>

  <xsl:template match="@*|node()">
    <xsl:copy><xsl:apply-templates select="@*|node()"/></xsl:copy>
  </xsl:template>
</xsl:transform>

For a working example see http://xsltransform.net/nb9MWtw

A:  <xsl:output method="xml" indent="yes"/>
    <xsl:template match="Root">
        <xsl:element name="Data">
            <xsl:apply-templates/>
        </xsl:element>
    </xsl:template>
    <xsl:template match="ClassA">
        <xsl:element name="ClassA">
            <group floder="{Groups/Group1/name()}">
                <group floder="{Groups/Group1/Group2/name()}">
                    <group floder="{Groups/Group1/Group2/Group3/name()}">
                        <xsl:value-of select="Groups/Group1/Group2/Group3"/>
                        <xsl:copy-of select="Data"/>
            </group>
                </group>
            </group>
        </xsl:element>
    </xsl:template>

Try if is benifial for you.


text:
Q: Numbering align-environments I'm writing in the article class. The align-environments are being numbered continuously, but I want them to be numbered like "section.number in this section". How can I do that? :)

A: Either use \numberwithin{equation}{section} from amsmath or mathtools or the chngcntr package (if more than this is needed, e.g. \counterwithout or the starred versions \counterwithin* etc.)
\documentclass{article}

\usepackage{chngcntr}

\usepackage{mathtools}
\counterwithin{equation}{section}

\begin{document}
\section{A section}
\begin{align}
  E &= mc^{2} \\
  E^2 &= p^{2}c^{2} + m^{2}c^{4}
\end{align}

\section{Another section}

\begin{align}
  E &= mc^{2} \\
  E^2 &= p^{2}c^{2} + m^{2}c^{4}
\end{align}

\counterwithout{equation}{section} % Remove the resetting by `section`

\section{Yet another section}

\begin{align}
  E &= mc^{2} \\
  E^2 &= p^{2}c^{2} + m^{2}c^{4}
\end{align}

\end{document}


text:
Q: Find equal side lengths for isosceles triangle from middle angle and area? I know that this is a really easy question, but I am looking for the answer to this question:

The area of this isosceles triangle is 5cm squared.
The angle ABC is 22 degrees.
Work out the lengths of the two equal sides of the triangle

Thanks
Here is an image of the question

A: from $$5cm^2=\frac{1}{2}x^2\sin(22^{\circ})$$ we get $$x=\sqrt{\frac{10cm^2}{\sin(22^{\circ})}}$$ now you can take a calculator.


text:
Q: What is the best way to play an animation frame by frame? I draw some GIS data dynamically, based on user's control, into CGImageRef.
But how to play these frame like an animation efficiently in an UIImageView?
After searching and surveying, the way to play an animation in UIImageView is preloading all images you need,and invoking the startanimating method,like this:
myImageView.animationimages=[NSArray arrayWithObjects:1uiimage,2uiimage,....,nil];
[myImageView startAnimating];
But the waiting time is too long if i preload all UIImages, because i have more than 400 frames each time.
I want to play the animation like a stream,real time stream, how to do that?
Deeply appreciating if you could give me any idea or an example. :)

A: Use CADisplayLink to get notified on each screen refresh. Change myImageView.image in the callback.
(You might have to do something more clever if you want to limit the framerate.)


text:
Q: Structure group and mobius bundle This question was asked in my assignment of Manifolds. I am taking an online course in manifolds.
Question: (a) T cannot be the structure group of the Mobius bundle $\to S^{1}$. Here T= Translation maps group $\subset Diff ( \mathbb{R})$. $\phi \in T$ iff there exists $ x\in \mathbb{R} : \phi(x) = x+G$. Fiber $F= \mathbb{R}$.
(b) {$+/- id_{R} $}$\subset  Diff(\mathbb{R})$ can be the structure group of Mobius Bundle.
Attempt: Definition of Mobius Bundle.

 (a) The definition of Structure group is following: The structure group of $P: B \to M$ is $G \subset Diff(F)$ if there exists a cover of Local trivalization $\phi_{i} : V_{i} \times F \to P^{-1} (U_i)$ such that for every $m \in U_i \cap U_j$ the map $\phi_m \in G \subset Diff(F)$.
$Diff(\mathbb{R})$ is the group of all diffeomorphisms of F ie all bijective maps $f: F \to F$ st f and $f^{-1}$ are smooth.
Let on the opposite T is a structure group of  Mobius Bundle ( say MB).
$P: MB \to M$ is $T \subset Diff(\mathbb{R})$. So, there exists a local trivalization $\phi_i: V_i \times \mathbb{R} \to P^{-1}{ (U_i)}$ such that for every $m\in U_i \cap U_j$ , $\phi_m \in T\ \subset Diff(\mathbb{R})$.
But I am not able to think on how can I find a contradiction given the things in my question. Can you please help me with this!
(b) I would like to solve again by myself when I have understood the given solution of (a).
Thank you very much!


text:
Q: HttpModule to serve file on different server I would like to create an HttpModule that can serve a file that is on a different server.
Server A is publicly accessible and receives a request for file.txt. This file is on server B and Server A will serve it to the user. Server B is not publicly available.
What would be the highest performance method of accomplishing this with an HttpModule?
I could let Server A download the file from Server B and stream it back to the user. That would require a lot of resources from Server A to do that.
Another option might be that Server A will serve the file directly from an open fileshare to Server B. This would probably require less memory on Server A, but would still need the file to be streamed from Server B to Server A.
I hope there is some way that the request can be redirected to Server B and then the file can be returned directly from Server B to the client, possible facilitated by Server A.
I cannot simply redirect to Server B as it's not directly available to the end user.

A: I would probably not invest in writing an HttpModule at all but instead I would use ARR (Application Request Routing) module to do the "proxying" for you in a way that is highly performant. You can also use its Caching functionality and that way if some files are "hot" they can be downloaded directly by the "front-end" server without hitting the back-end server. Using its cached will be the fastest option and since it can be pretty smart about caching it will be also one of the pain-less ways.
It is optimized to handle thousands of requests per second and does that in an async way that let it scale to huge numbers. Used in many content-delivery-network-type situations so you can count on it being really fast.


text:
Q: Graph and Tree Traversal Runtime I am a bit confused about the run time of traversing a tree vs traversing a graph. Usually the run time of traversing a tree is O(V) where v is the number of node in the tree (i.e postorder, inorder or preorder traversal) but for graph it is generally O(V+E) giving we are traversing each vertice and edge.
But if O(V+E) that is true for graph, why is O(V+E) not true for tree as well since we are also traversing tree edges when doing tree traversal. Or vice versa, if O(V) is true for tree, why is it not true for graph as well as we are also visiting each node once?

A:
why is O(V+E) not true for tree as well...?

Actually O(+) is also true for tree traversal, but this expression can be simplified in the case of a tree, because for a tree we have this equality:
       =  - 1
In other words, a tree has one less edge than it has nodes. So this means the following expressions are equivalent:
      O(+) = O(2-1)
In big O notation, which describes asymptotical complexity, we only have to regard the term with the highest order, and its coefficient is not relevant. So this is equivalent to O(). We could also have said O() with a similar reasoning.

Or vice versa, if O(V) is true for tree why is it not true for graph as well...?

Because in general we don't have a relationship between  and .
For instance, a dense graph will have many more edges than vertices. When traversing a graph, you typically visit a vertex and then check each of the edges that connect with this vertex to see if the connected neighboring vertex still needs visiting. So then the work to do is linear to the number of edges.
On the other hand, a disconnected graph (maybe a forest) may have many more vertices than edges. While traversing the graph you'll again want to check for each vertex which are its neighbors. In this case you will maybe find vertices that don't have neighbors at all, but the work needs to be done. So then you have at least work that is linear to the number of vertices.
To cover for both extremes, we can say that the complexity is O() where  is whichever is the greatest,  or . So we then have: O(max(, )). Note that this is equivalent to O(+).


text:
Q: Change table background dynamically angularjs How can I change the background of a table cell dynamically in HTML using AngularJS ?
In the following code I want to show a table with a bunch of names and the including status of an object. The status can weather be VALID (green background) or INVALID (red background).
Can this problem be solved in my  HTML tag or do I have to move on to CSS ?

      {{object.objectName}}
      {{object.objectStatus}}	 //this background should be colored

A: You can do this using ng-class:

      {{object.objectName}}
      {{object.objectStatus}}

Fiddle

A: you can use ng-class
e.x. :

green-bg and red-bg
are css classes and isValid is property, where you know expression isValid or no

A: CSS :
.invalid{
background-color:red;
}

.valid{
background-color:green;
}

HTML

      {{object.objectName}}
      {{object.objectStatus}}	 //this background should be colored

A: It can be solved both in the td tag or/and in your external css.
In Html

        {{object.objectStatus}}

With external css You can use @oto lolua implementation


text:
Q: Log adding random null string value to object
Hi,
I have an app that stores some expiration dates and I am trying to pass the data to another activity using SharedPreferences. As you can see in the .gif It logs correctly the data when the "Add" button is being pressed, however when I need to save the data and display it correctly in the landing page it adds this random null to the saved data.
Do you know where is this null value being added?
If you have any feedback or need any other relevant code, dont hesitate to indulge me!
FormActivity
import static tech.destinum.recorderis.adapters.FormAdapter.FORM_PREFERENCES;

public class Form extends AppCompatActivity {

private UserProfile mUserProfile;
private DBHelper mDBHelper;
private Auth0 mAuth0;
private Context mContext;
private RecyclerView mRecyclerView;
private ArrayList<Document> mArrayList;
private FormAdapter mAdapter;
private String soat, rtm, src, str, to;
private static final String PREFERENCES = "Preferences";
private static final String TAG = "Form Activity";

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_form);

    mRecyclerView = (RecyclerView) findViewById(R.id.recycler_view_form);

    mArrayList = new ArrayList<>();
    mArrayList.add(new Document(R.string.doc_soat, 0));
    mArrayList.add(new Document(R.string.doc_rtm, 1));
    mArrayList.add(new Document(R.string.doc_src, 2));
    mArrayList.add(new Document(R.string.doc_str, 3));
    mArrayList.add(new Document(R.string.doc_tao, 4));
    mAdapter = new FormAdapter(mContext, mArrayList);

    mRecyclerView.setItemAnimator(new DefaultItemAnimator());
    mRecyclerView.setHasFixedSize(true);

    mRecyclerView.setAdapter(mAdapter);
    mRecyclerView.setLayoutManager(new LinearLayoutManager(mContext, LinearLayoutManager.VERTICAL, false));

    getSupportActionBar().setDisplayHomeAsUpEnabled(true);

}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.form_menu, menu);
    return super.onCreateOptionsMenu(menu);
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {

    switch (item.getItemId()){
        case R.id.confirmation:
            createUser();
            Intent intent = new Intent(getApplicationContext(), Home.class);
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK| Intent.FLAG_ACTIVITY_CLEAR_TOP);
            startActivity(intent);
            finish();
            break;
        case android.R.id.home:
            onBackPressed();
            return true;
    }
    return super.onOptionsItemSelected(item);
}

//TODO: New method for premium version
//free version
private void createUser() {

    mAuth0 = new Auth0(getString(R.string.auth0_client_id), getString(R.string.auth0_domain));
    // The process to reclaim an UserProfile is preceded by an Authentication call.
    AuthenticationAPIClient aClient = new AuthenticationAPIClient(mAuth0);
    aClient.tokenInfo(CredentialsManager.getCredentials(this).getIdToken())
            .start(new BaseCallback<UserProfile, AuthenticationException>() {
                @Override
                public void onSuccess(final UserProfile payload) {
                    Form.this.runOnUiThread(new Runnable() {
                        public void run() {
                            mUserProfile = payload;
                            mDBHelper = new DBHelper(getApplicationContext());

                            SharedPreferences mSP = getSharedPreferences(FORM_PREFERENCES, Context.MODE_PRIVATE);

                            for (int i = 0; i < 6; i++){
                                switch (i){
                                    case 0:
                                        soat += mSP.getString("soat", "");
                                        Log.d(TAG, "Soat:" + soat);

                                        break;
                                    case 1:
                                        rtm += mSP.getString("rtm", "");
                                        Log.d(TAG, "RTM:" + rtm);

                                        break;
                                    case 2:
                                        src += mSP.getString("src", "");
                                        Log.d(TAG, "SRC:" + src);

                                        break;
                                    case 3:
                                        str += mSP.getString("str", "");
                                        Log.d(TAG, "STR:" + str);

                                        break;
                                    case 4:
                                        to += mSP.getString("to", "");
                                        Log.d(TAG, "TO:" + to);
                                        break;

                                }
                            }

                            String name = mUserProfile.getName();

                            if (mUserProfile.getEmail() == null){
                                SharedPreferences mSharedPreferences = getSharedPreferences(PREFERENCES, Context.MODE_PRIVATE);
                                String email = mSharedPreferences.getString("email", null);
                                mDBHelper.createNewUser(name, 0, 0, email, soat, rtm, str, src, to);
                            } else {
                                String email = mUserProfile.getEmail();
                                mDBHelper.createNewUser(name, 0, 0, email, soat, rtm, str, src, to);
                            }
                        }
                    });
                }

                @Override
                public void onFailure(AuthenticationException error) {
                    Form.this.runOnUiThread(new Runnable() {
                        public void run() {
                            Toast.makeText(Form.this, R.string.profile_request_failed, Toast.LENGTH_SHORT).show();
                        }
                    });
                }
            });
}

}
FormAdapter
public class FormAdapter extends RecyclerView.Adapter<FormAdapter.ViewHolder> {

public static final String FORM_PREFERENCES = "FormPreferences";
private Context mContext;
private ArrayList<Document> mDocuments;
private  ArrayList<Dates> list = new ArrayList<>();

public FormAdapter(Context mContext, ArrayList<Document> mDocuments) {
    this.mContext = mContext;
    this.mDocuments = mDocuments;
}

@Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
    return new ViewHolder(LayoutInflater.from(parent.getContext()).inflate(R.layout.format_form, parent, false));
}

@Override
public void onBindViewHolder(final ViewHolder holder, final int position) {
    final Document document = mDocuments.get(position);
    holder.mTitle.setText(document.getName());
    holder.mTitleExpanded.setText(document.getName());
    holder.mEditText.setTag(R.id.date_et, position);
    holder.mButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            int position = (int) holder.mEditText.getTag(R.id.date_et);
            Log.d("pos", String.valueOf(position));

            SharedPreferences mSP = v.getContext().getSharedPreferences(FORM_PREFERENCES, Context.MODE_PRIVATE);
            SharedPreferences.Editor mEditor = mSP.edit();

            String data = holder.mEditText.getText().toString();

            switch (position){
                case 0:
                    list.add(new Dates(0, data));
                    Log.d("SOAT", data);
                    mEditor.putString("soat", data);
                    mEditor.commit();

                    break;
                case 1:

                    list.add(new Dates(1, data));
                    Log.d("RTM", data);
                    mEditor.putString("rtm", data);
                    mEditor.commit();
                    break;
                case 2:
                    list.add(new Dates(2, data));
                    Log.d("SRC", data);
                    mEditor.putString("src", data);
                    mEditor.commit();
                    break;
                case 3:
                    list.add(new Dates(3, data));
                    Log.d("STR", data);
                    mEditor.putString("str", data);
                    mEditor.commit();
                    break;
                case 4:
                    list.add(new Dates(4, data));
                    Log.d("TO", data);
                    mEditor.putString("to", data);
                    mEditor.commit();
                    break;
            }
        }
    });
}

@Override
public int getItemCount() {
    return mDocuments != null ? mDocuments.size(): 0;
}

public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener{

    public TextView mTitle, mTitleExpanded;
    public Button mButton;
    public EditText mEditText;
    public ImageView mImageView;

    private int originalHeight = 0;
    private boolean isViewExpanded = false;
    private ConstraintLayout mConstraintLayout;
    private DateWatcher mDateWatcher;

    public ViewHolder(View view) {
        super(view);
        view.setOnClickListener(this);

        mConstraintLayout = (ConstraintLayout) view.findViewById(R.id.expanded);
        mTitle = (TextView) view.findViewById(R.id.name_title_tv);
        mTitleExpanded = (TextView) view.findViewById(R.id.name_title_tv_expanded);
        mButton = (Button) view.findViewById(R.id.add_button);
        mEditText = (EditText) view.findViewById(R.id.date_et);
        mImageView = (ImageView) view.findViewById(R.id.imageView_up);

        mDateWatcher = new DateWatcher(mEditText);
        mEditText.addTextChangedListener(mDateWatcher);

    }

A: In FormActivity, there seems no initialization for soat...
private String soat, rtm, src, str, to;
And the log is try to append string:
soat += mSP.getString("soat", "");
In the .gif, we can see the soat, rtm, src, str, to  are all null
Could you show the other operation on string soat, rtm, src, str, to ?
My opinion for debug is: Try to give some "word" to soat, rtm, src, str, to and see what happends.


text:
Q: NPE setting content view to any new activity using thread I use a thread and holder for downloading some data and then displaying a new view with buttons that allow you to browse further through the app.
But i think i'm doing something wrong, because any next activity i use, crashes with a null pointer exception on the setContentView line. When i comment this line, nothing goes wrong (so i guess that means that the activity is declared good in the manifest and starts normally).
It looks like because of the thread the new activity has no place to set the content to or something..
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.List;
import java.util.Locale;

import org.codehaus.jackson.JsonParseException;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.type.TypeReference;

import com.hera.ontdekdelft.model.JJsonResponse;
import com.hera.ontdekdelft.listclasses.ListData;

import android.app.Activity;
import android.content.Intent;
import android.content.res.AssetManager;
import android.graphics.drawable.Drawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;

public class StartUp extends Activity
  {
    private static final String tag = StartUp.class.getName();
     public static final String SERIALIZEDDATA = "SerializedData";
     ProgressBar pbar;
     TextView tv1;
     Drawable background;
     Button btCategory, btMakeMyDay;
     RelativeLayout loadedBackground, loadingBackground;

    @Override
    public void onCreate(Bundle savedInstanceState)
      {
        super.onCreate(savedInstanceState);
        LoadData task = new LoadData();
        task.execute();

        String language =  Locale.getDefault().getISO3Language();
        background = getBackgroundImage();

            setContentView(R.layout.startup_loading);
            tv1=(TextView)findViewById(R.id.tvloading);
            if(language.equals("nld")){
                tv1.setText("bijwerken");
            }else{
                tv1.setText("loading");
            }
            pbar=(ProgressBar)findViewById(R.id.progressBar1);
            pbar.setVisibility(1);
            loadingBackground=(RelativeLayout)findViewById(R.id.startup_background_loading);
            loadingBackground.setBackgroundDrawable(background);

        }

    public Drawable getBackgroundImage(){
        Drawable d;
        Calendar c = Calendar.getInstance();
        int month = c.get(Calendar.MONTH);
        Log.i("month",String.valueOf(month));
        switch (month){
        default: d = getResources().getDrawable(R.drawable.homescreen_summer);break;
        case 0:d = getResources().getDrawable(R.drawable.homescreen_winter);break;
        case 1:d = getResources().getDrawable(R.drawable.homescreen_winter); break;
        case 2:d = getResources().getDrawable(R.drawable.homescreen_spring);break;
        case 3:d = getResources().getDrawable(R.drawable.homescreen_spring);break;
        case 4:d = getResources().getDrawable(R.drawable.homescreen_spring);break;
        case 5:d = getResources().getDrawable(R.drawable.homescreen_summer); break;
        case 6:d = getResources().getDrawable(R.drawable.homescreen_summer); break;
        case 7:d = getResources().getDrawable(R.drawable.homescreen_summer); break;
        case 8:d = getResources().getDrawable(R.drawable.homescreen_autumn); break;
        case 9:d = getResources().getDrawable(R.drawable.homescreen_autumn); break;
        case 10:d = getResources().getDrawable(R.drawable.homescreen_autumn); break;
        case 11:d = getResources().getDrawable(R.drawable.homescreen_winter); break;
        }
        return d;

    }

    private class LoadData extends AsyncTask<Void, Void, String> {

        @Override
        protected void onPreExecute() {

            super.onPreExecute();
        }

        protected void onPostExecute(String language) {
            super.onPostExecute(language);
            setContentView(R.layout.startup_loaded);
            btCategory=(Button)findViewById(R.id.btn_category);
            loadedBackground=(RelativeLayout)findViewById(R.id.startup_background_loaded);
            loadedBackground.setBackgroundDrawable(background);
            if(language.equals("nld")){
                btCategory.setText("Ontdek Delft");
            }else{
                btCategory.setText("Discover Delft");
            }

              //newactivitybutton

            btCategory.setOnClickListener(new View.OnClickListener() {

                @Override
                public void onClick(View v) {
                    // TODO Auto-generated method stub
                    startActivity(new Intent(StartUp.this, Overview.class));
                    finish();
                }
            });

        }

        @Override
        protected String doInBackground(Void... params) {
            String language =  Locale.getDefault().getISO3Language();
             AssetManager assetManager = getAssets();
                InputStream inputStream = null;
                try {
                    inputStream = assetManager.open("originalDelftJson.json");
                } catch (IOException e) {
                    Log.e("tag", e.getMessage());
                }
                ObjectMapper objectMapper = new ObjectMapper();
                Log.i("tijdlog","start parsing" );
                try {

                     List<JJsonResponse> jsonResponse = objectMapper.readValue(inputStream, new TypeReference<List<JJsonResponse>>() { });
                        Log.i("tijdlog","einde parsing" );
                        //
                          final  List<JJsonResponse> myGlobalVariable = jsonResponse;

                          ((ApplicationController)getApplication()).setGlobalData(myGlobalVariable);

                          List<ListData> ld = new ArrayList<ListData>();
                         int selectedPic;
                         JJsonResponse e;
                         int k =0;
                         for(int i=0;i < jsonResponse.size() ;i++){
                             e = jsonResponse.get(i);
                             for(int j=0; j<e.venue.themes.size();j++){
                                 if (e.venue.themes.get(j).mobile == true){
                                     selectedPic = 0;
                                     String tip;
                                     String theme;
                                     if (language.equalsIgnoreCase("nld")){
                                         tip=e.venue.tip;
                                         theme=e.venue.themes.get(j).name;
                                     }else{
                                         tip=e.venue.tip_en;
                                         theme=e.venue.themes.get(j).name_en;
                                     }
                                     // pic selected pic
                                     String photoUrl = null;
                                     if (e.venue.venue_photos.isEmpty() == false){
                                        for(int l=0; l < e.venue.venue_photos.size() ;l++){
                                             if(e.venue.venue_photos.get(l).selected == true){
                                                 selectedPic = l;
                                             }
                                             photoUrl=e.venue.venue_photos.get(selectedPic).medium;
                                         }
                                     }else
                                         {
                                         photoUrl=null; // null no pic--> add link later
                                       }
                                     ld.add(new ListData(e.venue.id, e.venue.name, photoUrl, tip, theme));//nieuwe maken
                                     k++;
                                 }
                             }
                         }

                         Collections.sort(ld, ListData.ListDataThemeAndNameComparator); // vergelijken op thema
                         for(int z=0;z < ld.size() ;z++){
                             Log.i("ld nr " + String.valueOf(z), ld.get(z).name + " theme: " + ld.get(z).theme + " & venue id= "+ ld.get(z).venueID);
                         }

                // save
                         ((ApplicationController)getApplication()).setListData(ld);

                } catch (JsonParseException e) {
                    // XXX Auto-generated catch block
                    e.printStackTrace();
                } catch (IOException e) {
                    // XXX Auto-generated catch block
                    e.printStackTrace();
                }
            return language;
        }

    }

}
the new activity where my error occurs:

import android.app.Activity; import android.os.Bundle;
public class Overview extends Activity{
@Override   protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(findViewById(R.layout.splash));  }
}

xml splash;
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical"
    android:background="@drawable/splash"
    >

</LinearLayout>

edit:
i edited my code. now using a AsyncTask, it seemed to be the solution like LuxuryMode suggested below, but it doesn't work either. Still same nullpointerexception when setContentView...
error log:
07-24 19:53:50.411: E/AndroidRuntime(29618): FATAL EXCEPTION: main
07-24 19:53:50.411: E/AndroidRuntime(29618): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.hera.ontdekdelft/com.hera.ontdekdelft.Overview}: java.lang.NullPointerException
07-24 19:53:50.411: E/AndroidRuntime(29618):    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2787)
07-24 19:53:50.411: E/AndroidRuntime(29618):    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2803)
07-24 19:53:50.411: E/AndroidRuntime(29618):    at android.app.ActivityThread.access$2300(ActivityThread.java:135)
07-24 19:53:50.411: E/AndroidRuntime(29618):    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2136)
07-24 19:53:50.411: E/AndroidRuntime(29618):    at android.os.Handler.dispatchMessage(Handler.java:99)
07-24 19:53:50.411: E/AndroidRuntime(29618):    at android.os.Looper.loop(Looper.java:144)
07-24 19:53:50.411: E/AndroidRuntime(29618):    at android.app.ActivityThread.main(ActivityThread.java:4937)
07-24 19:53:50.411: E/AndroidRuntime(29618):    at java.lang.reflect.Method.invokeNative(Native Method)
07-24 19:53:50.411: E/AndroidRuntime(29618):    at java.lang.reflect.Method.invoke(Method.java:521)
07-24 19:53:50.411: E/AndroidRuntime(29618):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:858)
07-24 19:53:50.411: E/AndroidRuntime(29618):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
07-24 19:53:50.411: E/AndroidRuntime(29618):    at dalvik.system.NativeStart.main(Native Method)
07-24 19:53:50.411: E/AndroidRuntime(29618): Caused by: java.lang.NullPointerException
07-24 19:53:50.411: E/AndroidRuntime(29618):    at android.view.ViewGroup.addViewInner(ViewGroup.java:1977)
07-24 19:53:50.411: E/AndroidRuntime(29618):    at android.view.ViewGroup.addView(ViewGroup.java:1873)
07-24 19:53:50.411: E/AndroidRuntime(29618):    at android.view.ViewGroup.addView(ViewGroup.java:1853)
07-24 19:53:50.411: E/AndroidRuntime(29618):    at com.android.internal.policy.impl.PhoneWindow.setContentView(PhoneWindow.java:226)
07-24 19:53:50.411: E/AndroidRuntime(29618):    at com.android.internal.policy.impl.PhoneWindow.setContentView(PhoneWindow.java:216)
07-24 19:53:50.411: E/AndroidRuntime(29618):    at android.app.Activity.setContentView(Activity.java:1665)
07-24 19:53:50.411: E/AndroidRuntime(29618):    at com.hera.ontdekdelft.Overview.onCreate(Overview.java:12)
07-24 19:53:50.411: E/AndroidRuntime(29618):    at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1069)
07-24 19:53:50.411: E/AndroidRuntime(29618):    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2751)
07-24 19:53:50.411: E/AndroidRuntime(29618):    ... 11 more

A: There are two rules in the Android threading model: 1) dont block the main (UI) thread 2) dont manipulate the UI from off of the main (UI) thread. You seem to be having an issue with the second of those rules. You can try using Activity#runOnUiThread(Runnable) instead of using that handler, but in general what you're doing is really messy and generally a terrible idea :) Also, unless I'm missing something up, how exactly is your handler even usable inside of your startup thread if you're initializing it after you start the thread? You seem to be relying on the thread scheduling going a certain way which is just a bad idea as well.
In all likelihood, what you need to use is an AsyncTask. Set your contentview immediately in onCreate and then execute your AsyncTask which downloads your data. Then in onPostExecute of your task, do whatever relevant UI changes are necessary.
UPDATE -
in onPostExecute, call the super right away. Also, don't start your Activity by calling                     startActivity(new Intent ("com.hera.ontdekdelft.OVERVIEW"));, instead it should be startActivity(new Intent(Startup.this, Overview.class));
Also, from the looks of the stacktrace, the crash is occurring when you try starting the new Activity. So I would look there on line 12 to see what the problem is.
UPDATE -
As I pointed out in our discussion below:
You cannot set the contentView of your Activity to findViewById(whatever). findViewById looks through the current contentView and tries to find a view that matches the id you passed in. But you havent set any contentview yet so theres nothing to find. Therefore you crash with a nullpointer when you try setting the contentview to the null view returned by your call to findViewById! You need to set the view to whatever the view is for that Activity. setContentView(R.layout.overview_layout) or setContentView(new OverviewView(this))

A: setContentView(..) is a method of Activity. You can not call it in your Runnable, it's out of scope. Result is a nullpointer.
Your approach of setting the contentView inside a Runnable is rather weird.. Maybe alter your design a bit? Maybe you can create more than one Activity rather than switching layouts of 1 Activity..


text:
Q: "cannot do signed 4 byte relocation" on compile I'm going through Real world Haskell, and got to the example:
-- file: ch04/InteractWith.hs
-- Save this in a source file, e.g. Interact.hs

import System.Environment (getArgs)

interactWith function inputFile outputFile = do
  input <- readFile inputFile
  writeFile outputFile (function input)

main = mainWith myFunction
  where mainWith function = do
          args <- getArgs
          case args of
            [input,output] -> interactWith function input output
            _ -> putStrLn "error: exactly two arguments needed"

        -- replace "id" with the name of our function below
        myFunction = id

But when I try to compile it (ghc --make InteractWith) I get this error:
$ ghc --make InteractWith
[1 of 1] Compiling Main             ( InteractWith.hs, InteractWith.o )

/var/folders/38/38dlZO7fEXyCgGIFUZA0Ok+++TI/-Tmp-/ghc91310_0/ghc91310_0.s:309:0:
    suffix or operands invalid for `push'

/var/folders/38/38dlZO7fEXyCgGIFUZA0Ok+++TI/-Tmp-/ghc91310_0/ghc91310_0.s:358:0:
    suffix or operands invalid for `push'

/var/folders/38/38dlZO7fEXyCgGIFUZA0Ok+++TI/-Tmp-/ghc91310_0/ghc91310_0.s:384:0:
    32-bit absolute addressing is not supported for x86-64

/var/folders/38/38dlZO7fEXyCgGIFUZA0Ok+++TI/-Tmp-/ghc91310_0/ghc91310_0.s:384:0:
    cannot do signed 4 byte relocation

/var/folders/38/38dlZO7fEXyCgGIFUZA0Ok+++TI/-Tmp-/ghc91310_0/ghc91310_0.s:387:0:
    32-bit absolute addressing is not supported for x86-64

/var/folders/38/38dlZO7fEXyCgGIFUZA0Ok+++TI/-Tmp-/ghc91310_0/ghc91310_0.s:387:0:
    cannot do signed 4 byte relocation

I'm using GHC 6.10.4 on Mac OS 10.6 (Snow Leopard).

A: I was having similar problems compiling almost anything in Snow Leopard.  The solution I found was to replace the contents of /usr/bin/ghc (which is actually just a shell script) with the following:
#!/bin/sh

exec /Library/Frameworks/GHC.framework/Versions/610/usr/lib/ghc-6.10.4/ghc -B/Library/Frameworks/GHC.framework/Versions/610/usr/lib/ghc-6.10.4/. -optc-m32 -opta-m32 -optl-m32 -dynload wrapped ${1+"$@"}

I think it's actually just adding -optc-m32 -opta-m32 -optl-m32 but I can't remember...
(I originally found this somewhere on the internets, but I don't remember where.  It did take me a while too.)

A: Did you update to Snow Leopard recently? I believe this happens when you're trying to use an executable in Snow Leopard that was built using Leopard.


text:
Q: Change TabBadge opacity in Ionic 2 In my project I have some tabs and I want to update Badge's style when my value is 0. But I don't know how to change dynamically my tab's style. Moreover I don't know how to change the opacity of my badge in the style.
I want to have this result :

Thank you for your help ! :)
There is my code :
<ion-tabs color="secondary"  (ionChange)="changeTabs()">
  <ion-tab [root]="tab1" tabTitle="tab1" tabBadge="{{this.session.getToDoCount()}}" tabBadgeStyle="notif"></ion-tab>
  <ion-tab [root]="tab2" tabTitle="tab2" tabBadge="{{this.session.getToComeCount()}}" tabBadgeStyle="notif"></ion-tab>
  <ion-tab [root]="tab3" tabTitle="tab3"></ion-tab>
</ion-tabs>

A: You have to do with ngClass directive if your badge value is zero apply a custom style.
HTML:
<ion-item class="messages">
  <ion-icon name="logo-twitter" item-left></ion-icon>
  Followers
  <ion-badge class="message" item-right [ngClass]="{'me': badgeValue === 0}">260k</ion-badge>
</ion-item>

styles:
.messages {
  .message {
     background: #387ef5;
     color: #fff;
  }
  .message.me {
    background: #fff;
  }
}


text:
Q: Netbeans/Xdebug displays only some local variables in functions I've been debugging a PHP script on my local server using NetBeans and XDebug. Even with xdebug.show_local_vars = 1 set in php.ini Netbeans will only occasionally display local arrays in a function.
For example, in a minimal script like this:
<?php
test();
function test() {
  $dow = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'];
  $tod = ['AM', 'PM', 'EVE'];
  $mat = ['', '', '', '', '', '', ''];
}

I can view $mat in Netbean's variables window but not the other two. Changing the array names makes no difference.
Any thoughts on why $mat shows up but not the others?


text:
Q: How to observe objects count on realm db I want to observe the object count of the realm DB.
I wrote this approach:
let realm = try? Realm()
self.notificationToken = realm?.objects(AnalyticsEventDto.self).observe { _ in
    if let count = realm?.objects(AnalyticsEventDto.self).count {
        observer.send(value: count)
    }
}

There is another way to do so?
Thanks

A: I would use the RealmCollectionChange parameter rather than creating a new Results object in the closure. This also lets you handle the error:
let realm = try? Realm()
self.notificationToken = realm?.objects(AnalyticsEventDto.self).observe { change in
    switch change {
    case .initial(let results):
        observer.send(value: results.count)
    case .update(let results, deletions: _, insertions: _, modifications: _):
        observer.send(value: results.count)
    case .error(let error):
        observer.send(error: error)
    }
}

But a more ReactiveSwifty way of doing this might be to wrap the entire Realm collection notification API to make it reactive. This is a bit involved, but it is more general and potentially usable in multiple places in your code:
/// We want to send errors via the `ReactiveSwift` error event, so create a new `CollectionChange` enum that
/// mimics `RealmCollectionChange` except it doesn't have an `error` case.
enum CollectionChange<CollectionType> {
    case initial(CollectionType)
    case update(CollectionType, deletions: [Int], insertions: [Int], modifications: [Int])
}

/// Extending `ReactiveExtensionsProvider` and `Reactive` is the standard way to add reactive extensions
/// to existing types in a way that avoids name collisions.
extension Results: ReactiveExtensionsProvider { }

extension Reactive where Base: RealmCollection {
    /// This wraps Realm collection notifications in a very general reactive way.
    private func changeNotificationsRaw() -> SignalProducer<RealmCollectionChange<Base>, Never> {
        return SignalProducer { [base = self.base] observer, lifetime in
            let token = base.observe { change in
                observer.send(value: change)
            }

            lifetime.observeEnded {
                token.invalidate()
            }
        }
    }

    /// This just maps `RealmCollectionChange` to our own `CollectionChange` type while translating errors
    /// to ReactiveSwift error events.
    func changeNotifications() -> SignalProducer<CollectionChange<Base>, Error> {
        return changeNotificationsRaw().flatMap(.concat) { realmChange -> SignalProducer<CollectionChange<Base>, Error> in
            switch realmChange {
            case .initial(let collection):
                return SignalProducer(value: .initial(collection))
            case let .update(collection, deletions, insertions, modifications):
                return SignalProducer(value: .update(collection, deletions: deletions, insertions: insertions, modifications: modifications))
            case .error(let err):
                return SignalProducer(error: err)
            }
        }
    }
}

You could then use it like this:
realm.objects(AnalyticsEventDto.self).reactive.changeNotifications()
    .map { change -> Int in
        switch change {
        case .initial(let results):
            return results.count
        case .update(let results, _, _, _):
            return results.count
        }
    }
    .take(during: self.lifetime)
    .start { event in
        print(event)
    }


text:
Q: Confusion About Array and String in C What is the difference between S1, S2 and S3?
char S1[6];
S1[0] = 'A';
S1[1] = 'r';
S1[2] = 'r';
S1[3] = 'a';
S1[4] = 'y';

char S2[6] = {'A','r','r','a','y'};

string S3 = "Array";

When I run the program using if (strcmp(a,b) == 0), where a, b = S1, S2, S3.
It shows that S2 and S3 are the same, and S1 and S2 is different.
Why is this the case??
Why not all three are equivalent?
And when I add back '\0' to both S1b, S1c. All 3 are the same. This is understandable.
BUT why in my first trial, S2 and S3 are the same then?? I did not include '\0' too. And I suspect S1 and S2 should be the same, but not S2 and S3.
Can anyone tell me why my thought is wrong???
Thanks for your answers. I have tried and changed the settings to the followings:
char S1[5];
S1[0] = 'A';
S1[1] = 'r';
S1[2] = 'r';
S1[3] = 'a';
S1[4] = 'y';

char S2[5] = {'A','r','r','a','y'};

string S3 = "Array";

And now clearly S2 and S3 are not the same, since they differs by a '\0'.
However, I am still a bit confused why S1 and S2 are not the same this time again if I use strcmp to compare the two?

A: Compare the actual in-memory values of the arrays:

*

*S1 is 6 elements big, yet you only specify values for 0-5, the 6th element is not explicitly set, so it retains whatever value the memory location had prior to allocation.

*S2 is similar to S1 , only 5 elements are provided, however when using the {,} syntax any extra elements are zeroed. So char foo[5] = { 1, 2 } is identical to char foo[5] = { 1, 2, 0, 0, 0}.

*S3 uses the string syntax way of initialising an array, which creates an array of char (or wchar_t) with an extra element set to \0 (the null terminator).

Visually:
S1 = 0x41, 0x72, 0x72, 0x61, 0x79, 0x??
S2 = 0x41, 0x72, 0x72, 0x61, 0x79, 0x00
S3 = 0x41, 0x72, 0x72, 0x61, 0x79, 0x00

Note that you're running into a safety problem with strcmp: it doesn't have a length parameter, it keeps on searching until it encounters \0, which might be never (i.e. until it causes a segfault or access violation). Instead use a safer function like strncmp or (if using C++) the std::string type.

A: It shows that S2 and S3 are the same, and S1 and S2 is different.
S3 contains the nul terminator which S1 does not have. This string S3 = "Array"; means
| A | r | r | a | y | \0 |

While S2 is
| A | r | r | a | y | \0 |

While S1 is
| A | r | r | a | y | Garbage |

S1 and S2 comparison can lead to UB (i presume) because S1 is not nul-terminated and there is no length which we pass in strcmp.
#include <stdio.h>
#include <string.h>

int main(void)
{
    char S1[6];
    S1[0] = 'A';
    S1[1] = 'r';
    S1[2] = 'r';
    S1[3] = 'a';
    S1[4] = 'y';
    S1[5] = 0;

    char S2[6] = {'A','r','r','a','y', 0};
    printf("%d" ,strcmp(S1,S2));
    return 0;
}

Outputs:
0

A: strcmp() function starts comparing the first character of each string. If they are equal to each other, it continues with the following pairs until the characters differ or until a terminating null-character is reached.
I don't think it is safe to compare S1 and S2 using this. Input to strcmp is the address of first character. S1 is not null-terminated. Though 6 bytes are allocated in both cases, S1[5] is not initialised. Chances are that they have some garbage value. The risk here is that strcmp will end up comparing un-allocated memory also, in the search for character diff or null character. This can even lead to seg fault or access violation.
Visualising memory alignment of S1,S2,S3 might be something like this
S1 = A | r | r | a | y | ?
S2 = A | r | r | a | y | 0
S3 = A | r | r | a | y | 0

Any comparison between S2 and S3 is safe. S1 vs S2 or S3 might not be.

A: Just adding to the existing answers
char S2[6] = {'A','r','r','a','y'};

string S3 = "Array";

Both are NULL terminated and hence strcmp() works well and says that they both are same. While for S1 the assignment is done explicitly there is no NULL termination for this array. So this is not a valid string in C. So using strcmp() might lead to undefined behavior.
The point with S3 is that S3 is a string literal which is read-only. Mostly these sort of values are stored in read-only locations. So when you try to write something to S3 after initialization you might see a crash.So we should keep this in mind while using assignments like S3


text:
Q: Where should I put my Node.js web project folder in Ubuntu 14? I have created a Node.js web project and I would like to deploy this to my Ubuntu 14 server in order to access it from the internet. What would be the right location in Ubuntu?

A: Location does not matter for node server. You can run it from  any where.  I am running it from my user home directory.
There are some steps you need to learn.
(1) You may want to use nginx/apache , and direct nginx/apache to your node port.
(2) You may want to  use npm module called forever , to run is permanently.


text:
Q: Telerik Ajax RadCombobox CheckAllCheck Event not found I am using RadCombobox in Telerik Ajax and what I would like to do is to force users must at least select 1 item, so I try to prevent user to uncheck item when it is the only checked item.
Problem is that when I enable the EnableCheckAllItemsCheckBox to true, there will be a Check ALL option by default, and users can first check all items, then uncheck all items, which is what I am trying to prevent.
First I have find this client event:
http://docs.telerik.com/devtools/aspnet-ajax/controls/combobox/client-side-programming/events/onclientcheckallchecked
However it needs Version 2013+, while I am using 2012.1.411, so it does not work out.
Then I found this server event which probably provide same functionality:
http://docs.telerik.com/devtools/aspnet-ajax/controls/combobox/server-side-programming/checkallcheck
Now my problem is, I cannot find this server side event either!
The document did not say which version of the framework needed to use this event, I wonder Is there any reference / document listing what version of the framework support what kind of methods/events of each control?

A: I don't know is this what you want....
To get or trigger CheckAll in RadComboBox event in clientside use this...
    <asp:ScriptManager ID="sm" runat="server"></asp:ScriptManager>
    <telerik:RadComboBox ID="rcb" runat="server" EnableCheckAllItemsCheckBox="true" CheckBoxes="true" OnClientLoad="onChangingInCheckAll">
        <Items>
            <telerik:RadComboBoxItem Text="a" />
            <telerik:RadComboBoxItem Text="b" />
            <telerik:RadComboBoxItem Text="c" />
        </Items>
    </telerik:RadComboBox>

    <telerik:RadScriptBlock ID="rsb" runat="server">
        <script type="text/javascript">

            function onChangingInCheckAll() {
                $telerik.$('.rcbCheckAllItems').click(function () {
                    // Alert Testing
                    alert('a');

                    // Do your stuff
                });
            }

        </script>
    </telerik:RadScriptBlock>


text:
Q: How to convert "im" pixel image to raster? I am trying to convert an "im" pixel image I've produced into a raster image. The "im" was created with the following code:
library(sf)
library(spatstat)
library(rgeos)
library(raster)

# read ebird data
ebd_species <- ("ebd_hooded.txt") %>%
  read_ebd()

# extracting coordinates
latitude_species <- ebd_species$latitude
longitude_species <- ebd_species$longitude

#convert to spatial object
coordinates1 <- data.frame(x = longitude_species, y = latitude_species) %>% st_as_sf(coords = c("x", "y"))

# converting to point pattern data
coordinates <- as.ppp(coordinates1)

# density image
a <- density(coordinates,2)
plot(a)

This is the plot I get:
plot
What I want to do is convert this into a raster. I wanna then use the coordinates of the ebird data to extract the values of density from the raster.

A: Here is a minimal, self-contained, reproducible example (based on the first example in ?im):
library(spatstat)
mat <- matrix(1:1200, nrow=30, ncol=40, byrow=TRUE)
m <- im(mat)

Solution
library(raster)
r <- raster(m)

A: Looks like you are using geographic coordinates (longitude, latitude) directly in spatstat. Are you sure this is OK in your context? For regions away from the equator this can be quite misleading. Consider projecting to planar coordinates using sf::st_transform() (see other of my answers on this site for code to do this). Also, in newer versions of sf you can convert directly from sf to spatstat format with e.g. as.ppp().
If you want a kernel density estimate of the intensity at the data points you can use the option at = "points" in density.ppp():
a <- density(coordinates, 2, at = "points")

Then a is simply a vector with length equal to the number of points containing the intensity estimate for each data point. This uses "leave-one-out" estimation by default to minimize bias (see the help file for density.ppp).


text:
Q: WP Function does not trigger on Webhook API Call I have created a function that triggers and connect parent post with Child post based on a Custom Meta Field value. If Meta field value of an existing Parent post matches with the newly created child post then function automatically connect the parent post with child post. and this function works perfectly If I am creating the child post using WP Admin area or using a Frontend Post Submission form. But If I am creating the Child Post usign a Webhook Incoming data then function doesn't trigger. and it doesn't connect the parent post based on the Custom Meta field "wpcf-patient-id".
I am using WP Webhooks Pro to receive data from a external source that includes the post title, content, wpcf-patient-id, and few other details. Each time Webhook receives a payload data, it creates a new post using the received payload data. But the function doesn't trigger at all.
So if anyone can help me make it work, Please suggest the possible solution.
add_action( 'save_post', 'assign_parent_patient_func', 100,3 );
function assign_parent_patient_func( $post_id, $post, $update ) {

    // Only set for post_type = post!
    if ( !in_array($post->post_type, array('qev-attachment', 'note')) ) {
        return;
    }

    $patient_id = get_post_meta($post_id, 'wpcf-patient-id', true);
    if($patient_id){
        $client_ids = get_posts( array(
            'post_type' => 'client',
            'meta_key' => 'wpcf-patient-id',
            'meta_value'=> $patient_id,
            'fields' => 'ids'
        ));
        if(isset($client_ids[0])){
            $client_id = $client_ids[0];
            if($post->post_type == 'qev-attachment'){
                toolset_connect_posts('client-attachment', $client_id, $post_id);
            }
            if($post->post_type == 'note'){
                toolset_connect_posts('client-note', $client_id, $post_id);
            }
        }
    }
}

A: From what I see is the issue within your code.
Your issue is that you try to fetch the post type in your nested if-statements from the current post, even though at the first if statement, you validate against it and break the function.
What you want to do instead is to validate the post type against the $client_id variable.
$client_parent = get_post( $client_id );
$post_type = '';
if( ! empty( $client_parent ) && isset( $client_parent->post_type ) ){
    $post_type = $client_parent->post_type;
    if( $post_type === 'note' ){
        //run your logic
    }
}

In case it's still not working, you might want to take a look at the documentation of the update_post webhook action.


text:
Q: On the construction of the Verma module My question is about the construction of Verma module of a lie algebra $L$, there is one step in the construction which I do not quite understand.
Let $L=N_-\oplus H\oplus N_+$ be the triangular decomposition of a lie algebra $L$ over the field $\mathbb{C}$. Let $U(L)$ be the universal enveloping algebra of $L$. Define $I_\lambda$ be the left idea of $U(L)$ generated by $N_+$ and $h-\lambda(h)1$:
$$I_\lambda=\{xn_++y(h-\lambda(h)1)\ |\  x,y\in U(L),n_+\in N_+,h\in H\}.$$
I want to show that $I(\lambda)\cap N_-=(0)$. This is easy at the first sight, but then I found it's subtle to use the PBW theorem directly: when assuming $x,y$ are standard PBW basis monomials, and substitute them into the expressions above, one does not get a standard linear combinations of standard monomials. Can anyone help me fix this problem?


text:
Q: How to split strings in SQL Server I have the following input:
Data
-----
A,10
A,20
A,30
B,23
B,45

Expected output:
col1  Col2
----  -----
A      10
A      20
A      30
B      23
B      45

How can I split the string to produce the desired output?

A: I know the points has already been given, going to post it anyway because i think it is slightly better
DECLARE @t TABLE (DATA VARCHAR(20))

INSERT @t VALUES ('A,10');INSERT @t VALUES ('AB,101');INSERT @t VALUES ('ABC,1011')

SELECT LEFT(DATA, CHARINDEX(',',data) - 1) col1,
RIGHT(DATA, LEN(DATA) - CHARINDEX(',', data)) col2
FROM @t

A: SELECT substring(data, 1, CHARINDEX(',',data)-1) col1,
substring(data, CHARINDEX(',',data)+1, LEN(data)) col2
FROM table

A: if the values in column 1 are always one character long, and the values in column 2 are always 2, you can use the SQL Left and SQL Right functions:
SELECT LEFT(data, 1) col1, RIGHT(data, 2) col2
FROM <table_name>

A: declare @string nvarchar(50)
set @string='AA,12'

select substring(@string,1,(charindex(',',@string)-1) ) as col1
, substring(@string,(charindex(',',@string)+1),len(@string) ) as col2![my sql server image which i tried.][1]

A: it is so easy, you can take it by below query:
SELECT LEFT(DATA, CHARINDEX(',',DATA)-1) col1,RIGHT(Data,LEN(DATA)-(CHARINDEX(',',DATA))) col2 from Table


text:
Q: PatternTest vs Parallelization Bug introduced in 10.0 or earlier and fixed in 11.2

Consider the following function
slowNorm[x_?(Length[#] == 3 && VectorQ[#, IntegerQ] &)] :=
  (Pause[1]; Norm[x])

An equivalent implementation is
latticePoint3DQ = (Length[#] == 3 && VectorQ[#, IntegerQ] &);
slowNormAlt[x_?latticePoint3DQ] := (Pause[1]; Norm[x])

However, only the first function can be parallelized efficiently (in both cases all subkernels are already running):
In[1]:= ParallelTable[
          slowNorm[{i, 0, 0}], {i, 1, 5}] // AbsoluteTiming

Out[1]= {2.01148, {1, 2, 3, 4, 5}}

In[2]:= ParallelTable[
          slowNormAlt[{i, 0, 0}], {i, 1, 5}] // AbsoluteTiming

Out[2]= {5.00941, {1, 2, 3, 4, 5}}

Using Condition instead of PatternTest does result in the same behavior.
Is there a way to check arguments using latticePoint3DQ without losing the ability to parallelize?
Edit: I am using Version 11.1.1.0 of MMA and the Platform is Linux x86 (64-bit)

A: I can reproduce this in 11.1.1 but not in 11.2 or later.  I believe that the problem is that the definitions of latticePoint3DQ are not automatically distributed (probably because symbols in PatternTest and Condition are not being considered), thus slowNormAlt effectively ends up being evaluated on the main kernel.
The fix is simple:
DistributeDefinitions[latticePoint3DQ]

Update: This is very likely a problem with Language`ExtendedFullDefinition, discussed in this QA:

*

*Self contained APIFunction. Collecting definitions


text:
Q: how to convert a hive query into abstract syntax tree? Can anyone tell me how to convert a hive query into abstract syntax tree?
For example: select * from orders where cust_num = 100;
How can i convert this into AST? and how can i convert this AST into a QB tree? please help. Thanks in advance.

A: You can make use of EXPLAIN command with EXTENDED. Suppose I have a table called demo with a column as n1, then issuing Explain would give me this :
hive> EXPLAIN EXTENDED select * from demo where n1='aaa';
OK
ABSTRACT SYNTAX TREE:
  (TOK_QUERY (TOK_FROM (TOK_TABREF (TOK_TABNAME demo))) (TOK_INSERT (TOK_DESTINATION (TOK_DIR TOK_TMP_FILE)) (TOK_SELECT (TOK_SELEXPR TOK_ALLCOLREF)) (TOK_WHERE (= (TOK_TABLE_OR_COL n1) 'aaa'))))

STAGE DEPENDENCIES:
  Stage-1 is a root stage
  Stage-0 is a root stage

STAGE PLANS:
  Stage: Stage-1
    Map Reduce
      Alias -> Map Operator Tree:
        demo
          TableScan
            alias: demo
            GatherStats: false
            Filter Operator
              isSamplingPred: false
              predicate:
                  expr: (n1 = 'aaa')
                  type: boolean
              Select Operator
                expressions:
                      expr: n1
                      type: string
                      expr: n2
                      type: string
                outputColumnNames: _col0, _col1
                File Output Operator
                  compressed: false
                  GlobalTableId: 0
                  directory: hdfs://localhost:9000/tmp/hive-apache/hive_2013-06-13_19-55-21_578_6086176948010779575/-ext-10001
                  NumFilesPerFileSink: 1
                  Stats Publishing Key Prefix: hdfs://localhost:9000/tmp/hive-apache/hive_2013-06-13_19-55-21_578_6086176948010779575/-ext-10001/
                  table:
                      input format: org.apache.hadoop.mapred.TextInputFormat
                      output format: org.apache.hadoop.hive.ql.io.HiveIgnoreKeyTextOutputFormat
                      properties:
                        columns _col0,_col1
                        columns.types string:string
                        escape.delim \
                        serialization.format 1
                  TotalFiles: 1
                  GatherStats: false
                  MultiFileSpray: false
      Needs Tagging: false
      Path -> Alias:
        hdfs://localhost:9000/user/hive/warehouse/demo [demo]
      Path -> Partition:
        hdfs://localhost:9000/user/hive/warehouse/demo
          Partition
            base file name: demo
            input format: org.apache.hadoop.mapred.TextInputFormat
            output format: org.apache.hadoop.hive.ql.io.HiveIgnoreKeyTextOutputFormat
            properties:
              bucket_count -1
              columns n1,n2
              columns.types string:string
              field.delim ,
              file.inputformat org.apache.hadoop.mapred.TextInputFormat
              file.outputformat org.apache.hadoop.hive.ql.io.HiveIgnoreKeyTextOutputFormat
              location hdfs://localhost:9000/user/hive/warehouse/demo
              name default.demo
              serialization.ddl struct demo { string n1, string n2}
              serialization.format ,
              serialization.lib org.apache.hadoop.hive.serde2.lazy.LazySimpleSerDe
              transient_lastDdlTime 1370932655
            serde: org.apache.hadoop.hive.serde2.lazy.LazySimpleSerDe

              input format: org.apache.hadoop.mapred.TextInputFormat
              output format: org.apache.hadoop.hive.ql.io.HiveIgnoreKeyTextOutputFormat
              properties:
                bucket_count -1
                columns n1,n2
                columns.types string:string
                field.delim ,
                file.inputformat org.apache.hadoop.mapred.TextInputFormat
                file.outputformat org.apache.hadoop.hive.ql.io.HiveIgnoreKeyTextOutputFormat
                location hdfs://localhost:9000/user/hive/warehouse/demo
                name default.demo
                serialization.ddl struct demo { string n1, string n2}
                serialization.format ,
                serialization.lib org.apache.hadoop.hive.serde2.lazy.LazySimpleSerDe
                transient_lastDdlTime 1370932655
              serde: org.apache.hadoop.hive.serde2.lazy.LazySimpleSerDe
              name: default.demo
            name: default.demo

  Stage: Stage-0
    Fetch Operator
      limit: -1

Time taken: 5.316 seconds


text:
Q: how i can remove jQuery UI dialog mockup from the page? when dialog close the page have dialog mockup as hidden in page. so how i can remove them then they are removed with the mockup. means how i can remove dialog with the mockup so later their is no mockup same can found in DOM.

A: Try:
var dialog = $('#my_dialog').dialog();
$('#my_dialog').dialog('destroy').remove()

Or put it in the close event:
var dialog = $('#my_dialog').dialog({
    close: function() {
        $(this).dialog('destroy').remove();
    }
});

A: I think you you must use .dialog("destroy") withe the same selector you used to create it
or if you assind the dialog to a javascript variable you call the method on the variable.
$('#myid').dialog("destroy")//You created it with $('#myid').dialog()
mydialog.dialog("destroy")//You created it with var mydialog = $('#myid').dialog()

if you want to this when you close the dialag do this when creating it:
$('#myid').dialog({close: $('#myid').dialog("destroy")});

EDIT - ok i understood you wanted to remove the dialog. To remove the html i think you can do this:
$('#myid').dialog({close: $('#myid').remove()});
//this removes the element with the id myid from the DOM


text:
Q: Adding a Scrollbar to a Tkinter Graph of data which goes off the bottom for the screen Brand New to tkinter so please bare with. I've taken data from elsewhere and now I want to display in a table format with multiple data colums for that row. When I display the data like this it goes off the bottom for the screen and I lose data. How do I add a scrollbar to access the rest of this data?
from tkinter import *
from bs4 import BeautifulSoup
from lxml import html
import requests
import re

root = Tk()

def TableCreate(Title,Cost, count,col):
    ##Title and Cost are both Lists.

    #vertscroll = Scrollbar()
    #vertscroll.config(command=grid.yview)

    ##This was called Iterativley so would print over and over again
    btn_column = Button(root, text = "Link")
    btn_column.grid(row = count, column=col)
    btn_column = Button(root, text=Title)
    btn_column.grid(row = count,column=col+1)
    btn_column = Button(root, text=Cost)
    btn_column.grid(row = count,column=col+2)


text:
Q: Getting this error after running my test class "System.NullPointerException: Attempt to de-reference a null object" I'm currently modifying a test class made by someone because its getting this error. The part at which the error shows up is at the If condition. I'm not sure why it gives that error at that part instead of the previous line. Thanks.
 for(c2g__codaCashEntry__c cashRefund : ppIdToRefundMap.values())
    {
        List<c2g__codaTransactionLineItem__c> transLineList = accIdToReceiptTransLineListMap.get(cashRefund.c2g__Account__c);
        if(!transLineList.isEmpty())
        {
            Id jobId = System.enqueueJob(new JVCO_PayonomyMatchRefundQueueable(cashRefund, transLineList));
        }
    }

A: A Map isn't always guaranteed to have the key you are using. In this case, you need to check if the collection is null before checking if it is empty. Often you would know from the structure of your code that it will never be non-null and empty, but you have not shown us the code where accIdToReceiptTransLineListMap gets populated. Regardless, you need to add a null check before your empty check:
if (myList != null && !myList.isEmpty())


text:
Q: Встраивание данных в бинарный файл (Vala/C) Можно ли записать необходимую мне информацию (в данном случае - XML для Gtk-Builder) в бинарный файл? В Go для этого есть пакет go-bindata. А что с Vala/C?

A: Возможно Вам нужна GResource - Resource framework из библиотеки GIO. Библиотека GIO входит в Glib.


text:
Q: Javascript toggle isnt working I have the following code:
<input type="checkbox" onClick="toggle('husob_filter_orderby')" value=""/><?php echo JTEXT::_('FILTER_TH_ORDERBY'); ?></input>

    <select name="orderby" class="select">
        <option value="datetime_asc" ><?php echo JTEXT::_('FILTER_ORDER_DTASC'); ?></option>;
        <option value="datetime_desc"><?php echo JTEXT::_('FILTER_ORDER_DTDES'); ?></option>;
        <option value="ofiden_asc"><?php echo JTEXT::_('FILTER_ORDER_DENASC'); ?></option>;
        <option value="ofiden_desc"><?php echo JTEXT::_('FILTER_ORDER_DENDES'); ?></option>;
    </select>

The toggle inside the input isnt functioning correctly. When I click the button it just hides the checkbox and doesnt toggle the div.
What is wrong?
EDIT: The toggle function is being called inside an imported file and not very sure where I can locate it. I know the code works because it works on another version of Joomla but not on a newer version.
EDIT 2: I get no javascript errors.

A: i dont know what you mean by toggle()  and toggle isn't a built-in function but you can also use this for toggle
<input type="checkbox" onClick="$('#husob_filter_orderby').toggle();" value=""/>


text:
Q: Equivalence Relation on Prime Numbers. Let $P\subseteq\mathbb{N}$ be the set of all primes. Let $\sim$ over $P$ be defined as
$p\sim q$ when for every $n\in\mathbb{N}$, $$p+n\in P\Leftrightarrow q+n\in P.$$
I want to prove this  relation has an infinite number of equivalent classes.
Intuitively, I suspect that for every $p\in P$, $[p]=\{p\}$, otherwise we'd have two primes $p,q$ such that the sets of primes greater than each of them have the same patern, which doesn't seem correct.

A: The classes are sigletons, indeed. By Dirichlet's theorem, for every two differenet primes $p$ and $q$ there is some positive integer $k$ such that $p+kq$ is prime, but certainly $q+kq$ is not prime.


text:
Q: how to append row vectors to an empty matrix without knowing the size of the matrix using numpy? rows is a 343x30 matrix of real numbers. Im trying to append row vectors from rows to true rows and false rows but it only adds the first row and doesnt do anything afterwards. Ive tried vstack and also tried putting example as a 2d array ([example]) but it crashed my pycharm. what can I do?
true_rows = []
        true_labels = []
        false_rows = []
        false_labels = []
        i = 0
        for example in rows:
            if question.match(example):
                true_rows = np.append(true_rows , example , axis=0)
                true_labels.append(labels[i])
            else:
                #false_rows = np.vstack(false_rows, example_t)
                false_rows = np.append(false_rows, example, axis=0)
                false_labels.append(labels[i])
            i += 1

A: you can use only a simple list to append your rows and then transform this list to numpy array such as :
exemple1 = np.array([1,2,3,4,5])
exemple2 = np.array([6,7,8,9,10])
exemple3 = np.array([11,12,13,14,15])

true_rows = []
true_rows.append(exemple1)
true_rows.append(exemple2)
true_rows.append(exemple3)
true_rows = np.array(true_rows)

you will get this results:
true_rows = array([[ 1,  2,  3,  4,  5],
                   [ 6,  7,  8,  9, 10],
                   [11, 12, 13, 14, 15]])

you can also use np.concatenate if you want to get one dimensional array like this:
true_rows = np.concatenate(true_rows , axis =0)

you will get this results:
true_rows = array([ 1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12, 13, 14, 15])

A: Your use of [] and np.append suggests you are trying to imitate a common list append model with arrays.  You atleast read enough of the np.append docs to know you need to use axis, and that it returns a new array (the docs are quite clear this is a copy).
But did you test this idea with a small example, and actually look at the results (step by step)?
In [326]: rows = []
In [327]: rows = np.append(rows, np.arange(3), axis=0)
In [328]: rows
Out[328]: array([0., 1., 2.])
In [329]: rows.shape
Out[329]: (3,)

the first append doesn't do anything - the result is the same as arange(3).
In [330]: rows = np.append(rows, np.arange(3), axis=0)
In [331]: rows
Out[331]: array([0., 1., 2., 0., 1., 2.])
In [332]: rows.shape
Out[332]: (6,)

Do you understand why?  We join 2 1d arrays on axis 0, making a 1d.
Using [] as a starting point is the same starting with this array:
In [333]: np.array([])
Out[333]: array([], dtype=float64)
In [334]: np.array([]).shape
Out[334]: (0,)

And with axis, np.append is just a call to concatenate:
In [335]: np.concatenate(( [], np.arange(3)), axis=0)
Out[335]: array([0., 1., 2.])

np.append sort looks like list append, but it is not a clone.  It's really just a poorly named way to use concatenate.  And you can't use it properly without actually understanding dimensions.  np.append has an example with an error much like what you got with concatentate.
Repeated use of these array concatenates in a loop is not a good idea.  It's hard to get the dimensions right, as you found.  And even when it works, it is slow, since each step makes a copy (which grows with the iteration).
That's why the other answer sticks with list append.
vstack is like concatenate with axis 0, but it makes sure all arguments are 2d.  But if the number columns differ, it raise an error:
In [336]: np.vstack(( [],np.arange(3)))
Traceback (most recent call last):
  File "<ipython-input-336-22038d6ef0f7>", line 1, in <module>
    np.vstack(( [],np.arange(3)))
  File "<__array_function__ internals>", line 180, in vstack
  File "/usr/local/lib/python3.8/dist-packages/numpy/core/shape_base.py", line 282, in vstack
    return _nx.concatenate(arrs, 0)
  File "<__array_function__ internals>", line 180, in concatenate
ValueError: all the input array dimensions for the concatenation axis must match exactly, but along dimension 1, the array at index 0 has size 0 and the array at index 1 has size 3

In [337]: np.vstack(( [0,0,0],np.arange(3)))
Out[337]:
array([[0, 0, 0],
       [0, 1, 2]])

If all you are joining are rows of a (n,30) array, then you do know the column size of the result.
In [338]: res = np.zeros((0,3))
In [339]: np.vstack(( res, np.arange(3)))
Out[339]: array([[0., 1., 2.]])

If you pay attention to the shape details, it is possible to create an array iteratively.

But instead of collecting rows one by one, why not create a mask and do the collection once.
Roughly do
mask = np.array([question.match(example) for example in rows])
true_rows = rows[mask]
false_rows = rows[~mask]

this still requires an iteration, but overall should be faster.


text:
Q: Firebase transaction returns ArrayList handling I'm trying to check if a child already has a value or not, if not then increment a child value and add an array of data inside the child. ex:

and expect the code will add second child "2":

to do this I use doTransaction to check if there are any values within history/userId value,
Date c = Calendar.getInstance().getTime();
SimpleDateFormat df = new SimpleDateFormat("dd-MMM-yyyy", Locale.getDefault());
String formattedDate = df.format(c);
PlanHistory planHistory = new PlanHistory(formattedDate, plan.getPlan_key(), plan.getPlan_name(), plan.getLevel_name(), plan.getType_name(), plan.getPersonal_trainer_id(), plan.getUri());
mDatabase.child("history").child(user.getUid()).runTransaction(new Transaction.Handler() {
    @NonNull
    @Override
    public Transaction.Result doTransaction(@NonNull MutableData mutableData) {
        long value = 0;
        if(mutableData.getValue() != null) {
            String numQuestions = (String) mutableData.getValue();
            value = Long.parseLong(numQuestions, 16);
        }
        value++;
        String incHex = Long.toHexString(value);
        mutableData.setValue(incHex);
        mutableData.child(incHex).setValue(planHistory);
        return Transaction.success(mutableData);
    }

    @Override
    public void onComplete(@Nullable DatabaseError error, boolean committed, @Nullable DataSnapshot currentData) {

    }
});

the problem lies when there's already a value inside the child node, it returns ArrayList and cannot be cast to String

How can I fix the code so it can add the next node with incremented child name from previous one just like the expected result?

A: When you make this call:
String numQuestions = (String) mutableData.getValue();

You get the value of the MutableData object, which contains all data under mDatabase.child("history").child(user.getUid()) from your database. So that is way more data than a single string. My guess is that you're looking for:
String numQuestions = (String) mutableData.getKey();


text:
Q: File Locked Updated Sharepoint Document I'm trying to do some changes to the properties of the documents that users edit in a Sharepoint 2010 Document Library progammatically using an Event Handler. At the moment, I'm trying with the event ItemCheckedIn. The problem comes when I execute the following instruction:
item.File.Update();

It gives me an exception saying that the document is locked by user XXX.
Am I updating the properties in the wrong event? How can I avoid this exception?
Thank you in advance.

A: Try using
item.SystemUpdate()

instead

A: Microsoft Office Word is issuing a lock request on documents by default and it is different than 'Checked Out' state.
'Lock' is release only after document is closed by Word. While 'Check Out' can be performed via Word or web interface and it would remain such until explicitly requested to 'Check In'.
As previous comment suggest, the best remedy is to to use in your code:
item.SystemUpdate(false) as that would not obey to 'Lock' state and save any changes done via Event handler code.


text:
Q: Generate Passphrase for Encryption I am working on Encrypting some data using AES 128bit encryption algorithm (Symmetric Encryption Algorithm).
Problem I am facing with this is generating a Key ? As I have mutliple Users and I don't want to share the common key across the users.
Is there is any possibility to generate passphrase in such a way that it is not common to all and can be passed to AES to decrypt/Encrypt the same data?
Example:
 lets assume I have a table with employee and their salary. I want to encrypt Salary Column of Employee with AES encryption.
Now when Someone authorized from HR wants to see the salary of Employee they can check, but they should have their own Key (not the common Key).

A: One possible solution is to create an encrypted version of the master key per user.
So you will:

*

*Encrypt your data with a "master key"

*Encrypt your "master key" with a "personal key" (one for each user)

Then, when a user provides its personal key, you use it to decrypt the stored and encrypted master key, and then use that to decrypt the data. This way the encryption for the data can be done with always the same key, and you can regulate access with the personal keys.
This assumes though the master key and encrypted data never leave the server, you will have to decrypt on the server and send unencrypted to the user (but of course use a secure line for that, against eavesdropping).
There is no way to do this if you want to send the data to the user encrypted.

A:
Now when Someone authorized from HR wants to see the salary of Employee they can check, but they should have their own Key (not the common Key).

Using symmetric encryption - effectively there is only a single data encryption key (DEK). The DEK can be random and content specific. You cannot have multiple keys to decrypt the same encrypted content.
What is commonly done using asymmetric encryption, when someone authorizes (shares/assigns) an encrypted content to a user, the DEK is re-encrypted by the user's public key, so only an authorized user could decrypt the DEK and then content (though - the DEK is the same for all users).

when user logs in I will ask them Key

To log in the user anyway needs to provide a secret (its user password or other credentials), so - do you really need to go through all the hustle? Isn't enough to encrypt data at REST with some system-specific master key and provide the encrypted content only to an authenticated and authorized user?


text:
Q: Migration wicket 8.* from 7.*, problem with onRequestHandlerResolved() method on AbstractRequestCycleListener I'm working on Wicket 8.* migration when I struggle on onRequestHandlerResolved() under IRequestCycleListener method conversion.
As per my structure of logic in my code wicket 7.15.0
public class MyRequestCycleListener extends AbstractRequestCycleListener{
//All methods override here
    @Override
    public void onRequestHandlerResolved(RequestCycle cycle, IRequestHandler handler) {
       if (handler instanceof ListenerInterfaceRequestHandler) {
           ListenerInterfaceRequestHandler requestHandler = (ListenerInterfaceRequestHandler) handler;
           if (requestHandler.getListenerInterface().getListenerInterfaceClass().isAssignableFrom(         IFormSubmitListener.class)) {
                 //here made some login as well as every onSubmit
           }
       }
    }
}

As wicket 8.* changes
AbstractRequestCycleListener class converts to IRequestCycleListener interface
ListenerInterfaceRequestHandler renamed to ListenerRequestHandler
Deprecates RequestListenerInterface and also IFormSubmitListener makes error
How to convert code to migration on wicket 8.9.0 ?

A: It should be something like this:
public class MyRequestCycleListener implements IRequestCycleListener{

    @Override
    public void onRequestHandlerResolved(RequestCycle cycle, IRequestHandler handler) {
        if (handler instanceof ListenerRequestHandler) {
             ListenerRequestHandler requestHandler = (ListenerRequestHandler) handler;

            if (requestHandler.getComponent() instanceof Form) {
                  //here made some login as well as every onSubmit
                  Form form = (Form) requestHandler.getComponent();
            }
        }
    }
}


text:
Q: making datagrid addrow feature to work with entity framework i am writing this simple app that has two main tables one for picture information and another for a list of parameters about pictures just like picture below

I want to be able to add into parameters list inline without any other forms but when i add a row it adds another row correctly into database but saving the text entered doesn't works.(I am saving changes in "RowEditEnding" event)
here is XAML:
<Grid>
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="0.5*"/>
            <ColumnDefinition/>
        </Grid.ColumnDefinitions>
        <Grid Margin="10">
            <Grid.RowDefinitions>
                <RowDefinition/>
                <RowDefinition Height="50"/>
            </Grid.RowDefinitions>
            <ListBox Name="lstPicture" Grid.Column="0" ItemsSource="{Binding pictures, Mode=OneWayToSource}" DisplayMemberPath="Name" SelectedValuePath="ID">
            </ListBox>
            <Button Grid.Row="1" Content="جدید" Height="Auto" Margin="0,0,0,10"/>
        </Grid>
        <GroupBox Header="اطلاعات تصویر" Grid.Column="1" Margin="0,10,10,10">
            <!--Image Data Grid-->
            <Grid>
                <Grid.ColumnDefinitions>
                    <ColumnDefinition/>
                    <ColumnDefinition Width="200px"/>
                </Grid.ColumnDefinitions>
                <!--Image Data Right Grid-->
                <Grid>
                    <Grid.RowDefinitions>
                        <RowDefinition/>
                        <RowDefinition Height="100px"/>
                    </Grid.RowDefinitions>
                    <materialDesign:Card Margin="10" VerticalAlignment="Stretch" HorizontalAlignment="Stretch">
                        <Image Name="imgPreview" Margin="5" Source="{Binding SelectedItem.URL, ElementName=lstPicture}" MouseLeftButtonUp="Image_MouseLeftButtonUp">
                        </Image>
                    </materialDesign:Card>
                    <!--Image Data Fields-->
                    <Grid Grid.Row="1">
                        <Grid.ColumnDefinitions>
                            <ColumnDefinition Width="100px"/>
                            <ColumnDefinition/>
                        </Grid.ColumnDefinitions>
                        <Grid.RowDefinitions>
                            <RowDefinition/>
                            <RowDefinition/>
                            <RowDefinition/>
                        </Grid.RowDefinitions>
                        <Grid.Resources>
                            <Style TargetType="TextBlock">
                                <Setter Property="VerticalAlignment" Value="Center"/>
                                <Setter Property="Margin" Value="5"/>
                            </Style>
                            <Style BasedOn="{StaticResource MaterialDesignTextBox}" TargetType="TextBox">
                                <Setter Property="Margin" Value="5"/>
                            </Style>
                            <Style BasedOn="{StaticResource MaterialDesignRaisedButton}" TargetType="Button">
                                <Setter Property="Margin" Value="5"/>
                            </Style>
                        </Grid.Resources>
                        <TextBlock Text="نام تصویر"/>
                        <TextBox Grid.Column="1" Text="{Binding SelectedItem.Name, ElementName=lstPicture}"/>
                        <TextBlock Text="عکاس" Grid.Row="1"/>
                        <TextBox Grid.Column="1" Grid.Row="1" Text="{Binding SelectedItem.Author, ElementName=lstPicture}"/>
                        <TextBlock Text="انتخاب تصویر" Grid.Row="2"/>
                        <Button Name="btnChooseImage" Content="..." Grid.Column="1" Grid.Row="2" Height="Auto" Click="btnChooseImage_Click"/>
                    </Grid>

                </Grid>
                <DataGrid Name="dgrdQuestions" Grid.Column="1" Margin="10" ItemsSource="{Binding SelectedItem.tests, ElementName=lstPicture,Converter={StaticResource ObservableCollectionConverter},UpdateSourceTrigger=PropertyChanged}" AutoGenerateColumns="False" CanUserAddRows="True" CellEditEnding="DataGrid_CellEditEnding" RowEditEnding="dgrdQuestions_RowEditEnding" AddingNewItem="DataGrid_AddingNewItem">
                    <DataGrid.Columns>
                        <DataGridTextColumn Binding="{Binding Title}" Header="عنوان" Width="1*"/>
                    </DataGrid.Columns>
                    <DataGrid.ContextMenu>
                        <ContextMenu>
                            <MenuItem Name="btnAddQuestion" Header="جدید" Click="btnAddQuestion_Click"/>
                            <MenuItem Name="btnDeleteQuestion" Header="حذف" Click="btnDeleteQuestion_Click"/>
                        </ContextMenu>
                    </DataGrid.ContextMenu>
                </DataGrid>
            </Grid>
        </GroupBox>
    </Grid>

and here is code:
public AdminPanel()
{
    InitializeComponent();
    lstPicture.ItemsSource = App.Entities.pictures.ToList();
}

private void DataGrid_CellEditEnding(object sender, DataGridCellEditEndingEventArgs e)
{
    App.Entities.SaveChanges();
}

private void DataGrid_AddingNewItem(object sender, AddingNewItemEventArgs e)
{
    App.Entities.tests.Add(new test { pictureID = (int)lstPicture.SelectedValue });
    App.Entities.SaveChanges();
}

p.s:I always have such problems with WPF binding and entity framework that makes me use hacky ways to solve it. i would appreciate if someone explains to me the normal way to go with binding that doesn't cause such problems

A: Since EF doesn't know about your changed entity (it was changed by the ModelBinder and not EF itself, we need to tell EF that the object exists and that it is a modified App.Entities.Entry(test).State = EnitityState.Modified;
var datag = (DataGrid) sender;
var t = (Test) datag.SelectedValue;
App.Entities.Entry(test).State = EnitityState.Modified;
App.Entities.SaveChanges();

If the object not in this given DbContext for any reason, then you have to find it by Id and then change it and after that you can call App.Entities.SaveChanges();


text:
Q: Boot a Dell Server with no Monitor I have a few new dell r210s with windows 2008 server installed on them but I accidentally brought a DVI cable instead of a vga cable for the monitor. Is there anyway to remote into them without a DRAC installed?
(RDC is not setup on them yet because they are out-of-the-box new)

A: I ended up running down the street to purchase a cable

A: You could use a serial connection or you could setup an automated install of Windows server and hope it'll boot from the CD(or PXE). Other than that not really with some form of visual interface.


text:
Q: Google App Engine - JDODetachedFieldAccessException I'm pretty new to JPA/JDO and the whole objectdb world.
I have an entity with a set of strings, looks a bit like:
@Entity
public class Foo{

    @Id
    @GeneratedValue(strategy=GenerationType.IDENTITY)
    private Key id;

    private Set<String> bars;

    public void setBars(Set<String> newBars){
        if(this.bars == null)
            this.bars = new HashSet<String>;
        this.bars = newBars;
    }

    public Set<String> getBars(){
        return this.bars;
    }

    public void addBar(String bar){
        if(this.bars == null)
            this.bars = new HashSet<String>;
        this.bars.add(bar);
    }

}

Now, in another part of the code, I'm trying to do something like this:
EntityManager em = EMF.get().createEntityManager();
Foo myFoo = em.find(Foo.class, fooKey);
em.getTransaction().begin();
myFoo.addBar(newBar);
em.merge(myFoo);
em.getTransaction().commit();

When, of course, newBar is a String.
But, what I get is:
javax.jdo.JDODetachedFieldAccessException: You have just attempted to access field      "bars" yet this field was not detached when you detached the object. Either dont access this field, or detach it when detaching the object.

I've searched for an answer, but I couldn't find one.
I've seen someone ask about a Set of strings, and he was told to add an @ElementCollection notation.
I tried that, but I got an error about the String class Metadata (I don't really understand what it means.)
I would really appreciate some help on this thing, even a good reference to someone explaining this (in simple English).

A: OK,
So I found the answer in some blog.
So for anyone who's interested:
In order to use a Collection of simple data types (in JPA), a
    @Basic
notation should be added to the collection. So from my example at the top, It should've been written:
@Basic
private Set<String> bars;

A: So you are using JPA, right?  (I see EntityManager rather than JDO's PersistenceManager.)  Since you are getting a JDO error, I suspect that your app isn't configured properly for JPA.
JPA docs: http://code.google.com/appengine/docs/java/datastore/jpa/overview.html
JDO docs: http://code.google.com/appengine/docs/java/datastore/jdo/overview.html
You need to pick one datastore wrapper and stick with it.  The default new app with the Eclipse tools is configured for JDO, and it is a reasonable choice, but you'll have to change your annotations around a little bit.