text:
Q: Lucene.net Negation clause is not working I am very much new to Lucene.net and though I am not able to achieve basic functionality i.e. Not in.
My requirement is to search "road?construction" without "Works" word.
e.g.
Main Road Construction Works -- Invalid
Road Construction And Maintenance Services -- Valid (Doesn't contains word Works)
Please refer my code below.
string searchQuery = "\"road?construction\"*";
    BooleanQuery query2 = new BooleanQuery();
    Query query;
                try
                {
                    query = parser.Parse(searchQuery.Trim());
                }
                catch (ParseException)
                {
                    query = parser.Parse(QueryParser.Escape(searchQuery.Trim()));
                }

                query2.Add(query,Occur.SHOULD);
                query2.Add(new BooleanClause(new TermQuery (new Term("Name", "Works")), Occur.MUST_NOT));

This still gets both above mentioned record in to search result. I wish to cut invalid record(first).

Here is the result query generated in backend.
Please suggest workaround.
Thanks in advanced.

A: Not sure why your putting wildcard characters into the phrase. If you're looking for "road construction" then that's all you need. If you are looking to allow some variations then maybe a "slop phrase" is what you need ie. "road construction"~2. The number part allows for n "operations" like n additional words inbetween.
Here's a set of tests that show your examples (TestExpr2, TestExpr3) and some working variations (TestExpr1 and TestQuery).
Hope this helps
[TestClass]
public class UnitTest7
{
    [TestMethod]
    public void TestExpr1()
    {
        TestExpr("\"road construction\" -works");
    }
    [TestMethod]
    public void TestExpr2()
    {
        TestExpr("\"road?construction\"* -works");
    }
    [TestMethod]
    public void TestExpr3()
    {
        TestExpr(QueryParser.Escape("\"road?construction\"* -works"));
    }

    private void TestExpr(string expr)
    {
        var writer = CreateIndex();
        Add(writer, "Main Road Construction Works");
        Add(writer, "Road Construction And Maintenance Services");
        writer.Flush(true, true, true);
        var searcher = new IndexSearcher(writer.GetReader());

        var result = Search(searcher, expr);

        Assert.AreEqual(1, result.Count);
        Assert.IsTrue(result.Contains("Road Construction And Maintenance Services"));
        writer.Dispose();
    }

    [TestMethod]
    public void TestQuery()
    {
        var writer = CreateIndex();
        Add(writer, "Main Road Construction Works");
        Add(writer, "Road Construction And Maintenance Services");
        writer.Flush(true, true, true);
        var searcher = new IndexSearcher(writer.GetReader());

        var query = new BooleanQuery();
        var p = new PhraseQuery();
        p.Add(new Term("name", "road"));
        p.Add(new Term("name", "construction"));
        query.Add(p, Occur.MUST);
        query.Add(new TermQuery(new Term("name", "works")), Occur.MUST_NOT);

        var result = Search(searcher, query);

        Assert.AreEqual(1, result.Count);
        Assert.IsTrue(result.Contains("Road Construction And Maintenance Services"));
        writer.Dispose();
    }

    private List<string> Search(IndexSearcher searcher, string expr)
    {
        var analyzer = new StandardAnalyzer(Lucene.Net.Util.Version.LUCENE_30);
        var queryParser = new QueryParser(Lucene.Net.Util.Version.LUCENE_30, "name", analyzer);
        var query = queryParser.Parse(expr);
        return Search(searcher, query);
    }

    private List<string> Search(IndexSearcher searcher, Query query)
    {
        var collector = TopScoreDocCollector.Create(10, true);
        searcher.Search(query, collector);
        var result = new List<string>();
        var matches = collector.TopDocs().ScoreDocs;
        foreach (var item in matches)
        {
            var id = item.Doc;
            var doc = searcher.Doc(id);
            result.Add(doc.GetField("name").StringValue);
        }

        return result;
    }

    IndexWriter CreateIndex()
    {
        var directory = new RAMDirectory();
        var analyzer = new StandardAnalyzer(Lucene.Net.Util.Version.LUCENE_30);
        var writer = new IndexWriter(directory, analyzer, new IndexWriter.MaxFieldLength(1000));
        return writer;
    }

    void Add(IndexWriter writer, string text)
    {
        var document = new Document();
        document.Add(new Field("name", text, Field.Store.YES, Field.Index.ANALYZED));
        writer.AddDocument(document);
    }
}


text:
Q: How to connect to TLS using Vue? I want to connect to MQTT server using Vue.
I tried something similar to what I found on Google, but failed.

*

*node.js example

var mqtt = require('mqtt');
var fs = require('fs');

var options = {
  host: '127.0.0.1',
  port: 8883,
  protocol: 'mqtts',
  protocolId: 'MQIsdp',
  ca: [fs.readFileSync('<path>/ca.crt')],
  key: fs.readFileSync('<path>/client.key'),
  cert: fs.readFileSync('<path>/client.crt'),
  passphrase: 'CLIENT KEY PASSPHRASE',
  secureProtocol: 'TLSv1_method',
  protocolVersion: 3
};

var client = mqtt.connect(options);

*

*Results I wrote using a method I found on the blog

const option = {
      port: 48883,
      ca: [],
      key: '',
      cert: '',
      clientId: 'mqttjs_' + Math.random().toString(16).substr(2, 8),
      protocolId: 'MQTT',
      useSSL: true,
      passphrase: 'CLIENT KEY PASSPHRASE',
      secureProtocol: 'TLSv1_method',
      protocolVersion: 4,
      rejectUnauthorized: false,
    }

    axios.get('/' + 'ca.crt').then(response => {
     option.ca = [response.data]
    })

    axios.get('/' + 'client.key').then(response => {
     option.key = response.data
    })

    axios.get('/' + 'client.crt').then(response => {
     option.cert = response.data
    })

    const client = mqtt.connect('wss://url', option)

*

*error code

failed: WebSocket is closed before the connection is established.
WebSocket connection to 'wss://url' failed:

redpajama_set_name: RedPajamaStackExchange


text:
Q: Significant figures. Calculate how many gram of p-nitrophenol you require to prepare 250 mL of a 11 mM solution. (Answer to 3 significant figures)
I worked it out as $$250/1000 L * (11*10^{-3}\text{ M})$$ = $$2.75\times 10^{-3} \text{ moles} \times 139.11\text{ g/mol}$$ = $$0.3825525$$
is that 0.383 or 0.382 when approximated to 3 sig figs?

A: Note that "Leading zeros are never significant".
When approximating/rounding-off to n significant figures, your n-th digit should be rounded-off. In this case, your answer would be 0.383.
Please refer to the Wiki link above and this site for explanations and examples on working with significant digits.


text:
Q: ERROR : Attempt to invoke virtual method 'java.lang.String android.os.Bundle.getString(java.lang.String)' on a null object reference I am trying to pass data from Activity to Fragment.
This is my Calling Activity. using this activity i want to pass data to ProfileFragment
for this purpose i am using Bundle.
but i get error at ProfileFragment as show above
NewAccount.java
package com.example.takeattendence;

import androidx.appcompat.app.AppCompatActivity;

import android.app.Fragment;
import android.app.FragmentManager;
import android.content.ContentValues;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Base64;
import android.util.Patterns;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import java.io.ByteArrayOutputStream;
import java.util.ArrayList;
import java.util.List;
import com.example.takeattendence.database.LoginContract.LoginEntry;
import com.example.takeattendence.database.LoginContractStudent;
import com.example.takeattendence.database.LoginDbHelper;
import com.example.takeattendence.database.LoginContractStudent.LoginEntryStudent;

public class NewAccount extends AppCompatActivity
{

    //EditText field to First name of user
    private EditText mFirstNameEditText;

    //EditText field to Last Name of user
    private EditText mLastNameEditText;

    //EditText field to Phone Number of user
    private EditText mPhoneNumberEditText;

    //EditText field to Email Id of user
    private EditText mEmailIdEditText;

    //EditText field to Password of User
    private EditText mPasswordEditText;

    //Spinner field for post
    private Spinner mPostSpinner;

    private String mPost = "Leturer";

    //Spinner field to gender of user
    private Spinner mGenderSpinner;

    private String mGender = "Other";

    //Button for Register
    private Button mRegisterButton;

    //Textview for Log in
    private TextView mLogInTextView;
    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_new_account);

        mFirstNameEditText =(EditText)findViewById(R.id.editText_first_name);
        mLastNameEditText = (EditText)findViewById(R.id.editText_last_name);
        mPhoneNumberEditText =(EditText)findViewById(R.id.editText_phone_number);
        mEmailIdEditText = (EditText) findViewById(R.id.editText_email_id_sign_up);
        mPasswordEditText =(EditText) findViewById(R.id.editText_pass_sign_up);
        mPostSpinner = (Spinner)findViewById(R.id.spinner_post);
        mGenderSpinner=(Spinner) findViewById(R.id.spinner_gender);
        mRegisterButton = (Button) findViewById(R.id.button_register);
        mLogInTextView =  (TextView) findViewById(R.id.textview_log_in);

        setUpSpinnerPost();
        setUpSpinnerGender();

        mLogInTextView.setOnClickListener(new View.OnClickListener()
        {
            @Override
            public void onClick(View v)
            {
                Intent i = new Intent(NewAccount.this,MainActivity.class);
                startActivity(i);
            }
        });
        final LoginDbHelper mLoginDbHelper = new LoginDbHelper(this);

        mRegisterButton.setOnClickListener(new View.OnClickListener()
        {
            @Override
            public void onClick(View v)
            {
                //insert data
                insertUserData();

            }
        });

    }

    public void insertUserData()
    {

        Bundle bundle = new Bundle();
        bundle.putString("data", "Data");
        // Your fragment
        ProfileFragment obj = new ProfileFragment();
        obj.setArguments(bundle);

        Intent i = new Intent(NewAccount.this,WelcomeApp.class);
        startActivity(i);
    }

}

WelcomeApp.java
package com.example.takeattendence;

import androidx.annotation.NonNull;
import androidx.appcompat.app.ActionBarDrawerToggle;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.core.view.GravityCompat;
import androidx.drawerlayout.widget.DrawerLayout;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.MenuItem;

import com.google.android.material.navigation.NavigationView;

public class WelcomeApp extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener
{
    private DrawerLayout drawerLayout;

    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_welcome_app);

        Toolbar toolbar = findViewById(R.id.nav_toolbar);
        setSupportActionBar(toolbar);

        drawerLayout = findViewById(R.id.drawer_layout);

        NavigationView navigationView = findViewById(R.id.nav_view);
        navigationView.setNavigationItemSelectedListener(this);

        ActionBarDrawerToggle actionBarDrawerToggle = new ActionBarDrawerToggle(this,drawerLayout,toolbar,
                R.string.navigation_drawer_open,R.string.navigation_drawer_close);

        drawerLayout.addDrawerListener(actionBarDrawerToggle);
        actionBarDrawerToggle.syncState();

        if(savedInstanceState == null)
       {
            getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,
                    new ProfileFragment()).commit();

//            Intent i = new Intent(WelcomeApp.this, TestAcitivity.class);
//            startActivity(i);
            navigationView.setCheckedItem(R.id.nav_profile);
        }

//        finish();
    }

    @Override
    public boolean onNavigationItemSelected(@NonNull MenuItem menuItem)
    {
        switch (menuItem.getItemId())
        {
            case R.id.nav_profile:

                getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,
                        new ProfileFragment()).commit();
                break;

            case R.id.nav_update_profile:
                getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,
                        new UpdateProfileFragment()).commit();
                break;

            case R.id.nav_see_database:
                getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,
                        new StudenetInfoFragment()).commit();
                break;

            case R.id.nav_logout:
//                Intent in = new Intent(WelcomeApp.this,MainActivity.class);
//                startActivity(in);
//                finish();

//                SharedPreferences.Editor editor = getSharedPreferences("POS", MODE_PRIVATE).edit();
//                editor.putString("password", "");
//                editor.putString("email", "");
//                editor.putBoolean("isLoggedIn", false);
//                editor.apply();
//
//                Intent intent = new Intent(getApplicationContext(), MainActivity.class);
//                intent.putExtra("finish", true);
//                intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
//                startActivity(intent);

//                finish();

                SharedPreferences.Editor editor = getSharedPreferences("name", MODE_PRIVATE).edit();
                editor.putString("password", "");
                editor.putString("email", "");
                editor.putBoolean("isLoggedIn", false);
                editor.apply();

                Intent intent = new Intent(getApplicationContext(), MainActivity.class);
                intent.putExtra("finish", true);
                intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                startActivity(intent);

                finish();

                break;

            default:
        }

        drawerLayout.closeDrawer(GravityCompat.START);
        return true;
    }
    @Override
    public void onBackPressed()
    {
        moveTaskToBack(true);
    }

}

ProfileFragment.java
package com.example.takeattendence;

import android.content.Intent;

import android.graphics.Bitmap;
import android.os.Bundle;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;

import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import androidx.fragment.app.Fragment;

import static android.app.Activity.RESULT_OK;

public class ProfileFragment extends Fragment //implements LoaderManager.LoaderCallbacks<Cursor>
{

    public ProfileFragment()
    {

    }
    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState)
    {
        View view = inflater.inflate(R.layout.fragment_profile,container,false);

        TextView firstNameTextView = (TextView)view.findViewById(R.id.textview_profile_first_name);

        String strtext = this.getArguments().getString("data");
        firstNameTextView.setText(strtext);
        return view;

    }

I had searched on google but I am not getting proper solution.
Thank You in Advance.

A: Use this in fragment instantiation:
ProfileFragment frag = new ProfileFragment();
Bundle b = new Bundle();
b.putString("data", "your data goes here");
frag.setArguments(b);

getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container, frag)
    .commit();


text:
Q: running external program in java If I am running external program(batch file) from java then, What I need to do:
if (process.exitValue() == 0) {//means executed successfully ???

Can't the return value be something else and batch executed successfully.
Is that the only way to check??

A: I'm a bit confused by your wording, but by convention, [exitValue()](http://download.oracle.com/javase/1.4.2/docs/api/java/lang/Process.html#exitValue()) returns 0 upon a successful execution. This is, as far as I know, the only way to check.
EDIT:
I suppose you could use [getErrorStream()](http://download.oracle.com/javase/1.4.2/docs/api/java/lang/Process.html#getErrorStream()) - I assume it'll be blank if there are no errors in the process...

A: Pick one from here

A: You could read the output stream ( or the error stream )  and interpret it

A: The exit code of the batch process will be defined by that process but generally an exit code of 0 is defined as successful and a non zero value indicates that something went wrong.  In your batch file you can set the return code by calling:
EXIT /B %ERROR_CODE%

%ERROR_CODE% is the number that will be returned as the exit code.

A: On Linux, your program can return any status you want. By convention 0 means success.
For example, if you execute a shell script, the return status will be the return status of the last command executed in your script.

A: In many programs 0 is is success, negative numbers are errors and positive numbers are warnings. Of course this is just a convention and it all depends on what convention was followed. In most programming languages you can define an exit code for a program and that is what is picked up.
In Java System.exit(n)
In C main is defined as int main(int argc, char* argv[]) and the return from main is the return from the program.


text:
Q: how to know the current activity of a workflow instance openerp I am new to Odoo OpenERP, I am working on V8, currently I am trying to understand the workflow.
I am thinking if there is a way to know what is the current activity of a specific workflow instance.

A: I found the solution, I would like to share it with you.
you can check the database table, wkf_workitem, in this table you will find the act_id (activity id) field of the latest executed activity on the workflow instance (inst_id).
Hope this may help.
Feel free to contact me for any detail.


text:
Q: Drawing a bufircation diagram $\dot x=x(\mu+x-2)(\mu+2x-x^2)$
The first thing I did was to check the fixed points in the $(\mu,x)$-plane:
$x=0$
$x=2-\mu$ (saddle node at 0 when $\mu$)
$x_{1,2}=1+-\sqrt{\mu+1}$ (no fixed point for $\mu<1$)
Did I specified the type for the bufircation points correctly?
How does the bifurcation diagram now looks like? I do not know how to draw them.

A: You would look at the qualitative behavior for various values of $\mu$ and validate your critical points.
Here are four cases for $\mu =-2, -1, 0 , +1$. Look for the critical points and see what happens at each. You should also learn to draw these by hand as you know the derivative information, you know the critical points and you can choose several values between regions and determine direction. Look at what happens in each and make sure it matches your analysis (which is correct).


text:
Q: Has the deployment of resource files and site maps been improved in SharePoint 2010 All the SharePoint applications I work on use resource files to allow localisation and sitemap files to integrate with breadcrumbs.
It has always been a problem to deploy and process these files as part of a standard WSP deployment as the recommended API call (ApplyApplicationContentToLocalServer) requires local administrator access for the owstimer service, which goes against best practices.
I know there are a number of ways around this in SharePoint 2007, which involve basically writing your own implementation of ApplyApplicationContentToLocalServer, but I had hoped that in SharePoint 2010 this obvious flaw would have been fixed.
Unfortunately the code still checks if the current user is local administrator (I used reflector on the SP2010 Microsoft.SharePoint.dll file)
if (!SPAdministrationServiceUtilities.IsCurrentUserMachineAdmin())
{
    throw new SecurityException(SPResource.GetString("AccessDenied", new object[0]));
}

So, to cut a long and very frustrating story short. Is there a new, built-in, way in SharePoint 2010 to deploy resource files to the App_GlobalResources folder and process sitemap files?
For a good breakdown of the problem see this excellent post by Sean McDonough.
Update: We have completely rewritten the deployment mechanism for sitemaps and resource files. We can now deploy everything to all machines in a farm for SP2007 as well as SP2010. Keep an eye on our blog as we hope to release the code in the near future.

A: Good news on one of those fronts at least - resources CAN now be easily deployed to the App_GlobalResources folder. One of the enhancements to the WSP framework is that it now has the capability to deploy files to this location, courtesy of a new XML element 'App_GlobalResourceFile'.
To use, simply mark your resource file as 'AppGlobalResource' for the DeploymentType property in Visual Studio, and this element will be created for it.
[Note that the 'resources' and 'wpresources' folders within the web application root can also be targeted (using DeploymentType = 'ApplicationResource' or 'DwpFile' respectively), but are considered legacy.]
Unfortunately, these are the only locations under the web application root (as opposed to the SharePoint root) that the WSP framework can target. Yeah I wish this wasn't the case too. So you'll have to use the same techniques as before for sitemap files, or indeed anything under the web app root which isn't a resource. Still, the improvements for resources are definitely welcomed by those creating localized solutions.
P.S. I talked about this and other enhancements to the Features and Solutions frameworks at the SharePoint Evolutions conference last week - I'll be posting the slide decks over the next couple of days if that's of interest.

A: Dont know about the sitemap file, but read this blog post on how localization is done in VS2010
http://blogs.msdn.com/johnwpowell/archive/2009/11/29/sharepoint-2010-localization-with-visual-studio-2010.aspx


text:
Q: bulleted list in cv markdown Is it me or does the markdown in the cv editor not support a bulleted list?
I tried to add one in the responsibilities section for a previous employer and it doesn't render with bullets. The edit box has the 'this field supports rich markdown formatting. live preview' text below it so I thought the '  - ' would work.

A: I can't repro this.
I entered the following text for responsibilities:

- bullet 1
- bullet 2
- bullet 3

And I got this on the public cv view:
http://img691.imageshack.us/img691/1281/image3i.png


text:
Q: Remove noise(hours) for parsing time in Y/M/D format I am parsing the dates of my dataset, but am encountering a lot of ParserError because the hours are often in the wrong format. I've decided to skip the hours and only focus on Years, Months, Days
These are the variants I have for date:
| Startdate |
| --- |
| March 23, 2022 6:00 |
| March 23, 2022 7:0 |
| March 23, 2022 7: |
| March 23, 2022 7 |
For now, only the first date/row works for parsing data. I currently skip the other rows, however I would want to also include them by just excluding the hours.

for date in df_en['Startdate']:

    try:

        parse(date).date()

    except Exception:

        pass

What is the right way to still parse the other dates without having to bother with hours?
I've tried to convert the time into a valid hours format. using pd.to_datetime did not work because the time format was a str march not number 3. When manually changed towards 3, it still gave the error ValueError: unconverted data remains: :00. Therefore with no relevancy for hours, I just wanted to skip it.
Source: https://serveanswer.com/questions/converting-to-datetime-parsererror-unknown-string-format-2022-02-17-7

dates = ['December 1, 2021 6:00', 'March 23, 2022 6']

for date in dates:

    date.replace(' (\d{1})', ' 0\\1')

    pd.to_datetime(date, format='%m %d, %Y %H')

    print(date)

Endgoal:
| Year | Month | Day |
| --- | --- | --- |
| 2022 | March | 23 |
| 2022 | March | March |

A: I guess you can just dump the hour part
dates = ['March 23, 2022 6:00', 'March 23, 2022 7:0', 'March 23, 2022 7:', 'March 23, 2022 7']
pd.to_datetime([' '.join(x.split(' ')[:-1]) for x in dates])

DatetimeIndex(['2022-03-23', '2022-03-23', '2022-03-23', '2022-03-23'], dtype='datetime64[ns]', freq=None)

after that you can do df['date'].dt.year to extract year, month, day

A: If you just need year/month/day columns, there's actually no need to parse to datetime. Just deal with the strings by splitting and rearranging; EX:
import pandas as pd

df = pd.DataFrame({'Startdate': ['December 1, 2021 6:00', 'March 23, 2022 6']})

parts = df['Startdate'].str.split('\ |, ')

df['year'], df['month'], df['day'] = parts.str[2], parts.str[0], parts.str[1]

print(df)
#                Startdate  year     month day
# 0  December 1, 2021 6:00  2021  December   1
# 1       March 23, 2022 6  2022     March  23


text:
Q: How to determine correct replacement transformer for flyback converter in commercial product I have an MPPT charge controller that has recently started behaving strangely and upon investigation I found a very hot mosfet and a transformer (below) that has clearly seen more heat than it should have.

The manufacturer isn't particularly helpful in providing information about this. I've been able to figure out what's going on, but not why this happened in the first place nor what is required to repair it.
From what I could determine, the particular circuit is a step-up converter that generates 15V from the original 5V. I have no idea what values are used, it is hard to decipher. The final 15V regulator is a 78l15, so I know the voltage on that end is below 35V and the current will be below 0.1A.

The input signal is a 5V 40khz square wave generated by a PIC microcontroller.
I suspect, though I'm not 100% sure yet, that this 15V is used to drive the main mosfet. This particular controller switches in the positive line (as is the proper way to do it), so a higher-than-input voltage is required. I think this is it. That's why it needs to be isolated.
My question: What would be the simplest way to replace either the whole step-up converter with another -- with the proviso that it MUST be isolated -- or to somehow replace that transformer with something off the shelf?
I do not presently have the equipment to measure inductors. I do own an oscilloscope but lack a function generator. This makes it hard to really get into it further, which is why I would also strongly consider another off-the-shelf solution to just replace the whole converter, possibly with something that's even more efficient.

A: If you are 100% sure about the schematic you provide I would estimate the transformer to be a certain type of 1:4 or 1:5 job, depending on the smoothing capacitor and current drain.
If then, again you are 100% sure about the schematic not doing anything fiddly with the generated 40kHz on any other point (another winding? The incoming "+5V"?) this is an exceptional candidate for replacing with an isolated DC/DC module.
A very good reason to build this like they did is that in mass production the components may be cheap compared to a 1W5 avg / 3W peak DC/DC module.
Another very good reason is needing the resulting 40kHz wave at another point, or secretly tapping off another voltage somewhere. So you do need to make absolutely sure you don't interrupt anything but the 5V to 15V conversion.
The safest thing to do is leave the 15V regulator in place and replace the remaining circuit by a DC/DC unit that makes (one way or another) at least 18V, since we do not know the ripple requirements on the output. If it's just a gate voltage (and you can absolutely verify that it is) 100mVpp on 15V won't be much of an issue and you can go for 15V DC/DC blocks. In the latter case you may need to add an extra capacitance on the output (with or without Schottky and/or small resistor) to make the module's regulation less susceptible to the MOSFET's peak gate current.
If you have a floating bench top supply that does a nice 15V and/or 18V I strongly suggest you try it with that at a conservative current limit shortly to see if that works okay, since you can know and control the parameters with those and what happens upon a mistake with a DC/DC module is always a bit guess work.
Another thing to be very weary of is that the PIC might turn the auxiliary DC/DC off by stopping the signal and you may have to account for that in any of the possible fixes, since then it may assume its "off-ness" at other points in control loops. So certainly consider that in any further research.
As to the "laboured" square, that's possibly explained with the parallel capacitor, though I would say you'd still want some kind of a protection zener to prevent the MOSFET from getting into dangerous waters. If there is none of that at all, that is your first clue they might have not spent enough time on the DC/DC design, IMHO.


text:
Q: Inserting text at index in an file; problems with encoding I want to add some text at a specific position in a specific line. This is what I got so far:
public void AddSomeTextToFile(string FilePath, int LineNumber, int IndexInLine, string TextToAdd)
{
    string[] WholeFile = File.ReadAllLines(FilePath);
    WholeFile[LineNumber - 1] = WholeFile[LineNumber - 1].Insert(IndexInLine, TextToAdd);
    File.WriteAllLines(FilePath, WholeFile);
}

This, code, however, has some issues with encoding.
For example, text that was  becomes . I've tried using Encoding.UTF8 and Encoding.Unicode, both with no success.
Is there any way to insert some text into a file and preserve and special characters?

Solution
Based on floele's code, this is the code that solved my problems:
public void AddSomeTextToFile(string FilePath, int LineNumber, int IndexInLine, string TextToAdd)
{
    byte[] bytes = File.ReadAllBytes(FilePath);
    List<List<byte>> lines = bytes.SplitOn((byte)'\n').ToList();
    byte[] bytesToInsert = Encoding.Default.GetBytes(TextToAdd);
    lines[LineNumber - 1].InsertRange(IndexInLine, bytesToInsert);
    File.WriteAllBytes(FilePath, lines.SelectMany(x => x).ToArray());
}

static class EnumerableExtensions
{
    public static IEnumerable<List<T>> SplitOn<T>(
        this IEnumerable<T> source,
        T delimiter)
    {
        var list = new List<T>();
        foreach (var item in source)
        {
            if (delimiter.Equals(item))
            {
                list.Add(item);
                yield return list;
                list = new List<T>();
            }
            else
            {
                list.Add(item);
            }
        }
        yield return list;
    }
}

A: Encoding.UTF8 is actually the default encoding used by WriteAllLines and ReadAllLines. So if reading and writing using this encoding "corrupts" your data, you need to use a different one.
You need to determine what the original encoding of the file located at FilePath is and then specify it like this
File.ReadAllLines(FilePath, *encoding*);
File.WriteAllLines(FilePath, WholeFile, *encoding*);

A likely encoding would be Encoding.Default (windows-1252), try it out. If that doesn't work, you have to check how the file is actually written before you append to it.
However, if it contains a lot of non-character data as your screenshots indicate, maybe you have to consider the file to be a "binary" type. In this case you should use ReadAllBytes / WriteAllBytes, split the file manually into lines (searching the byte array for \r\n) and then insert new data at the desired locations. You need to convert strings to a byte array for this purpose using Encoding.GetBytes("...") (using the right encoding).
Taking some code from another linked answer, full code for this would like:
static class MyEnumerableExtensions
{
    //For a source containing N delimiters, returns exactly N+1 lists
    public static IEnumerable<List<T>> SplitOn<T>(
        this IEnumerable<T> source,
        T delimiter)
    {
        var list = new List<T>();
        foreach (var item in source)
        {
            if (delimiter.Equals(item))
            {
                yield return list;
                list = new List<T>();
            }
            else
            {
                list.Add(item);
            }
        }
        yield return list;
    }
}

public InsertLine()
{
    byte[] bytes = File.ReadAllBytes(...);
    List<List<byte>> lines = bytes.SplitOn((byte)'\n').ToList();
    string lineToInsert = "Insert this";
    byte[] bytesToInsert = Encoding.Default.GetBytes(lineToInsert);
    lines.Insert(2, new List<byte>(bytesToInsert));
    File.WriteAllBytes(..., lines.SelectMany(x => x).ToArray());
}

A: Why not use the StreamReader.ReadLine method for getting the lines in the file into an array, insert the lines you want and then use StreamWriter.WriteLine for writing the lines back.
http://msdn.microsoft.com/en-us/library/system.io.streamreader.readline(v=vs.110).aspx
http://msdn.microsoft.com/en-us/library/system.io.streamwriter.writeline(v=vs.110).aspx


text:
Q: Ruby callback when any module is included I know that we can define the included callback for any individual module.
Is there any way to define a callback that is invoked whenever any module gets included in another module or class? The callback would then preferably have access to both the module included, and the class/module where it is included.

A: I cannot think or find a builtin way in Ruby to do it.
One alternative would be to monkey patch the Module class directly to create the callback. To do it we can add some wrapper methods around the original methods include and extend to force the execution of our defined callbacks each time the include or extend methods are called.
Something along the following lines should work:
class Module

  def self.before
    m_include = instance_method(:include)
    m_extend = instance_method(:extend)

    define_method(:include) do |*args, &block|
      included_callback(args[0])
      m_include.bind(self).call(*args, &block)
    end

    define_method(:extend) do |*args, &block|
      extend_callback(args[0])
      m_extend.bind(self).call(*args, &block)
    end
  end

  def included_callback(mod_name)
    puts "#{self} now has included Module #{mod_name}"
  end

  def extend_callback(mod_name)
    puts "#{self} now has extended Module #{mod_name}"
  end

  before
end

An example to test that it works:
module Awesome

  def bar
    puts "bar"
  end

  def self.baz
    puts "baz"
  end
end

class TestIncludeAwesome
  include Awesome
end

class TestExtendAwesome
  extend Awesome
end

The example code should print as output the following:
> TestIncludeAwesome now has included Module Awesome
> TestExtendAwesome now has extended Module Awesome

A: class D
  def self.callback(mod)
    include mod
  end
end

module M
  def hello
    puts 'hi'
  end

  def self.included(klass)
    D.callback(self) unless klass == D
  end
end

class C
  include M
end

C.new.hello #=> 'hi'
D.new.hello #=> 'hi'

When C includes M, M::included is executed with klass#=>C. Since klass == D is false, D.callback(M) is executed. callback includes M in class D, then M::included is executed with klass#=>D. Since klass == D is now true, M is not included into D a second time.


text:
Q: input() command issue in jupyter notebook and vs code interactive mode I am running the following code in a jupyter noteboook or in vs code (interactive mode):
from IPython.display import clear_output

for i in range(5):
    print('This is a test!')
    a = input('Enter something: ')
    clear_output()

It is supposed to print the message first and then ask for the input. Sometimes it happens that the input is asked without the message being printed. In the next step of the loop the message is then printed twice.
NOTE: sometimes the above example works how it is supposed to (the number of repeats is small enough I guess). In my real world application I have a couple of hundreds of inputs to do and the above error pops up sooner or later.
I found this solution: Show question/input in vscode jupyter notebook output
But I'd prefer the notebook environment.


text:
Q: Constructor on type not found .NET Core I create.NET Core API then I decide to create Repository so create DataAccessLayer with interfaces and implementations
public class GappedData : IGappedData
{
    private readonly GappedContext context;
    private readonly IDictionary<Type, object> repositories;

    public GappedData(GappedContext context)
    {
        this.context = context;
        this.repositories = new Dictionary<Type, object>();
    }

    public IRepository<ApplicationUser> ApplicationUser => this.GetRepository<ApplicationUser>();

    private IRepository<T> GetRepository<T>() where T : class
    {
        var type = typeof(T);

        if (!this.repositories.ContainsKey(type))
        {
            var typeOfRepository = typeof(IRepository<T>);
            var repository = Activator.CreateInstance(typeOfRepository, this.context);

            this.repositories.Add(type, repository);
        }

        return (IRepository<T>)this.repositories[type];
    }
}

so when I try to call it throws an exception

Constructor on type 'Gapped.DataAccessLayer.Interfaces.IRepository`1[[Gapped.Entities.Models.ApplicationUser.ApplicationUser, Gapped.Entities, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]]' not found.

A: You are trying to create an instance of an interface here:
var typeOfRepository = typeof(IRepository<T>);
var repository = Activator.CreateInstance(typeOfRepository, this.context);

You are getting that error because interfaces don't have constructors.
Change typeof(IRepository<T>) to be typeof the concrete implementation instead. (Like typeof(Repository<T>) if Repository<T> implements the IRepository<T> interface.


text:
Q: Stray first pair when writing values to dictionary? I currently have a list of nodes (integers) saved in python, and a corresponding list of stress values (floats) also saved to a list in Python.
Using:
combined_list = list(zip(node_list, stress_list))
sorted_combined_list = sorted(combined_list, key=lambda x: x[0])

I now have a list of pairs, ordered by ascending node value with a corresponding stress value.
I am now trying to write these to a dictionary, where the nodes are the keys. To do this I have tried the following:
stress_dict = {}
for node, stress in sorted_combined_list:
    stress_dict[node] = stress

When I print stress_dict the output is what I would expect, with the exception that the first key value pair is a seemingly random node - the output looks as follows:
{40632320: 0.0, 2: 0.169, 3: 0.0, 4: ....}

Does anyone know what I may have missed, or why this is the case? Any help would be appreciated!


text:
Q: Excluding certain Regex Permutations Is there a way to exclude certain permutations in RegEx?
at present I am replacing all instances of:
[ouh]+
with:
[ouh]+
and it returns:
oo
ou
oh
uo
uu
uh
ho
hu
hh
I would like to exclude uo, uu, uh, ho, hu, and hh. How do I do this?

A: Based on your somewhat limited example, it appears you want to find all two-character strings composed only of the letters o, u, and h, where the first letter is not u or h. If that is the case, then perhaps o[ouh] would be a better regex to start with...


text:
Q: Terraform 11 Additional Security Group Error I'm adding additional security groups in Terraform 11, using AWS Provider 2.70.0 to an EFS Mount Target.
The code block is:
resource "aws_efs_mount_target" "default" {
  count          = "${length(split(",",var.backend_subnets)) > 0 ? length(split(",",var.backend_subnets)) : 0}"
  file_system_id = "${aws_efs_file_system.default.id}"
  ip_address     = "${var.mount_target_ip_address}"
  subnet_id      = "${element(split(",", var.backend_subnets), count.index)}"
  security_groups = ["${var.additional_security_groups == "" ? aws_security_group.efs_default_sg.id : format("%s,%s",var.additional_security_groups,aws_security_group.efs_default_sg.id)}"]
}

The variable definition is:
variable "additional_security_groups" {
  description = "Comma separated string of security group ID's"
  default     = ""
}

But the following errors are occurring:
* module.efs.aws_efs_mount_target.default[1]: 1 error(s) occurred:

* aws_efs_mount_target.default.1: ValidationException:
status code: 400, request id: 5ee48121-27c3-432b-98e9-e2ffdc6e0fdd

plugin.terraform-provider-aws_v2.70.0_x4: 2021/03/26 17:49:50 [ERR] plugin: plugin server: accept unix /tmp/plugin935042092: use of closed network connection

There is no issue when run without the additional security group.

A: So the issue was not with the plugin but was with the compare statement for the security groups.
The working compare:
security_groups = ["${split(",", length(var.additional_security_groups) > 0 ? join(",", concat(list(aws_security_group.efs_default_sg.id), var.additional_security_groups)) : join(",", list(aws_security_group.efs_default_sg.id)))}"]

And to support this, the variable type had to be changed to list:
variable "additional_security_groups" {
  description = "Comma separated list of security group ID's"
  default     = ["sg-123","sg-789"]
}


text:
Q: Keeping HTTP Basic Authentification alive while being redirected We are using web service with basic authentication.
It all worked all fine, till owners of web service implemented balancing service.
Which is simply redirects requests to different instances of web service.
The problem is that after being redirected basic authentication fails.
There is "request authentication credentials was not passed" exception.
Additional info:

*

*We have to create request manually.
    var req = (HttpWebRequest)WebRequest.CreateDefault(new Uri(Settings.Default.HpsmServiceAddress));

    req.Headers.Add("Authorization", "Basic aaaaaaaaaaa");
    req.PreAuthenticate = true;
    req.AuthenticationLevel = AuthenticationLevel.MutualAuthRequested;
    req.UserAgent = "Apache-HttpClient/4.1.1 (java 1.5)";
    req.KeepAlive = false;

    ServicePointManager.Expect100Continue = false;

    req.ContentType = "text/xml; charset=utf-8";
    req.Method = "POST";
    req.Accept = "gzip,deflate";
    req.Headers.Add("SOAPAction", actionName);
    byte[] buffer = Encoding.UTF8.GetBytes(envelop);
    Stream stm = req.GetRequestStream();
    stm.Write(buffer, 0, buffer.Length);
    stm.Close();

    WebResponse response = req.GetResponse();
    string strResponse = new StreamReader(response.GetResponseStream()).ReadToEnd();
    response.Dispose();

*We are redirected with HTTP 307 redirect

A: Follow the MSDN for HttpWebRequest.AllowAutoRedirect Property i found this :

The Authorization header is cleared on auto-redirects and
  HttpWebRequest automatically tries to re-authenticate to the
  redirected location. In practice, this means that an application can't
  put custom authentication information into the Authorization header if
  it is possible to encounter redirection. Instead, the application must
  implement and register a custom authentication module. The
  System.Net.AuthenticationManager and related class are used to
  implement a custom authentication module. The
  AuthenticationManager.Register method registers a custom
  authentication module.

Solution is to write a custom Authentication Module.
Here what i've found about it :
http://msdn.microsoft.com/en-us/library/system.net.authenticationmanager.aspx
And here the AllowAutoRedirect properties page :
http://msdn.microsoft.com/en-us/library/system.net.httpwebrequest.allowautoredirect.aspx
UPDATE
Can you try to use CredentialCache instead of add header to webrequest ?
CredentialCache myCache = new CredentialCache();

myCache.Add(
new Uri("http://www.contoso.com/"),"Basic",new NetworkCredential(UserName,SecurelyStoredPassword));
req.Credentials = myCache;

A: Indeed, CredentialCache is working correctly. However, if you would like to add multiple basic auth credentials (for example if there is redirection that you are aware of) you can use following function that I have made:
private void SetNetworkCredential(Uri uriPrefix, string authType, NetworkCredential credential)
{
    if (request.Credentials == null)
    {
        request.Credentials = new CredentialCache();
    }

    if (request.Credentials.GetCredential(uriPrefix, authType) == null)
    {
        (request.Credentials as CredentialCache).Add(uriPrefix, authType, credential);
    }
}

I hope it will help somebody in the future.


text:
Q: How to delay my AI move I am doing a game like chess. As soon my player move is completed(if he starts move from one place to another),  my AI move is started (before my player reaching his destination ). Sometimes i find difficult which AI coin is moved now. how to delay it.

A: If your player movement is bounded by Core Animation, you can setup the setAnimationDidStopSelector to a custom STOP function and starts your AI there.
If you have a game loop with states, just add enough states (e.g. user_move_began, user_move_ended, ai_think_began, ai_think_ended, ai_move_began .. ) to sequence the flow.

A: I think I understand what you are saying now.
You need to do a CCSequence, with your AI function call in a CCCallFunc at the end:
CCSequence *playerMove = [CCSequence actions:
                          [CCMoveTo actionWithDuration: 0.4f position: CGPointMake(10,10)],
                          [CCCallFunc actionWithTarget: self selector: @selector(doAIstuff)],
                          nil];

[playerSprite runAction: playerMove];

You need to have your AI be a callable function (i.e. doAIstuff).  It is confusing to that you say the code is in draw().


text:
Q: My Stateless Component not rendering (Reactjs and Redux) For some reason or another, my allEmployees stateless component isn't being rendered and I can't figure out why. I'm getting the following warning:
Unknown prop employeesData on <allEmployees> tag. Remove this prop from the element.
Container
class employeeListPage extends React.Component {
 constructor(props) {
 super(props);
 this.state = {
    employees : {}
 };
}

render(){
  return(

        <allEmployees employeesData = {this.props.employees} />

  )
}

}
function mapStateToProps(state, ownProps){
 return{
    employees: state.employees
}
}

function mapDispatchToProps(dispatch){
 return {
    employeeActions : bindActionCreators(employeeActions, dispatch)
 };
}

export default connect(mapStateToProps, mapDispatchToProps )(employeeListPage);

allEmployees Component
 const allEmployees = (props) => (

             Employee Number
             Employee Full Name
             Active Employee
             Origin
             Modify
             Remove

      {props.employeesData.map( employee => {

                    {employee.Number}
                    {employee.FullName}
                    {employee.IsActive}
                    {employee.Origin}
                    <button>Modify</button>
                    <button>Remove</button>

      })};

);

export default allEmployees;

A: When it comes to the warning, have a look at the official React guidance: https://facebook.github.io/react/warnings/unknown-prop.html
This may also be caused by a recent library update. Try using a previous version. More info here:  https://stackoverflow.com/a/38177862/4186037
Also, in order to render React components, their names need to start with an upper-case letter: https://facebook.github.io/react/docs/jsx-in-depth.html#html-tags-vs.-react-components
Here is a demo showing that a component starting with a lower-case letter (article2) will not render: http://codepen.io/PiotrBerebecki/pen/YGxRqq
class App extends React.Component {
  render() {
    return (

        <Article1/>
        <article2/>

    );
  }
}

// this component will render as it starts with a capital letter
class Article1 extends React.Component {
  render() {
    return (

        Article1

    );
  }
}

// this component will not render as it starts with a lower case letter
class article2 extends React.Component {
  render() {
    return (

        article2

    );
  }
}

ReactDOM.render(
  <App />,
  document.getElementById('app')
);

A: I think you need your component to be pascal case, here is a jsfiddle
const AllEmployees = (props) => (

     working because pascal case

);

ReactDOM.render(
  <AllEmployees />,
  document.getElementById('container2')
);

You can also try it here, try renaming FormattedDate to formattedDate.

A: When a component name starts with lowercase, React treats it as a HTML tag. Try changing it to AllEmployees and it should work.


text:
Q: Django template variable default value not working I am using Django 3.2
I am passing a boolean flag to a Javascript function in my base template. However, when the variable is set, it seems the default value is still being used in my template logic.
Here is my code snippet:
/path/to/urls.py
urlpatterns = [
                # ...
                path('foo', TemplateView.as_view(template_name="foo.html", extra_context={'show_subscription_popup':0}), name='blog'),

                path('admin/', admin.site.urls),
              ]

/path/to/foo.html
{% block content %}
{{ show_subscription_popup}}
{% endblock content %}

{% block body_js %}

When I render the page, I see that the variable show_subscription_popup has the correct value of 0, which it is passed to the TemplateView, however, in the javascript, the code reads like this:
if (1){
   /* do something */
}

Why is the default value overwriting the value I passed to the template, and how do I resolve this issue?

A: The value of your show_subscription_popup variable is 0. It is stated in the documentation that:

If value evaluates to False, uses the given default. Otherwise,
uses the value.

And if you see bool(0) is False, i.e. 0 is a falsey value in python (In fact False is actually just a 0), hence your default of 1 is rendered.
Note that this rendering into JavaScript is a bad practice and makes you vulnerable to XSS attacks!! Instead I would do something like the follows:
{% block content %}
{{ show_subscription_popup}}
{% endblock content %}

{% block body_js %}

A: This is because 0 is a Falsy value in python, so show_subscription_popup is False and the default value is used instead.
Falsy values:

*

*Empty lists []

*Empty tuples ()

*Empty dictionaries {}

*Empty sets set()

*Empty strings ""

*Empty ranges range(0)

*Zero of any numeric type.

*Integer: 0

*Float: 0.0

*Complex: 0j

*None

*False

A: As default template tag documentation states:

If value evaluates to False, uses the given default. Otherwise, uses
the value.


text:
Q: Как сохранять ListView с множественным выбором в SharedPreferences В своем андроид-приложении я использую ListView с множественным выбором (multiplyChoice). Могу ли я сохранять выбранные элементы в SharedPreferences после выхода из приложения и затем восстанавливать их оттуда.

A: Вы можете это конвертировать в json
В результате у вас должно получиться что-то вроде этого и эту строку вы можете сохранить в sharedpreferences
{"id":"0","choices":{"choice_one":"abc","choice_two":"bbc"}},{"id":"1","choices":{"choice_one":"abc","choice_two":"bbc"}},{"id":"2","choices":{"choice_one":"abc","choice_two":"bbc"}}
Для этого вам нужно будет создать класс а потом список из этих классов преобразовать в json
Вот есть развернутый ответ по этому поводу:
Как и чем парсить Json на Java?


text:
Q: Existence of dense graph with relatively small codegree? Let $n$ be some parameter tending to infinity. I am wondering does there exists some kind of graphs $G$ on vertex-set $[n]$ with maximum degree less than $D$, so that

*

*$D\ge n/w_1(n)$,

*$e_G$, the number of edges of $G$ satisfies $e_G\ge\frac{nD}{2w_2(n)}$,

*maximum codegree $\max_{u,v\in V_G:u\neq v}|\{w:wv,wu\in E_G\}|\le D/w_3(n)$,

where $w_1,w_2,w_3\to\infty$ as $n\to \infty$, and $w_1,w_2\ll w_3$
? For $\ll$, I mean it will be good if $w_1,w_2$ are less than some power of $\log w_3$ or some small power of $w_3$. Definitely we assume $w_3$ less than some small power of $n$.

A: No. At least for $w_1,w_2$ polylog$(n)$ and $w_3 \geq n^{\epsilon}$ for some $\epsilon \in \Omega(1)$, there is no such graph.
Suppose otherwise. Pick the set $B$ of $b = 2w_1w_2\log n$ vertices of the highest degree in $G$. The sums of the degrees of these vertices has to be at least $\frac{bD}{2w_2} \geq n \log n$.
However, let for each vertex $u \in G$, let $N_B(u)$ be the number of neighbors that $u$ has in $B$. Then $\sum_{u \in V(G)} N_B(u)$ is the sums of the degrees of vertices in $B$ which is $\frac{bD}{2w_2}$ $\geq n \log n$.
Furthermore, $N_B(u)$ is upper-bounded by $b$. So there are at least
$(\frac{bD}{2w_2} - n)/b$ vertices $u$ adjacent to 2 or more vertices in $B$.
As $\frac{bD}{2w_2}$ is at least $n \log n$, it follows that $\frac{bD}{2w_2}-n$ is at least $\frac{bD}{4w_2}$, and so (*) there are at at least
$\frac{D}{4w_2}$ vertices $u$ adjacent to 2 or more vertices in $B$
However, the bound on the max codegree implies that (**) the number of vertices $u$ adjacent to 2 or more vertices in $B$ is no more than $\frac{b^2D}{w_3}$ which is $O(\frac{b^2D}{n^{\epsilon}})$ if $w_3 = n^{\epsilon}$.
However, note that $b$ is only polylog if $w_1$ and $w_2$ are polylog, so at most only one of (*) and (**) may hold if both $w_1$ and $w_2$ are polylog and $w_3$ is $\Omega(n^{\epsilon})$ for some $\epsilon \in \Omega(1)$.


text:
Q: why the use of mobx caused the onChange of the table twice? The first click on the page number will only trigger onChange once, and then click the page number will trigger twice.
codesandbox: https://codesandbox.io/s/late-shape-mznvvf?file=/demo.tsx
import "@arco-design/web-react/dist/css/arco.css";

import React from "react";
import { Table, TableColumnProps } from "@arco-design/web-react";
import { makeAutoObservable, runInAction } from "mobx";
import { observer } from "mobx-react";

class P {
  pagination = {
    current: 1,
    pageSize: 2
  };

  constructor() {
    makeAutoObservable(this, {
      onChange: false
    });
  }

  onChange(pagination) {
    runInAction(() => {
      this.pagination = pagination;
    })
    console.log("exec!");
  }
}

const columns: TableColumnProps[] = [
  {
    title: "Name",
    dataIndex: "name"
  },
  {
    title: "Salary",
    dataIndex: "salary"
  },
  {
    title: "Address",
    dataIndex: "address"
  },
  {
    title: "Email",
    dataIndex: "email"
  }
];
const data = [
  {
    key: "1",
    name: "Jane Doe",
    salary: 23000,
    address: "32 Park Road, London",
    email: "jane.doe@example.com"
  },
  {
    key: "2",
    name: "Alisa Ross",
    salary: 25000,
    address: "35 Park Road, London",
    email: "alisa.ross@example.com"
  },
  {
    key: "3",
    name: "Kevin Sandra",
    salary: 22000,
    address: "31 Park Road, London",
    email: "kevin.sandra@example.com"
  },
  {
    key: "4",
    name: "Ed Hellen",
    salary: 17000,
    address: "42 Park Road, London",
    email: "ed.hellen@example.com"
  },
  {
    key: "5",
    name: "William Smith",
    salary: 27000,
    address: "62 Park Road, London",
    email: "william.smith@example.com"
  },
  {
    key: "6",
    name: "Jane Doe",
    salary: 23000,
    address: "32 Park Road, London",
    email: "jane.doe@example.com"
  },
  {
    key: "7",
    name: "Alisa Ross",
    salary: 25000,
    address: "35 Park Road, London",
    email: "alisa.ross@example.com"
  },
  {
    key: "8",
    name: "Kevin Sandra",
    salary: 22000,
    address: "31 Park Road, London",
    email: "kevin.sandra@example.com"
  },
  {
    key: "9",
    name: "Ed Hellen",
    salary: 17000,
    address: "42 Park Road, London",
    email: "ed.hellen@example.com"
  },
  {
    key: "10",
    name: "William Smith",
    salary: 27000,
    address: "62 Park Road, London",
    email: "william.smith@example.com"
  }
];

const application = new P();

const App = observer(() => {
  return (
    <Table
      pagination={application.pagination}
      columns={columns}
      data={data}
      onChange={(pagination) => application.onChange(pagination)}
    />
  );
});

export default App;

why the use of mobx caused the onChange of the table twice?
know why the use of mobx caused the onChange of the table twice?


text:
Q: How to find coefficient of multiple binomial expansions quickly?
Find the coefficient of $(x^{-2})$ in the expansion of $(x-1)^3(\frac1{x}+2x)^6$

How can this be done quickly without expanding the two brackets?
I tried writing the general formula in terms of $r$ for both brackets and equated $-2$ to the sum of the powers of $x$ in terms of $r$.
$${3 \choose r}   (x^{3-r})  (-1)^r  {6 \choose r} \left(\frac1{x}^6-r\right)(2x)^r$$
I understand that there are multiple ways of getting $x^{-2}$, but shouldn't this be accounted for in the general formula method? (multiple $x^{-2}$ terms can be simplified to one number which should obey the general term formula).
I'd really appreciate your help;)

A: To convert to a more familiar form, multiply and divide by $x^6$:
$$(x-1)^3 (1+2x^2)^6 x^{-6}$$
Now you're looking for the coefficient of $x^4$ in $(x-1)^3 (1+2x^2)^6$. You can get $x^4$ out of this product either by multiplying $x^2$ with $x^2$ or $1$ with $x^4$. Each of those coefficients should be easy to calculate, then you just add them.

A: Here is a variation which goes consecutively through the factors expanding one by one up to terms which are needed ignoring other terms. We also start with the factors with greatest exponents which keep the number of terms which are to expand small.
It is convenient to use the coefficient of operator $[x^k]$ to denote the coefficient of $x^k$ in a series.

We obtain
  \begin{align*}
\color{blue}{[x^{-2}]}&\color{blue}{(x-1)^3\left(\frac{1}{x}+2x\right)^6}\\
&=[x^4](1+2x^2)^6(x-1)^3\tag{1}\\
&=[x^4]\left(1+\binom{6}{1}2x^2+\binom{6}{2}4x^4\right)(x-1)^3\tag{2}\\
&=\left([x^4]+12[x^2]+60[x^0]\right)(x-1)^3\tag{3}\\
&=12\binom{3}{2}(-1)+60\binom{3}{0}(-1)^3\tag{4}\\
&\,\,\color{blue}{=-96}
\end{align*}

Comment:

*

*In (1) we factor out $\frac{1}{x^6}$ and apply the rule $[x^{p-q}]A(x)=[x^p]x^qA(x)$.

*In (2) we expand the $(1+2x^2)^6$ up to terms which contribute to $[x^4]$. Other terms can be ignored.

*In (3) use the linearity of the coefficient of operator.

*In (4) we select the coefficients of $(x-1)^3$ accordingly.


text:
Q: SqlAlchemy and PostgreSql datetime update I have a PostgreSql table in which I want to update an attribute of type timestamp with timezone (I tried also without timestamp but it does not work). I'm using SqlAlchemy session for that purpose.
I fetch an existing record, and update it with a current timestamp:
from model import Table
from dbconf import session

t=session.query(Table).filter(Table.id==1).first()
t.available=datetime.now()
session.add(t)
session.commit()

After this command nothing change in the database. What am I doing wrong?

A: I can assume that you have model of this table, you should add there new update method like this:
class table(Base):
    __tablename__ = 'table'

    id = Column(Integer, primary_key=True)
    available = Column(DateTime)
    asd = Column(Unicode(255))

    def update(self, available=None, asd = None):  #etc.
        if available:
            self.available = available
        if asd:
            self.asd = asd

and updating happens then like this:
import transaction
with transaction.manager:
    t=session.query(Table).filter(Table.id==1).first() #search the object what you want to update
    t.update(available=datetime.now()) #you can update only one or several cell like this


text:
Q: How to remove a certain print to file feature of Devexpress document Viewer hi im just wondering when i tried to print the report on devexpress document viewer i found a weird feature that i donw really need in terms of functionality and i want to remove it is there a way to remove it??.. this is the feature that i want to remove kindly see image for reference

Is there a way to remove it? i spend hours looking for solution for this but i cant find it i just thought that you guys could possibly help me thank in advance

A: You can replace the DefaultPrintDialogRunner, returned by the PrintDialogRunner.Instance property, with a customized version of the SystemPrintDialogRunner or the DefaultPrintDialogRunner  class.
Here is the way to replace the default PrintDialogRunner:
using DevExpress.XtraEditors.Preview;
// ...
static void Main(string[] args) {
    PrintDialogRunner.Instance = new SystemPrintDialogRunner(); // !!!
    // ...
}

The code above will result that the PrintTool.PrintDialog method will invoke the standard system Print dialog:

Then you should create your own version of PrintDialogRunner that invokes the PrintDialogRunner.Run method with the the specific flags and use this class in the approach mentioned above:
class CustomPrintDialogRunner : DefaultPrintDialogRunner {
    public override DialogResult Run(PrintDocument document, UserLookAndFeel lookAndFeel,
        IWin32Window owner, PrintDialogAllowFlags flags) {
        // Disable the print-to-file option.
        flags &= ~PrintDialogAllowFlags.AllowPrintToFile;
        return base.Run(document, lookAndFeel, owner, flags);
    }
}
//...
PrintDialogRunner.Instance = new CustomPrintDialogRunner ();


text:
Q: Leader re-election without leader being down? Is there any accepted method of leader election in a distributed environment wherein the leader may change after every fixed interval of time(or rounds) without the current leader going down/disconnecting?
This may sound like a very wrong way but I do need to implement it but cannot find any research/reference.

A: I'm not immediately aware of any system that does this, since electing a leader when both the current leader is functioning properly and all functioning workers are able to talk to the leader (i.e. there is no network partition) is unnecessary overhead.
However, it should be easy to add this functionality to an existing system, such as Raft. Section 5.2 describes the leader election process. An election is only triggered when a worker does not receive a heartbeat from the leader for a certain amount of time (the election timeout). You can simply add a condition that also triggers an election when the fixed interval of time you reference in your question has passed.
You can modify other systems in a similar way to achieve the same result.


text:
Q: Layout Updates in theme.xml to pick up parent theme's xml I've created a theme package called hoi with a default theme.  In the app/design/frontend/hoi/default/etc/theme.xml I've set a parent theme to be the a theme we purchased called blacknwhite.
This almost works but it does not pick up the layout.xml from the blacknwhite theme as my own theme's xml overwrites it.  It works when I copy and paste the contents from the blacknwhite theme's xml into my own theme's xml.  But I would rather not do this as so I tried to create a new layout update in my theme's theme.xml.
theme.xml
<theme>
    <parent>blacknwhite/default</parent>
    <layout>
        <updates>
            <hoi_default>
                <!--should be linking to app/design/frontend/hoi/default/layout/parentslocal.xml-->
                <file>hoi/parentslocal.xml</file>
            </hoi_default>

            <hoi_default>
                <!--should be linking to app/design/frontend/hoi/default/layout/local.xml-->
                <file>hoi/local.xml</file>
            </hoi_default>
        </updates>
    </layout>
</theme>

This way I hoped to have my own local.xml for my theme which would fall back onto a parentslocal.xml which I would then copy the contents of the parents local.xml to. But it's not working.
I tested it by putting the below in my local.xml but it did not work.
<layout version="0.1.0">
    <default>
        <reference name="header">
            <remove name="cart_sidebar"/>
        </reference>
    </default>
</layout>

I would have thought Magento would inherit from it's parent's theme more seamlessly.
I'm thinking it is perhaps better off putting my sub theme in blacknwhite/hoi!

A: I found the problem was with my syntax, as per Alan Storms post on infinite theme's fallaback the proper syntax is:
<?xml version="1.0"?>
<theme>
    <parent>rwd/enterprise</parent>
    <layout>
        <updates>
            <my_new_file_name>
                <file>my_new_file_name.xml</file>
            </my_new_file_name>
        </updates>
    </layout>
</theme>

So in my case this meant I needed:
<theme>
    <parent>blacknwhite/default</parent>
    <layout>
        <updates>
            <parentslocal>
                <!--should be linking to app/design/frontend/hoi/default/layout/parentslocal.xml-->
                <file>parentslocal.xml</file>
            </parentslocal>
        </updates>
    </layout>
</theme>


text:
Q: Icon in createMaterialBottomTabNavigator isn't showing I'm trying to set up a MaterialBottomTabNavigator in my app with custom icons using react-native-vector-icons, but the icons are not showing up. Am I doing something wrong in the NavigatorConfig?
At first I thought it was because my icons aren't loading in correctly, but placing them in a View on another screen (anywhere but inside the MaterialBottomTab) makes them show up no problem. Even the standard MaterialIcons provided with vector-icons aren't showing up in the bottomTab, but any other place is no problem.
I've tried shifting the configs around, placing the tabBarIcon in both the screen config, aswell as the navigator config, but still no result.
I've also tried the showIcon option, but also no results.
Here's my code right now:
export const userNavigation = createMaterialBottomTabNavigator({Bars, Settings}, {
    Bars: {
        screen: Bars,
        navigationOptions: {
            tabBarIcon: ({focused}) => <Icon name="bars" size={20} color={focused ? '#FFF' : '#DACE91'}/>,
        },
    },
    shifting: false,
    labeled: true,
    activeColor: '#FFF',
    inactiveColor: '#DACE91',
});

I expect the icons to show up in the bottomTab, but I get no error messages or any other feedback as to why they aren't showing.

A: You are putting in the tab configs the route configs.
createMaterialBottomTabNavigator({
                                Bars:{
                                    screen: Bars,
                                    navigationOptions:{
                                                      tabBarIcon: ({focused}) =><Icon name="bars" size={20} color={focused ? '#FFF' : '#DACE91'}/>,
                                          }
                                     }
                                },{
                                    shifting: false,
                                    labeled: true,
                                    activeColor: '#FFF',
                                    inactiveColor: '#DACE91',
                                   })

Hopefully this will help!

A: to fix then icon
  add these in bootom navigation
   shifting: false,
    labeled: true,


text:
Q: If statement in Excel to recognize a leap year How could I write a If statement in Excel to divide a cell by 2088 if it is a leap year, and if it is not a leap year divide the same cell by 2080?

A: If you put this in A2:
=IF(OR(MOD(A1,400)=0,AND(MOD(A1,4)=0,MOD(A1,100)<>0)),2088, 2080)

And then put the year you care about in A1 and your value in B1 and then do:
=B1/A2

See this Technet article for further info (I used the IF statement from there as a base).
Edit: Or do you mean that you want to divide the year by that value? If so add the following in any cell but A1:
=IF(OR(MOD(A1,400)=0,AND(MOD(A1,4)=0,MOD(A1,100)<>0)), A1 / 2088, A1 / 2080)

And put the year in A1.

A: In GREGORIAN CALENDAR most years which are multiple of 4 are leap years.
But three leap years are omitted every 400 years.
So in order to be a leap year, the year should be divisible by 4 except the centennial years, which are not divisible by 400.
for eg. 2000 was a leap year but 2100,2200 and 2300 will not be.
And to be more precise check this link
http://support.microsoft.com/kb/214019


text:
Q: After importing MySQL db I can no longer log in to phpMyAdmin Not paying attention, I exported a database from a MySQL 5.5 server, and imported it into a MySQL 5.1 server.  Both via phpMyAdmin.
No errors were reported in any logs.  I was also immediately able to browse the database as well.
No other changes have been made to the servers or the software.  However, following that event, I am unable to log into MySQL via phpMyAdmin using any available login.
I am able to log in via console, and have dropped the added database with no effect.  I have also updated the max_allowed_packet size to 16M per other recommended steps also to no avail.
When I try logging in, I get the following message: "#2006 Cannot log in to the MySQL server".
I have not been able to locate any additional information regarding fixes for this.  Any recommendations?
Options currently under consideration:

*

*Upgrade phpMyAdmin

*Upgrade MySQL (needed as well as required for item 1)

A: Have you tried changing your max_allowed_packet size to a bigger value, such as 100M?

A: I have not been able to determine the exact cause of this issue, but a fresh install of the same version of phpMyAdmin (installed to a new folder) fixed the issue.
Thanks for the willing assistance.
Next up: upgrading the MySQL server.


text:
Q: H2 database tcp remote via Shell: SQL Exception: Connection is broken: "java.net.SocketTimeoutException: connect timed out" Java (Servlet 3.1 webapp in Tomcat 8.5):
org.h2.tools.Server web = Server.createWebServer("-ifExists", "-webSSL", "-webPort", "8085", "-webAllowOthers").start();
org.h2.tools.Server tcp = Server.createTcpServer("-ifExists", "-tcpSSL", "-tcpPort", "8089", "-tcpAllowOthers").start();

The H2 Console runs fine over the web after making adjustment in the properties file.
Running Shell from command line in a different machine:
$ java -cp h2-2.1.210.jar org.h2.tools.Shell

URLs I've tried (all failed):
jdbc:h2:tcp://mySite.net//Users/xyz/tomcat/webapps/ROOT/WEB-INF/database/myh2db;IFEXISTS=TRUE;MODE=MySQL;CASE_INSENSITIVE_IDENTIFIERS=TRUE
jdbc:h2:tcp://mySite.net/Users/xyz/tomcat/webapps/ROOT/WEB-INF/database/myh2db;IFEXISTS=TRUE;MODE=MySQL;CASE_INSENSITIVE_IDENTIFIERS=TRUE
jdbc:h2:tcp://mySite.net:8089/Users/xyz/tomcat/webapps/ROOT/WEB-INF/database/myh2db;IFEXISTS=TRUE;MODE=MySQL;CASE_INSENSITIVE_IDENTIFIERS=TRUE
jdbc:h2:tcp://mySite.net:8089/file:/Users/xyz/tomcat/webapps/ROOT/WEB-INF/database/myh2db;IFEXISTS=TRUE;MODE=MySQL;CASE_INSENSITIVE_IDENTIFIERS=TRUE
jdbc:h2:tcp://mySite.net:8089//file:Users/xyz/tomcat/webapps/ROOT/WEB-INF/database/myh2db;IFEXISTS=TRUE;MODE=MySQL;CASE_INSENSITIVE_IDENTIFIERS=TRUE
jdbc:h2:ssl://mySite.net//Users/xyz/tomcat/webapps/ROOT/WEB-INF/database/myh2db;IFEXISTS=TRUE;MODE=MySQL;CASE_INSENSITIVE_IDENTIFIERS=TRUE
jdbc:h2:ssl://mySite.net/Users/xyz/tomcat/webapps/ROOT/WEB-INF/database/myh2db;IFEXISTS=TRUE;MODE=MySQL;CASE_INSENSITIVE_IDENTIFIERS=TRUE
jdbc:h2:ssl://mySite.net:8089/Users/xyz/tomcat/webapps/ROOT/WEB-INF/database/myh2db;IFEXISTS=TRUE;MODE=MySQL;CASE_INSENSITIVE_IDENTIFIERS=TRUE
jdbc:h2:ssl://mySite.net:8089/file:/Users/xyz/tomcat/webapps/ROOT/WEB-INF/database/myh2db;IFEXISTS=TRUE;MODE=MySQL;CASE_INSENSITIVE_IDENTIFIERS=TRUE
jdbc:h2:ssl://mySite.net:8089//file:Users/xyz/tomcat/webapps/ROOT/WEB-INF/database/myh2db;IFEXISTS=TRUE;MODE=MySQL;CASE_INSENSITIVE_IDENTIFIERS=TRUE

Shell gives same result every time (no log elsewhere to be found):
SQL Exception: Connection is broken: "java.net.SocketTimeoutException: connect timed out"

No lock on the db was seen.
What am I missing?
UPDATE
After opening port 8089 on router, the following formats work:
jdbc:h2:tcp://mySite.net:8089/file:/Users/xyz/tomcat/webapps/ROOT/WEB-INF/database/myh2db;IFEXISTS=TRUE;MODE=MySQL;CASE_INSENSITIVE_IDENTIFIERS=TRUE
jdbc:h2:tcp://mySite.net:8089//Users/xyz/tomcat/webapps/ROOT/WEB-INF/database/myh2db;IFEXISTS=TRUE;MODE=MySQL;CASE_INSENSITIVE_IDENTIFIERS=TRUE

Any URL using ssl fails with:
SQL Exception: Connection is broken: "javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target

Since port 8443 is already in use, I am unable to bind it to the TcpServer for ssl. I need to learn to open up another SSL/HTTPS port on Tomcat for H2 tcpSSL.


text:
Q: Does firebase/firestore no longer support method chaining? It's been a while since I used firebase and it looks like things have changed. Previously, I could do something like this (using method chaining):
const app = firebase.initializeApp(firebaseConfig);
const db = app.firestore();

const itemQuerySnapshot = db
    .collection('companies')
    .doc(data.userData.company)
    .collection('items')
    .get()

But now, it seems that's no longer supported (or perhaps the Typescript typings have changed for the latest version). With the latest version, method chaining appears out of the picture.
So my question is: which version of firebase supports the kind of method chaining shown in the code above so that I can downgrade to it.
I'd also appreciate it if someone can help explain the benefits (if any) of the current pattern used in the latest version of firebase.

A: It's not completely clear from your question, but I'm assuming you've upgraded to v9 of the SDK, which uses a new modular syntax.
If you want to use the new SDK with the older syntax, you can use its compat modules as explained here.
If you want to stick to the older SDKs entirely, the 8.x are the latest SDK versions that support the older syntax.
I recommend reading more about the new modular SDKs here:

*

*Introducing the new Firebase JS SDK

*The new Firebase JS SDK is now GA

*Upgrade from version 8 to the modular Web SDK


text:
Q: GridView out of memory error I use GridView to display thumbnails from MediaStore.
If I launch and close my application 2-3 times it crashes with out of
memory error.
System.gc() is called in onCreate of main activity.
If comment call setImageURI then no errors.
Maybe I need to explicitly clear memory somehow?
Please, help.
   public View getView(int position, View convertView, ViewGroup parent){
           ImageView i;
           if (convertView == null) {
                   i = new ImageView(activity.getApplicationContext());
                   i.setLayoutParams(new GridView.LayoutParams(92, 92));
                   i.setScaleType(ImageView.ScaleType.CENTER_CROP);
           } else {
                   i = (ImageView) convertView;
           }
           Uri imageUri = thumbUri(position);
           i.setImageURI(imageUri);   //  <--- no error if this string is commented
           return i;
   }

A: I got it. My solution based on Francesco answer, but onPause instead of onDestroy.
@Override
protected void onPause() {
    GridView gridView = (GridView) findViewById(R.id.public_photos);
    int count = gridView.getCount();
    for (int i = 0; i < count; i++) {
        ImageView v = (ImageView) gridView.getChildAt(i);
        if (v != null) {
            if (v.getDrawable() != null) v.getDrawable().setCallback(null);
        }
    }
    super.onPause();
}

A: It seems you are leaking memory elsewhere.
Try to remove all callbacks from your ImageView with something like this:
@Override
protected void onDestroy(){
    super.onDestroy();

    int count = gridView.getCount();
    for (int i = 0; i < count; i++){

        final ImageView v = (ImageView) gridView.getChildAt(i);
        v.getDrawable().setCallback(null);
    }

}


text:
Q: On the density of colossally abundant numbers. Define $\sigma(n) = \sum_{d\mid n} d$. A integer $n>1$ is said to be colossally abundant (CA) if there exists some exponent $\varepsilon > 0$ such that $$\frac{\sigma(n)}{n^{1+\varepsilon}} \geq \frac{\sigma(m)}{m^{1+\varepsilon}}$$ for every integer $m>1$. Let $p_{k} >20000$ be the largest prime factor of the CA number $n$. Is it necessarily true that $n \in [N_k, N_{k+1})$ where $N_j$ denotes the product of the first $j$ primes ?
P.S.: This result was stated without proof on page 206 of http://zakuski.utsa.edu/~jagy/Robin_1984.pdf, so either it's completely trivial or an assumption.

A: Thank you for providing the exact reference!
My translation of the relevant passage is: "Consequently, if $N_k \le n < N_{k+1}$, with $p_k \ge 20000$, we have: [displayed equation]. If $n\le N_{k_1}$ [note the subscript is $k_1$, which I missed earlier], we use the results calculated by computer in Proposition 3 of Section 3." In the first line of the proof (same page), Robin writes: "Let $N_k = \prod_{i=1}^k p_i$ [he writes $p_k$ but surely that is a typo] and suppose that $p_k \ge 20000$ ($k\ge k_1$).", which I believe is the implicit definition of the integer $k_1$.
So I believe what is happening is:

*

*if $n$ is at most $N_{k_1}$, which is the product of all the primes up to $20000$, then the computer results are relevant;

*otherwise, there exists some integer $k\ge k_1$ such that $N_k \le n < N_{k+1}$, in which case the displayed equation is relevant.

In the OP, it is claimed that $n$ is colossally abundant and that $p_k$ is its largest prime factor; but I don't believe that either statement is necessarily true in the context of this remark. Rather, $n$ is any integer at all, and $p_k$ is only mentioned to help clarify what $N_k$ is.


text:
Q: Proper cross validation for stacking models Lets assume that we have dataset that contains continuous variable $Y$ which we want to predict and 10 predictors $X_{1}, ..., X_{10}$. The number of observations is $n=1000$. I have questions about proper cross validation in two following situations:

*

*I want to add variable $X_{11}$ which is equal to average of $Y$ from 10 nearest observations (the metric is not important). On this extended dataset I would like to make linear regression. What is the proper way of CV (kfold for $k=5$)?

*

*Add $X_{11}$ using whole data set and then do 'normal' kfold cross validation? In such situation some information about test set will be included in training part so there will be bias in error.

*Add $X_{11}$ separately in each fold using only training data. But then the question is how to add $X_{11}$ in test set, should only test set be used? Because of number of cases in test dataset the variable $X_{11}$ might be biased.

*Two models were built (for example: random forest and gradient boosting machine) and now want to make linear blending of those two models. What predictions from the model should be put as predictiors? One solution is:

*

*Split data set into train/test (800/200), build those two models using training dataset and the blend those probabilities and test final predictions on test dataset. Repeat that 5 times for different folds in test dataset.
I believe that this solution might not be perfect because random forest tends to overfit on training data set. I feel that it would be better to blend probabilities not from training data set. To overcome this one might do following:

*Split data set into train/test (800/200). Then do kfold CV on the training data set and use as predictor out of bag estimates (so the split is 640/160). This is much more time consuming solution, but should be more reliable. The drawback is that if we want to make kfold cross validation for k=5 then in the models that are input for blending we will have 16/25 example in the training dataset.

I strongly believe that both cases are well known, but I would like to know what is the state of the art in that matter.

A: Question 1: local prediction & cross validation
Looking for closeby cases and upweighting them for prediction is referred to as local models or local prediction.
For the proper way to do cross validation, remember that for each fold, you only use training cases, and then do with the test cases exactly what you do for prediciton of a new unkown case.
I'd recommend to see the calculation of $X_1$ as part of the prediction. E.g. in a two level model consisting of a $n$ nearest neighbours + a second level model:

*

*For each of the training cases, find the $n$ nearest neighbours and calculate $X_{11}$

*Calculate the "2nd level" model based on $X_1, ..., X_{11}$.

So for prediction of a case $X_{new}$, you

*

*find the $n$ nearest neighbours and calculate the $X_{11}$ for the new case

*then calculate the prediction of the 2nd level model.

You use exactly this prediction procedure to predict the test cases in the cross validation.

Question 2: combining predictions

random forest tends to overfit on training data set

Usually random forest will overfit only in situations where you have a hierarchical/clustered data structer that creates a dependence between (some) rows of your data.
Boosting is more prone to overfitting because of the iteratively weighted average (as opposed to the simple average of the random forest).
I did not yet completely understand your question (see comment).
But here's my guess:
I assume you want to find out the optimal weight you should use for random forest and boosted prediction, which is a linear model of those two models.
(I don't see how you could use the individual trees within those ensemble models because the trees will totally change between the splits). This again amounts to a 2 level model (or 3 levels if combined with the approach of question 1).
The general answer here is that whenever you do a data-driven model or hyperparameter optimization (e.g. optimize the weights for random forest prediction and gradient boosted prediction by test/cross validation results), you need to do an independent validation to assess the real performance of the resulting model. Thus you need either yet another independent test set, or a so-called nested or double cross validation.

*

*So the 1st approach would not work unless you derive the weights from the training data.

*As you point out for the 2nd approach, having more and more levels of cross validation needs huge sample sizes to start with.

I'd recommend a different approach here: try to cut down as far as possible the number of splits you need by doing as few data-driven hyperparameter calculations or optimizations as possible. There cannot be any discussion about the need of a validation of the final model. But you may be able to show that no inner splitting is needed if you can show that the models you try to stack are not overfit. In addition this would remove the need to stack at all:
Ensemble models only help if the underlying individual models suffer from variance, i.e. are unstable. (Or if they are biased in opposing directions, so the ensembe would roughly cancel the individual biases. I suspect that this is not the case here, assuming that your GBM uses trees like the RF.)
As for the instability, you can measure this easily by repeated aka iterated cross validation (see e.g. this answer). If this does not point to substantial variance in the prediction of the same case by models built on slightly varying training data (i.e. if your RF and GBM are stable), producing an ensemble of the ensemble models is not going to help.

A: Question 1:
This is really similar to what is called KFold Target Encoding, and a correct way to do it is explained here:
https://medium.com/@pouryaayria/k-fold-target-encoding-dfe9a594874b
Your encoding is slightly different than what is describe in the article above, but you can apply the same design.


text:
Q: Linearity and nonlinearity of a system Is $y(t)=\sin(t)$ and $y(t)=\cos(t) \, u(t)$ linear or nonlinear system?
İn many resources about linear systems, the relation between $y(t)$ and $u(t)$ is examined. For the first system, there is no $u(t)$ part hence should I think $u(t)=1$ for the first system? Thanks.

A: A linear function $y(t)$ must satisfy two properties:

*

*Additivity: $y(t_1+t_2) = y(t_1) + y(t_2)$

*Homogeneity: $y(\alpha t) = \alpha y(t)$
Since, $sin(t_1+t_2) \neq sin(t_1) + sin(t_2)$ and $cos(t_1+t_2) \neq cos(t_1) + cos(t_2)$, then $sin(t)$ and $cos(t)$ violate the additivity property and are therefore not linear.
However, the term linear in your case is used to denote how the input $u(t)$ affects an output $y(t)$. So in your example $y(t) = cos(t) u(t)$, we can think of $y$ as having two arguments: $t$ and $u$, such that $y = y(t,u)$. Now we can see that  $y(t,u)$ is a linear function with respect to $u$ by looking at the additivity and homogeneity properties:

*

*$y(t,u_1+u_2) = cos(t)(u_1+u_2) = cos(t) u_1 + cos(t) u_2 = y(t,u_1) + y(t,u_2)$

*$y(t,\alpha u) = cos(t)\alpha u = \alpha cos(t)u = \alpha y(t,u)$


text:
Q: Doing a simple search I am doing a simple search, would the following query be correct?
mysql_query("SELECT * FROM products WHERE name LIKE'$searchquery' AND description LIKE'$searchquery'");

EDIT:
LIKE '$searchquery; this part needed a space, it turns out it was a syntax issue. I am quite intrigued by doing it the second way. As suggested by @yes123.
SELECT * FROM products WHERE MATCH(name,description) AGAINST ('$searchQuery')

I do this and I get:
Warning: mysql_numrows(): supplied argument is not a valid MySQL result resource in /home/search.php on line 62

A: For searching purpouse you should use a FULL TEXT index. At that point your query becomes something like:
[...] WHERE MATCH(col1,col2) AGAINST ('your search') [...]

And please use PDO

A: Yes the syntax is correct, only problem seems to be is with spaces after LIKE, hence try
SELECT * FROM products WHERE NAME LIKE '$searchquery' AND description LIKE '$searchquery';

A: That would be correct, however, you need to put a space between LIKE and '$searchquery' in both places.


text:
Q: Why not put a space between commands and parameters? I hope this is just a matter of taste, but is there any reason not to separate a command from its first parameter with a space? (Or multiple parameters with intervening spaces for that matter.)
\chapter{Introduction}
\chapter {Introduction}

\setcounter{chapter}{2}
\setcounter {chapter} {2}

I like the second ones better. This makes prose more readable to me. I was wondering if this can get me into trouble, though.

A: The space after a command name is absorbed while parsing the command name and does not make a token at all. The space between the } { does make a character token, but space tokens are skipped when looking for macro arguments so it is fine to put in the spaces if you wish.
\setcounter {chapter} {2}

Note there is a difference between these spaces; if you go
\newcommand\foo{%
    \setcounter {chapter} {2}%
}

In that here, the space after \setcounter really isn't there in the definition of \foo but the space after {chapter} is there, there is a character token so TeX needs to record its value (32) and catcode (10) (although I have a feeling it optimises spaces somewhere, no doubt someone will post the exact line of tex.web)  in any case the definition is one or two bytes bigger because of the space. It is unlikely that your documents are big enough that an extra byte will make you run out of memory, but this was a real issue when LaTeX was designed, which is why if you look at the sources of latex and most of the core packages you will see a coding style in which all removable braces and spaces are removed. That doesn't necessarily mean it's a good coding style now:-)


text:
Q: Show build configuration in Xcode I have a project (C++ project within XCode 5) with multiple build configurations that I regularly switch between. Currently, to see the active configuration I have to click on the scheme and select 'Edit Scheme...' to view/change the configuration. It'd be nice to put this information somewhere more visible, or access it with a hotkey. Is this possible?

A: You can use Command+Shift+< to open the "Edit Scheme...". You can change the hotkey in XCode->Preference->KeyBindings->Menu->Product Menu->Scheme-EditScheme

A: Another option that I like is to create multiple schemes. Manage schemes and select your production scheme. Click the + button to add another scheme and name it with a -Dev postfix. Select the appropriate configuration.
Now you'll have multiple schemes that can be selected from the popup-menu easily for running and archiving.

Also by using this method, stored binaries in the Archive are tagged with the scheme name which can be useful.


text:
Q: js- can i authenticate a user into my app using OAuth with only javascript->clientside, and js/java->server side? I want to use OAuth in one of my apps, specifically a Google Chrome extension. Can it be done through JavaScript code?  My only requirement is that it should be done with client side Javascript code, and the server can use either JavaScript or Java.
If this cannot be done, then can I use simple userid-password authentication?
Again, my only requirement is that it should be done with client side Javascript code, and the server can use either javascript or java.

A: You can definitely use OAuth in a Google Chrome extension, although bear in mind that your application keys and secrets will be readable in the bundle.
For more information: http://code.google.com/chrome/extensions/tut_oauth.html (the example uses one of Google's API enpoints but you could use any OAuth1.0a provider). Since you are interested in doing a Chrome extension you will not be affected by the normal hassle of request origin (cross site scripting) restrictions.
You can use "normal" userid and password authorization as well of course (especially over SSL/HTTPS). If you plan on going public with the APIs then I would recommend OAuth though.

A: JavaScript is pure client side scripting language. It cant be used in server side.
Second, If you want your client get authenticated  there must be a server side program to do so.


text:
Q: Looping over array that includes promises im building an angularjs application, were in
$scope.list Arary items are stored, that are created by a specific ngResource factory. I delete some items on the fly by simply slicing them from the list.
$scope.list.splice(pos,1);

Later in code I iterate over existing elements and want to save them with :
for (var elem in $scope.list ){
     $scope.list[elem].$save();
 }

The Problem is that, if the list is empty i have an $promise in the $scope.list
How should i process, so that the save is not called for the element that just have an promise?

A: You should start by filtering your array and then save the items in the filtered array:
$scope.list
.filter(function (elem) {
  return typeof elem.then !== 'function';
})
.forEach(function (elem) {
  elem.$save();
});


text:
Q: Set theory, images and preimages Let f:X→Y.
a)Show that f^−1(f(A)) ⊇ A for all A ⊆ X, and show that these two sets can be unequal.
b)Show that f(f^−1(B))⊆B for all B⊆Y
I would be very appreciative if someone can help me in these questions and help me on how to approach these exercises since i find this chapter quite challenging and i am not confident in my abilities

A: Try to visualise what is going on by taking an example of any subset and function to know the intuition what is going on and do practice. It will help.
1st part:
Suppose x $\subseteq$ A.
Then f(x)$\subseteq$ f(A)
Imply $f^{-1}f(x)$ $\subseteq$ $f^{-1}f(A)$.
There can be more than one element belonging to $f^{-1}f(x)$.
But atleast x $\in$ $f^{-1}f(x)$.
So x belong to $f^{-1}f(A)$.
Imply E$\subseteq$$f^{-1}f(A)$
Second part
Suppose $$y\in ff^{-1}B$$
Then y=f(x) for some element x in $f^{-1}(B)$
But this imply y=f(x) and y belongs to $ff^{-1}B$
Imply y=f(x) and $f(x)\in B$.
Imply $y \in B$.
And hence $f(f^{-1}B)$$\subseteq$ B.


text:
Q: CDT compare broken? Help. I have been relying on the compare editor for code review, and it mostly works quite well.
But for some reason, on some files, it is giving me inconsistent results and telling me that some code is different when it is not. It can't seem to deal with commented out code in this file.
It tells me that later functions are different and tries to match lines in those functions.
I have also found cases where it simply thinks the code is different but it is not.
It then decides that there must be changes in hundreds of lines below this.
I am able to work around by remove the code with #if 0, #endif, but it is not pretty.
Has anyone else seen this and do you know of any way to fix it?
I am trying to get a clean diff do I can see just the actual changes between the files.
It is driving me to drink - and it is still early in the day!


text:
Q: Copy and reverse char* in the C++ I would like to copy reversed char* to the another char*. I miss one letter in the second line of the output.
I did:
#include <iostream>

using namespace std;

void cp(char *str2, char *str1){
    char *pom1 = str1;
    while(*pom1){
        pom1++;
    }
    char* pom2 = str2;
    while(*pom1 != *str1){
         pom1--;
        *pom2 = *pom1;
         pom2++;
    }
    *pom2 = '\0';
}

int main()
{
    char *str1 = "ppC", str2[10] = "Witaj";
    cout << "Napis str2 "<< str2 << endl;
    cp(str2,str1);
    cout << "Napis str2 "<< str2 << endl;
    cp(str2,"CJP");
    cout << "Napis str2 "<< str2 << endl;
    return 0;
}

and the output is:
Napis str2 Witaj
Napis str2 Cp
Napis str2 PJC

While it should be:
Napis str2 Witaj
Napis str2 Cpp
Napis str2 PJC

A: The bug is in this statement of the function
while(*pom1 != *str1){

There must be
while( pom1 != str1){

Take into account that string literals have type of constant arrays. So for example variable str1 has to be declared as
const char *str1 = "ppC";

Also the function should be declared as
void cp( char *str2, const char *str1 );

Also It will be useful to know that there is standard algorithm std::reverse_copy declared in header <algorithm>:)

A:
There's reverse_copy in the stdlib

... and that it's used like:
template <typename CharT, size_t Ndest>
void cp(CharT (&dest)[Ndest], CharT const *src){
    auto f = src, l = src + std::strlen(src);
    assert(std::distance(f,l) < Ndest);
    *(std::reverse_copy(f, l, dest)) = '\0';
}

So, see it Live On Coliru
#include <iostream>
#include <algorithm>
#include <cstring>
#include <cassert>

template <typename CharT, size_t Ndest>
void cp(CharT (&dest)[Ndest], CharT const *src){
    auto f = src, l = src + std::strlen(src);
    assert(std::distance(f,l) < Ndest);
    *(std::reverse_copy(f, l, dest)) = '\0';
}

#include <iostream>

int main()
{
    char str1[]   = "ppC";
    char str2[10] = "Witaj";

    std::cout << "Napis str2 "<< str2 << std::endl;
    cp(str2, str1);
    std::cout << "Napis str2 "<< str2 << std::endl;
    cp(str2,"CJP");
    std::cout << "Napis str2 "<< str2 << std::endl;
    return 0;
}

A: Just use the Standard Library, std::reverse_copy() in this case:
std::reverse_copy( input , input + strlen( input ) , output );

A: copy paste solution
int len(const char *p) {
    int c = 0;
    while (*p != '\0')
    {
        c++;
        p++;
    }
    return(c);
}

void cp(char *str2, const char *str1){
if(!(len(str2)<len(str1))){
   const char *pom1 = str1;

    while(*pom1){
        pom1++;
    }
    char* pom2 = str2;
   while( pom1 != str1){
         pom1--;
        *pom2 = *pom1;
         pom2++;
    }
    *pom2 = '\0';
}
}


text:
Q: ajax and linked resources There must be something I don't understand about ajax. I want to display part of page (page B) on another page (Page A) using ajax. But linked page (page B) depends on some linked resources (page C) and these resources don't display on the original page (Page A). Is there anyway around this?
Here's the script (from Page B) I want to display on the original page (page A) using ajax:
echo "
To comment, please first prove that you are human being
";
echo "<form method='post' action='../recapatcha_verify.php'>";
 require_once('../../phpfunctions/recaptchalib.php');
  $publickey = "key"; // you got this from the signup page
 echo recaptcha_get_html($publickey);
 echo "<input type='submit' />";
    echo "</form>"

When this page is called through ajax -- the
 element shows up as well as the form and submit button. But the recapatcha widget accessed through linked resource (page C) does not show up. I know script works however, because if I load the page itself (page B) everything is fine.
Any thoughts? suggestions? thanks

A: Your recaptcha is likely injected into the page by running a script.


text:
Q: Jquery firing function once per element So, I have a small table with some content, which with the click of a button can be expanded to show a container div with extra content.
I'm trying to tie a function to this action, but when I do, the function seems to get fired once per number of table row.
JSFiddle:
https://jsfiddle.net/jtby9c12/
Table:
<button id="toggle-descriptions-button">+</button>

      Download
      Size
      Notes

        Item

Description Text

      1.2MB
      Note

*The actual table contains 22 rows and descriptions, this just shows the structure sample.
Jquery:
var descriptions = $(".div-container")
var descButton = $("#toggle-descriptions-button")

descButton.click(function(){
    console.log("Button Clicked!")
    descriptions.toggle(400, function() {
        console.log("I'm a fucntion!")
    });
});

As you can see, it calls the function 22 times, and I'm trying to get it to call just once.

I'm looking to get a single call back for the function, it's one state change for all descriptions, I only need one return.

A: To achieve this you can use the promise() returned from the toggle() calls. Attach a done() event handler to it, which will fire after all the promises have been resolved:

var $descriptions = $(".div-container")
var $descButton = $("#toggle-descriptions-button")

$descButton.click(function() {
  console.log("Button Clicked!")
  $descriptions.toggle(400).promise().done(function() {
    console.log("I'm a function!")
  });
});

<button id="toggle-descriptions-button">+</button>

      Download
      Size
      Notes

      Item

Description Text

      1.2MB
      Note

      Item

Description Text

      1.2MB
      Note

      Item

Description Text

      1.2MB
      Note