text:
Q: Hibernate nested embedded primary keys or flat fields? I have two classes with nested composite primary-keys (composite PK of B includes composite PK of A)
class A {
    @EmbeddedId
    APk aId;
}

@Embeddable
class APk {
    @Column
    Long x;
    @Column
    Long y;
}

class B {
    @EmbeddedId
    BPk bId;
}

Knowing that composite primary-keys in hibernate are not recommended: what is the recommended way to implement the primary key type for B?
Alternative 1 - with the PK of A embedded?
Alternative 2 - or with all 3 properties declared in a more flat implementation?
@Embeddable
class BPk {
    // Alternative 1
    @Embedded
    APk aId;
    @Column
    Long z;
}

@Embeddable
class BPk {
   // Alternative 2
    @Column
    Long x;
    @Column
    Long y;
    @Column
    Long z;
}

A: There is not much difference between these two alternatives. You will be able to override the mapping of the properties in both cases, if needed. If APk is reused more than once, alternative 1 would be better. Otherwise, keep it simple with alternative 2.


text:
Q: Is there any difference between buying Frozen Synapse: Red on Steam or the developer site? I already own Frozen Synapse the base game on Steam, and with the newly released DLC Frozen Synapse: RED I wonder whether to buy it on Steam, or pick it up directly at the website of the developer.
Is there a difference between the two shops (content or price wise)?

A: Buying Frozen Synapse, either on Steam or from the developer's web site, gets you a key code for the DLC.
No matter how you download the DLC, you must activate it by running Frozen Synapse and pressing the "Activate DLC" button to paste in the code.
In addition, you can take the FS Red DLC code and activate it in Steam by going to Games->Activate A Product On Steam.
Whether you buy through Steam or through the developer's web site, you get a code that can be entered in FS and also added to Steam.
If you purchase from Mode 7's web site, the developers get more of the money!
From IRC (Omroth is Ian Hardingham, the lead developer):

(23:23:05) Goateh: Omroth! does it make a difference if i buy the dlc
  through steam or through your site?
(23:23:54) Omroth: more money via us
(23:24:00) Omroth: and you can activate it on steam :P

A: The content is the same. For me the price is the same too, but that may depend on your region (I'm from mainland Europe, UK and US often have to pay less, Australia and Canada more).
Steam offers more payment options. Neither Frozen Synapse nor its DLC are in the 'Which retail CD Keys are accepted on Steam?'-List, so I can't say if a copy you buy from the developers website activates and downloads through steam.
Buying from the developers website might be better for them because Steam takes a cut of every sale. But since they use an external payment provider and I have no way of knowing if they take a higher/lower/equal percentage I can't say.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to create an rpm without a build step I'm trying to create an rpm of some code which doesn't need to be built.  It will just need to run a script when it's installed on the destination system (i.e. I just need the %install portion of the spec file).
I've left both %build and %configure sections of my rpm spec file empty, yet rpmbuild continues to try and execute ./configure with a bunch of parameters.
Does anyone know how I can have rpmbuild create the rpm without trying to run ./configure?

A: The rpm specfile syntax is confusing. %configure isn't a section like %build is. It's a macro which expands to running ./configure with system-specific parameters. That's what you're seeing. And the solution is easy — remove it, and there you go.

A: If you do rpmbuild --short-circuit -bi /path/to/specfile, it will skip the %prep and %build stages and go straight to the %install stage.  That should do what you want.

A: rpmbuild -ba /path/to/specfile

A: It's a kludge, but put a noop in %build and %configure ?


text:
Q: Reading input/output from Chatting program[exe file] what i tried
try {
    File fileDir = new File("B:\\Palringo\\palringo.exe");
    BufferedReader in = new BufferedReader(
       new InputStreamReader(
              new FileInputStream("B:\\Palringo\\palringo.exe"), "UTF8"));

    String str;

    while ((str = in.readLine()) != null) {
        System.out.println(str);
    }

        in.close();
    }
    catch (UnsupportedEncodingException e)
    {
        System.out.println(e.getMessage());
    }

Output :
unreadable Strings

what i want
i want to control the (palringo.exe) so i can make Bot for it
What is palringo.exe ?:
its a chatting program you can download it or use web version (palringo.im).
am i doing wrong by opening a file that is exe ? should i connect to the website by Connection classes in java ? if so , how i can connect it ?

A: This doesn't work. You cannot read an exe file.
You need to have the source code or library to add that software to you code. You simply cannot read a exe file and extract code, because exe file will be encrypted and it will be in lower level languages.
But you can use exec() to run that exe file.

A: I know this is a very late answer, if you are looking to connect and manipulate palringo, there are a couple of APIs available.
https://github.com/calico-crusade/PalringoApi
This specific one can also be found on Nuget, though it is for C#. You could copy over the majority of the connection code to Java if you wish.


text:
Q: Ignore ssl certificate requests in webview I make small app which involve aspx pages , I try open it throw my webview I got blank screen .
I try open it with chrome browser it give me certificate needed

my code is very simple I add some documentation to explain what is going on
@SuppressLint("SetJavaScriptEnabled")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_web);
        Bundle bundle = getIntent().getExtras();
        if(bundle != null){
            urlSite = bundle.getString("passed_url");
        }
     _toolbar = (Toolbar)findViewById(R.id.toolbar);
    setSupportActionBar(_toolbar);
    getSupportActionBar().setDisplayHomeAsUpEnabled(true);
    _toolbar.setNavigationOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            onBackPressed();
        }
    });
    webView = (WebView) findViewById(R.id.webView);
    WebSettings webSettings = webView.getSettings();

    // enable javascript
    webSettings.setJavaScriptEnabled(true);
    webSettings.setDomStorageEnabled(true);
    webSettings.setJavaScriptCanOpenWindowsAutomatically(true);
    webSettings.setUseWideViewPort(true);
    webSettings.setLoadWithOverviewMode(true);
    webSettings.setPluginState(WebSettings.PluginState.ON_DEMAND);

    webView.setWebChromeClient(new WebChromeClient());
    webView.setWebViewClient(new WebViewClient() {
        @Override
        public void onPageFinished(WebView view, String url) {
            super.onPageFinished(view, url);
            new ParseURl().execute(new String[]{urlSite});
        }

        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            view.loadUrl(url);
            return true;
        }
    });
    if(urlSite != null){
        webView.clearCache(true);
        webView.loadUrl(urlSite);
       // webView.loadUrl("file:///android_asset/af.html");
    }
}

A: After some research I found the answer, just override onReceivedSslError method and skip it.
@Override
public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
    handler.proceed(); // Ignore SSL certificate errors
}


text:
Q: WSO2 + WCF Data Services For our project we use WSO2 products, for data access was selected WCF Data Services technology by Microsoft. How we can generate proxy service for our WCF Data Service use WSO2 ESB or WSO2 Data Service Server?
Any solutions?

A: Use WSO2 ESB to expose your proxy services.


text:
Q: Python how to call AJAX URL (to trigger onchange event for website select menu) I am trying to automate Internet Explorer interaction with a website using Python. I am using the IEC library to do this.
The website is set to trigger an action whenever a username is selected from a dropdown menu. The html code snippet is as follows:
<select name="ClientID" tabIndex="1001" title="Select a client" class="client-select focus-default need-focus-object valid" style="width: auto;" onchange="localChangeClient()">
  <option value="0">
  <option value="2629049">

I am able to programmatically set the user name in the dropdown list, but this does not trigger the "onchange" event. I have read some other references (links below) that indicate I should look for the AJAX request and trigger it directly, but I am not sure how to do this.

*

*Trigger Javascript event on remote website with Python

*on Change of dropdown list showld call the php function
I gather that 'onchange' triggers a call to a function called localChangeClient(). How do I call / trigger that function directly from Python IEC?
From the examples I linked, it seems an AJAX request would be made inside that localChangeClient function - is that right? How do I know what the AJAX request to call is, given that I cannot see the actual function details?
EDIT: The following describes continued efforts / developments. I think I just need to know how to call an AJAX URL directly
So I was reading more about AJAX requests. I found out I could use Firebug (Console window) to tell me the particular AJAX url that gets called for the onchange event. Firebug told me the following (snipped for clarity) when I changed the dropdown menu:
POST https://example.com/MyBasket/MyBasket.asp?update=Update%20Basket&ClientID=2629049,0&SDT=417.577989&SCheck=49913&Checkout=&ClientID=2629049&ClientID=0&CurrentPageUrl=&FullPage=false&MyBasketPage=1&OnClickScheduleCheckboxName=&OverlayRequest=true&TransactionStarted=0&ajax=true&cbxRegQuantity=1&cbxRegQuantity=1&update=no

So I think I am on the right track. But now I don't know how to trigger that url from Python. If I simply "ie.Navigate(url)", it does not seem to work. It takes me to a non-formatted window, and the dropdown menu is still not selected.
I checked a Microsoft support site (http://support.microsoft.com/kb/167658), which talked about encoding the request data as bytes etc, but I was unclear if that would apply here.
I would really appreciate if someone could provide some details on how to "do the AJAX request directly"

A: Use Python's requests library to make the call to that URL you found. You'll also need to find the body and any custom HTTP headers of that POST request in the Firebug console in order to replicate it in your script.
res = requests.post(<url>, data=<request-body>, headers=<headers>)


text:
Q: How to implement Sha3Algorithm Adjust difficulty I've succesfully created a proof of work node with a constant as difficulty.
Now i've created the sha3algorithm struct that should fetch the difficulty from the runtime
                let pow_block_import = sc_consensus_pow::PowBlockImport::new(
                    client.clone(),
                    client.clone(),
                    crate::pow::Sha3Algorithm::new(client.clone()),
                    0,
                    select_chain,
                    inherent_data_providers.clone()
                );

A: Add this to your runtime apis
    impl sp_consensus_pow::DifficultyApi<Block, U256> for Runtime {
        fn difficulty() -> U256 {
            U256::from(10000000)
        }
    }

From here you can call any module that calculates the difficulty


text:
Q: in python - how to save multi HTML Source code to one single text file I have list for Links (stored in links.txt file )
This code can save result of one link
but I do not know how to make it download ALL the source codes of ALL links inside (links.txt) and SAVE THEM AS ONE SINGLE text file for next step of processing ...
import urllib.request
urllib.request.urlretrieve("https://www.ebay.com/sch/i.html?_from=R40&_nkw=abc&_sacat=0&_pgn=1", "result.txt")

Example links form links.txt
https://www.ebay.com/sch/i.html?_from=R40&_nkw=abc&_sacat=0&_pgn=1
https://www.ebay.com/sch/i.html?_from=R40&_nkw=abc&_sacat=0&_pgn=2
https://www.ebay.com/sch/i.html?_from=R40&_nkw=abc&_sacat=0&_pgn=3
https://www.ebay.com/sch/i.html?_from=R40&_nkw=abc&_sacat=0&_pgn=4
https://www.ebay.com/sch/i.html?_from=R40&_nkw=abc&_sacat=0&_pgn=5
https://www.ebay.com/sch/i.html?_from=R40&_nkw=abc&_sacat=0&_pgn=6
https://www.ebay.com/sch/i.html?_from=R40&_nkw=abc&_sacat=0&_pgn=7
....

A: urllib
import urllib.request

with open('links.txt', 'r') as f:
    links = f.readlines()

for link in links:
    with urllib.request.urlopen(link) as f:
        # get html text
        html = f.read().decode('utf-8')

        # append html to file
        with open('result.txt', 'w+') as f:
            f.write(html)

requests
you could also use requests library which i find much more readable
pip install requests

import requests

with open('links.txt', 'r') as f:
    links = f.readlines()

for link in links:
    response = requests.get(link)
    html = response.text

    # append html to file
    with open('result.txt', 'w+') as f:
        f.write(html)

Use loop for page navigation
Use for loop to generate page links as the only thing that is changing is the page no.
links = [
  f'https://www.ebay.com/sch/i.html?_from=R40&_nkw=abc&_sacat=0&_pgn={n}'
  for n in range(1, 10) # [1, 2, 3, 4, 5, 6, 7, 8, 9]
]

or as you go along
for n in range(1, 10):
  link = f'https://www.ebay.com/sch/i.html?_from=R40&_nkw=abc&_sacat=0&_pgn={n}'

  [...]

A: Actually, it's usual better to use requests lib, so you should start from installing it:
pip install requests

Then I'd propose to read the links.txt line by line, download all the data you need and store it in file output.txt:
import requests

data = []
# collect all the data from all links in the file
with open('links.txt', 'r') as links:
    for link in links:
        response = requests.get(link)
        data.append(response.text)

# put all collected to a single file
with open('output.txt', 'w+') as output:
    for chunk in data:
        print(chunk, file=output)


text:
Q: Asp.net c# Grid view update Error Every attempt to use the onrowupdating function a System.NullReferenceException error is thrown. The Gridview has no problem binding on page load and I can also delete rows without a problem.Here is my code:
Aspx..
<asp:GridView ID="datagrid" runat="server" DataKeyNames="Emp_ID" CssClass="EmployeeGridView" EditRowStyle-CssClass="GridViewEditRow" PagerStyle-CssClass="pager" HeaderStyle-CssClass="header" RowStyle-CssClass="rows"
        AutoGenerateColumns="false" AllowPaging="true" OnRowCancelingEdit="OnRowCancelingEdit" OnRowDeleting="OnRowDeleting"
        OnRowEditing="OnRowEditing" OnRowUpdating="OnRowUpdating"
        OnPageIndexChanging="OnPageIndexChanging" PageSize="10"
        >
        <Columns>
        <asp:BoundField ItemStyle-Width="150px" DataField="Emp_ID" HeaderText="Employee ID" />
        <asp:BoundField ItemStyle-Width="150px" DataField="FName" HeaderText="First Name" />
        <asp:BoundField ItemStyle-Width="150px" DataField="LName" HeaderText="Last Name" />
        <asp:BoundField ItemStyle-Width="150px" DataField="Email" HeaderText="Email" />
        <asp:BoundField ItemStyle-Width="100px" DataField="DOB" HeaderText="DOB" />
        <asp:BoundField ItemStyle-Width="150px" DataField="EmpRole" HeaderText="Role" />
        <asp:BoundField ItemStyle-Width="150px" DataField="Notes" HeaderText="Notes" />
        <asp:CommandField ShowEditButton="true" />
        <asp:CommandField ShowDeleteButton="true" />
        </Columns>
       </asp:GridView>

c#..
protected void OnRowUpdating(object sender, GridViewUpdateEventArgs e)
    {
        GridViewRow row = datagrid.Rows[e.RowIndex];
        int Emp_ID = Convert.ToInt32(datagrid.DataKeys[e.RowIndex].Values[0]);
        string FName = (row.Cells[2].Controls[0] as TextBox).Text;
        string LName = (row.Cells[3].Controls[0] as TextBox).Text;
        string Email = (row.Cells[4].Controls[0] as TextBox).Text;
        string DOB = (row.Cells[5].Controls[0] as TextBox).Text;
        string role = (row.Cells[6].Controls[0] as TextBox).Text;
        string notes = (row.Cells[7].Controls[0] as TextBox).Text;
        string constr = ConfigurationManager.ConnectionStrings["MainFYPConnectionString"].ConnectionString;
        using (SqlConnection con = new SqlConnection(constr))
        {
            using (SqlCommand cmd = new SqlCommand("UPDATE tbl_Employees SET FName=@FName, LName=@LName, Email=@Email, DOB=@DOB, EmpRole = Emp@Role, Notes = @Notes  WHERE (Emp_ID = @Emp_ID)"))
            {
                cmd.Parameters.AddWithValue("@Emp_ID", Emp_ID);
                cmd.Parameters.AddWithValue("@FName", FName);
                cmd.Parameters.AddWithValue("@Lname", LName);
                cmd.Parameters.AddWithValue("@Email", Email);
                cmd.Parameters.AddWithValue("@DOB", DOB);
                cmd.Parameters.AddWithValue("@EmpRole", role);
                cmd.Parameters.AddWithValue("@Notes", notes);
                cmd.Connection = con;
                con.Open();
                cmd.ExecuteNonQuery();
                con.Close();
            }
        }
        datagrid.EditIndex = -1;
        this.BindGrid();
    }

If anyone has any idea what is wrong the help would be greatly appreciated


text:
Q: Adding Entity Framework Model on Visual Studio 2022 I am using Visual Studio 2022 with.Net 6.0, I installed Entity Framework 6.4.4 after adding it when I create an Entity Framework model. I am getting a Popup message saying that.

The project's target framework does not contain Entity Framework runtime assemblies. Please review the target framework information on the project's property page.

Can somebody tell us how to solve that problem?

A: Ensure you have Target Framework as show.

A: You can install .Net Framework 4.8.
.Net Core 1 - 3.2 & .Net 5 & 6 has no Entity Framework Data Model available with EF Core.
You want to use EF 6 (not Core) and Data Model you have to use .Net Framework 4.8 or lower than that.

A: Try this to generate/update entire DbContext and models:
Scaffold-DbContext -Connection "Server=(local);Database=DefenderRRCart;Integrated Security=True;Trusted_Connection=True;" -Provider Microsoft.EntityFrameworkCore.SqlServer -OutputDir RRStoreContext.Models -context RRStoreContext -Project RR.DataAccess -force

See this post for more info.
https://stackoverflow.com/a/41413291/4588756


text:
Q: How to find the pmf of the number of students who get their passport back? $4$ passports are returned randomly to $4$ students. Let the random variable $X$ be the number of students who get their passport back. Determine the pmf of $X$.
Answer:
$$p(0) = \frac{9}{24}, p(1) = \frac{1}{3}, p(2) = \frac{1}{4}, p(3) = 0, p(4) = \frac{1}{24}$$

I understand that $p(3) = 0$ because if $3$ people get the correct passport back then that implies the remaining person got the wrong passport which is not possible since the remaining passport must be the correct passport. I think my answer makes more sense even though it is incorrect. My question is how is the answer above obtained and why is my answer incorrect?
My answer:
Let $e=${at least one person gets their passport back}$=${$e_1$,$e_2$,$e_3$,$e_4$} where $e_i$ is the subevent that $i$th person gets back their passport.
So the pmf $P(X=e)=p(e)$ is
$$p(0) = p(\bar e)=1-p(e)=1-[p(1)+p(2)+p(3)+p(4)]$$
$$p(1) = \frac{\binom{4}{1}}{4!}, p(2) = \frac{\binom{4}{2}}{4!}, p(3) = \frac{\binom{4}{3}}{4!}, p(4) = \frac{\binom{4}{4}}{4!}$$
which simplifies to
$$p(0) =\frac{9}{24}, p(1) = \frac{4}{24}, p(2) = \frac{6}{24}, p(3) = \frac{4}{24}, p(4) = \frac{1}{24}$$
Only $p(1)$ and $p(3)$ are incorrect. Although the correct answer for $p(3)=0$, I think $p(3)=\frac{4}{24}$ because technically $4$ people are getting back their passports if $3$ people get back the correct passport. Can someone explain why my answer is wrong? Also my probabilities still add up to $1$ although it is incorrect.

A: Let me show you a very simple way to solve the problem. You have to calculate 5 probabilities

*

*$P(0)$

*$P(1)$

*$P(2)$

*$P(3)$

*$P(4)$
$P(3)=0$, trivial because, as you noted, if 3 passports are correct it is not possible to have the fourth wrong.
$P(0)=\frac{9}{24}$ as there are
$!4=4!\left(\frac{1}{2!}-\frac{1}{3!}+\frac{1}{4!}\right)=9$ favourable ways to have permutations of elements all wrong on 24 possible ways
$P(4)$, conversely, there
is only 1  favourable permutation on the 24 possible
with similar reasoning as $P(0)$
$$P(1)=\frac{ !3}{6}=\frac{1}{3}$$
$P(2)$ can be derived as complement probability to 1

A: $p(3) = 0$ because as you mentioned, if three people get their passport back then the remaining person cannot get the wrong passport, hence this event never occurs.
Your answer for $p(1)$ is close to the correct answer. You have to multiply $p(1)=\frac{\binom{4}{1}}{24}$ by 2  because $\binom{4}{1}$ is the number of ways to select one person to get the correct passport out of four possible people. This is equivalent to the number of people who get the incorrect passport. For instance, let the three remaining people/passports be $p_1,p_2,p_3$. There are 2*$\binom{4}{1}$ ways they can get the incorrect passport.
For example,

*

*if $p_1$ gets $p_2$'s passport then

*$p_2$ gets $p_3$'s passport and

*$p_3$ gets $p_1$'s passport.

This can happen in $2$ ways, hence $p(1)=\frac{2*\binom{4}{1}}{24}=\frac{8}{24}$

A: *

*Your formula is $\frac{combinations}{permutations}$. As you know
$combinations=\frac{permutations}{redundancies}$, so each probability
that you calculated is $\frac{combinations}{permutations}=\frac 1
   {redundancies}$ and doesn't have much meaning. For example, for
$\frac{4\choose 2}{4!}=\frac{1}{2!2!}$ is the probability of picking
a unique sequence when you've got two groups of two things, e.g. if
we were to put A, B where the underscores are and C, D in the
exclamation marks, _ ! ! _, you have calculated the probability of
getting one unique sequence such as ACDB. The immediate relation to
the problem is not clear.

*Instead, you should reason as follows. For p(1), there is 1/4 chance
that the correct letter goes to student-1. Then the remaining letters
have a 2/3 * 1/2 * 1 chance of going to an incorrect student. Now
this can also happen to students, 2, 3, and 4, so multiply this
probability by 4 to get $\frac 1 4\left(\frac 2 3 *\frac 1 2*
   1\right)*4=\frac 1 3$. For p(3), it is not possible to get exactly 3
right matches because of exactly what you said. p(4) is a separate
case than p(3). p(4) is when all 4 people get their passports back,
but it so happens that it is not p(3) because p(3) is when 3 people
get their passports back and 1 does not - there is an important
distinction.


text:
Q: How to add additional field to drupal organic group 'User and Group' relation? Im using Drupal Organic group module and I want to create a group and need to assign users (filter by perticular role) to that group. I have done that part easily but the problem is that, I need to add aditional note on per each group user relation.
Lets say there is a group called "School Prefects" and need to add users to that group whos role is student. In here I need to put a small description for each relation.
Please help me to figure this out.
Thanks in advance.

A:
I will probably deal with the same problem soon.
I think a possible workaround is to use the relation module and
the rules module. You could set up a rule to create a relation
each time a user is assigned to a group, or something like that.
Relations made by the relation module are fieldable. But it would be
maybe better to add a field to the og user-group relation directly.

Update: now that I tackled the issue, I have a different solution. We don't need to add new relations, the og_membership shipped standard with og is all that we need. This is how I did it.
I created a new membership type from admin/config/group/group-membership. It's a fildable entity so I added the required fields: in your case it will be "description".
Then I changed the used membership type per user, I did it in admin/config/people/accounts/fields/og_user_node (I needed to change the field "group membership" in user account).
So, now when you (or a group administrator) go to "manage group page" (clicking the group tab in group node), where you can add new people or manage members, either way you can edit your custom field "description" on each membership users-group.
Besides, you can clone the "og members" view adding the field "description", so in people panel in the group homepage we see name + description.
I my use-case I had to see (per group member): name, role, start date, end date. E.g. John Doe, president, from 1997 to 2003.


text:
Q: Can I create a Play! framework project and use existing Java code? I'm currently in a project which already has some codebase in plain Java, we need to develop a new web application which will leverage on this plain Java code.
We already have code for database access, some business rules, etc. I really just want to use Play for the web development part and don't want to do a whole new implementation of models using a Play approach.
What I thought when looking for a Java web framework was to find something that I could embed in the project, start a server (like Jetty or something) in my application and it would take care of the web part. But reading Play's documentation I can only find examples on how to run Play, not how to embed it into some project.
What I want to know is: can I embed a Play application inside another application? If not, how can I use my already developed plain Java code inside a Play! project?
Thanks for your attention!

A: Provide your existing code as a Jar file and call it from your Play app.
If your application is too big/this can't be done for whatever reason, create some API in your app that Play can connect to (via webservices, etc) and use it.
I would not recommend embedding Play inside, not because it can't be done (I'm sure it can) but would be messy and it is probably a good idea to keep the different concerns (web/whatever your app does) separated for easier maintenance/upgrades.

A: If your codebase is small, you can try this solution:
put your code into app/ folder (should be generated by play).
3rd party jars addition explained here: http://www.playframework.com/documentation/2.0.4/SBTDependencies


text:
Q: Map projections for each quadrant of the globe I am using an xarray data and matplotlib to plot it before export
This is the xarr data used
<xarray.DataArray 't2m' (latitude: 361, longitude: 720)>
array([[273.9, 273.9, 273.9, ..., 273.9, 273.9, 273.9],
       [274.1, 274.1, 274.1, ..., 274.1, 274.1, 274.1],
       [274.5, 274.5, 274.5, ..., 274.5, 274.5, 274.5],
       ...,
       [220.6, 220.6, 220.6, ..., 220.6, 220.6, 220.6],
       [221.6, 221.6, 221.6, ..., 221.6, 221.6, 221.6],
       [223. , 223. , 223. , ..., 223. , 223. , 223. ]], dtype=float32)
Coordinates:
  * latitude    (latitude) float64 90.0 89.5 89.0 88.5 ... -89.0 -89.5 -90.0
  * longitude   (longitude) float64 -180.0 -179.5 -179.0 ... 178.5 179.0 179.5
    step        timedelta64[ns] 03:00:00
    valid_time  datetime64[ns] 2020-09-14T03:00:00
Attributes:
    standard_name:  air_temperature

The longitude range is from -180 to +180. If I use the below data with projections the image produced is correct.
import xarray as xr
import matplotlib.pyplot as plt
import cartopy.crs as ccrs

imgDpi = 100
fig = plt.figure(figsize=(512/imgDpi, 512/imgDpi), dpi=imgDpi) #to convert from inches to px
ax = fig.add_subplot(1,1,1, projection=ccrs.epsg(3857))
ax.imshow(xarr, transform=ccrs.PlateCarree(), origin='upper', cmap='viridis')
ax.axis('off')
fig.tight_layout(pad=0)
plt.show()
fig.savefig('unsliced.png', format="png", transparent=True, dpi=imgDpi)

But if I slice the data into four quadrants and plot, there is an issue with projection
topLeft = xarr.sel(longitude=slice(-180, 0), latitude=slice(90, 0))
topRight = xarr.sel(longitude=slice(0, 180), latitude=slice(90, 0))
bottomLeft = xarr.sel(longitude=slice(-180, 0), latitude=slice(0, -90))
bottomRight = xarr.sel(longitude=slice(0, 180), latitude=slice(0, -90))

axTL = fig.add_subplot(2,2,1, projection=ccrs.epsg(3857))
axTL.imshow(topLeft, transform=ccrs.PlateCarree(), origin='upper', cmap='viridis')
axTL.axis('off')

axTR = fig.add_subplot(2,2,2, projection=ccrs.epsg(3857))
axTR.imshow(topRight, transform=ccrs.PlateCarree(), origin='upper', cmap='viridis')
axTR.axis('off')

axBL = fig.add_subplot(2,2,3, projection=ccrs.epsg(3857))
axBL.imshow(bottomLeft, transform=ccrs.PlateCarree(), origin='upper', cmap='viridis')
axBL.axis('off')

axBR = fig.add_subplot(2,2,4, projection=ccrs.epsg(3857))
axBR.imshow(bottomRight, transform=ccrs.PlateCarree(), origin='upper', cmap='viridis')
axBR.axis('off')

A: I applied Global ccrs and set the min-max for cmap along with extent.
globe_w = ccrs.Globe(datum="WGS84",ellipse="WGS84")
ax1 = fig.add_subplot(1,1,1, projection=ccrs.PlateCarree(globe=globe_w))
ax1.imshow(data1, transform=ccrs.PlateCarree(globe=globe_w), origin='upper', cmap='viridis', vmin=minTemp, vmax=maxTemp, extent=(-180, 180, 90, -90))
ax1.axis('off')
ax1.set_aspect(2)


text:
Q: setting query string in volley is not working I've tried to send a GET request using my custom request class which inherits request. I've tried to set parameters through getParams() method. But when i send the request I'm getting a username or password invalid error. I have no idea why this is happening. But when i send request through url containing its parameters like http://myurl.com/method?user="username"&password="password" it works.Can somebody tell me why this is happening?
CustomRequest request=new CustomRequest(number,url,new MyListener(number),new ErrorListner(number)){

            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                Map<String, String> query=new HashMap<>();
                query.put("user",data.getString("user"));
                query.put("password",data.getString("password"));
                query.put("sender",data.getString("senderid"));
                query.put("SMSText",data.getString("message"));
                query.put("GSM",number);
                return  query;

            }
        };

A: Reading the javadocs you will see that getParams is only used by POST or PUT, not GET. You need to add the query parameters to the URL yourself.
/**
 * Returns a Map of parameters to be used for a POST or PUT request.  Can throw
 * {@link AuthFailureError} as authentication may be required to provide these values.
 *
 *
Note that you can directly override {@link #getBody()} for custom data.

 *
 * @throws AuthFailureError in the event of auth failure
 */
protected Map<String, String> getParams() throws AuthFailureError {
    return null;
}


text:
Q: In Salesforce Apex how do I serve up a binary file I have a VF page that is basically a view into our CMS system.  It logs in with a generic ID and with web services is able to get and display a list of files.  Now I would like to be able to click on a file and have it opened in a new window.  I have a CMS web service that returns a byte stream of the file.  How do I set an Apex Remote Action to return that stream to the browser?  And furthermore how do I open this in a new tab?
I'd like a remove action like:
public static HttpResponse sendRequest(String endpoint, String method)
{
    HttpRequest req = new HttpRequest();
    req.setMethod(method);
    req.setEndpoint(endpoint);

    HttpResponse resp;
    if (Test.isRunningTest())
    {
        resp = new HttpResponse();
        resp.setBody('');
    }
    else
    {
        Http http = new Http();
        resp = http.send(req);
    }

    return resp;
}

@RemoteAction
public static HttpResponse open(docid)
{
    return sendRequest(API_DOMAIN + '/ws/open/' + docid + '/', 'GET');
}

And then on the UI side:
MainBehavior.Open= function(docid) {
    Visualforce.remoting.Manager.invokeAction(
        '{!$RemoteAction.ResourceCenterController.open}',
                    docid,
        function(result, event)
        {
            if (event.status)
            {
                 return result;
            }
            else if (event.type === 'exception')
            {
                alert('Not able to open!\n\n' + event.message);
            }
            else
            {
                alert('Not able to open!');
            }
        }
    );

And later on with a click event:
window.open(MainBehavior.Open(docid), '_blank');

I know this code doesn't work as is, but this is my goal.  Any suggestions on how to go about this?

A: if (event.status) {
 // window.open(result,'_blank'); //file in new window
 window.location.href =result;    //file in same window
}

This line will open file. Avoid opening in new window. AdBlockers will block new window opened through JS in most of the browsers.


text:
Q: OrientDB embedded and distributed I should use OrientDB in embedded mode in a Java-Groovy application. At the same time, I have to distribute this java-groovy application in several machines.
The question is: is it possible to access the same database from all the machines? In other words: is it possible to have a distributed database in embedded mode in OrientDB?
Thank you

A: Yes, take a look at: https://github.com/orientechnologies/orientdb/wiki/Embedded-Server. With the distributed configuration multiple embedded servers can be synchronized across the network.

A: I know I am answering this question a little late, but I hope this will help someone else googling for the same issue:
I am able to run OrientDB in Embedded mode with Clustering (Distribution) on. Below is the complete code
System.setProperty("ORIENTDB_HOME","/your path to OrientDB/orientdb-community-1.7-rc1");

  OServer server = OServerMain.create();
  server.startup(
   "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>\n" +
   "<orient-server>\n" +
   "    <handlers>\n" +
   "        <!-- CLUSTER PLUGIN, TO TURN ON SET THE 'ENABLED' PARAMETER TO 'true' -->\n" +
   "        <handler class=\"com.orientechnologies.orient.server.hazelcast.OHazelcastPlugin\">\n" +
   "            <parameters>\n" +
   "                <!-- <parameter name=\"nodeName\" value=\"europe1\" /> -->\n" +
   "                <parameter name=\"enabled\" value=\"true\" />\n" +
   "                <parameter name=\"configuration.db.default\" value=\"${ORIENTDB_HOME}/config/default-distributed-db-config.json\" />\n" +
   "                <parameter name=\"configuration.hazelcast\" value=\"${ORIENTDB_HOME}/config/hazelcast.xml\" />\n" +
   "                <parameter name=\"conflict.resolver.impl\" value=\"com.orientechnologies.orient.server.distributed.conflict.ODefaultReplicationConflictResolver\" />\n" +
   "                \n" +
   "                <!-- PARTITIONING STRATEGIES -->\n" +
   "                <parameter name=\"sharding.strategy.round-robin\" value=\"com.orientechnologies.orient.server.hazelcast.sharding.strategy.ORoundRobinPartitioninStrategy\" />\n" +
   "            </parameters>\n" +
   "        </handler>\n" +
   "        <!-- AUTOMATIC BACKUP, TO TURN ON SET THE 'ENABLED' PARAMETER TO 'true' -->\n" +
   "        <handler class=\"com.orientechnologies.orient.server.handler.OAutomaticBackup\">\n" +
   "            <parameters>\n" +
   "                <parameter name=\"enabled\" value=\"false\" />\n" +
   "                <parameter name=\"delay\" value=\"4h\" />\n" +
   "                <parameter name=\"target.directory\" value=\"backup\" />\n" +
   "                <parameter name=\"target.fileName\" value=\"${DBNAME}-${DATE:yyyyMMddHHmmss}.json\" /><!-- ${DBNAME} AND ${DATE:} VARIABLES ARE SUPPORTED -->\n" +
   "                <parameter name=\"db.include\" value=\"\" /><!-- DEFAULT: NO ONE, THAT MEANS ALL DATABASES. USE COMMA TO SEPARATE MULTIPLE DATABASE NAMES -->\n" +
   "                <parameter name=\"db.exclude\" value=\"\" /><!-- USE COMMA TO SEPARATE MULTIPLE DATABASE NAMES -->\n" +
   "            </parameters>\n" +
   "        </handler>\n" +
   "        <!-- MAIL, TO TURN ON SET THE 'ENABLED' PARAMETER TO 'true' -->\n" +
   "        <handler class=\"com.orientechnologies.orient.server.plugin.mail.OMailPlugin\">\n" +
   "            <parameters>\n" +
   "                <parameter name=\"enabled\" value=\"true\" />\n" +
   "                <!-- CREATE MULTIPLE PROFILES WITH profile.<name>... -->\n" +
   "                <parameter name=\"profile.default.mail.smtp.host\" value=\"localhost\" />\n" +
   "                <parameter name=\"profile.default.mail.smtp.port\" value=\"25\" />\n" +
   "                <parameter name=\"profile.default.mail.smtp.auth\" value=\"true\" />\n" +
   "                <parameter name=\"profile.default.mail.smtp.starttls.enable\" value=\"true\" />\n" +
   "                <parameter name=\"profile.default.mail.smtp.user\" value=\"\" />\n" +
   "                <parameter name=\"profile.default.mail.smtp.password\" value=\"\" />\n" +
   "                <parameter name=\"profile.default.mail.date.format\" value=\"yyyy-MM-dd HH:mm:ss\" />\n" +
   "            </parameters>\n" +
   "        </handler>\n" +
   "        <!-- SERVER SIDE SCRIPT INTERPRETER. WARNING! THIS CAN BE A SECURITY HOLE: ENABLE IT ONLY IF CLIENTS ARE TRUCT, TO TURN ON SET THE 'ENABLED' PARAMETER \n" +
   "            TO 'true' -->\n" +
   "        <handler class=\"com.orientechnologies.orient.server.handler.OServerSideScriptInterpreter\">\n" +
   "            <parameters>\n" +
   "                <parameter name=\"enabled\" value=\"false\" />\n" +
   "            </parameters>\n" +
   "        </handler>\n" +
   "    </handlers>\n" +
   "    <network>\n" +
   "        <protocols>\n" +
   "            <!-- Default registered protocol. It reads commands using the HTTP protocol and write data locally -->\n" +
   "            <protocol name=\"binary\" implementation=\"com.orientechnologies.orient.server.network.protocol.binary.ONetworkProtocolBinary\" />\n" +
   "            <protocol name=\"http\" implementation=\"com.orientechnologies.orient.server.network.protocol.http.ONetworkProtocolHttpDb\" />\n" +
   "        </protocols>\n" +
   "        <listeners>\n" +
   "            <listener protocol=\"binary\" ip-address=\"0.0.0.0\" port-range=\"2424-2430\" />\n" +
   "            <listener protocol=\"http\" ip-address=\"0.0.0.0\" port-range=\"2480-2490\">\n" +
   "                <parameters>\n" +
   "                    <!-- Connection's custom parameters. If not specified the global configuration will be taken -->\n" +
   "                    <parameter name=\"network.http.charset\" value=\"utf-8\" />\n" +
   "                    <!-- Define additional HTTP headers to always send as response -->\n" +
   "                    <!-- Allow cross-site scripting -->\n" +
   "                    <!-- parameter name=\"network.http.additionalResponseHeaders\" value=\"Access-Control-Allow-Origin: *;Access-Control-Allow-Credentials: true\" /-->\n" +
   "                </parameters>\n" +
   "                <commands>\n" +
   "                    <command\n" +
   "                        pattern=\"GET|www GET|studio/ GET| GET|*.htm GET|*.html GET|*.xml GET|*.jpeg GET|*.jpg GET|*.png GET|*.gif GET|*.js GET|*.css GET|*.swf GET|*.ico GET|*.txt GET|*.otf GET|*.pjs GET|*.svg\"\n" +
   "                        implementation=\"com.orientechnologies.orient.server.network.protocol.http.command.get.OServerCommandGetStaticContent\">\n" +
   "                        <parameters>\n" +
   "                            <!-- Don't cache html resources in development mode -->\n" +
   "                            <entry name=\"http.cache:*.htm *.html\" value=\"Cache-Control: no-cache, no-store, max-age=0, must-revalidate\\r\\nPragma: no-cache\" />\n" +
   "                            <!-- Default caching -->\n" +
   "                            <entry name=\"http.cache:default\" value=\"Cache-Control: max-age=120\" />\n" +
   "                        </parameters>\n" +
   "                    </command>\n" +
   "                </commands>\n" +
   "            </listener>\n" +
   "        </listeners>\n" +
   "        <cluster>\n" +
   "        </cluster>\n" +
   "    </network>\n" +
   "    <storages>\n" +
   "    </storages>\n" +
   "    <users>\n" +
   "    </users>\n" +
   "    <properties>\n" +
   "        <!-- Uses the Hazelcast's distributed cache as 2nd level cache -->\n" +
   "        <!-- <entry name=\"cache.level2.impl\" value=\"com.orientechnologies.orient.server.hazelcast.OHazelcastCache\" /> -->\n" +
   "\n" +
   "        <!-- DATABASE POOL: size min/max -->\n" +
   "        <entry name=\"db.pool.min\" value=\"1\" />\n" +
   "        <entry name=\"db.pool.max\" value=\"20\" />\n" +
   "        \n" +
   "        <!-- LEVEL1 AND 2 CACHE: enable/disable and set the size as number of entries -->\n" +
   "        <entry name=\"cache.level1.enabled\" value=\"false\" />\n" +
   "        <entry name=\"cache.level1.size\" value=\"1000\" />\n" +
   "        <entry name=\"cache.level2.enabled\" value=\"true\" />\n" +
   "        <entry name=\"cache.level2.size\" value=\"1000\" />\n" +
   "        \n" +
   "        <!-- PROFILER: configures the profiler as <seconds-for-snapshot>,<archive-snapshot-size>,<summary-size>  -->\n" +
   "        <entry name=\"profiler.enabled\" value=\"true\" />\n" +
   "        <!-- <entry name=\"profiler.config\" value=\"30,10,10\" />  -->     \n" +
   "\n" +
   "        <!-- LOG: enable/Disable logging. Levels are: finer, fine, finest, info, warning -->\n" +
   "        <entry name=\"log.console.level\" value=\"info\" />\n" +
   "        <entry name=\"log.file.level\" value=\"fine\" />\n" +
   "    </properties>\n" +
   "</orient-server>");
  server.activate();

We need to add the following jars
concurrentlinkedhashmap-lru-1.3.1.jar
hazelcast-3.1.jar
javassist-3.16.1-GA.jar
orient-commons-1.7-rc1.jar
orientdb-client-1.7-rc1.jar
orientdb-core-1.7-rc1.jar
orientdb-distributed-1.7-rc1.jar
orientdb-enterprise-1.7-rc1.jar
orientdb-object-1.7-rc1.jar
orientdb-server-1.7-rc1.jar

A: I created a small example project which demonstrates how to setup an embedded orientdb cluster.
The example consists of two tests which are located in two different projects. Each test starts a new orientdb server. One of the tests writes data and the second test reads the data which has been written.
I'm still trying to figure out some quirks but so far it is able to illustrate the basic principal.
https://github.com/Jotschi/orientdb-cluster-test


text:
Q: How can I create Haskell-like functional dependencies Background: I'm using the nalgebra library and I want to create a structure that represents a multivariate normal distribution. The number and row type is uniquely determined by a square matrix type, so I want to write something like this:
#[allow(non_snake_case)]
pub struct Multivar<M: SquareMat<N, V>> {
    μ: V,
    Σ: M,
}

If I was using Haskell, I would specify a functional dependency between M and N and V. What's the best way to do this in Rust?

A: While Haskell has two things to express such relationship between types, fundeps and associated types, Rust has only the latter. Traits in Rust can contain type members which are assigned with concrete values at the implementation site, and the compiler considers them uniquely identified by the combination of type parameters of the trait (including Self). So you need to define SquareMat trait like this:
trait SquareMat {
    type N;
    type V;
    ...
}

impl SquareMat for SomeStruct {
    type N = Four;
    type V = f64;
    ...
}

And then this trait can be used like this:
#[allow(non_snake_case)]
pub struct Multivar<M: SquareMat> {
    μ: M::V,
    Σ: M,
}

If you don't control SquareMat, well, then you're out of luck - you cannot define a functional dependency at the trait usage site, only at the trait declaration site, just like in Haskell.


text:
Q: convert associate array to XML in php How do i convert an associate array to an XML string? I found this but get the error 'Call to a member function addChild() on a non-object' when running the line
$node = $xml->addChild($key);

A: Use the PHP Document Object Model:
$xml = new DOMDocument('1.0', 'utf-8');
$root = $xml->createElement('top');
$xml->appendChild($root);
foreach ($arr as $k => $v) {
  $node = $xml->createelement($k);
  $text = $xml->createTextNode($v);
  $node->appendChild($text);
  $root->appendChild($node);
}
echo $xml->saveXml();

A: Did you initialize the $xml object? That's probably your problem.

A: Its pretty similar to how you would do something like this:
while($row = mysql_fetch_assoc($result))

You can't use $result as an array, but you can foreach or while through the different entries.

A: PEAR's XML_Serialize is pretty good if you want a easy solution.  Doing the DOM manually is arguably faster.


text:
Q: php integer variable pass in mysql query? Is it possible to pass  php integer variable in mysql query?
like $g = 44 ;
$sql="
    SELECT
        idtransactiondetails,
        idtransactionmaster,
        T.idacledger,
        acledgername,
        transactionamount,
        chequeno
    from transactiondetails T,
         acledger L
    where
        T.idacledger=L.idacledger
        and idtransactionmaster=int()$g";

but in case $g its not working .

A: $sql="SELECT idtransactiondetails,idtransactionmaster,T.idacledger,acledgername,transactionamount,chequeno from transactiondetails T,acledger L where T.idacledger=L.idacledger and idtransactionmaster="`.$g;`

A: try this
$sql="SELECT idtransactiondetails,idtransactionmaster,T.idacledger,acledgername,transactionamount,chequeno from transactiondetails T,acledger L where T.idacledger=L.idacledger and idtransactionmaster=$g";

A: Concatenate the string:
    $sql = "SELECT idtransactiondetails, idtransactionmaster, T.idacledger, acledgername, transactionamount, chequeno
FROM transactiondetails T, acledger L
WHERE T.idacledger = L.idacledger
AND idtransactionmaster=" . (int) $g. ";";

A: not need to use int in Query,
$sql="SELECT idtransactiondetails,idtransactionmaster,T.idacledger,acledgername,transactionamount,chequeno from transactiondetails T,acledger L where T.idacledger=L.idacledger and idtransactionmaster= $g ";

A: Confirms your variable contains integer value if you are trying to avoid sql injections & all
$g = "50'a+_)(*&^%$#@!";
$integer = intval($g); // 50
$sql = "SELECT idtransactiondetails,idtransactionmaster,T.idacledger,acledgername,transactionamount,chequeno from transactiondetails T,acledger L where T.idacledger=L.idacledger and idtransactionmaster = '$integer'";


text:
Q: An error occurred while updating the entries. See the inner exception for details. - Asps.net MVC 3 i am having this exception coming everytime i run and try to create the post..
i am having a simple User,Post,Comment,Tag entity. which has relationship association defined by me. when i am checking the innerException it says "Cannot insert the value NULL into column 'CommentID', table " ... and its pointing to my context where i have a relationship defined..please check my relationship and help me finding this where i have delclared that null is not allowed in Comment ID...

*

*1 user can have many posts, can create many tags, can have many
comments

*1 post can have 1 user, many comments, and can have many tags

*1 tag can have 1 user, many post

*1 comment can have 1 user, 1 post

RelationShip...
modelBuilder.Entity<User>().HasMany(p => p.Posts).WithRequired(u => u.Users).HasForeignKey(P=>P.UserID);
            modelBuilder.Entity<User>().HasMany(t => t.Tags).WithRequired(u => u.Users);
            modelBuilder.Entity<User>().HasMany(c => c.Comments).WithRequired(u => u.Users);

            modelBuilder.Entity<Post>().HasRequired(u => u.Users).WithMany(p=>p.Posts);
            modelBuilder.Entity<Post>().HasMany(t => t.Tags).WithMany(p => p.Posts);
            modelBuilder.Entity<Post>().HasOptional(c => c.Comments);

            modelBuilder.Entity<Comment>().HasRequired(u => u.Users);
            modelBuilder.Entity<Comment>().HasRequired(p => p.Posts);

            modelBuilder.Entity<Tag>().HasRequired(u => u.Users);
            modelBuilder.Entity<Tag>().HasMany(p => p.Posts).WithMany(t => t.Tags);

Model - User
[ScaffoldColumn(true)]
        [Key]
        public int UserID { get; set; }

        [StringLength(15)]
        [DisplayName("First Name")]
        [Required(ErrorMessage="First Name is Required")]
        public string FirstName { get; set; }

        [StringLength(15)]
        [DisplayName("Last Name")]
        [Required(ErrorMessage = "Last Name is Required")]
        public string LastName { get; set; }

        [DataType(DataType.EmailAddress,ErrorMessage="please enter valid email")]
        [DisplayName("Email Address")]
        [Required(ErrorMessage = "Email is Required")]
        [Remote("CheckUniqueEmail","User",ErrorMessage="An account with this email address already exists.")]
        public string Email { get; set; }

        [DataType(DataType.Password)]
        [Required(ErrorMessage = "Password is Required")]
        public string Password { get; set; }

        [DataType(DataType.Date)]
        [ScaffoldColumn(true)]
        public DateTime JoiningDate { get; set; }

        [DataType(DataType.Date)]
        [ScaffoldColumn(true)]
        public DateTime? LastActivityDate { get; set; }

        public virtual ICollection<Post> Posts { get; set; }

        public virtual ICollection<Comment> Comments { get; set; }

        public virtual ICollection<Tag> Tags { get; set; }

Model - Post
[Key]
        [ScaffoldColumn(true)]
        public int PostID { get; set; }

        [Required(ErrorMessage="Required")]
        [StringLength(250)]
        public string Title { get; set; }

        [Required(ErrorMessage="Required")]
        [DataType(DataType.MultilineText)]
        public string Body { get; set; }

        [DataType(DataType.Date)]
        public DateTime DateCreated { get; set; }

        [DataType(DataType.Date)]
        public DateTime DateModified { get; set; }

        [ScaffoldColumn(false)]
        public int UserID { get; set; }

        [ScaffoldColumn(false)]
        public int? CommentID { get; set; }

        [ScaffoldColumn(false)]
        public int? TagID { get; set; }

        public virtual ICollection<Comment> Comments { get; set; }

        public virtual User Users { get; set; }

        public virtual ICollection<Tag> Tags { get; set; }

Model = Comment
[Key]
        [ScaffoldColumn(true)]
        public int CommentID { get; set; }

        [DisplayName("Your Comment")]
        public string Body { get; set; }

        [DataType(DataType.Date)]
        [ScaffoldColumn(true)]
        public DateTime DateCreated { get; set; }

        [ScaffoldColumn(true)]
        public int PostID { get; set; }

        [ScaffoldColumn(true)]
        public int UserID { get; set; }

        public User User { get; set; }

        public Post Posts { get; set; }

model = Tag
[Key]
        [ScaffoldColumn(true)]
        public int TagID { get; set; }

        [StringLength(15)]
        public string Name { get; set; }

        [ScaffoldColumn(true)]
        public int UserID { get; set; }

        public User Users { get; set; }

        public ICollection<Post> Posts { get; set; }

A: You need to post your Models here to go in to more details.But as I can see there are several issues with your model configuration.
As you said,
1 comment can have 1 user, 1 post

so what's the point of  keeping colllection of users in Comment
modelBuilder.Entity<Comment>().HasRequired(u => u.Users);

it shoud be like this
 modelBuilder.Entity<Comment>().HasRequired(u => u.User);

and this is also applied for Post as well.


text:
Q: Prevent incompatible function casts in C? Sometimes it is useful to cast function callbacks without.
For example, we may have a function to duplicate some data:
struct MyStruct *my_dupe_fn(const struct MyStruct *s)
But pass it as a generic callback:
typedef void *(*MyGenericCopyCallback)(void *key);
Eg: ensure_key_in_set(my_set, my_key, (MyGenericCopyCallback)my_dupe_fn);
Since the difference between const struct MyStruct * and void * is not going to cause problems in this case, it won't cause any bugs (at least in the function call its self).
However, if later on an arguments added to my_dupe_fn, this could cause a bug which wouldn't give a compiler warning.

Is there a way to cast a function, but still show warnings if the arguments or return values are different sizes?

Obligatory disclaimer: of course C isn't *safe*, but ways to prevent potential bugs in a widely used language are still useful.

A: You say "won't cause any bugs", however it causes undefined behaviour to call a function through a function pointer with incompatible return types or parameter types, even in your example code.
If you want to rely on undefined behaviour then that's your risk to take. Relying on UB has a tendency to cause bugs sooner or later. A better idea would be to re-design the callback interface to not rely on undefined behaviour. For example, only use functions of the correct type as the callback function.
In your example this might be:
typedef void *MyCallback(void *key);    // style: avoid pointer typedefs

struct MyStruct *my_dupe_fn(const struct MyStruct *s)
{ ... }

void *my_dupe_fn_callback(void *s)
{
     return my_dupe_fn(s);
}

void generic_algorithm(MyCallback *callback)
{
    // ....
    ensure_key_in_set(my_set, my_key, callback);
    // ....
}

// elsewhere
generic_algorithm(my_dupe_fn_callback);

Note the lack of casts. Managing a style policy of not using any function casts is simpler than a policy of allowing certain types.

A: If you are using gcc and are not afraid of using helpful extensions, you might have a look at plan9-extensions. In combination with anonymous struct fields (standard since C99) as the first field, they allow to build a type-hierarchy with static functions, etc. Avoids tons of casts in my code and makes it much more readable.
Not sure, but according to the gcc documentation, the MS-compiler supports some (all?) these features, too. No warranty for that, however.

A: That later error is coming from two pieces of code that say the same thing getting out of sync -- the first where you define the type of my_dupe_fn, and the second where you cast the generic callback pointer back to its original type.
This is where DRY (do not repeat yourself) comes in.  The whole point is to only say something once, so that you can't later come back and change only one instance.
In this case, you'd want to typedef the type of a pointer to my_dupe_fn, preferably very close to where you declare the function itself, to help ensure that the typedef always changes along with the function signiture itself.
The compiler is never going to catch this for you as long as it thinks that it is just dealing with a generic void pointer.

A: Unfortunately you typically have to forgo some of this compile-time safety if you're using C. You might get a warning at best, but if you have a design that is uniformly casting function pointers this way, you're likely to ignore or outright disable them. Instead you want to place your emphasis on achieving safe coding standards. What you can't guarantee by force, you can encourage strongly by policy.
I would suggest, if you can afford it, to start by casting arguments and return values rather than whole function pointers. A flexible representation is like so:
typedef void* GenericFunction(int argc, void** args);

This emulates the ability to have variadic callbacks, and you can uniformly do runtime safety checks in debug builds, e.g., to make sure that the number of arguments matches the assumptions:
void* MyCallback(int argc, void** args)
{
    assert(argc == 2);
    ...
    return 0;
}

If you need more safety than this for the individual arguments being passed and can afford a typically-small cost of an extra pointer per argument with a slightly bulky structured solution, you can do something like this:
struct Variant
{
    void* ptr;
    const char* type_name;
};

struct Variant to_variant(void* ptr, const char* type_name)
{
    struct Variant new_var;
    new_var.ptr = ptr;
    new_var.type_name = type_name;
    return new_var;
}

void* from_variant(struct Variant* var, const char* type_name)
{
     assert(strcmp(var->type_name, type_name) == 0 && "Type mismatch!");
     return var->ptr;
}

void* pop_variant(struct Variant** args, const char* type_name)
{
     struct Variant* var = *args;
     assert(var->ptr && "Trying to pop off the end of the argument stack!");
     assert(strcmp(var->type_name, type_name) == 0 && "Type mismatch!");
     ++*args;
     return var->ptr;
}

With macros like so:
#define TO_VARIANT(val, type) to_variant(&val, #type);
#define FROM_VARIANT(var, type) *(type*)from_variant(&var, #type);
#define POP_VARIANT(args, type) *(type*)pop_variant(&args, #type);

typedef struct Variant* GenericFunction(struct Variant* args);

Example callback:
struct Variant* MyCallback(struct Variant* args)
{
    // `args` is null-terminated.
    int arg1 = POP_VARIANT(args, int);
    float arg2 = POP_VARIANT(args, float);
    ...
    return 0;
}

A side benefit is what you can see in your debugger when you trace into MyCallback through those type_name fields.
This kind of thing can be useful if your codebase supports callbacks into dynamically-typed scripting languages, since scripting languages should not be doing type casts in their code (typically they're meant to be a bit on the safer side). The type names can then be used to automatically convert the arguments into the scripting language's native types dynamically using those type_name fields.


text:
Q: Run function after modal dismissed in Swift I want to call a function on a view controller after a modal has been dismissed. I have spent hours trying to get this to work and all of the responses I have found have not worked. I have followed instructions by others and set up a protocol but this still isn't working.
MainController:
class ViewController: UIViewController, UIPopoverPresentationControllerDelegate, loadStoreDelegate{

Then to trigger the modal I use
func displaySelectStorePopup(){
        if let viewController = self.storyboard?.instantiateViewControllerWithIdentifier("SelectStoreView"){
            let selectStoreController = viewController
            selectStoreController.modalPresentationStyle = .Popover
            if let sctrl = selectStoreController.popoverPresentationController{
                sctrl.delegate = self
                sctrl.sourceView = self.view
                sctrl.sourceRect = CGRectMake(CGRectGetMidX(self.view.bounds), CGRectGetMidY(self.view.bounds),0,0)

                sctrl.permittedArrowDirections = UIPopoverArrowDirection()
                delay(0.1){
                    sctrl.passthroughViews = nil
                }

                selectStoreController.modalInPopover = true

                selectStoreController.preferredContentSize = CGSizeMake(400, 400)

                self.presentViewController(selectStoreController, animated: true, completion: nil)
            }
        }
    }

Then the function id like to use
func loadStore() {
        print(2)
        //let vc : AnyObject! = self.storyboard!.instantiateViewControllerWithIdentifier("DashboardView")
        //self.showViewController(vc as! UIViewController, sender: vc)
    }

ModalViewController:
The protocol
protocol loadStoreDelegate{
    func loadStore()
}

class SelectStoreViewController: UIViewController, UITableViewDataSource, UITableViewDelegate{...

var delegate: loadStoreDelegate?

Then call the function on tableview click
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath){
        self.delegate?.loadStore()
        if(tableView == selectStoreTable){
            currentStore = userStores[indexPath.row]
            self.dismissViewControllerAnimated(false, completion: nil)
        }
    }

A: Your SelectStoreViewController class has a delegate instance property. But you are never setting this property to anything. So it is nil when you self.delegate?.loadStore(). So naturally nothing happens.
I think you want something like this:
func displaySelectStorePopup(){
    if let viewController = self.storyboard?.instantiateViewControllerWithIdentifier("SelectStoreView") as? SelectStoreViewController {
        let selectStoreController = viewController
        selectStoreController.delegate = self // *
        // ... and so on ...

A: After a lot of reading it seems that using the popover is what is preventing my desired results from the delegate. I ended up solving this by creating a class for the workstation that holds a reference to the current view, then a function that runs the action I needed.
Class:
class Workstation{
    var currentView: UIViewController? = nil
    var currentStore : Store? = nil

    func loadInStore(store: Store){
        currentStore = store
        if let view = currentView{
            let vc : AnyObject! = view.storyboard!.instantiateViewControllerWithIdentifier("DashboardView")
            view.showViewController(vc as! UIViewController, sender: vc)
        }
    }

    class var workstationInstance: Workstation{
        struct Static {
            static let instance = Workstation()
        }
        return Static.instance
    }
}

SecondController:
override func viewDidDisappear(animated: Bool) {
        if let store = selectedStore{
            Workstation.workstationInstance.loadInStore(store)
        }
    }

In my main controller I am simply loading in the popup and setting the current view
override func viewDidAppear(animated: Bool) {
     Workstation.workstationInstance.currentView = self
}

func displaySelectStorePopup(){
        if let viewController = self.storyboard?.instantiateViewControllerWithIdentifier("SelectStoreView"){
            let selectStoreController = viewController
            selectStoreController.modalPresentationStyle = .Popover
            if let sctrl = selectStoreController.popoverPresentationController{
                sctrl.sourceView = self.view
                sctrl.sourceRect = CGRectMake(CGRectGetMidX(self.view.bounds), CGRectGetMidY(self.view.bounds),0,0)

                sctrl.permittedArrowDirections = UIPopoverArrowDirection()
                delay(0.1){
                    sctrl.passthroughViews = nil
                }

                selectStoreController.modalInPopover = true

                selectStoreController.preferredContentSize = CGSizeMake(400, 400)

                self.presentViewController(selectStoreController, animated: true, completion: nil)
            }
        }
    }


text:
Q: Function like rand(), to generate random number in CUDA _global_ kernel? I am trying to create a Random generator for initialization of a vector.
The kernel function that I wrote in CUDA is as below:
__global__ void randgenvec( int *a, int t) {
    int tid = blockIdx.x; // handle the data at this index
    if (tid < t){
        a[tid] = rand() % 100; //****ang replacement for rand() here expect cuRAND?*****
    }
}

I got to know that I cant use rand() function inside a kernel function. Is there any other function which I can replace with rand().
I know we have cuRAND library which we can use. But want to make my code more portable and light and cuRAND needs linker for execution, which I don't want to use.
The objective of my randomisation is to generate any int between 1 to 100.

By linker, I mean :: linker flag -lcurand

Any other suggestion much appreciated.

A: attempt this
 unsigned short lfsr = 0xACE1u;
  unsigned bit;

  unsigned randomize()
  {
    bit  = ((lfsr >> 0) ^ (lfsr >> 2) ^ (lfsr >> 3) ^ (lfsr >> 5) ) & 1;
    return lfsr =  (lfsr >> 1) | (bit << 15);
  }


text:
Q: My loop doesnt finish, how to close it when the file reaches the end of file //entrada is the fstream I opened
if (entrada.is_open())
{
    while (!entrada.eof())
    {
        char palabra[1024];
        entrada >> palabra;
        if(entrada.eof())break;
        cout << palabra << endl;

    }

entrada.close();
}

the program shows me the text and doesnt finish the loop of the while, doesnt reach the .eof

A: Change the loop to:
char palabra[1024];
while (entrada >> palabra )
{
    cout << palabra << endl;
}

See Why is iostream::eof inside a loop condition considered wrong?


text:
Q: Modbus and the Sunny Boy I am using libmodbus to connect to the a SunnyBoy 2.5 inverter. I make the connection as follows:
#include <modbus/modbus.h>
#include <stdio.h>
#include <errno.h>

int main()
{
    modbus_t *mb;
    uint16_t tab_reg[32];
    int rc;
    int socket;

    mb = modbus_new_tcp("192.168.100.1", 502);
    if (mb == NULL)
    {
        fprintf(stderr, "Unable to allocate libmodbus context\n.");
        return -1;
    }

    if (modbus_connect(mb) == -1)
    {
        fprintf(stderr, "Connection failed: %s\n",
                modbus_strerror(errno));
        modbus_free(mb);
        return -1;
    }
    else
    {
        socket = modbus_tcp_listen(mb, 1);
        if (socket == -1)
        {
            fprintf(stderr, "Socket problem: %s\n", modbus_strerror(errno));
        }
        modbus_tcp_accept(mb, &socket);
        printf("Connection successful.\n");
    }
}

When I attempt to listen on the socket (modbus_tcp_listen), it gives me a "permission denied" error. How does one gain permission to the SunnyBoy to talk Modbus to it / how do you implement that in the code?

A: You're getting this message because modbus uses port 502. In Unix port numbers below 1024 require root access, so try using
sudo bash

To get a root shell and give it a try.
You'd also be better off using a scripting language that has a modbus library. This will let you produce fast prototypes with your Sunny Boy.


text:
Q: show tray in taskbar windows 10 electronjs I'm using system tray of electron but when I start my app the tray hide in the dropdow of the taskbar like this image :
(icon with S)

I want the tray apear like this :

A: Windows hides icons in the notification area (its not called "the tray") because in the past (Windows 95 through Windows Vista) too many programs arrogantly thought they were important enough that the user should always see them there - which leads to noisy and cluttered examples like this:

To prevent this from happening and degrading the user-experience, since Windows 7 programs cannot (feasibly) promote themselves out of the "More icons..." window.
What you should do instead is give your users instructions on how they can tell Windows to keep an icon visible (Settings > Personalization > Taskbar > "Select which icons appear on the taskbar") themselves. But you cannot do it yourself in program code: there is no (public and documented) API for controlling this for the reasons I described above.

A: Try api/tray
const electron = require("electron")
const app = electron.app
function createTray() {
  const tray = new electron.Tray( __dirname + 'Myfavicon.ico')
  const contextMenu = electron.Menu.buildFromTemplate([
    { label: 'Item1', type: 'radio' },
    { label: 'Item2', type: 'radio' },
    { label: 'Item3', type: 'radio', checked: true },
    { label: 'Item4', type: 'radio' }
  ])
  tray.setToolTip('This is my application.')
  tray.setContextMenu(contextMenu)
}

app.on("ready", createTray)


text:
Q: Vuejs 2 + form validation Since vue-validator https://github.com/vuejs/vue-validator is being ready for Vuejs 2, what is the best way to implement frontend validation?
UPDATE
I've found this awesome plugin
Vee Validate

A: In my opinion, a good way to implement front end validation for VueJS is to use vuelidate.
It's very simple to use and powerful. It offers model-base validation, it means that it's what you define in data that is validated, so it's totally decoupled from the templates. It comes with common built-in validators for email , min and max length or required. And many others.

A: Since it's all ultimately Javascript, you could also use some of the existing Javascript validation libraries like Parsely.js or Validate.js to hook this up. One thing that's nice about the Validate.js library is that it's format could easily be stored in the global store if you're using Vuex:
var constraints = {
  creditCardNumber: {
    presence: true,
    format: {
      pattern: /^(34|37|4|5[1-5]).*$/,
      message: function(value, attribute, validatorOptions, attributes, globalOptions) {
        return validate.format("^%{num} is not a valid credit card number", {
          num: value
        });
      }
    },
    length: function(value, attributes, attributeName, options, constraints) {
      if (value) {
        // Amex
        if ((/^(34|37).*$/).test(value)) return {is: 15};
        // Visa, Mastercard
        if ((/^(4|5[1-5]).*$/).test(value)) return {is: 16};
      }
      // Unknown card, don't validate length
      return false;
    }
  },
  creditCardZip: function(value, attributes, attributeName, options, constraints) {
    if (!(/^(34|37).*$/).test(attributes.creditCardNumber)) return null;
    return {
      presence: {message: "is required when using AMEX"},
      length: {is: 5}
    };
  }
};

Then used as such:
validate({creditCardNumber: "4"}, constraints);
// => {"creditCardNumber": ["Credit card number is the wrong length (should be 16 characters)"]}

validate({creditCardNumber: "9999999999999999"}, constraints);
// => {"creditCardNumber": ["9999999999999999 is not a valid credit card number"]}

validate({creditCardNumber: "4242424242424242"}, constraints);
// => undefined

validate({creditCardNumber: "340000000000000"}, constraints);
// => {"creditCardZip": ["Credit card zip is required when using AMEX"]}

You could also hook those validate() functions to your component with something along the lines of @blur=validate(...)

A: Currently there are not many choices. Take a look at vue-awesome where you can find the most relevant libraries. There are 2 at the moment.

A: If you are using semantic-ui or its an option for you they have an amazing form validation plugin.
semantic-ui-form-validation
I've used it with Vuejs and it works great.

A: I found this validator simple, flexible and well documented. It cover most scenarios of validating forms in Vue Js.
I used Jquery validator plugin in the past. Compared to that, this simple-vue-validator really stands out in its flexibility and its ability to validate both hard-coded and dynamically generated forms.
https://github.com/semisleep/simple-vue-validator
I used it extensively for my SaaS project and so far it has gone on really well.


text:
Q: Postgresql 9.4 installation/Windows 8.1/ COMSPEC issue I've just downloaded postgreSQL 9.4 from http://www.enterprisedb.com/products-services-training/pgdownload#windows for windows x86-64.
And when I Launch the installer i got an error:
The environment variable COMSPEC does not seem to point to the cmd.exe or there is a trailing semi colon present.
I checked it with command
echo %COMSPEC%
C:\WINDOWS\system32\cmd.exe
no semi colon.

What I 've already tested:
Everything listed there :Problems Installing PostgreSQL 9.2 and all links from this page.
Thx for help,
Info : Windows 8.1 64bits, user: as admin.

A: I too had the same problem a while ago, but I fixed it. In fact, it's quite easy.
Just open Advanced System Settings in Control Panel and create a new System Variable( mind it 'System Variable' instead of 'User Variable'
In the variable name, enter 'ComSpec' and then in the variable value , enter 'C:\Windows\system32\cmd.exe'.
That's all. Hope it works!

A: The problem came from the user folder name. It has a special character:&.
Changing the name make it work perfectly.
For those who encounter this issue, be advised that changing users folder name is not an easy task, and from my side, I reinstalled Windows and took care of the computer's name.

A: For me in addition to the above methods, I overcame this issue by following the steps below:

*

*Win+R and type REGEDIT

*Browse to HKEY_CURRENT_USER/Software/Microsoft/Command Processor

*Here right-click on Autorun and click Modify.

*Under value data change the value to 0.

*Solved!!!

A: Easy fix:

*

*Open Environment Variables, you can do this on Windows 7 by typing "environment variables" in the Search program and files bar when pressing start button at bottom left of desktop. And create a new System Variable( in the 'System Variable' instead of 'User Variable' section).

*In the variable name, enter 'ComSpec' and then in the variable value , enter 'C:\Windows\system32\cmd.exe'.
That's all. Hope it works!
Alternative fix:
If you got akready the ComSpec variable in the System Variable section, remove the ;at the end of it this should fix it.

A: I had the same problem, but other solutions did not work for me. I also changed the environment variable name and value. Later during exploring, I found that this error comes due to a virus in your system. I installed Rkill antivirus software that helped me to run my cmd and it works for me and I install PostgreSQL smoothly.

A: this is the solution %ComSpec%\System32\cmd.exe
%ComSpec%\System32\cmd.exeenter image description here

A: Create a environment variable named COMPSPEC all caps and add this in path C:\WINDOWS\system32\cmd.exe. It worked for me.

A: Open the CMD prompt as administrator and enter the command
fsutil behavior set disable8dot3 1
Restart the computer.
Worked for me on Windows 10.

A: I faced the same problem too, and I solved it by changing the 'Value' databox to 0. Here are the detailed steps, hope it will be helpful to you.

*

*Window + R => REGEDIT

*Locate and then click the registry subkey: HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\FileSystem.

*Right-click NtfsDisable8dot3NameCreation, and then click Modify.

*In the Value data box, type 1, and then click OK.


text:
Q: Android button animate I have these buttons here and i want them both to have some animation onclick.
To grow up a little bit and then return to normal.
Here are the buttons xml codes.
<ImageButton
        android:layout_width="165dp"
        android:layout_height="60dp"
        android:text="next"
        android:id="@+id/next"
        android:src="@drawable/next"
        android:background="@android:color/transparent"
        android:layout_alignParentBottom="true"
        android:layout_alignRight="@+id/linearLayout"
        android:layout_alignEnd="@+id/linearLayout" />

    <ImageButton
        android:layout_width="170dp"
        android:layout_height="60dp"
        android:text="confirm"
        android:src="@drawable/confirm"
        android:background="@android:color/transparent"
        android:id="@+id/confirm"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:layout_alignParentBottom="true"
         />

These buttons are on one activity_main.xml file.
Can someone help me showing me some stuff of what should i do to make it happen?
Thanks a lot for your time.

A: Use Animator can achieve the goal easily:
findViewById(R.id.next).setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Animator scale = ObjectAnimator.ofPropertyValuesHolder(v,
                    PropertyValuesHolder.ofFloat(View.SCALE_X, 1, 1.5f, 1),
                    PropertyValuesHolder.ofFloat(View.SCALE_Y, 1, 1.5f, 1)
                    );
            scale.setDuration(1000);
            scale.start();
        }
    });

A: In the button's onclick, we start the animation we want to use using the view.startAnimation() method. We first load the required animation using AnimationUtils.loadAnimation()
button.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View view) {
        view.startAnimation(AnimationUtils.loadAnimation(context, R.anim.button_click));
    }
}

Now create a file under the anim folder called button_click.xml or whatever you want to name it.

anim/button_click.xml

<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android">
    <scale
    android:fromXScale = "1"
    android:toXScale = "0.9"
    android:fromYScale = "1"
    android:toYScale = "0.9"
    android:pivotX="50%"
    android:pivotY="50%"
    android:duration = "50">
    </scale>
</set>


text:
Q: Create User from a different DB in SQL Server Is there any way I can create a user on a database from the master DB(or any other DB)
IF EXISTS (SELECT 1 FROM   j_test.sys.database_principals WHERE  name = N'test_user')
  DROP USER j_test.[test_user]; --doesnt't work.

A: You either need to change the context to that database or dynamically go there:
EXEC j_test..sp_executesql N'DROP USER test_user;';

A: Logins are done at the server level, I usually create them from the [master] database.  Just my convention.
Users are done at the database level.  You need to have your context set to that database.  The USE command allows you to switch between databases.
This snippet is from my blog that shows a hypothetical database [BSA] with a schema named [STAGE].
-- Which database to use.
USE [master]
GO

-- Delete existing login.
IF  EXISTS (SELECT * FROM sys.server_principals WHERE name = N'BSA_ADMIN')
DROP LOGIN [BSA_ADMIN]
GO

-- Add new login.
CREATE LOGIN [BSA_ADMIN] WITH PASSWORD=N'M0a2r0c9h11$', DEFAULT_DATABASE=[BSA]
GO

-- Which database to use.
USE [BSA]
GO

-- Delete existing user.
IF  EXISTS (SELECT * FROM sys.database_principals WHERE name = N'BSA_ADMIN')
DROP USER [BSA_ADMIN]
GO

-- Add new user.
CREATE USER [BSA_ADMIN] FOR LOGIN [BSA_ADMIN] WITH DEFAULT_SCHEMA=[STAGE]
GO


text:
Q: WPF Label content shows DependencyProperty.UnsetValue in design mode I have an WPF label and I have bound some data into a string using StringFormat from xaml:
<Label Grid.Row="0" Grid.Column="1" Style="{StaticResource MyLblResource}">
    <Label.Content>
        <TextBlock VerticalAlignment="Center">
            <TextBlock.Text>
                <MultiBinding StringFormat="{}({0}) {1}">
                    <Binding Path="MyDataModel.Id" />
                    <Binding Path="MyDataModel.Desc" />
                </MultiBinding>
            </TextBlock.Text>
        </TextBlock>
    </Label.Content>
</Label>

Above code works fine, no problems but in design time, in xaml view, in the TextBlock content it is shown:
{{DependecyProperty.UnsetValue}} {{DependencyProperty.UnsetValue}}

Why is this being shown instead of being shown as empty? Is there any way to show this as empty?

A: This should do the trick:
 public class StringFormatConverter : MarkupExtension, IMultiValueConverter
    {
        public string StringFormat { get; set; } = @"({0}) {1}";

        public string PlaceHolder { get; set; } = "Empty";

        public override object ProvideValue(IServiceProvider serviceProvider) => this;

        public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)
        {
            return string.Format(StringFormat, GetValues(values));
        }

        private IEnumerable<string> GetValues(object[] values)
        {
            foreach (var value in values)
                yield return value == DependencyProperty.UnsetValue || value == null ? PlaceHolder : value.ToString();
        }

        public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture)
        {
            return new[] { Binding.DoNothing, Binding.DoNothing };
        }
    }

Use it like this:
 <MultiBinding Converter="{converter:StringFormatConverter PlaceHolder=MyPlaceHolderText}">
   <Binding Path="MyDataModel.Id" />
   <Binding Path="MyDataModel.Desc" />
</MultiBinding>

Please be aware that you can only set static values in StringFormat and PlaceHolder - because they are no DependencyProperty.


text:
Q: Using IndexedDB asynchronously Loading data and store them in indexeddb database. Periodically I have the database crashes and lost access to it.
Give me, please, a solution how use indexeddb asynchronously!
Sample code that I'm use now:
var dataTotal = 0;
var threads = 6;

//openIndexeddbConnection();

function start(total){

dataTotal = total;
  for (var i = 0; i < threads; i++) {
    loadData(i);
  }
}

function loadData(dataNum){
  var dataNext = dataNum + threads;
  if(dataNext > dataTotal){
    //checkEnd();
    return;
  }

  $.ajax({
    url: baseUrl,
    data: {offset: dataNum},
    success: function (data) {
      successData(dataNext, data);
    },
    type: 'GET'
  });
}

function successData(dataNext, data){
  var dataArray = data.split(';');

  saveData(dataArray);

  loadData(dataNext);
}

function saveData(dataArray){

  putItem();
  function putItem(i) {
    var count = i || 0;
    if(dataArray.length <= i){
      return;
    }

    var transaction = Indexeddb.transaction([dataTableName], "readwrite");
    transaction.onsuccess = function (event) {
      //continue
      putItem(count);
    };
    var objectStore = transaction.objectStore(dataTableName);

    var request = objectStore.add({data: dataArray[count++]});
  }
}

A: I've been using idb - a simple library that wraps IndexedDB with promises. These make asynchronous DB actions much easier to use.
If you're targeting Chrome (or are using a transpiler that supports them) you can use async and await to simplify your code:
async function saveData(dataArray) {
    const db = await idb.open('YourDB', currentVersion, upgradeFunction);
    const tran = await db.transaction('StoreName', 'readwrite');
    const store = tran.objectStore('StoreName');

    // This will add the items sequentially
    for(let item of dataArray) {
        await store.add({data:item});
    }
}

A: You can use promises to load and save data asynchronously to indexedDB. Here are two example functions to load and save data to a simple objectstore in indexedDB.
Asynchronous loading from indexedDB:

function loadFromIndexedDB(storeName, id){
  return new Promise(
    function(resolve, reject) {
      var dbRequest = indexedDB.open(storeName);

      dbRequest.onerror = function(event) {
        reject(Error("Error text"));
      };

      dbRequest.onupgradeneeded = function(event) {
        // Objectstore does not exist. Nothing to load
        event.target.transaction.abort();
        reject(Error('Not found'));
      };

      dbRequest.onsuccess = function(event) {
        var database      = event.target.result;
        var transaction   = database.transaction([storeName]);
        var objectStore   = transaction.objectStore(storeName);
        var objectRequest = objectStore.get(id);

        objectRequest.onerror = function(event) {
          reject(Error('Error text'));
        };

        objectRequest.onsuccess = function(event) {
          if (objectRequest.result) resolve(objectRequest.result);
          else reject(Error('object not found'));
        };
      };
    }
  );
}

Asynchronous saving to indexedDB:

function saveToIndexedDB(storeName, object){
  return new Promise(
    function(resolve, reject) {
      if (object.id === undefined) reject(Error('object has no id.'));
      var dbRequest = indexedDB.open(storeName);

      dbRequest.onerror = function(event) {
        reject(Error("IndexedDB database error"));
      };

      dbRequest.onupgradeneeded = function(event) {
        var database    = event.target.result;
        var objectStore = database.createObjectStore(storeName, {keyPath: "id"});
      };

      dbRequest.onsuccess = function(event) {
        var database      = event.target.result;
        var transaction   = database.transaction([storeName], 'readwrite');
        var objectStore   = transaction.objectStore(storeName);
        var objectRequest = objectStore.put(object); // Overwrite if exists

        objectRequest.onerror = function(event) {
          reject(Error('Error text'));
        };

        objectRequest.onsuccess = function(event) {
          resolve('Data saved OK');
        };
      };
    }
  );
}

Example usage code

var data = {'id' : 1, 'name' : 'bla'};

saveToIndexedDB('objectstoreName', data).then(function (response) {
  alert('data saved');
}).catch(function (error) {
  alert(error.message);
});

// Load some data
var id = 1;
loadFromIndexedDB('objectstoreName', id ).then(function (reponse) {
  data = reponse;
  alert('data loaded OK');
}).catch(function (error) {
  alert(error.message);
});


text:
Q: How to achieve this structure I'm trying to create a word file with the following structure:
A. Heading 1
1.1 Heading 2
1.2 Heading 2
1.2.1 Heading 3

B. Heading 1
1.1 Heading 2
1.2 Heading 2
1.2.1 Heading 3

etc.
I've tried to modify the headings manually and set the numbering
and i've tried to set it via paragraph -> multilevel-list but neither of those two worked...
I can't really seem to get it right... :(
Can you please tell me how to achieve this?
Thanks in advance

A: The headings belongs to the basics of the MS Word knowledge:

*

*Click in the first Heading 1 heading in your document.

*On the Home tab, in the Paragraph group, click Multilevel List.

*Under List Library, click one of the styles that includes the word Heading or Chapter in gray text.

For example, click 1 Heading 1, 1.1 Heading 2, 1.1.1 Heading 3.
[EDITED]
To have A instead of 1. as Heading 1 just rename it:


text:
Q: Swift - Character is not a subtype of string myText = "word 1 / word 2"
var testVar = split(myText, { $0 == "/"}, maxSplit: Int.max, allowEmptySlices: false)

This code works but it takes empty space "word 1 " when I use testVar[0]
when I write empty spaces
var testVar = split(myText, { $0 == " / "}, maxSplit: Int.max, allowEmptySlices: false)

I get an error: 'Character' is not a subtype of 'String'
Anyone who knows how to fix that?

A: The split() function only works on Swift strings by comparing each element of the string as a Character. To use a string to split a string, use .componentsSeparatedByString:
var testVar = myText.componentsSeparatedByString(" / ")


text:
Q: AMD Raid 5 drive not accessible in windows I'm running RAID 5 using the onboard AMD RAID controller.
Until this afternoon I have successfully been running windows, but after a system freeze and reboot, Windows went to system repair. Diskpart reported no drives attached to the system.
Rebooting into the RAID utility, I can see the raid array and it is reported as "Functional".
Rebooting Windows 7 installation asks for a missing driver disk and it also does not display the raid drive

A: I rebooted into the BIOS and under the SATA configuration changed the OnChip SATA type from RAID to AHCI and rebooted. Windows of course started the system repair utility and I rebooted again. This time I changed the OnChip SATA type back to RAID, saved and rebooted again.
Windows successfully booted and all was right with the world again.


text:
Q: Can I control 2 Bootstrap Carousels with one set of controllers? I have two sliding carousels side by side and i want to control them with one set of controls. My main goal is to have one carousel with two carousels in it and change the direction/animation of one of them to make something cool. I have tried this is my curent code:

    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css" integrity="sha384-9aIt2nRpC12Uk9gS9baDl411NQApFmC26EwAOH8WgZl5MYYxFfc+NcPb1dKGj7Sk" crossorigin="anonymous">
    <link href="http://maxcdn.bootstrapcdn.com/font-awesome/4.1.0/css/font-awesome.min.css" rel="stylesheet">

                              Previous

                              Next

I have tried to changing hrefs to class but i failed miserably. Any suggestions?

A: Try using selective triggering adding the snippet as illustrated below:
$('.kampany .carousel-control-next,.kampany .carousel-control-prev').on('click', function (e) {
      var inst = $(this).data("slide");
      if(inst== "prev"){
      $("#carouselExampleControls").carousel("prev")}
      else{ $("#kampanyacontrol").carousel("next")}
    })

The full solution will be:

    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css" integrity="sha384-9aIt2nRpC12Uk9gS9baDl411NQApFmC26EwAOH8WgZl5MYYxFfc+NcPb1dKGj7Sk" crossorigin="anonymous">
    <link href="http://maxcdn.bootstrapcdn.com/font-awesome/4.1.0/css/font-awesome.min.css" rel="stylesheet">

                              Previous

                              Next


text:
Q: Using href="tel:XXXXX" in links for contact numbers on web pages Would it be recommended to use href="tel:XXXXXX" for contact telephone numbers on web pages?
I appreciate that this can benefit mobile users when they access your site but are there any potential pitfalls, such as spam calls?
Is there a best practice method that could be used that will benefit the user and website owner?
Thanks in advance for any advice.
Regards
Noel

A: I'm using this for over a year now on my homepage and didn't get any spam calls. It could irritate users with desktop-browsers if you display the link as any other link, though.

A: Instead of hyperlinking the telephone number itself, how about placing a small phone icon next to the number and hyperlinking it instead.


text:
Q: Unit Testing against Windows Form I am new to unit testing and am using Visual Studio and I have a public variable in the form called mm_x which is calculated in a function in the form (not in a class) and when I try to do a test I can't find a way to reference it from the UnitTest Method. It was easy to test other variables that are on classes but this particular one I can't find the best way to do it.
Should I:
Put all of the logic for the variable calculation in the form in a business class and then unit test the business class?
Keep the form logic in the form and somehow unit test against the form?
As a reference, here's the method IN the form which contains the variable I'm trying to test:
(poi_navegacion_individual and MR are 2 classes I use but I'm interested in teting the results of mm_X)
 private void Leer_NDI_tracker(object sender, EventArgs e)
        {

            if (MR != null)
            {
                mm_X = poi_navegacion_individual.POR_x * Convert.ToDecimal(MR.MR0) + poi_navegacion_individual.POR_y * Convert.ToDecimal(MR.MR1) + poi_navegacion_individual.POR_z * Convert.ToDecimal(MR.MR2) + Convert.ToDecimal(MR.MR9);
            }
         }

Thank you,

A: As you mentioned in your question - you should keep all business logic separated from UI elements. This would not only make it easy to test your calculation, but would also make the method reusable by other parts of the program.

A: I'd advise looking into the MVC (Model, View, Controller) method of implementing a Windows Forms app. It helps keep the UI and code separated.
I personally haven't used it since I've only worked with WPF apps where MVVM (Model, View, ViewModel) is used but the reasoning behind the two models is similar in that they aim to separate code and UI.
Take a look here for more information on implementing MVC: How would you implement MVC in a Windows Forms application?


text:
Q: How to sort an array with digital size and occurrences I have an array of numbers
var number = [7,7,6,9,9,9,3,3]

and we want to sort it by number of occurrences.
In this example the result should be:
[6,3,3,7,7,9,9,9]

We tried to use sort, but couldn't figure it out.
If we only can use sort, how could we solve this problem in one sort?
var number = [7,7,6,9,9,9,3,3];
number.sort(function(a,b) {
    //code here
});

A: It's very hard and inefficient to do it by sort alone. You want your frequency counts first.
var freq = {};
number.forEach(function(i) {
  freq[i] = (freq[i] || 0) + 1;
})
number.sort(function(a,b) {
  return (freq[a] - freq[b]) || (a - b);
});
// => [6, 7, 7, 3, 3, 9, 9, 9]

If you really, really, really need it in one function call,
number.sort(function(a, b) {
  var afreq = number.filter(function(i) { return i == a; }).length;
  var bfreq = number.filter(function(i) { return i == b; }).length;
  return (afreq - bfreq) || (a - b);
});

but as I said above, very, very inefficient.
EDIT: Thanks to Derek 朕會功夫 for golfing it!
EDIT2: Fixed the bug that mixed numbers of same frequency. Thanks again, Derek 朕會功夫!


text:
Q: Update sliderInput in Shiny reactively I am trying to change the values from a sliderInput dynamically. The difficulty now is that I want to change from a sliderInput with one value, to a sliderInput with a range, which seems not to work.
The first actionbutton in the code below works, while the second does not what it is intended to do.
Is the only possibility to switch to an uiOutput element?
Code
library(shiny)
app <- shinyApp(
   ui = bootstrapPage(
      sliderInput("sld1", min = 0, max = 10, label = "y1", value = 5),
      actionButton("acb1", "Change Value"),
      actionButton("acb2", "Change Value to Range")
   ),
   server = function(input, output, session) {
      observeEvent(input$acb1, {
         updateSliderInput(session, "sld1", value = 2)
      })
      observeEvent(input$acb2, {
         updateSliderInput(session, "sld1", value = c(2,7))
      })
   })
runApp(app)

A: You can maybe add the slider dynamically using renderUI
#rm(list = ls())
library(shiny)
app <- shinyApp(
  ui = bootstrapPage(
    uiOutput("myList"),
    actionButton("acb1", "Change Value"),
    actionButton("acb2", "Change Value to Range")
  ),
  server = function(input, output, session) {

    slidertype <- reactiveValues()
    slidertype$type <- "default"

    observeEvent(input$acb1,{slidertype$type <- "normal"})
    observeEvent(input$acb2, {slidertype$type <- "range"})

    output$myList <- renderUI({

      if(slidertype$type == "normal"){
        sliderInput("sld1", min = 0, max = 10, label = "y1", value = 2)
      }
      else if(slidertype$type == "range"){
        sliderInput("sld1", min = 0, max = 10, label = "y1", value = c(2,7))
      }
      else{
        sliderInput("sld1", min = 0, max = 10, label = "y1", value = 5)
      }
    })
})
runApp(app)


text:
Q: random effects and clustered errors I am running a panel model using an linear regressor. A Haussman test indicates that the random effects model is better than a fixed effects. I am also clustering the errors on country code.
I would just like some sober second thought on this approach. In my view, random effects and clustering do slightly different things. RE is more about the coefficient and clustering is more about the significance (standard errors), to put it crudely. If so, running a model with both would actually be a fairly good idea, especially since RE models have such strong assumptions.
Happy to be proven wrong (or right, of course).
Any impressions would be welcome.

A: In the usual setting (in most programs) the hausman test in valid only under full set of random effects assumptions. In this case it makes no sense to report robust standard errors because, even while they are still valid, they will less efficient per definition (you have a loss with no gain).
Other than this; yes you are correct it always makes sense to report robust standard errors (and most people do) since the assumption needed for the usual standard errors to be correct are strict and (somewhat) arbitrary.


text:
Q: How to jump into bootloader in Ada? I am writing embedded code in Ada. I want to jump into bootloader code which is located at address 0x0E00. I am trying to use following code:
with Interfaces; use Interfaces;
with System;

package AVR.bootloader is

   procedure Call;
   pragma No_Return(Call);
   pragma Import (Assembler,Call);
   for Call'Address use System'To_Address (16#0E00#);

end AVR.bootloader;

The problem is this does not work.
Edit: I want to do a following C equivalent:
void (*boot)(void)=0x0E00;

A: Since normally a boot-loader runs on reset, the simplest method is to force a processor reset.  A boot-loader may reasonably assume that it is running on an uninitialised system in reset state and may perform initialisation that is not valid on an already initialised system, so forcing a reset is the safest method.
Your processor may have a reset instruction or a reset controller that can perform this directly.  Failing that it may have a watchdog timer that can generate a reset. Start the watchdog timer with a suitably short time-out and let it run without servicing it.

A: I did a small experiment on this Macbook Pro, and your code seems to do what you meant it to; I modified the code to read
with System;

procedure Bootloader is

   procedure Call;
   pragma No_Return (Call);
   pragma Import (Assembler, Call);
   for Call'Address use System'To_Address (16#0E00#);

begin
   Call;
end Bootloader;

and when I compile with gnatmake -c -u -f -S bootloader.adb the saved assembler is
        .text
        .globl __ada_bootloader
__ada_bootloader:
LFB1:
        pushq   %rbp
LCFI0:
        movq    %rsp, %rbp
LCFI1:
        subq    $16, %rsp
LCFI2:
        movq    $3584, -8(%rbp)
        movq    -8(%rbp), %rax
        call    *%rax
        leave
LCFI3:
        ret
[...]

which looks hopeful, though I'm not familiar enough with asm to know.
Running it under gdb I get (after a lot of chatter)
(gdb) run
Starting program: /Users/simon/tmp/bootloader
Reading symbols for shared libraries ++........................ done

Program received signal EXC_BAD_ACCESS, Could not access memory.
Reason: KERN_INVALID_ADDRESS at address: 0x0000000000000e00
0x0000000000000e00 in ?? ()
(gdb) bt
#0  0x0000000000000e00 in ?? ()
Cannot access memory at address 0xe00
#1  0x0000000100000d93 in main (argc=1, argv=140734799805048, envp=140734799805064) at /Users/simon/tmp/b~bootloader.adb:121
#2  0x0000000100000bf4 in start ()

which looks even more hopeful.
Perhaps your AVR compiler isn't code-generating properly?


text:
Q: does a git repository have its own local value for core.autocrlf that overrides the global one? As per this question, I understand that core.autocrlf=true in git will cause CRLF to LF translations.
However when I type :
     git config core.autocrlf
I see:
     false
However, when I stage modified files that are already in the repo, I still get these warnings:
Warning: CRLF will be replaced by LF in File1.X.
The file will have its original line endings in your working directory.

My guess is that the repo copy of the file is already set to "autocrlf=true".
Questions: A. How do I query whether a file or git repo is already forcing AutoCrlf?
B. How do I turn it autocrlf off?

A: Git allows you to override your global setting on a per-repository basis with a .gitattributes file. You put it in the root directory of the repository, and becomes a file committed as part of the repository. I suspect this is happening in your case.
Github has a good page on this: https://help.github.com/articles/dealing-with-line-endings
In short, you can use the text attribute to set the line endings for a particular file extension. For instance, forcing sln files to CRLF would require the following line in a .gitattributes file :
# Declare files that will always have CRLF line endings on checkout.
*.sln text eol=crlf