text:
Q: Equilibrium of differential mass element of a homogeneous rod hanging from ceiling I was solving a question that asked me to find the change in length of a rod when it is hung from the ceiling. When I saw the solution, they took some differential elements and said that a force due to the mass of the rod below the element would cause the extension and they integrated it but I had done the opposite. I took differential element but thought that the mass of the rod above the element will be compressing it and even the answer was the same.
This also made me question another thing If I take a differential element in the rod and since it is in equilibrium then the mass of the upper part(shown in blue) should be equal to the mass of the part below it(shown in green) but since the rod is homogeneous it is clearly visible that it is not.
Why is it so?

A:
...but thought that the mass of rod above the element will be
compressing it...

It is not. But that would be the case if the bar was resting in the floor, instead of hanging from the ceiling. The situation is symmetric, so its expected to reach the same differential equation.

since it is in equilibrium than the mass of upper part(shown in blue)
should be equal to the mass of part below it(shown in green)

What matters is the equilibrium of forces, not masses. The force of the bottom part over the element is indeed proportional to its mass ($m_bg$). But the force of the upper part over the element is not related to its (the upper part) mass.

A: The equation of indefinite equilibrium for a continuum reads
$\mathbf{0} = \rho \mathbf{g} + \nabla \cdot \mathbb{T}$,
being $\rho$ the density, $\mathbf{g}$ the field of volume forces, $\mathbb{T}$ the stress tensor.
If we assume a 1D model of an elastic beam in the regime of small displacement is a good model of the system, the vertical component of the equation of equilibrium can be recasted as
$0 = m g +  N'$,
being $m$ the mass per unit length of the beam, and $N$ the internal axial action, that can be written as $N = EA w'$ using the elastic constitutive law, being $EA$ the axial stiffness and $w(x)$ the axial displacement of the field.
Prescibing the boundary conditions $w(0) = 0$ and $EA w'(\ell) = 0$, we can solve the differential equation
$EA w''(z)  = -mg$
and find the solution
$w'(z) = -\dfrac{mg}{EA}(z - \ell)$
$w(z) = -\dfrac{mg}{EA}\left(\dfrac{1}{2}z^2 - \ell z \right)$


text:
Q: Regression table in R with stargazer for multiple columns and robust standard errors I'm trying to create a nice regression table in R with stargazer but using robust standard errors. I have no problem in doing this for a single model, but I have no idea how to do it for multiple models which should be integrated into the same regression table. My code looks like this for the case of normal standard errors:
stargazer(ols1, ols2, title = "Results", align = TRUE,
          add.lines = list(c("Controls", "No", "Yes")),
          covariate.labels=c("Bitcoin quantity", "Monetary Policy-related Interest Rate",
                             "Unemployment Rate", "GDP per Capita"),
          dep.var.labels=c("Domestic Retail Lending to GDP"), no.space=TRUE,
          type = "text")

However, I need robust standard errors for both models, i.e. ols1 and ols2. I've tried the following alternatives:
#robust standard errors option A
stargazer(coeftest(ols1, vcovHC), title = "Results", align = TRUE, add.lines = list(c("Controls", "No", "Yes")), covariate.labels=c("Bitcoin quantity", "Monetary Policy-related Interest Rate", "Unemployment Rate", "GDP per Capita"), dep.var.labels=c("Domestic Retail Lending to GDP"), no.space=TRUE, type = "text")
stargazer(coeftest(ols2, vcovHC), title = "Results", align = TRUE, add.lines = list(c("Controls", "No", "Yes")), covariate.labels=c("Bitcoin quantity", "Monetary Policy-related Interest Rate", "Unemployment Rate", "GDP per Capita"), dep.var.labels=c("Domestic Retail Lending to GDP"), no.space=TRUE, type = "text")
#robust standard errors option B
cov1 <- vcovHC(ols1, type = "HC")
cov2 <- vcovHC(ols2, type = "HC")
robust_se1    <- sqrt(diag(cov1))
robust_se2    <- sqrt(diag(cov2))
stargazer(ols1, type = "text", se = list(NULL, robust_se1))
stargazer(ols2, type = "text", se = list(NULL, robust_se2))

Although both alternatives are executed without errors in R, option A and option B are giving different robust standard errors. Does someone know why?
Furthermore, I would like to have both models in a single regression table with robust standard errors. How can I do this?

redpajama_set_name: RedPajamaStackExchange


text:
Q: Horizontally swap/flip (Mirror Image) the contents of the entire device screen I need a simple Android  app that can reverse the screen; horizontally swap/flip (Mirror Image) the contents of the entire device screen, left to right, including text, video, everything. When this app is started, I need a visible "button" located maybe at the top left or maybe a user selectable location (I'm open to suggestions for the on/off event), that when tapped, will instantly reverse the entire screen and, if tapped again, will put the device screen back to normal view.

A: wrap your scaffold with Transform widget and have tapped boolean to toggle
Transform(
            transform: Matrix4.identity()
              ..setEntry(3, 2, 0.002)
              ..rotateX( tapped ?  pi : 0),
            alignment: FractionalOffset.center,
            child: Scaffold(),
          ),

you can apply animation of you want also
also your mirror direction depends on rotateX or rotateY function to call


text:
Q: Unable to start Tomcat 7 Server error org.springframework.beans.factory.xml.XmlBeanDefinitionStoreException i am trying to start my tomcat 7 server . I got Page Not Found on my browser . When i check my console i can see below error.
org.springframework.beans.factory.xml.XmlBeanDefinitionStoreException: Line 19 in XML document from ServletContext resource [/WEB-INF/spring-servlet.xml] is invalid; nested exception is org.xml.sax.SAXParseException; lineNumber: 19; columnNumber: 52; cvc-complex-type.2.4.c: The matching wildcard is strict, but no declaration can be found for element 'aop:aspectj-autoproxy'.
    at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.doLoadBeanDefinitions(XmlBeanDefinitionReader.java:396)
    at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.loadBeanDefinitions(XmlBeanDefinitionReader.java:334)
    at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.loadBeanDefinitions(XmlBeanDefinitionReader.java:302)
    at org.springframework.beans.factory.support.AbstractBeanDefinitionReader.loadBeanDefinitions(AbstractBeanDefinitionReader.java:143)
    at org.springframework.beans.factory.support.AbstractBeanDefinitionReader.loadBeanDefinitions(AbstractBeanDefinitionReader.java:178)
    at org.springframework.beans.factory.support.AbstractBeanDefinitionReader.loadBeanDefinitions(AbstractBeanDefinitionReader.java:149)
    at org.springframework.web.context.support.XmlWebApplicationContext.loadBeanDefinitions(XmlWebApplicationContext.java:124)
    at org.springframework.web.context.support.XmlWebApplicationContext.loadBeanDefinitions(XmlWebApplicationContext.java:93)
    at org.springframework.context.support.AbstractRefreshableApplicationContext.refreshBeanFactory(AbstractRefreshableApplicationContext.java:130)
    at org.springframework.context.support.AbstractApplicationContext.obtainFreshBeanFactory(AbstractApplicationContext.java:467)
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:397)
    at org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:467)
    at org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:483)
    at org.springframework.web.servlet.FrameworkServlet.initWebApplicationContext(FrameworkServlet.java:358)
    at org.springframework.web.servlet.FrameworkServlet.initServletBean(FrameworkServlet.java:325)
    at org.springframework.web.servlet.HttpServletBean.init(HttpServletBean.java:127)
    at javax.servlet.GenericServlet.init(GenericServlet.java:158)
    at org.apache.catalina.core.StandardWrapper.initServlet(StandardWrapper.java:1284)
    at org.apache.catalina.core.StandardWrapper.loadServlet(StandardWrapper.java:1197)
    at org.apache.catalina.core.StandardWrapper.load(StandardWrapper.java:1087)
    at org.apache.catalina.core.StandardContext.loadOnStartup(StandardContext.java:5253)
    at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5543)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
    at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1574)
    at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1564)
    at java.util.concurrent.FutureTask.run(FutureTask.java:262)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
    at java.lang.Thread.run(Thread.java:745)

Caused by: org.xml.sax.SAXParseException; lineNumber: 19; columnNumber: 52; cvc-complex-type.2.4.c: The matching wildcard is strict, but no declaration can be found for element 'aop:aspectj-autoproxy'.
    at com.sun.org.apache.xerces.internal.util.ErrorHandlerWrapper.createSAXParseException(ErrorHandlerWrapper.java:198)
    at com.sun.org.apache.xerces.internal.util.ErrorHandlerWrapper.error(ErrorHandlerWrapper.java:134)
    at com.sun.org.apache.xerces.internal.impl.XMLErrorReporter.reportError(XMLErrorReporter.java:437)
    at com.sun.org.apache.xerces.internal.impl.XMLErrorReporter.reportError(XMLErrorReporter.java:368)
    at com.sun.org.apache.xerces.internal.impl.XMLErrorReporter.reportError(XMLErrorReporter.java:325)
    at com.sun.org.apache.xerces.internal.impl.xs.XMLSchemaValidator$XSIErrorReporter.reportError(XMLSchemaValidator.java:458)
    at com.sun.org.apache.xerces.internal.impl.xs.XMLSchemaValidator.reportSchemaError(XMLSchemaValidator.java:3237)
    at com.sun.org.apache.xerces.internal.impl.xs.XMLSchemaValidator.handleStartElement(XMLSchemaValidator.java:1917)
    at com.sun.org.apache.xerces.internal.impl.xs.XMLSchemaValidator.startElement(XMLSchemaValidator.java:746)
    at com.sun.org.apache.xerces.internal.impl.XMLNSDocumentScannerImpl.scanStartElement(XMLNSDocumentScannerImpl.java:379)
    at com.sun.org.apache.xerces.internal.impl.XMLDocumentFragmentScannerImpl$FragmentContentDriver.next(XMLDocumentFragmentScannerImpl.java:2786)
    at com.sun.org.apache.xerces.internal.impl.XMLDocumentScannerImpl.next(XMLDocumentScannerImpl.java:606)
    at com.sun.org.apache.xerces.internal.impl.XMLNSDocumentScannerImpl.next(XMLNSDocumentScannerImpl.java:117)
    at com.sun.org.apache.xerces.internal.impl.XMLDocumentFragmentScannerImpl.scanDocument(XMLDocumentFragmentScannerImpl.java:510)
    at com.sun.org.apache.xerces.internal.parsers.XML11Configuration.parse(XML11Configuration.java:848)
    at com.sun.org.apache.xerces.internal.parsers.XML11Configuration.parse(XML11Configuration.java:777)
    at com.sun.org.apache.xerces.internal.parsers.XMLParser.parse(XMLParser.java:141)
    at com.sun.org.apache.xerces.internal.parsers.DOMParser.parse(DOMParser.java:243)
    at com.sun.org.apache.xerces.internal.jaxp.DocumentBuilderImpl.parse(DocumentBuilderImpl.java:347)
    at org.springframework.beans.factory.xml.DefaultDocumentLoader.loadDocument(DefaultDocumentLoader.java:75)
    at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.doLoadBeanDefinitions(XmlBeanDefinitionReader.java:388)
    ... 28 more

Here is my XML file .
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
    xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx"
    xmlns:jee="http://www.springframework.org/schema/jee" xmlns:lang="http://www.springframework.org/schema/lang"
    xmlns:util="http://www.springframework.org/schema/util" xmlns:mvc="http://www.springframework.org/schema/mvc"
    xmlns:aop="http://www.springframework.org/schema/aop"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans.xsd
    http://www.springframework.org/schema/context
    http://www.springframework.org/schema/context/spring-context-3.0.xsd
    http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee.xsd
    http://www.springframework.org/schema/lang http://www.springframework.org/schema/lang/spring-lang.xsd
    http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd
    http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd
    http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.1.xsd
    http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.1.xsd ">
    <aop:aspectj-autoproxy proxy-target-class="false"></aop:aspectj-autoproxy>

I am not able to solve this error.
sometimes showing this error or sometime it can not showing that error.
If anyone know Please provide me solution.
Thanks in Advance ..!!

A: Thanks to all for your replay . Actually i am using two different ISP. When i tried to connect with another ISP and try to start it works .I am connecting to AWS hosted database in my code. It might be ISP blocking IP or firewall.


text:
Q: Why is the second alert still displaying the first view model (vm1)? I have the below code and I'm confused why is the second alert displaying the first view model (vm1) instead of the second one (vm2)?

A: It's showing the first ViewModel (vm1) only because when you apply the binding, you pass viewmodel of the vm1.
ko.applyBindings(new vm1(), document.getElementById('main'));

Also, bindingContext parameter from ko.bindingHandlers will get you the viewModel that you pass to the ko.applyBinidngs. Since you pass the first viewmodel during the binding, you'll only get that information.
http://knockoutjs.com/documentation/custom-bindings.html
If you want to get both v1 and v2 from the ko.bindingHandlers, you can create another viewmodel and create 2 properties for each of them.
function vm1() {
    this.firstName = "test first name"
}

function vm2() {
    this.lastName = 'test last name';
}

function viewModel() {
  this.vm1 = new vm1();
  this.vm2 = new vm2();
}

ko.bindingHandlers.testBinding = {
    init: function(element, valueAccessor, allBindings, viewModel,
          bindingContext) {

          alert(JSON.stringify(bindingContext.$data))
    },
};

ko.applyBindings(new viewModel(), document.getElementById('main'));

Then you'll get this result on the alert box
{"vm1":{"firstName":"test first name"},"vm2":{"lastName":"test last name"}}


text:
Q: t sql replicate rows in cascading tables I have a situation in which I have several related/cascaded tables.  Lets say all 1-to-many relationships cascading down table1, table2, table3, table4, etc.  What I have are default rows in the tables.  They start with 1 record in table1 and have 1 or more related records in other tables.
What I am looking for is an easy way to replicate the rows and create/maintain new primary keys for each.  By maintain I mean, table1.ID1 is replicated, so now there is a table1.ID2 with all the rest of the columns being the same, only the ID has changed.
On top of that all its related rows in all the other tables are replicated and the foreigns keys/primary keys all point to the new ones.
So table2 would have a foreign key of table1.ID2 a primary key of say table2.ID#, and the rest of the columns in the table2 row being the same as the row replicated in table2.
I am being lazy and trying to get out of having to manage the ID's and creating a very long Stored Procedure.
I don't think this can be done, but am hoping I am wrong. Thanks in advance.

A: We had to do this for some functionality in one our projects recently.
We ended up doing it using a recursive stored procedure. Each call needed two pieces of information:

*

*The name of the table where the records are being duplicated

*The primary key of the parent table of the table being duplicated

So if you had two tables A and B, where A.aid is the primary key of A, and B.aid references it, you would need to do the following in pseudocode:
Function deep_copy (table, parent)
  For each record in table whose parent is parent
    Create a new PK and copy this record
    For each subtable of table
      Call self with parameters (subtable, newPK)

You'd call deep_copy on each record of A you want to copy. Then deep_copy would call itself on the records in B that need to be copied, and any other sibling tables to B. The catch is you need the metainformation to know that B is a child of A. We happened to have that metainformation stored already so we didn't have to do anything special to acquire it.
Which ends up not being a very big stored procedure. If your PKs are all identity columns it makes it a whole lot easier. It branches out a hell of a lot, though. Not exactly an efficient algorithm. But then again it's an inherently complex problem for which relational data models aren't designed to deal with gracefully.

A: Triggers were created for exactly this. However , good triggers are difficult to write and a pain to maintain. But if you get them right, it is easy to implement the scenario you describe.


text:
Q: ERROR Response with status: 401 OK for URL Here is the image of the error
 I am trying to implement authGuard for my webste. But when I interfere with error codes, the app call back office and send  error.
Please help me!.
My AuthGuard.ts
public canActivate(route: ActivatedRouteSnapshot, state:     RouterStateSnapshot): boolean {
        // L'utilisateur est identifié, on accède à la page demandée
        if (Tools.isIE()) {
            this.router.navigate(['/redirect']);
            return false;
        } else {
            if (localStorage.getItem('currentUser')) {
                return true;
            }
                       this.router.navigate(['/login']);
            return false;
        }
    }
}


text:
Q: C# iLogger when Log is called unable to write to file because file is in use My application uses iLogger and I've implemented a log provider to write to a local log file.
The problem I'm having is there is a lot being logged especially in debug mode and what I'm finding is that the file is in use and can't open to append to it.  I'm looking for some suggestions on how to avoid this issue.
I thought about having Log function add to a Queue and have another thread start and process the queue so that there is no issues blocking writing but the iLogger doesn't have a deconstructor that I can find what would allow it to finish emptying the queue before destroying the queue and shutting down.
try
{
    _locker.AcquireWriterLock(int.MaxValue);
    File.AppendAllText(fullFilePath, logRecord);
}
catch (Exception ex)
{
        throw ex;
}
finally
{
    _locker.ReleaseWriterLock();
}

A: The Easy Solution
The easy solution would be to use a library like Serilog for persisting logs.
The Not-So-Easy and Tricky Solution
In case the easy option is not available, I suggest you move your application to Generic Host model and setup a BackgroundService for log persistence. Inside the service you can use Channel to queue the logs for persistece and persist the logs inside the ExecuteAsync into file using an asynchronous implementation.
The ExecuteAsync would look something like this:
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
    // open file
    while (!stoppingToken.IsCancellationRequested)
    {
        try
        {
            // get item from the queue and persist it asynchronously
        }
        catch (Exception ex)
        {
            // this might not be a good idea since the new log would also be queued up creating an infinite loop
            _logger.LogError(ex,
                "Error occurred executing {WorkItem}.", nameof(workItem));
        }
    }
}

protected override async Task StopAsync(CancellationToken stoppingToken)
{
  // do similar while loop then close the file
}

This rough setup has some corner cases and is not ideal at all but would get the job done in a test application.

A: In any case you need to write concurrently in the same file you can do the following:
async Task WriteToFileAsync(string path, string text)
{
    byte[] byteArray = Encoding.Unicode.GetBytes(text);
    using var stream = new FileStream(path, FileMode.Append, FileAccess.Write, FileShare.ReadWrite, bufferSize: 2048, useAsync: true);
    await stream.WriteAsync(byteArray);
}

If, lets say, you have a list of tasks that you need to execute concurrently, you can fire them all using await Task.WhenAll().
var path = Environment.CurrentDirectory + "/logs.txt";
var tasks = Enumerable.Range(0, 10).Select(i => WriteToFileAsync(path, $"Log #{i}\n"));
await Task.WhenAll(tasks);

Update:
Based on https://github.com/dotnet/docs/blob/main/docs/core/extensions/snippets/configuration/console-custom-logging
Because Log(...) method of ILogger must be void you could make the WriteToFile sync:
private static void WriteToFile(string text)
{
     var path = Environment.CurrentDirectory + "/logs.txt";
     byte[] byteArray = Encoding.Unicode.GetBytes(text);
     using var stream = new FileStream(path, FileMode.Append, FileAccess.Write, FileShare.ReadWrite, bufferSize: 2048);
     stream.Write(byteArray);
}

and in Log method you can use it like:
public void Log<TState>(
        LogLevel logLevel,
        EventId eventId,
        TState state,
        Exception? exception,
        Func<TState, Exception?, string> formatter)
    {
        if (!IsEnabled(logLevel))
        {
            return;
        }

        ColorConsoleLoggerConfiguration config = _getCurrentConfig();
        if (config.EventId == 0 || config.EventId == eventId.Id)
        {
            // ...
            WriteToFile($"{formatter(state, exception)}");
        }
    }

Then you can inject the ILogger in any class you want:
public class App
{
    private readonly ILogger<App> _logger;

    public App(ILogger<App> logger)
    {
        _logger = logger;
    }

    public async Task ExecuteTaskAsync(string txt)
    {
        _logger.LogInformation(txt);
        await Task.CompletedTask;
    }
}

Finally the same code ( await Task.WhenAll ) should work and you will write to the file concurrently:
using IHost host = Host.CreateDefaultBuilder(args)
    .ConfigureServices((_, services) =>
    {
        services.AddScoped<App>();
    })
    .ConfigureLogging(builder =>
        builder.ClearProviders()
            .AddColorConsoleLogger(configuration =>
            {
                // Replace warning value from appsettings.json of "Cyan"
                configuration.LogLevels[LogLevel.Warning] = ConsoleColor.DarkCyan;
                // Replace warning value from appsettings.json of "Red"
                configuration.LogLevels[LogLevel.Error] = ConsoleColor.DarkRed;
            }))
            .Build();
// ...
var app = host.Services.GetRequiredService<App>();
var tasks = Enumerable.Range(0, 10).Select(i => app.ExecuteTaskAsync($"Log #{i}\n"));
await Task.WhenAll(tasks);

await host.RunAsync();


text: Q: Is it possible to use the node library @ibm-cloud/cloudant as a mixin in Moleculer framework? I'm using moleculer microservices framework and IBM Cloudant database. Is it possible to use the node library @ibm-cloud/cloudant as a mixin so that I can inherit all the methods in the services? Thank you


text:
Q: SearchView on support.v7.appcompat library issue: default 9-patch background not renders properly I'm developing an app with ActionBar using support.v7.appcompat library. The action bar works, the SearchView is shown, the hint shows. The only problem is that the background of the SearchView is not scalling properly. Insead of the usual, it appears big and with the 9-patch black lines.
Using:

*

*Developing from command line, using ant debug to compile.

*On Linux Mageia 3, ant version: Apache Ant(TM) version 1.8.4 compiled on January 11 2013

*Linking to library with project.properties line:

android.library.reference.1=../../../../../sdk/extras/android/support/v7/appcompat/

*

*Using @style/Theme.AppCompat.Light

*Tested in device with CM10-1, in device with stock 4.1, and emulator with API 8 (Android 2.2). Same result in all devices.

Screenshot:

Code:
DiccionariCatala.java (main activity):
import android.support.v7.app.ActionBarActivity;
import android.support.v7.widget.SearchView;
import android.support.v4.view.MenuItemCompat;
import android.app.Activity;
import android.app.SearchManager;
import android.content.Context;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MenuInflater;

public class DiccionariCatala extends ActionBarActivity
{
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu){
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.menu_actions, menu);
        SearchManager SManager =  (SearchManager) getSystemService(Context.SEARCH_SERVICE);
        MenuItem searchMenuItem = menu.findItem(R.id.action_search);
        SearchView searchViewAction = (SearchView) MenuItemCompat.getActionView(searchMenuItem);
        searchViewAction.setSearchableInfo(SManager.getSearchableInfo(getComponentName()));
        searchViewAction.setIconifiedByDefault(false);
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item){
        switch (item.getItemId()) {
                case R.id.action_search:
                    //openSearch();
                    return true;
                default:
                    return super.onOptionsItemSelected(item);
        }
    }
}

menu_actions.xml (menu xml)
<menu xmlns:android="http://schemas.android.com/apk/res/android"
      xmlns:diccionaricatala="http://schemas.android.com/apk/res-auto" >
    <item android:id="@+id/action_search"
          android:title="@string/action_search_title"
          diccionaricatala:showAsAction="ifRoom"
          diccionaricatala:actionViewClass="android.support.v7.widget.SearchView" />
</menu>

AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
      package="com.mypackage.apps"
      android:versionCode="1"
      android:versionName="1.0">
      <uses-sdk android:minSdkVersion="8"  android:targetSdkVersion="16"/>
      <application android:label="@string/app_name"
                   android:icon="@drawable/ic_launcher"
                   android:theme="@style/Theme.AppCompat.Light">

       <activity android:name="DiccionariCatala"
                 android:label="@string/app_name">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
            <intent-filter>
                <action android:name="android.intent.action.SEARCH" />
            </intent-filter>
            <meta-data android:name="android.app.searchable"
                       android:resource="@xml/searchable"/>
        </activity>
   </application>
</manifest>

project.properties
target=android-16
android.library.reference.1=../../../../../sdk/extras/android/support/v7/appcompat/

Any help would me much apreciated. I can't find anything wrong, and there's also the weird fact that despide this, everything else work.  Thanks.

A: Ok, I want to kill myself. I've fixed it. Don't know how. I can't reproduce the bug again!
what I think has fixed the bug: I've added import android.support.v7.app.ActionBar;
Then I've removed it to reproduce the bug, but it's not back.
I also did uninstall Build-tools 18.0.1 (which is in italics and made me suspicious), so I thought it might be the source of the bug. But I've reinstalled it, and can't reproduce the bug either.
I don't know what else could possibly be. Anyway, moving on... (sight)
Edit:
It happened again, and this time I've been able to narrow it down. Turns out it is a bug of Build Tools v18.*, downgrading to v17 solves the issue.

A: This is usually an issue where the resources (R) file has not been correctly generated and some references are misaligned.
Doing a clean is usually a good fix, as it regenerates this file. This is what you inadvertently did when reinstalling.

A: I had the same issue with build tools 19.0.1, but newer version 19.0.3 fixed the problem. Try it, hopefully it will help you too.


text:
Q: convert fwrite in matlab to python I want to convert matlab code to python. This is to write the little_endian format file.
I appreciate if anyone can help me.
The matlab code is:
function fileformat(data, filename, type)
file_id = fopen(filename, 'wb','l');
fwrite(file_id , data, type,'l');
fclose(file_id );

The python code that dose not work correctly is:
def formatfile (data, dir_filename, dtype):
    f = open(dir_filename, 'wb')
    f.write(data)
    f.close()


text:
Q: How to send a base64 image to the server without damage I have the function to send the data to the server. I need to send the data, including the image, when sending the data attached the image, appears error, and the image arrive to the server is corrupted, and when the data is sent without it does not occur any error
this is my code:
func Register() {
        let Name = FullName.text
        let Phone = Phone_Num.text
        let Password = self.Password.text
        let Board = Board_Num.text
        let Details = Car_Type.text! + " " + Car_Brand.text! + " " + Car_Model.text!
        let CarImage:UIImage = Car_Image.image!
        if let dataImage = UIImageJPEGRepresentation(CarImage, 0.5)?.base64EncodedString() {
            let fullBase64String = "data:image/png;base64,\(dataImage))"
            let url = "someURL"
            let parameter = ["driver_name": Name!, "phone_number": Phone!, "card_number": Password!, "board_number": Board!, "car_details": Details, "car_image": "\(fullBase64String)"]
            Alamofire.request(url, method: .post, parameters: parameter, encoding: JSONEncoding.default).responseJSON { response in
                print(response.request as Any)
                print(response.response as Any)
                print(response.result as Any)
                print(response.result.value as Any)
                do {
                    let json = try JSON(data: response.data!)
                    let Status = json["Status"].stringValue
                    if Status == "Success" {
                        self.myActivityIndicator.stopAnimating()
                        self.alert(errormessage: "Done")
                    } else {

                    }
                } catch {
                    self.myActivityIndicator.stopAnimating()
                }
            }
        }
    }

this is the error:

[BoringSSL] Function boringssl_session_errorlog: line 2868 [boringssl_session_write] SSL_ERROR_SYSCALL(5): operation failed externally to the library


text:
Q: Why could this C++ program run successfully even without constructing the class object? Why do this C++ program could run successfully even without constructing the class object?
Let's see the code as below:
#include<iostream>

using namespace std;

class Dopey
{
  public:
    Dopey() {cout << "Dopey\n";}
};

class Bashful
{
  public:
    Bashful() { cout << "BashFul\n";}
    void f() { cout << " f \n";}
    int i;
};

class Sneezy
{
  public:
    Sneezy(int i) {cout << "copy int \n";}
    Sneezy(Bashful d) { cout << "copy Bashful\n";}
    Sneezy(Bashful* d) {d->f();d->i=100;} //How could this be correct without
                                              //  constructing d !!!!!!!!
    Sneezy();
};

class Snow_White
{
  public:
    Snow_White();
    Dopey dopey;
    Sneezy sneezy;
    Bashful bashful;
  private:
    int mumble;
};

Snow_White::Snow_White() : sneezy(&bashful)
{
    mumble = 2048;
}

int main()
{

    Snow_White s;

    return 0;
}

This program could run successfully , the cout are as below:
Dopey
f
BashFul

see, without constructing bashful,the f() could be invoked, why?
and when i change the function Snow_White::Snow_White() to the below:
Snow_White::Snow_White() : sneezy(bashful)
{
    mumble = 2048;
}

it also runs successfully without constructing bashful , the cout are as below:
Dopey
copy Bashful
Bashful

Any interpretation will be appreciated ! THX !

A: Your program has undefined behaviour because you are accessing bashful before it has been constructed.

A: Your problem has to do with your initialization list.
bashful is declared after sneezy.
Therefore, in this code:
Snow_White::Snow_White() : sneezy(&bashful)

bashul has not been constructed yet, because according to Snow_White's declaration, sneezy must be constructed first (yes, the order matters). Therefore, the parameter passed in to sneezy's constructor points to an unitialized object. At this point, the reason it works is what chris has linked to. Keep in mind, that although this works, according to the C++ standard the behaviour is undefined and that means you cannot and must not rely on it to work.
However, the real problem is that bashful hasn't been constructed yet.
To fix that, you would need to alter the declaration of your Snow_White class so that bashful comes before sneezy:
class Snow_White
{
  public:
    Snow_White();
    Dopey dopey;
    Bashful bashful;
    Sneezy sneezy;
  private:
    int mumble;
};

One way to avoid this kind of thing occuring is to always keep your declarations and initialization lists in alphabetical order.
The other way is to keep your classes small to begin with, so this is never an issue :)

A: The bashful member is being constructed as is shown by the inclusion of Bashful in the output.  It is true that it is not constructed prior to the address of bashful being taken and passed to the other member's constructor.
There are specific rules as to the order in which member are initialized, but the order initialization or use in the constructor initialization list is not one of the factors in those rules.


text:
Q: Yoneda embedding and Horn sentences The following is taken from Borceux and Bourn's Mal'cev, Protomodular, Homological, and Semi-Abelian Categories.

Metatheorem 0.1.3. Let $\mathcal P$ be a statement of the form $\varphi\implies \psi$, where $\varphi$ and $\psi$ can be expressed as conjunctions of properties in the following list:

*

*some finite diagram is commutative;

*some morphism is a monomorphism;

*some morphism is an isomorphism;

*some finite diagram is a limit diagram;

*an arrow $f:\rightarrow B$ factors (of course, uniquely) through some specified monomorphism $s:S\rightarrowtail B$.

If this statement is valid in the category of sets, it is valid in every category.

After the proof comes the following remark.

It is probably useful to make a comment. The list of properties in our metatheorem is not exhaustive. A better way to express the metatheorem would have been to state it for Horn sentences and the "unique existential quantifier $\exists!$", but we do not want to enter those considerations here.

I tried googling 'Yoneda embedding horn sentence' but didn't find anything I thought was relevant. What is the "better way to express the metatheorem", and why is it true? I'm guessing some topos theory comes in, but I don't really know anything about (the logical aspect of) it.


text:
Q: How to pass multiple params into a delegate in Javascript? I have the following JS code, which uses jQuery:
var anArray=[];
var passIntoFun =100; // calculated value;

function ArrayIteratorFun(index, element, thirdParam){
   // function code.
}

I want to call ArrayIteratorFun using .each construct, like:
$(anArray).each(ArrayIteratorFun(passIntoFun));

I could only call it like, by wrapping into a function:
$(anArray).each(function(i,e){ArrayIteratorFun(i,e,passIntoFun);});

is there any better way to write the code above?

A: Assuming your example is oversimplified and your function does not have access to the variable you wish to pass in as an argument (as one comment alludes to)...
The problem you have is that of pre-filling certain arguments (thirdParam in your case) of your ArrayIteratorFun.  Sometimes you'll see this kind of technique called partial application or currying.
You happen to want to apply the third argument (leaving the preceding ones unfilled), which removes the possibility of using Function.prototype.bind.  Bind is useful, but I often use the more flexible partial function from underscore.
With partial you can apply arbitrary arguments, by using _ in place of arguments that you want to apply/fill later:
$(anArray).each(_.partial(ArrayIteratorFun, _, _, passIntoFun));

The above ignores the first 2 arguments of ArrayIteratorFun (using underscores) and applies the value of passIntoFun to the third argument.
EDIT: I'm not aware of any way that jQuery provides of doing the same thing as _.partial.  However if you are restricted to not using underscore (or a similar framework) then I recommend you check out the implementation of partial in underscore and this great article on the subject of partial application in javascript.  These both provide ways of implementing using only plain javascript.


text:
Q: meaning of query in elasticsearch Query DSL I am trying to understand the semantics of elasticsearch querys. I understand that every query is an object containing the objects "query" and "filter" and maybe some other options. Now inside some leaf query objects one might have a  "query" object instead of raw data like text or a number, however this seems to be a different object than the query at the beginning. I tried to understand the documentation but I couldn't find definitions of these two objects.
What I struggle with is that I try to understand querys starting from the leafs and working my way back and looking at it this way, the "query" object inside a leaf is returning some words or data which is used in the leaf query object like "match" as input but this is not what the 'main' query object is doing since this is returning the results of the search.
Are these two objects completely different or are they the same kind of objects and I'm missing the point completely?

A: Working from the bottom up might make understanding the DSL difficult.  The way the Elasticsearch documentation is laid out is actually pretty helpful for learning the DSL.  If you start on this page and just click forward, I think it explains the DSL fairly well.
As for your specific question, the Elasticsearch DSL object structure does use the field name "query" for different purposes.  All Request-Body queries (meaning, those that are not Query-String queries) start with the query context.  This is the container for the clauses of the query that affect the score.  The clauses are the various leaf nodes such as match and term that are used to define the search.  The query can also contain a filter context, which contains clauses that further refine the results, but do not affect the score.  Some of the clauses have a property named query, such as the Match Query.  In this case, the query property is used to define the value being matched.


text:
Q: How can I get my jQuery Menu to be at the very (VERY) top of the page? I've got a jQuery menu on my page, and it's working great (thanks to the people who helped me on my last post), but it's floating about 15px (by my very rudimentary calculations) from the top of the page, and I want it to sit at the very very top if possible.
EDIT:  It floats 10px down in chrome and firefox
Here's a couple screenshots of what's going on

Here's my css for the menu bar, so you can see what's going on:
#menu{
    height:30px;
    width: 100%;
}

#menu > li{
    float:left;
}

#menu > li > ul > li{
position:relative;
width:auto;
}

#file-menu{
width:75px;
}

#applications-menu{
width:160px;
}

A: Use this:-
body{
    margin:0px;
    padding: 0px;
}

A: body {
margin: 0;
padding: 0;
}

This will remove the padding or margin that a browser adds in with default options.
Read more about CSS Resetting here.

A: It seems your body probably has a margin or padding set to it.
You should get into a habit of using a CSS Reset (which resets all styles to be consistent [as they can] across browsers)
Include this file before all other CSS style sheets you have, it should resolve your issues.
<link rel="stylesheet" type="text/css" href="http://yui.yahooapis.com/3.10.3/build/cssreset/cssreset-min.css">

Alternatively, you can just add the css:
body{margin:0; padding:0} /* At the very top of your CSS sheet */

A: I usually use the following.
* { padding:0px;margin:0px;outline:0px }

In most of my designs. By using * you are applying the styles to everything. Then, if you need some of the built in padding/margins later, you can easily add them. Makes styling things much more customizable.
Goodluck.


text:
Q: OneToMany Mapping Child Parent Hi I am using Spring Boot app with MVC. I have two model classes Parent and Child. Parent to Child has OnetoMany Mapping. I have a form submit in which I'm passing few fields of child class, now what is happening when I bind the child class in the controller method is that it picks up the id of Parent class and binds it automatically to Child object in Controller.Please suggest what I am missing in here.
Following is the code for the same:
@PostMapping("/{id}/child")
    public String editChildPOST(@PathVariable Long id,
            Child child, Model model, BindingResult errors,
            Principal principal) {

        logger.info("editChildPOST: " + child.getId);
        model.addAttribute("aaaa", aaaa);
        model.addAttribute("bbbb", "bbbb");
        return "redirect:/xxxx";
    }

Following is the mapping in the parent Class :
class Parent{
@OneToMany(cascade= ALL, orphanRemoval=true)
    @JoinColumn(name="parent_id")
    private List<Child> child;
}

SO in debug mode if I try to check the value of child in Controller it shows Child Id as parent's Id although I haven't set Child Id anywhere in the form submit.


text:
Q: Can 74HCT buffers work just as well as 74HC buffers between parallel port and target? I'm making a circuit to program the AT89S52 microcontroller in a serial fashion as follows:

Call me paranoid but this time I'm using resistors on all outputs to the micro as well as RC networks on the reset and clock lines. I also am using a jumper on the EA/VPP line in case I need to use it for programming as well.
I am using NOR gates (I know I know, I'm using the european version instead of the US version of the symbols but they're designed more neatly) as a latch to control all communications.
Because this design (that I made the PCB for) calls for 74HC series of chips, I happen to own a 74HCT02 NOR gate, but I don't own any 74HC02 NOR gates.
This circuit is powered with regulated 5VDC and the parallel port is set to run in Standard Parallel port mode with no bidirectional capability.
If I replaced the 74HC02 with 74HCT02, would the circuit still work without the need for any extra parts?

A: The outputs are the same and both input thresholds are compatible with minimal noise <1Vpp. 74HCTxxx Vth=1.5V +- x % and 74HCxxx Vth =Vdd/2 +- xx % over temp.

A: I'm having similar problems with other config and just to point out, if you read the Phillips datasheet, which by the way is wonderful reading, the 74HC has some more variations which are dependent on the Vcc input. HCT are more stable and have fewer variations, also they have some internal plus:

The 74HCT input stage is similar to that of a 74HC device. It has the same characteristics for LSTTL levels as a 74HC input has for CMOS levels, so there is no trade-off in speed or power dissipation. The switching threshold is lower, 1.4 V at VCC = 5 V. In addition, the 74HCT input circuit, shown in Fig.24, has an enlarged n-channel transistor (N1) and a level-shift diode (D3) has been added. The natural drain voltage of the p-channel transistor (P1) is approximately VCC − 0.6 V, but when the input voltage is LOW, an auxiliary pull-up transistor (P2) raises this to VCC, cutting off p-channel transistor P3 completely. The input stage is well matched to the load presented by the second stage so that symmetrical propagation delays are obtained.

So HCT have some enhancements and the price difference is irrelevant, I think HCT would work better.


text:
Q: How to Customize a ContextMenu for a wpf ListBox Consider a ListBox that may not be completely filled with ListBoxItems at run time.  I want to customize the ContextMenu for that ListBox depending on whether the user right clicks on one of the ListBoxItems or on the blank space where no items exist.
The problem I'm having is that in the latter case, no ListBox events are fired, only the ContextMenuOpening event is fired.  And from that event I cannot figure out how to ascertain whether the user right clicked on an existing ListBoxItem or not.
I have looked at all the ListBox properties and events but canot come up with an approach that differentiates these two cases.  I've considered using Style Triggers but, again, the core problem is that a Right-Click in the blank space does not trigger any ListBox events.  I've also reviewed the links that SO suggests but none speak to this question.
How can this be done?

A: Here is a more concise approach to define two different ContextMenu for ListBox and its ListBoxItem without the need to any code-behind checking, it works like a charm:
<ListBox ContextMenu="{StaticResource ListContextMenu}">
    <ListBox.Resources>
        <!-- Context Menu when right click on selected List Item -->
        <ContextMenu x:Key="ItemContextMenu">
            <MenuItem Header="Eat"></MenuItem>
            <MenuItem Header="Delete"></MenuItem>
            <Separator></Separator>
            <MenuItem Header="Send To Friend"></MenuItem>
        </ContextMenu>
        <!-- Context Menu when right click on listbox space -->
        <ContextMenu x:Key="ListContextMenu">
            <MenuItem Header="Save Fruits"></MenuItem>
            <MenuItem Header="Add Or Remove Fruits"></MenuItem>
        </ContextMenu>
        <!-- Applying Context Menu to ListBoxItem with Style -->
        <Style TargetType="{x:Type ListBoxItem}">
            <Setter Property="ContextMenu" Value="{StaticResource ItemContextMenu}">
            </Setter>
        </Style>
    </ListBox.Resources>

    <ListBox.ContextMenu>
        <Binding Source="{StaticResource ListContextMenu}"></Binding>
    </ListBox.ContextMenu>

    <ListBoxItem>Banana</ListBoxItem>
    <ListBoxItem>Apple</ListBoxItem>
    <ListBoxItem>Orange</ListBoxItem>
</ListBox>

If you want to modify contents of ListBoxItem.ContextMenu dynamically based on selected item you can hook up a handler for the ContextMenu.Opened event and in that handler you check the selected item and add new MenuItem Collection to your ContextMenu in code.
Note that these two ContextMenus will be displayed only inside this ListBox thats because they are defined in its ListBox.Resources.

A: I devised a solution which is not pretty but does work.  Basically, whenever the ListBox loses focus, I force it to have nothing selected by setting
ListBox.SelectedIndex = -1

Now, in the ContextMenuOpening event when the focus is back to the ListBox, it is possible to get the get the ListBox.SelectedIndex and if it is -1 then the user clicked in the blank portion of the ListBox otherwise a ListBoxItem was clicked on.
Coding this logic is straightforward.

A: Maybe I didn't get your intention: You can define different ContextMenu either in XAML or Code-behind like this:
XAML:
<ListBox PreviewMouseDown="ListBox_PreviewMouseDown">
    <ListBox.ItemContainerStyle>
        <Style TargetType="{x:Type ListBoxItem}">
            <Setter Property="Template">
                <Setter.Value>
                    <ControlTemplate TargetType="{x:Type ListBoxItem}">
                        <ContentPresenter>
                            <ContentPresenter.ContextMenu>
                                <ContextMenu>
                                    <MenuItem Header="ListBoxItem"></MenuItem>
                                    <MenuItem Header="ListBoxItem"></MenuItem>
                                    <MenuItem Header="ListBoxItem"></MenuItem>
                                </ContextMenu>
                            </ContentPresenter.ContextMenu>
                        </ContentPresenter>
                    </ControlTemplate>
                </Setter.Value>
            </Setter>
        </Style>
    </ListBox.ItemContainerStyle>
    <ListBoxItem>Item1</ListBoxItem>
    <ListBoxItem>Item2</ListBoxItem>
    <ListBoxItem>Item2</ListBoxItem>
    <ListBoxItem>Item2</ListBoxItem>
    <ListBox.ContextMenu>
        <ContextMenu>
            <MenuItem Header="ListBox"></MenuItem>
            <MenuItem Header="ListBox"></MenuItem>
            <MenuItem Header="ListBox"></MenuItem>
        </ContextMenu>
    </ListBox.ContextMenu>
</ListBox>

Code-behind:
private void ListBox_PreviewMouseDown(object sender, MouseButtonEventArgs e)
{
    if(e.ChangedButton == MouseButton.Right)
    {
        var listBoxItem = e.Source as ListBoxItem;
        if (listBoxItem != null)
        {
            // clicked on ListBoxItem, customize the ContextMenu
        }

        var listBox = e.Source as ListBox;
        if (listBox != null)
        {
            // clicked on ListBox, customize the ContextMenu
        }
    }
}


text:
Q: Best format for compression of large amount of small files I tried to use .rar and I get a great rate of compression. However it take a lot of time to show the folder structure when I open the .rar file (tried different programs), it looks it is needed to read every file before displaying the folder structure. (I need to compress like 1 million files)
What compression format should I use so I can open the archive and extract some file on it fast when needed?

A: There will be trade off between speed/compression ratio.
You may want to view the blog post, Linux Compression Comparison (GZIP vs BZIP2 vs LZMA vs ZIP vs Compress). The author's results reflect my general experiences with the various compression algorithms. Pay specific attention to the decompression graph.
The ZIP format provides the best platform compatibility (both Windows and OS X support zip natively). However, its compression ratio will likely be worse than RAR.
The GZIP format is a very popular choice in the Linux world. It provides very quick compression while average compression rates. Mac OS X supports gzip archives natively, however with Windows you need an application such as 7zip.
The BZIP2 and LZMA formats tend to take a much longer time to compress and decompress files, however they tend to yield much better compression ratios. I think OS X supports both of these formats natively, again with Windows, you will need to use something like 7zip.
The type of files being compressed makes a huge difference in compression time, decompression, and compression ratio and differs for each format.
Ultimately you will need to try various formats and see which meets your needs tho best.


text:
Q: Openvpn forward all routing to a socks port Is it possible to configure openVPN to route all client connections through a socks port? ie, I want the setup to be:
Client -> openvpn server -> localhost socks5 port -> socks5 port forward -> the internet
machine 1    machine 2           machine 2              machine 3

How would I go about doing that?
So far I've been doing the same thing but with an SSH tunnel instead of vpn and while it's been working fine, I'm going to be adding new devices which don't do ssh tunneling as well as vpn.

A: I don't think you can.
SOCKS isn't a networking (layer 3) protocol, it's a layer-4 protocol, up with the rest of the applications.  Leaving OpenVPN (which does operate at layer 3) out of the picture, clients normally have to be SOCKS-aware if they want to route their traffic via a SOCKS proxy.  Each piece of client software has to know where the SOCKS proxy is, each has to know how to open a SOCKS connection via that proxy, and so on.
When you add OpenVPN into the picture, it doesn't suddenly make the end-client applications brighter.  Nor does a remote OpenVPN server have the ability to magically enagage in SOCKSification for any client traffic that passes along it.
OpenVPN is SOCKS-aware to the extent that it can build its tunnels to remote end-nodes via a local SOCKS proxy, but I believe that's as far as it goes.

A: MadHatter's answer is correct, however I suspect this is a case of XY Problem. If you terminate OpenVPN on a machine that is capable of routing and NATing traffic (read: any modern server operating system) then it is absolutely possible to configure OpenVPN and the said machine to act as a network proxy in the sense that client connections will appear on the public internet as if they are coming from the proxy machine. If this is the problem you're trying to solve, iptables NAT and some routing tweaks works great for me.


text:
Q: How to limit floating numbers in runif in R? I have a few problems.
1 - How to limit the number of floating numbers in runif function in R? For example, I use the code below to generate a matrix.
n1 = runif(10,1,5)
n2 = runif(10,1,6)
n3 = runif(10,1,7)
n4 = runif(10,1,8)
numvect=list(transpose(n1),transpose(n2),transpose(n3),transpose(n4))
#put the number vectors into a matrix
# construct a matrix with 10 rows and 4 columns

matrixnum = matrix(,nrow=10,ncol=4)
for(i in 1:8){
  matrixnum[,i] <- numvect[[i]]
}
write.table(matrixnum,'num4.txt',sep = "\t",row.names=F,col.names=F,options(digits=4)) # write the matrix

But in the results, it still have 14 or 15 floating numbers. I think the options(digits=4) argument doesn't work here.
2 - When writing a matrix to a .txt output, how to control the numbers in the file to be not of scientific notation?

A: If you're trying to turn the four random-number vectors into a 10x4 matrix rounded to four decimals places, I think you can just do this:
n1 = runif(10,1,5)
n2 = runif(10,1,6)
n3 = runif(10,1,7)
n4 = runif(10,1,8)

matrixnum = matrix(round(c(n1,n2,n3,n4), 4), nrow=10)

Another option to convert the values into a matrix is the following. This might be easier in this case, since you know you want each of your vectors to be a column and this avoids having to worry about setting nrow or ncol correctly in matrix():
round(as.matrix(cbind(n1,n2,n3,n4)), 4)

Then, to write the matrix to a file:
write.table(matrixnum, 'num4.txt', sep = "\t", row.names=F, col.names=F)


text:
Q: Xamarin Android Save sms I have the following code
var context = Application.Context.ApplicationContext;
var values = new ContentValues();
values.Put("address", "+27824318637");
values.Put("body", "Testing C");
values.Put("read", false);
values.Put("date", "???");
context.ContentResolver.Insert(Uri.Parse("content://sms/inbox"), values);

However I do not know how to format the current datetime,
I Tried ToString()
I Tried (Now - MinValue).TotalMiliSeconds
And also Now.ToString("ddMMyyhhmmss")
None gives the correct date in the inbox always 1970 january 2 or 1

A: I managed to succeed by Converting the DateTime to a Java.Util.Date
Here is my code
    private void SaveToInbox(ShortMessages shortMessage)
    {
        var now = shortMessage.MessageDate.HasValue ? shortMessage.MessageDate.Value : DateTime.Now;
        var d = new Date((now.Year - 1900), now.Month - 1, now.Day, now.Hour, now.Minute, now.Second);
        var context = Application.Context.ApplicationContext;
        var values = new ContentValues();
        values.Put("address", shortMessage.From);
        values.Put("body", shortMessage.Message);
        values.Put("read", false);
        values.Put("date", d.Time);
        context.ContentResolver.Insert(Android.Net.Uri.Parse("content://sms/inbox"), values);
    }


text:
Q: Sending NSNumber to another class method - Objective C I am having trouble sending over an NSInteger to another class.  Here is what I am doing.
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = [collectionView cellForItemAtIndexPath:indexPath];
    NSInteger tag = cell.tag;
    impact* myScript = [[impact alloc] init];
    [myScript startProcess:tag];
}

Here I am sending a NSInteger to the impact's startProcess method.  The issue is when sending it over I get the following error:
No visible @interface for 'impact' declares the selector 'startProcess:'

But the thing is I am defining the startProcess method.
Here is the impact.h file:
-(NSInteger *)startProcess;

Here is the impact.m file:
#pragma mark - Table view delegate
- (void)startProcess:(NSInteger **)number {
    [UITableView reloadData];

}

So to recap, I am trying to send over an NSInteger to another class's method and than reload the entire table.  Now sure why I am getting this error though.
Suggestions, thoughts?

A: You are on the right track, but you will notice two main problems:

*

*The declaration in the header file does not match the implementation in the implementation file. The basic format of a method is - (ReturnType)methodName:(<ParamType>)paramName; In the header you are defining a method that takes no parameters and is returning an NSInteger *. In the implementation file you are defining a method that takes an NSInteger ** and returns nothing (void). The version in the implementation file is closer to what you want.

*NSInteger is not a class but a simple type. You do not have to pass it by reference like you do objects so you can just specify the parameter as NSInteger instead of NSInteger * or NSInteger **
That leaves you with this code in the header:
- (void)startProcess:(NSInteger)number;

and this code in the implementation file
- (void)startProcess:(NSInteger)number {
    [UITableView reloadData];
}

A: There's a lot wrong here so I'll iterate through the ones I could catch first.
The first thing I noticed is that your definition for startProcess is horribly different than how its defined in your implementation.
Your header states it should return a pointer to an NSInteger and take no arguments, but your implementation says it should return nothing and take an NSInteger ** as an argument.
Furthermore, the reloadData method for UITableView is not a class method, it is an instance method. [UITableView reloadData] does not function because UITableView is a class, not an instance ( and you'd want to specify which tableView you'd want to refresh wouldn't you? )
As to answer the question, redefine your declaration in your impact.h file to be
-(void)startProcess:(NSInteger)tag;

and edit it's respected implementation to use an NSInteger as well.
I don't see why you'd need a pointer to a NSInteger.
Also, NSInteger as far as I remember is not an NSNumber, which means it's not an objective-c object. NSInteger is a typedef for a 'long'
typedef long NSInteger;


text:
Q: How to return/convert Flow from Boolean in Kotlin Coroutines? I have an Android library in which I am listening to network changes, what I want to do is, observe those changes using Flow/launch of coroutines
This is my NetworkReceiver, which lets me know when there are changes in the connection
I have taken a variable isNetworkConnectionActive which is set to false on the init of the library and is set true false in the below function based on the network changes
class ConnectionChangeReceiver: BroadcastReceiver() {
    override fun onReceive(context: Context?, p1: Intent?) {
        if(isNetworkConnectionActive(context)) {
            OfflineDataLibrary.isNetworkConnectionActive = true
            Toast.makeText(context, "isNetworkConnectionActive - YES", Toast.LENGTH_LONG).show()
        } else {
            OfflineDataLibrary.isNetworkConnectionActive = false
            Toast.makeText(context, "isNetworkConnectionActive - NO", Toast.LENGTH_LONG).show()
        }

    }

    fun isNetworkConnectionActive(context: Context?): Boolean {
        val connectivityManager: ConnectivityManager = context?.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
        var isConnectionActive = false
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            val nw      = connectivityManager.activeNetwork ?: return false
            val actNw = connectivityManager.getNetworkCapabilities(nw) ?: return false
            return when {
                actNw.hasTransport(NetworkCapabilities.TRANSPORT_WIFI) -> true
                actNw.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR) -> true
                else -> false
            }
        } else {
            val nwInfo = connectivityManager.activeNetworkInfo ?: return false
            return nwInfo.isConnected
        }
    }
}

OfflineDataLibrary which has isNetworkConnectionActive
object OfflineDataLibrary {
    lateinit var context: Context
    var isNetworkConnectionActive: Boolean = false
    fun init(ctx: Context) {
        context = ctx.applicationContext
        val offlineDataChangeListener = OfflineDataChangeListener()
        offlineDataChangeListener.observeOfflineDataChanges()
    }
}

Now I want to listen to changes happening on isNetworkConnectionActive variable using a Flow
*HERE I HAVE A TYPE MISMATCH, I WANT TO RETURN FLOW OF BOOLEAN BUT BUT I AM RETURNING BOOLEAN.
  fun getNetworkAvailability(): Flow<Boolean> {

        return OfflineDataLibrary.isNetworkConnectionActive
    }

I can access the above function and listen to changes like this
  fun getIsNetworkAvailable() {
        launch {
        OfflineDatabaseManager.getInstance(app.applicationContext).getNetworkAvailability().collect {
                //DO something
            }
        }
    }

How can I convert Boolean to Flow<Boolean>?
If you think there can be any other way to subscribe to changes happening on the network, please let me know.

A: With StateFlow you don't have to use a LiveData or a ConflatedChannel and you don't even have to convert a Channel into a Flow:
class ConnectionChangeReceiver: BroadcastReceiver() {

    private val _networkConnectionActivated = MutableStateFlow(false) //An initial value is required
    val networkConnectionActivated: StateFlow<Boolean>
        get() = _networkConnectionActivated

    override fun onReceive(context: Context?, p1: Intent?) {
        _networkConnectionActivated.value = isNetworkConnectionActive(context)
    }

    fun isNetworkConnectionActive(context: Context?): Boolean {
        val connectivityManager: ConnectivityManager = context?.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
        var isConnectionActive = false
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            val nw      = connectivityManager.activeNetwork ?: return false
            val actNw = connectivityManager.getNetworkCapabilities(nw) ?: return false
            return when {
                actNw.hasTransport(NetworkCapabilities.TRANSPORT_WIFI) -> true
                actNw.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR) -> true
                else -> false
            }
        } else {
            val nwInfo = connectivityManager.activeNetworkInfo ?: return false
            return nwInfo.isConnected
        }
    }
}

All you have to do is collect its value from outside the class. Remember it's conflated so observers won't be notified until its value changes:
myConnectionChangeReceiver.networkConnectionActivated
    .collect {  isNetworkConnectionActive ->
        //Do something here
    }

Don't forget to stop all the observers when required by cancelling all the coroutines where they're running on.
You can find StateFlow official documentation here.

A: Flow is supposed to be self-contained stream of data.
You can only send data through flow builder while initialization. You cannot randomly emit data to it from outside the builder.
So, for your purpose, you can use LiveData instead of Flow.
Just create an instance of MutableLiveData<Boolean> and return it inside getNetworkAvailability().
Whenever network state changes just call setValue() with value (or postValue() if in background thread) to send latest state.
and on the other side observe the changes using networkLiveData.observe() and use the changes to do stuff.
Besides LiveData, you can also use ConflatedBroadcastChannel.
Hope it helps.

A: I think you need a Channel, then you can convert it to a Flow using extension functions receiveAsFlow and consumeAsFlow (at the moment of writing this answer it is an experimental feature). So in an abstract manner, your code would look like:
class YouClass {
    private val networkConnectionChannel : Channel<Boolean>(Channel.CONFLATED)

    var isNetworkConnected: Boolean
    get
    set {
        field = value
        networkConnectionChannel.sendBlocking(value)
    }

    fun getNetworkConnectionFlow() : Flow<Boolean> =
        networkConnectionChannel.receiveAsFlow()
}


text:
Q: Request header and JSON parsing in Android Retrofit I'm trying to learn Retrofit and use it in the project I have right now. I have successfully implemented some basic GET and POST methods, but right now I am stuck trying to add information to the header of my request.
This is the Client class:
public class CategoryClient {

    public static final String BASE_URL = "URL is here";
    private static Retrofit retrofit = null;

    public static Retrofit getClient() {
        if (retrofit==null) {
            retrofit = new Retrofit.Builder()
                    .baseUrl(BASE_URL)
                    .addConverterFactory(GsonConverterFactory.create())
                    .build();
        }
        return retrofit;
    }
}

This is the interface with the GET method:
public interface CategoryService {

    @GET("/v3/projects/{projectId}/categories/")
    Call<CategoryResponse> getProjectCategories(@Query("projectId") String projectId);
}

This is my Category class:
public class Category2 {

    @SerializedName("_id")
    private String _id;
    @SerializedName("name")
    private String name;
    @SerializedName("tasks")
    private int tasks;

    public Category2(String _id, String name, int tasks) {

        this._id = _id;
        this.name = name;
        this.tasks = tasks;
    }

    public String get_id(){
        return _id;
    }
    public void set_id(String _id){
        this._id = _id;
    }
    public String getName(){
        return name;
    }
    public void setName(String name){
        this.name = name;
    }
    public int getTasks() {
        return tasks;
    }
    public void setTasks(int tasks){
        this.tasks = tasks;
    }
}

This is my CategoryResponse class (where I get the list of categories from the request):
public class CategoryResponse {

    private List<Category2> results;

    public List<Category2> getResults() {
        return results;
    }

    public void setResults(List<Category2> results) {
        this.results = results;
    }
}

And this is me calling it from my Activity:
categoryService =
                CategoryClient.getClient().create(CategoryService.class);

        Call<CategoryResponse> call = categoryService.getProjectCategories(projectId);
        call.enqueue(new Callback<CategoryResponse>() {
            @Override
            public void onResponse(Call<CategoryResponse> call, Response<CategoryResponse> response) {

                int statusCode = response.code();
                categoriesList2 = new ArrayList<>();
                categoriesList2 = response.body().getResults();
            }

            @Override
            public void onFailure(Call<CategoryResponse> call, Throwable t) {
                // Log error here since request failed
                Log.e(TAG, t.toString());
            }
        });

I need to add a token in the header of the request, but this token will change constantly so I can not use it above my interface with "@Header". Is there any way to add this header from my Activity?

A: In your interface modify your method with @Header
@GET("/v3/projects/{projectId}/categories/")
Call<CategoryResponse> getProjectCategories(@Query("projectId") String
projectId, @Header("Token") String token);

Later you can call this method from your activity:
String token = "someRandomtoken";
categoryService =
            CategoryClient.getClient().create(CategoryService.class);

    Call<CategoryResponse> call = categoryService.getProjectCategories(projectId, token);
    call.enqueue(new Callback<CategoryResponse>() {
        @Override
        public void onResponse(Call<CategoryResponse> call, Response<CategoryResponse> response) {

            int statusCode = response.code();
            categoriesList2 = new ArrayList<>();
            categoriesList2 = response.body().getResults();
        }

        @Override
        public void onFailure(Call<CategoryResponse> call, Throwable t) {
            // Log error here since request failed
            Log.e(TAG, t.toString());
        }
    });

A: I am working with the same scenario where I have to change the token each day and for each new user ofcourse, Interceptors will help you creating the header request and you can add it to the http client while building it.
Since your scenario is quite similar to mine, I have added my scenario here which I use and works perfect for me.
If you want to understand more about it refer here.
      Interceptor interceptorSecure = chain -> {

        Request original = chain.request();

        // Request customization: add request headers
        Request.Builder requestBuilder = original.newBuilder()
                .method(original.method(), original.body());

        requestBuilder.header("Authorization", "Bearer " + token);
        requestBuilder.header("Origin", ORIGIN_URL);
        Request request = requestBuilder.build();
        return chain.proceed(request);
      };

      //after that use this to http client builder
      //add it to your httpClientBuilder
      yourHttpClientBuilder.addInterceptor(interceptorSecure);
      OkHttpClient client = yourHttpClientBuilder.build();

      //this is your retrofit builder, the way you have built with base url and gson convertors..
      Retrofit retrofit = yourRetrofitBuilder.client(client).build();
      retrofit.create(CategoryService.class);


text:
Q: Regex with negative Lookahead with special grouping I'm trying to construct a regex pattern, that matches only if another pattern does not exist before...
I need to match §+\s?(\d+)
It is important that the group (\d+) is the first group in the result set (it is what I need to extract from the input and it would be ways more easier if it is the first group)
What must not be present anywhere before that match is \d+ [A-Z]{2} [A-Z]{3}
What I have so far is
^.*(?!\d+ [A-Z]{2} [A-Z]{3}).*§+\s?(\d+).*$

First it is not working and second I wonder if the negative Lookeahead is present as a group if it matches, because then I need another solution as mentioned above.
Valid examples
Whatever §§ 123 might contain after 1234 AB CDE
Whatever §1 the big brown fox

Invalid example
must not contain before 1234 AB CDE §§ 123

Hopefully this is not a big deal.
Thank you for reading!

A: In VB.NET, in .NET regex, you may use an infinite-width negative lookbehind:
(?<!\d+\s+[A-Z]{2}\s+[A-Z]{3}\s.*)§+\s?(\d+)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

See the regex demo
The (?<!\d+\s+[A-Z]{2}\s+[A-Z]{3}\s.*) construct is a negative lookbehind failing a match if there is:

*

*\d+ - 1+ digits

*\s+ - 1+ whitespaces

*[A-Z]{2}  - 2 uppercase ASCII letters

*\s+ - 1+ whitespaces

*[A-Z]{3} - 3  uppercase ASCII letters

*\s - a whitespace

*.* - any 0+ chars other than a newline, as many as possible

... before the

*

*§+ - 1+ § symbols

*\s? - 1 or 0 (optional) whitespace

*(\d+) - Group 1: one or more digits.


text:
Q: General Theorem About Symmetric Polynomials Let $F$ be a field. It is known that

1. Every symmetric polynomial in $F[x_1, \ldots, x_n]$ can be expressed as a polynomial in the elementary symmetric polynomials.

A polynomial $f\in F[x_1, \ldots, x_n]$ is said to be semi-symmetric if $f(x_{\sigma(1)}, \ldots, x_{\sigma(n)})=f(x_1, \ldots, x_n)$ for every even permutation $\sigma\in S_n$. We have

2. Every semi-symmetric polynomial in $F[x_1, \ldots, x_n]$ is of the form $f+\delta g$ where $f$ and $g$ are symmetric polynomials and $\delta=\prod_{i<j}(x_i-x_j)$.

A natural question arises. For a subgroup $G$ of $S_n$, let us say that a polynomial $f\in F[x_1, \ldots, x_n]$ is $G$-symmetric if $f(x_{\sigma(1)}, \ldots, x_{\sigma(n)})=f(x_1, \ldots, x_n)$ for all $\sigma\in G$.

Question. Are there some general results known about $G$-symmetric polynomials for an arbitrary subgroup $G$ of $S_n$?

A: This is a big subject called invariant theory. Here are some nice lecture notes I stumbled on when researching this answer. I can try to point out the main results.
Let $G$ be a subgroup of $S_n$. Let $S = k[x_1, x_2, \ldots, x_n]$ for a field $k$, let $A$ be the subring of $G$-invariants and let $R$ be the subring of $S_n$ invariants , so $R \subset A \subset S$. As you say, $R$ is generated by the elementary symmetric polynomials. Also, by Galois theory, $[\mathrm{Frac}(A) : \mathrm{Frac}(R)] = [S_n : G]$.
Note that the ring $S$ is finitely generated as an $R$-module (in fact, it is free -- a basis is the monomials $x_1^{a_1} x_2^{a_2} \cdots x_n^{a_n}$ with $0 \leq a_j \leq n-j$). Since $R$ is Noetherian, this shows that $A$ is also finitely generated as an $R$-module. So at least there will be a finite list of polynomials, analogous to your example of $\{ 1, \delta \}$ in the case $G = A_n$.
Life is much better than that! Assuming the characteristic of $k$ does not divide $\#(G)$, the ring $A$ is Cohen-Macaulay! (Theorem 8.1 in the linked notes. I believe the original source is Hochster and Eagon "Cohen-Macaulay Rings, Invariant Theory, and the Generic Perfection of Determinantal Loci" 1971, Proposition 13.) Using the properties of Cohen-Macaulay rings, one can show that $A$ is in fact free as an $R$-module. Since $[\mathrm{Frac}(A) : \mathrm{Frac}(R)] = [S_n : G]$, the rank of this free module in $[S_n:G]$.
Thus, there always exist polynomials $f_1$, $f_2$, ..., $f_{[S_n:G]}$ providing a free basis of $A$ over $R$. One can show that the $f_j$ can always be taken homogenous, and their degrees can be computed by Molien's formula:
$$\frac{1}{\#(G)} \sum_{g \in G} \frac{1}{\det(\mathrm{Id} - t g)} = \frac{ \sum_{j=1}^{[S_n:G]} t^{\deg f_j}}{(1-t)(1-t^2) \cdots (1-t^n)} .$$
On the left hand side, we have identified a permutation $g$ with its permutation matrix.
For example, suppose we wanted to study polynomials in $x_1$, $x_2$, $x_3$, $x_4$ invariant under the dihedral symmetry group $G=\langle (12)(34), \ (1234) \rangle$. The left hand side is
$$\frac{1}{8} \left( \frac{1}{(1-t)^4} + \frac{2}{(1-t)^2(1-t^2)}+\frac{3}{(1-t^2)^2}+\frac{2}{(1-t^4)} \right).$$
because $G$ contains one element of cycle type $1^4$, two of cycle type $1^2 2$, three of cycle type $2^2$ and two of cycle type $4$. We compute that this sum is
$$\frac{1+t^2+t^4}{(1-t)(1-t^2)(1-t^3)(1-t^4)}$$
Thus, $A$ is free over $R$ with generators in degrees $0$, $2$ and $4$. An explicit choice is $\{ 1, x_1 x_3+x_2 x_4, (x_1 x_3+x_2 x_4)^2 \}$.


text:
Q: Handle device lock and screen timeout In my application, I want to show the application's lock screen when user lock the phone and unlock it and I don't want to implement this feature when the display goes off and on (screen timeout).
We can use Intent.ACTION_SCREEN_OFF/ Intent.ACTION_SCREEN_ON to show the application's lock screen when user lock the phone and unlock it. But this could lock the app even when screen display goes off and on which I don't want to.
Do anybody have any idea about this? I mean how not to show the application lock screen when screen display goes off and on?


text:
Q: How can I replace command git log --first-parent (any analogues?) I have an old git version in CI and can't update it
git version: 1.8.3.1
but I need this command git log --first-parent
Are there any analogues of this command that can be used in versions up to 1.8.3.1?


text:
Q: How to make yield work with this.req.on('data') without requiring more modules? Obviously, the reason here is because of the async nature of on('data'), and the combination of using yield, but how can I make this work? I tried "thunkifying" _this.req.on, but to no avail. I'm still getting the hang of generators, yield and thunks but I'm a bit stumped here.
Is there any other clever solution without requiring another module dependency?
var thunkify = require('thunkify');
var request = thunkify(require('request'));

//...

if (['GET', 'DELETE'].indexOf(_this.req.method) === -1) {
        _this.req.on('data', function(chunk) {
            options.json = chunk.toString();
        });
    }

//...

var resp = yield request(options);
_this.body = resp[0].body;

A: I was able to make this work by using co-body module. Here's an example:
var thunkify = require('thunkify');
var request = thunkify(require('request'));
var parse = require('co-body');

//...

if (['GET', 'DELETE'].indexOf(_this.req.method) === -1) {
        options.json = yield parse.json(_this.req);
    }

//...

var resp = yield request(options);
_this.body = resp[0].body;

BUT, I don't like the fact that I have to require another module every time I have to do something. Anyone got a better one?


text:
Q: Proof with using combination proof (no algerbic methods) that $n^2=\sum_{i=1}^n (2i-1)$ I have the following problem :
Proof using combination :
$$n^2=\sum_{i=1}^n (2i-1)$$
I used the following problem :
Problem : Number of vectors of length $2$, with letters $\{1,2,..,n\}$
Left : choose the first letter $n$ possibilities then choose the second letter $n$ possibilities.
Right : I can't figure it out, what $(2i-1)$ has to do?
Any ideas?
Thanks!

A: $2i-1$ is the number of vectors of length $2$ with letters $1,\cdots ,n$ for which the maximum entry is exactly $i$

A: You can draw square $n\times n$ and inside this square another squares $(n-1)\times(n-1)$,... with the same vertex and use $n^2-(n-1)^2=2n-1.$


text:
Q: Aspose.Word alternatives Does anyone know of a good Aspose.Word alternative (or similar) product?
Can you mention any pro/con for using either?
I am currently evaluating Aspose.Word, and although it works like a charm, it's missing some of the functionalities that I require.
UPDATE: We ended up writing our own DOCX generator. We are still using Aspose.Word to convert to DOC/HTML when needed.

A: Our team is using Docentric Toolkit Professional Edition. One of the most important reasons for our decision was also it's relatively affordable price for teams of up to 5 developers.
The toolkit works nice with MS Office 2007/2010/2013. In our scenario, reports are produced centrally on the server, using our custom developed reporting engine, which uses Docentric api calls. Because Docentric uses OpenXML, no Word installation is needed on the server.
We have several hundreds different templates, which are ordinary Word documents, enhanced with placeholders which Docentric recognizes and fills with data at runtime during report creation.
Other features which we are using extensively are tables (included nested ones), images, graphs, conditional content and Header/Footer dynamic content.

A: I don't know if it's suited for your purpose but you might want to have a look at the b2xtranslator project on SourceForge:

http://b2xtranslator.sourceforge.net/

A: TX Text Control has an express version, but it doesn't have all the features the full version has. The express is free, and I've used it, and if your sole purpose is to create a word processor, it will not provide all of the features. Like Aspose.Words, buying the full version is REALLY expensive ($2,398.00!), and in my opinion, a ripoff.
The pros and cons are evaluating the free version
Cons:

*

*No spell check in the free version

*Cannot read .docx or .doc in the free version

*No headers, footers, or dragable textboxes (like there are in Word) in the free version

Pros:

*

*Free

*Page breaks

*Basic Document editing features

Our company used it for a bit, but got sick of the lack of features, and ended up just ditching it.

A: If Java is an option (or a preference), you could try docx4j


text:
Q: How can I make histogram without using numpy histogram import cv2
import numpy as np
import matplotlib.pyplot as plt

def my_histogram(img, bins, range):
    hist =
    return hist

I need to fill out hist without using np.histogram or other histogram function
img = cv2.imread('sample.jpg')
img_g = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
hist = my_histogram(img_g, 256, [0,256])

plt.plot(hist)
plt.xlim([0,256])
plt.show()

A: np.unique is a less efficient histogram utility, since it sorts the data instead of processing it directly:
bins, hist = np.unique(img.ravel(), return_counts=True)

A: I won't provide you with the exact answer since this looks like a homework. Basically each pixel in your grayscale image has a number associated to it that range from 0 to 255. What you want to do is sum the number of pixels that have the same value (how many have the value 0, how many have the value 1, how many have the value 2, etc.). You probably can use numpy to help you without calling the histogram function (take a look at this link for example).
You can then plot you bar graph with matplotlib, to show your histogram.


text:
Q: System.Text.Json: Handling Infinity values From what I can tell, this is the appropriate way to handle double "Infinity" values when using NewtonsoftJson, to avoid those values when serializing.
x.SerializerSettings.FloatFormatHandling = FloatFormatHandling.DefaultValue;

What is the corresponding way to do this when using System.Text.Json?

A: Without a custom converter you cannot instruct System.Text.Json to write a 0, but - for the record - NaN and the infinities can be handled with JsonNumberHandling.AllowNamedFloatingPointLiterals.
From JsonNumberHandling Enum:

The "NaN", "Infinity", and "-Infinity" String tokens can be read as floating-point constants, and the Single and Double values for these constants will be written as their corresponding JSON string representations.

using System.Text.Json;

var options = new JsonSerializerOptions {
        NumberHandling = System.Text.Json.Serialization.JsonNumberHandling.AllowNamedFloatingPointLiterals
    };

Console.WriteLine(JsonSerializer.Serialize(Double.NaN, options));
Console.WriteLine(JsonSerializer.Serialize(Double.NegativeInfinity, options));
Console.WriteLine(JsonSerializer.Serialize(Double.PositiveInfinity, options));

Console.WriteLine(JsonSerializer.Deserialize<double>("\"NaN\"", options));
Console.WriteLine(JsonSerializer.Deserialize<double>("\"-Infinity\"", options));
Console.WriteLine(JsonSerializer.Deserialize<double>("\"Infinity\"", options));

prints
"NaN"
"-Infinity"
"Infinity"
NaN
-∞
∞

A: I ended up using a custom converter.
In startup.cs
.AddJsonOptions(options =>
            options.JsonSerializerOptions.Converters.Add(new DoubleInfinityConverter())
        );

The converter
internal class DoubleInfinityConverter : JsonConverter<double>
{
    public override double Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) => reader.GetDouble();

    public override void Write(Utf8JsonWriter writer, double value, JsonSerializerOptions options)
    {
        if (double.IsNaN(value) || double.IsInfinity(value))
        {
            writer.WriteStringValue(default(double).ToString());
            return;
        }
        writer.WriteStringValue(value.ToString());
    }
}


text:
Q: Change default pagination style in wordpress I am beginner in WordPress and started to learn it. I am designing a new child theme from an existing parent theme. The Pagination of Home page in parent
«   Previous   1   2   3   Next   »

But I want to modify it like this:
Page 1 of 45   1   2   3   NEXT   10    20    30    LAST

Following is my code :
if (!is_singular()) {
            global $wp_query, $rtp_post_comments;
            if (isset($rtp_post_comments['pagination_show']) && $rtp_post_comments['pagination_show']) {
                if (( $wp_query->max_num_pages > 1)) {
                        ?>
                    <?php
                    echo "Page 1 of " . $wp_query->max_num_pages . "";
                    echo paginate_links(array(
                        'base' => str_replace(999999999, '%#%', esc_url(get_pagenum_link(999999999))),
                        'format' => '?paged=%#%',
                        'current' => max(1, get_query_var('paged')),
                        'total' => $wp_query->max_num_pages,
                        'prev_text' => esc_attr($rtp_post_comments['prev_text']),
                        'next_text' => esc_attr($rtp_post_comments['next_text']),
                        'end_size' => $rtp_post_comments['end_size'],
                        'mid_size' => $rtp_post_comments['mid_size']
                    ));
                        ?>
                    <?php
                }
            } elseif (function_exists('wp_pagenavi')) {
                wp_pagenavi();
            } elseif (get_next_posts_link() || get_previous_posts_link()) {
                    ?>

                    <?php if (get_next_posts_link()) { ?>
<?php next_posts_link(__('Older Entries')); ?>
<?php } ?>
                    <?php if (get_previous_posts_link()) { ?>
<?php previous_posts_link(__('Newer Entries')); ?>
<?php } ?>
                <?php
            }
        }

Where should I change this?

A: Have a look at paginate links codex page
paginate_links() is located in wp-includes/general-template.php. (It is not advised to edit the core files.)
Or you can try this plugin: WP-PageNavi which will give an option to add "Page 1 of 45" on the beginning.

A: I've found that for some of the custom stuff wordpress functions are less than understandable. But a nice workaround is this:
global $page, $numpages;

if ( $numpages > 1 ) :
                if ( $page == 1 ) {
                    $prev_link = ' ';
                    $next_link = 'Next Page';
                } else if ( $page == $numpages ) {
                    $prev_link = 'Prev. Page';
                    $next_link = ' ';
                } else {
                    $prev_link = 'Prev. Page';
                    $next_link = 'Next Page';
                }
            ?>

<?php echo $prev_link; ?>

<?php echo $page.' / '.$numpages; ?>

<?php echo $next_link ?>

This is very easy to customize, style AND understand.


text:
Q: Area of shapes in python So I have a function called the_rectangle that I run twice to create two rectangles. However, I want python to figure out the Area's of each rectangle and determine which is bigger by printing ("The bigger rectangle's area is: )
and then printing ("The smaller rectangle's area is: ). Also I want it to use the arguments width and length to find the value of each area. Is this possible?
import turtle
import math

def the_rectangle(width, length, color):
    turtle.color(color)
    turtle.begin_fill()
    turtle.forward(width)
    turtle.left(90)
    turtle.forward(length)
    turtle.left(90)
    turtle.forward(width)
    turtle.left(90)
    turtle.forward(length)
    turtle.left(90)
    turtle.end_fill()

def main():
    the_rectangle(200, 100, "red")
    turtle.penup()
    turtle.forward(300)
    turtle.pendown()
    the_rectangle(100, 250, "yellow")

main()

A: Try making your rectangle a class. That way you have all your data in one place.
class Rectangle:
    def __init__(self, length, width, color): # Initialization
        self.length = length
        self.width = width
        self.color = color

    def draw(self, turtle): # Draws the rectangle
        turtle.color(color)
        turtle.begin_fill()
        turtle.forward(width)
        turtle.left(90)
        turtle.forward(length)
        turtle.left(90)
        turtle.forward(width)
        turtle.left(90)
        turtle.forward(length)
        turtle.left(90)
        turtle.end_fill()

    def area(self): # Calculates the area
         return self.length * self.width

To use this class to compare areas, simply use the below code.
def main():
    rectangle1 = Rectangle(200, 100, "red")
    a1 = rectangle1.area()
    rectangle2 = Rectangle(100, 250, "yellow")
    a2 = rectangle2.area()

    print("The bigger rectangle's area is:", str(max(a1, a2)))
    print("The smaller rectangle's area is:", str(min(a1, a2)))

    # Draw the rectangles
    rectangle1.draw()
    turtle.penup()
    turtle.forward(300)
    turtle.pendown()
    rectangle2.draw()

A: If you are trying to determine which rectangle is bigger, then storing the rectangle (or its area) is going to be paramount. You could calculate the area before or after the rectangle is drawn, based on dimensions:

# This will allow you to create a rectangle and store its area
# as a three-element tuple
def area(l, w):
    # returns a three-element tuple to represent a rectangle
    return (l, w, l*w)

Now, you can take the rectangle you return, and draw it. I'd unpack the dimensions using argument unpacking with *, and then you know you will just duplicate the length and width to draw it, lessening the amount of extra code you have to write:
def draw_rectangle(*dimensions, color="red"):
    dims = dimensions[:2]*2 # creates a list [l, w, l, w]
    for dim in dims:
        turtle.forward(dim)
        turtle.left(90)

Now, to compare a rectangle, one is truly bigger than another if its area is larger, and therefore you can take any number of rectangles and pair them using itertools.combinations. Then you compare each pair and you can print the results out:
from itertools import combinations

def compare_recs(*rectangles):
    for r1, r2 in combinations(rectangles, 2):
        # The third element of your tuple, denoted by the index [2],
        # is your area, which is what you are comparing against here
        bigger, smaller = (r1, r2) if r1[2] >= r2[2] else (r2, r1)
        print(f"The bigger rectangle is {bigger}")
        print(f"The smaller rectangle is {smaller}")

r1 = area(10, 20)
r2 = area(10, 15)
draw_rectangle(*r1, color='red')
draw_rectangle(*r2, color='yellow')

compare_recs(r1, r2)
The bigger rectangle is (10, 20, 200)
The smaller rectangle is (10, 15, 150)

You could do this with classes, but I think this is a fair place to start if you're new with Python.

A: There are a lot of ways to accomplish what you want, but the simplest modification to your existing code may be to have "the_rectangle" return the area.
You need to get the returned value and calculate the max/min area.
If you want to make this a larger-scale program, you'll need to go to creating classes, like mentioned in the other answers.
import turtle
import math

def the_rectangle(width, length, color):
    # This function draws a rectangle and returns the area
    turtle.color(color)
    turtle.begin_fill()
    turtle.forward(width)
    turtle.left(90)
    turtle.forward(length)
    turtle.left(90)
    turtle.forward(width)
    turtle.left(90)
    turtle.forward(length)
    turtle.left(90)
    turtle.end_fill()
    return width*length

def main():
    area_1 = the_rectangle(200, 100, "red")
    turtle.penup()
    turtle.forward(300)
    turtle.pendown()
    area_2 = the_rectangle(100, 250, "yellow")
    print("Largest rectangle is " + str(max(area_1,area_2)))
    print("Smallest rectangle is " + str(min(area_1,area_2)))

main()

A: If you don't want to update existing function the_rectangle, you can create a decorator function which will print the area of rectangle, this area can be saved and later used to compare with other rectangle's area to check which is smaller and which is larger.
This is the sample code:
def area(function):
    def wrapper(*args):
        print('Area of rectangle %d*%d is: %d' % (args[0], args[1], args[0]*args[1]))
        return function(*args)
    return wrapper

@area
def the_rectangle(width, length, color):
    ...


text:
Q: Use Accelerometer for Roll-a-ball Movement I'm working on maze game for Android in Unity 5.1.1f1 and I have troubles with controlling my ball with accelerometer. At start I tried:
public class PlayerController : MonoBehaviour {

    public GameObject sphere;
    public Camera camera;
    public float speed=200;

    private Rigidbody myRigidBody;

    void Start()
    {
        myRigidBody = gameObject.GetComponent<Rigidbody> ();
    }

    void FixedUpdate()
    {
        float moveH = Input.acceleration.x;
        float moveV = -Input.acceleration.z;

        Vector3 move = new Vector3 (moveH, 0.0f, moveV);
        myRigidBody.AddForce (move * speed*Time.deltaTime);
    }
}

But the ball is not moving as it should. Then I tried another solution. But my ball still doesn't move right. It seems like it's sometimes hard to move left/right/forward/backward, also it's possible my ball will rotate in the opposite direction.
public class PlayerController : MonoBehaviour {

    public float speedAc = 10;

    //accelerometer
    private Vector3 zeroAc;
    private Vector3 curAc;
    private float sensH = 10;
    private float sensV = 10;
    private float smooth = 0.5f;
    private float GetAxisH = 0;
    private float GetAxisV = 0;

    // Use this for initialization
    void Start () {

        ResetAxes();
    }

    //accelerometer
    void ResetAxes(){
        zeroAc = Input.acceleration;
        curAc = Vector3.zero;
    }

    void FixedUpdate () {

        curAc = Vector3.Lerp(curAc, Input.acceleration-zeroAc, Time.deltaTime/smooth);

        GetAxisH = Mathf.Clamp(curAc.x * sensH, -1, 1);
        GetAxisV = Mathf.Clamp(-curAc.z * sensV, -1, 1);

        Vector3 movement = new Vector3 (GetAxisH, 0.0f, GetAxisV);
        GetComponent<Rigidbody>().AddForce(movement * speedAc);
    }
}

Can someone help me, please?

A: I have answered this one in another SO question: Unity 3D realistic accelerometer control - you've got two variants of control there, just copy the one you find fit.
If you're having more problems, ask.


text:
Q: Save and update a json file with a foreign key? I need to save some data about a merchandise in a database and in a json file.
I have a name,and a category, that is a foreign key.
How can I have a structure like that in a json file? And can I?
I would need something like this...
{
"id":1,
"name":"Merchandise #1",
"category":{
  "id":1,
  "name":"category #1"
  }
}

How can I save and edit this file? Do I do it as it is normal,how do I treat this category part? If I do,do I duplicate the category name and id for every entry?
My model classes would be:
public class Category
{

public int id {get; set;}
public string name {get; set;}

}

public class Merchandise
{

public int id {get; set;}
public string name {get; set;}

public int categoryId {get; set;}
public Category category {get; set;}

}

A: This would be the code for saving the data...Edit is similar.
 private void MerchInsert()
    {
        RootObject product = new RootObject();
        product.name = "Apple";
        product.id = 3;

        Category cat = new Category();
        cat.id = 3;
        cat.name = "category";
        product.category = cat;
        string objjsonData = JsonConvert.SerializeObject(product);
        File.WriteAllText(jsonFileM, objjsonData);
   }


text:
Q: Best way to extract text from a photo/image in React Native? I am building an app with React Native.
After a user takes a photo of an invoice, I would like to be able to extract some key data from the text in the image. I know I will need an OCR of some sort. Is there an easy solution to this? I've seen react-native-text-detector. Is that my best option? Is there a best solution to this?

A: You can use react-native-firebase-mlkit. It has a lot more functionality than just performing OCR. It also has both on-device support and cloud based support depending on your need.

Here is the library's GitHub page.
It's a wrapper for Google's ML Kit

Heres's a simple example of how to use it:
import RNMlKit from 'react-native-firebase-mlkit';

export class textRecognition extends Component {
  ...

  async takePicture() {
    if (this.camera) {
      const options = { quality: 0.5, base64: true, skipProcessing: true, forceUpOrientation: true };
      const data = await this.camera.takePictureAsync(options);
      // for on-device (Supports Android and iOS)
      const deviceTextRecognition = await RNMlKit.deviceTextRecognition(data.uri);
      console.log('Text Recognition On-Device', deviceTextRecognition);
      // for cloud (At the moment supports only Android)
      const cloudTextRecognition = await RNMlKit.cloudTextRecognition(data.uri);
      console.log('Text Recognition Cloud', cloudTextRecognition);
    }
  };

  ...
}


text:
Q: With MavensMate I get the error Could not update lightning components: Cannot read property 'Id' of undefined I am using Sublime Text and MavensMate.
I created a new lightning component in the dev console and then added it to the package in MavensMate.  Usually at this point I have to clean my project or I get the error.  Now nothing seems to fix it.
When I try to compile my component I get "[ERROR]: Could not update lightning components: Cannot read property 'Id' of undefined."
I have tried:

*

*deleting the .lightning file in config

*cleaning the project

*creating a new project

*refreshing the metadata and updating the project.

none of them helped.
I manually added the component, css, controller, and helper to the .lightning file and that worked until I updated my project and then it lost the updates to the .lightning file.
Does anyone have a suggestion on how to get my component to compile?

A:
I don't have an answer to your problem, however mavens mate is no longer maintained. You should look into vscode with the Salesforce extensions. You do not have to use scratch orgs to develop and can connect to sandboxes – Programmatic Jul 15 at 20:55

this is exactly what I had to do.  I have shifted to VSCode and found that most of what I do in sublime works in vscode with extensions.