问:
div style display:inline-block doesn't work when printing. When I removed, it prints the first page blank
```<code>.gunlukProgramCerceve {
    width: 100%;
    height: auto;
    /*display: inline-block;*/
    border-bottom: 1px dashed #0274bd;
    padding: 0.2%;
    margin-top: 2px;
    margin-bottom: 3px;
}

<tr class="gosterme islem   @(item.isSaatBelirsiz? "saatbelirsizelem" : " saatbellielem nosort")">
                            <td colspan="2">
                                <input type="hidden" name="ID" value="@item.ID" />
                                <input type="hidden" name="SiralamaTarih" value="@(item.SiralamaTarih==null?item.Tarih:item.SiralamaTarih)" />
                                <table class="ictablo" width="100%" style="text-align:left;border-bottom: 0px; vertical-align:top;">
                                    <tr class="@renkClass prgOzet" data-link="@Url.Action("ProgramOzetTooltip", "Program", new { ID = item.ID, area = "yonetim", TurID = item.TurID,Tarih=item.Tarih.Value.ToString("dd.MM.yyyy HH:mm") })">
                                        <td colspan="2">
                                            <div style=" ">
                                                <div class="gunlukProgramCerceve">
                                                    <div class="gunlukProgramBaslik">
                                                        <span class="saatYazi" style="font-weight:bold;">
                                                            @if (item.isSaatBelirsiz)
                                                            {

                                                                @("../..")

                                                            }
                                                            else
                                                            {
                                                                @item.Tarih.Value.ToString("HH:mm")
                                                            }

                                                        </span>
</code>```

It doesn't print when display:inline-block is in div style. It gives an error loading preview. When I remove it, the first page is blank. Actually, the first page is blank when there is a lot of data(picture 1). It works fine when there is little data(picture 2).

All code:

```<code>   <tbody class="SaatBelli sortelem" style="display:@(Model.Liste.Any(d =>d.DurumID!=prgSablonID&& ((d.Sure != Sabitler.PrgTumGun && (!d.isSaatBelirsiz||(d.isSaatBelirsiz&&(d.SiralamaTarih!=null&&d.SiralamaTarih <= SBSiralamaTarih))))))?"":"none")">
                    @foreach (var item in Model.Liste.Where(d => d.DurumID != prgSablonID && ((d.Sure != Sabitler.PrgTumGun && (!d.isSaatBelirsiz || (d.isSaatBelirsiz && (d.SiralamaTarih != null && d.SiralamaTarih <= SBSiralamaTarih)))))).OrderBy(d => d.SiralamaTarih))
                    {
                        string renkClass = "";

                        if (item.TurID == (int)Sabitler.ZiyaretTur.Program)
                        {
                            renkClass = item.DurumID == prgGerceklestiID ? "kayitGray" : (item.DurumID == prgIptalID || item.DurumID == prgGerceklesmediID) ? "kayitRed" : "";
                        }
                        else if (item.TurID == (int)Sabitler.ZiyaretTur.Arz)
                        {

                            renkClass = item.DurumID == ArzEdildiID ? "kayitGray" : (item.DurumID == ArzEdilemediID || item.DurumID == ArzIptalID) ? "kayitRed" : "";
                        }
                        else if (item.TurID == (int)Sabitler.ZiyaretTur.Bilgi)
                        {

                            renkClass = item.DurumID == BilgiGerceklestiDurumID ? "kayitGray" : (item.DurumID == BilgiGerceklesmediDurumID) ? "kayitRed" : "";
                        }

                        string KayitTurYazi = Fonksiyonlar.ProgramKayitTurYaziVer(item.TurID, item.DurumID);

                        <tr class="gosterme islem   @(item.isSaatBelirsiz? "saatbelirsizelem" : " saatbellielem nosort")">
                            <td colspan="2">
                                <input type="hidden" name="ID" value="@item.ID" />
                                <input type="hidden" name="SiralamaTarih" value="@(item.SiralamaTarih==null?item.Tarih:item.SiralamaTarih)" />
                                <table class="ictablo" width="100%" style="text-align:left;border-bottom: 0px; vertical-align:top;">
                                    <tr class="@renkClass prgOzet" data-link="@Url.Action("ProgramOzetTooltip", "Program", new { ID = item.ID, area = "yonetim", TurID = item.TurID,Tarih=item.Tarih.Value.ToString("dd.MM.yyyy HH:mm") })">
                                        <td colspan="2">
                                            <div style=" ">
                                                <div class="gunlukProgramCerceve">
                                                    <div class="gunlukProgramBaslik">
                                                        <span class="saatYazi" style="font-weight:bold;">
                                                            @if (item.isSaatBelirsiz)
                                                            {

                                                                @("../..")

                                                            }
                                                            else
                                                            {
                                                                @item.Tarih.Value.ToString("HH:mm")
                                                            }

                                                        </span>
                                                        @if (item.Sure != 0)
                                                        {
                                                            <br /><span class="programsurec saatYazi">@(item.Sure == Sabitler.ProgramSuresiBelirsiz ? " Süre belirsiz " : Fonksiyonlar.ToplantiSureCevir(item.Sure))</span>
                                                        }
                                                        @if (item.TurID != (int)Sabitler.ZiyaretTur.Program)
                                                        {
                                                            <br /><span class="programdurum saatYazi @(item.TurID == (int)Sabitler.ZiyaretTur.Arz ? "programArzBg" : "programZiyaretciBg")">
                                                                @(KayitTurYazi)
                                                                @if (DvtKesinDegilDurumID == item.DurumID)
                                                                {
                                                                    <span class="davetKatilimKesinDegil tooltips" data-original-title="Katılım Kesin Değil"> ? </span>
                                                                }
                                                            </span>
                                                        }
                                                        else if (item.TurID == (int)Sabitler.ZiyaretTur.Program && isTaslakprgVar && item.KategoriID == TaslakPrgKategori.ID)
                                                        { <br />
                                                            <span class="programdurum saatYazi programArzBg">
                                                                Taslak
                                                            </span>
                                                        }
                                                    </div>
                                                    <div class="gunlukProgramDetay">
                                                        <span class="icerikBolum" style="display:block;">
                                                            @if ((item.TurID != (int)Sabitler.ZiyaretTur.Ziyaret || item.isRandevuAciklama))
                                                            {
                                                                @Html.Raw(item.Aciklama)

                                                            }
                                                            @if (Model.Filtre.EkstraNot && !string.IsNullOrEmpty(item.EkstraNot))
                                                            {
                                                                <span style="color:red">@item.EkstraNot</span>
                                                            }
                                                        </span>
                                                        @if (!string.IsNullOrEmpty(item.PrgNotu) && item.TurID != (int)Sabitler.ZiyaretTur.Ziyaret && Model.Filtre.PrgNot)
                                                        {
                                                            <span class="katilimcilarNot icerikBolum"> @(Html.Raw(item.PrgNotu))</span>
                                                        }
                                                        @if (string.IsNullOrEmpty(item.Aciklama) && item.TurID != (int)Sabitler.ZiyaretTur.Program && item.katilimcilar.Any() && !Model.Filtre.Katilimci)
                                                        {
                                                            YeniKisiModel katilimci = item.katilimcilar.FirstOrDefault();
                                                            if (katilimci != null)
                                                            {

                                                                <b>@(KayitTurYazi + " :" + katilimci.AdSoyad )</b>
                                                                <span class="icerikBolum" style="font-size:@(Model.Filtre.yazi)px;"> @(katilimci.Aciklama)</span>

                                                            }

                                                        }
                                                        @if (item.katilimcilar.Any() && ((Model.Filtre.Katilimci && (item.TurID != (int)Sabitler.ZiyaretTur.Davetiye))))
                                                        {
                                                            bool isFirst = false;
                                                            <br />
                                                            foreach (var jitem in item.katilimcilar)
                                                            {
                                                                @(Html.Raw(isFirst ? "<br />" : ""))

                                                                <div class="katilimcilar icerikBolum">
                                                                    @(jitem.AdSoyad)
                                                                </div>
                                                                if (!string.IsNullOrEmpty(jitem.Aciklama))
                                                                {

                                                                    <span class="icerikBolum" style="font-size:@(Model.Filtre.yazi)px;"> @(jitem.Aciklama)</span>
                                                                }

                                                                if (!isFirst)
                                                                {
                                                                    isFirst = true;
                                                                }
                                                            }
                                                        }
                                                    </div>
                                                </div>
                                            </div>
                                        </td>
                                    </tr>
                                </table>
                                @if (Fonksiyonlar.YetkiKontrol("Program Ekle##") && isPrgGosterim && !Model.Filtre.isDisardan &&
                                    (!isKisitli ||
                                (isKisitli &&
                                ((GunSinir == (int)Sabitler.ProgramGunSinir.SadeceGecmis && Trh.Date >= BugunBas) ||
                                (GunSinir == (int)Sabitler.ProgramGunSinir.SadeceGelecek && Trh.Date <= BugunSon) ||
                                (GunSinir >= 0 && (Trh.Date >= SinirBasTarih && Trh.Date < SinirBitTarih))))))
                                {
                                    <div class="yeniekle hidden-print" onclick="YeniProgramModal(0,'@string.Format("{0:00}", item.Tarih.Value.Hour):00','@(Trh.ToString("dd-MM-yyyy"))');"><span><i class="fa fa-plus"></i> yeni ekle</span></div>
                                }
                                <div class="hidden-print bg-gosterme">
                                    <label class="font-xs" for="gosterme"> Yazıcıda Gösterme <input type="checkbox" id="gosterme" class="yazicidagosterme" /></label>
                                </div>
                            </td>
                        </tr>
                    }

                    </tbody>
</code>```

Body:
.gunlukProgramCerceve {
    width: 100%;
    height: auto;
    /*display: inline-block;*/
    border-bottom: 1px dashed #0274bd;
    padding: 0.2%;
    margin-top: 2px;
    margin-bottom: 3px;
}

                                <input type="hidden" name="ID" value="@item.ID" />
                                <input type="hidden" name="SiralamaTarih" value="@(item.SiralamaTarih==null?item.Tarih:item.SiralamaTarih)" />

                                                            @if (item.isSaatBelirsiz)
                                                            {

                                                                @("../..")

                                                            }
                                                            else
                                                            {
                                                                @item.Tarih.Value.ToString("HH:mm")
                                                            }

It doesn't print when display:inline-block is in div style. It gives an error loading preview. When I remove it, the first page is blank. Actually, the first page is blank when there is a lot of data(picture 1). It works fine when there is little data(picture 2).

All code:

d.DurumID!=prgSablonID&& ((d.Sure != Sabitler.PrgTumGun && (!d.isSaatBelirsiz||(d.isSaatBelirsiz&&(d.SiralamaTarih!=null&&d.SiralamaTarih <= SBSiralamaTarih))))))?"":"none")">
                    @foreach (var item in Model.Liste.Where(d => d.DurumID != prgSablonID && ((d.Sure != Sabitler.PrgTumGun && (!d.isSaatBelirsiz || (d.isSaatBelirsiz && (d.SiralamaTarih != null && d.SiralamaTarih <= SBSiralamaTarih)))))).OrderBy(d => d.SiralamaTarih))
                    {
                        string renkClass = "";

                        if (item.TurID == (int)Sabitler.ZiyaretTur.Program)
                        {
                            renkClass = item.DurumID == prgGerceklestiID ? "kayitGray" : (item.DurumID == prgIptalID || item.DurumID == prgGerceklesmediID) ? "kayitRed" : "";
                        }
                        else if (item.TurID == (int)Sabitler.ZiyaretTur.Arz)
                        {

                            renkClass = item.DurumID == ArzEdildiID ? "kayitGray" : (item.DurumID == ArzEdilemediID || item.DurumID == ArzIptalID) ? "kayitRed" : "";
                        }
                        else if (item.TurID == (int)Sabitler.ZiyaretTur.Bilgi)
                        {

                            renkClass = item.DurumID == BilgiGerceklestiDurumID ? "kayitGray" : (item.DurumID == BilgiGerceklesmediDurumID) ? "kayitRed" : "";
                        }

                        string KayitTurYazi = Fonksiyonlar.ProgramKayitTurYaziVer(item.TurID, item.DurumID);

                                <input type="hidden" name="ID" value="@item.ID" />
                                <input type="hidden" name="SiralamaTarih" value="@(item.SiralamaTarih==null?item.Tarih:item.SiralamaTarih)" />

                                                            @if (item.isSaatBelirsiz)
                                                            {

                                                                @("../..")

                                                            }
                                                            else
                                                            {
                                                                @item.Tarih.Value.ToString("HH:mm")
                                                            }

                                                        @if (item.Sure != 0)
                                                        {

@(item.Sure == Sabitler.ProgramSuresiBelirsiz ? " Süre belirsiz " : Fonksiyonlar.ToplantiSureCevir(item.Sure))
                                                        }
                                                        @if (item.TurID != (int)Sabitler.ZiyaretTur.Program)
                                                        {

                                                                @(KayitTurYazi)
                                                                @if (DvtKesinDegilDurumID == item.DurumID)
                                                                {
                                                                     ?
                                                                }

                                                        }
                                                        else if (item.TurID == (int)Sabitler.ZiyaretTur.Program && isTaslakprgVar && item.KategoriID == TaslakPrgKategori.ID)
                                                        {

                                                                Taslak

                                                        }

                                                            @if ((item.TurID != (int)Sabitler.ZiyaretTur.Ziyaret || item.isRandevuAciklama))
                                                            {
                                                                @Html.Raw(item.Aciklama)

                                                            }
                                                            @if (Model.Filtre.EkstraNot && !string.IsNullOrEmpty(item.EkstraNot))
                                                            {
                                                                @item.EkstraNot
                                                            }

                                                        @if (!string.IsNullOrEmpty(item.PrgNotu) && item.TurID != (int)Sabitler.ZiyaretTur.Ziyaret && Model.Filtre.PrgNot)
                                                        {
                                                             @(Html.Raw(item.PrgNotu))
                                                        }
                                                        @if (string.IsNullOrEmpty(item.Aciklama) && item.TurID != (int)Sabitler.ZiyaretTur.Program && item.katilimcilar.Any() && !Model.Filtre.Katilimci)
                                                        {
                                                            YeniKisiModel katilimci = item.katilimcilar.FirstOrDefault();
                                                            if (katilimci != null)
                                                            {

                                                                @(KayitTurYazi + " :" + katilimci.AdSoyad )
                                                                 @(katilimci.Aciklama)

                                                            }

                                                        }
                                                        @if (item.katilimcilar.Any() && ((Model.Filtre.Katilimci && (item.TurID != (int)Sabitler.ZiyaretTur.Davetiye))))
                                                        {
                                                            bool isFirst = false;

                                                            foreach (var jitem in item.katilimcilar)
                                                            {
                                                                @(Html.Raw(isFirst ? "
" : ""))

                                                                    @(jitem.AdSoyad)

                                                                if (!string.IsNullOrEmpty(jitem.Aciklama))
                                                                {

                                                                     @(jitem.Aciklama)
                                                                }

                                                                if (!isFirst)
                                                                {
                                                                    isFirst = true;
                                                                }
                                                            }
                                                        }

                                @if (Fonksiyonlar.YetkiKontrol("Program Ekle##") && isPrgGosterim && !Model.Filtre.isDisardan &&
                                    (!isKisitli ||
                                (isKisitli &&
                                ((GunSinir == (int)Sabitler.ProgramGunSinir.SadeceGecmis && Trh.Date >= BugunBas) ||
                                (GunSinir == (int)Sabitler.ProgramGunSinir.SadeceGelecek && Trh.Date <= BugunSon) ||
                                (GunSinir >= 0 && (Trh.Date >= SinirBasTarih && Trh.Date < SinirBitTarih))))))
                                {

 yeni ekle

                                }

                                     Yazıcıda Gösterme <input type="checkbox" id="gosterme" class="yazicidagosterme" />

                    }


来源: stackexchange

问:
Tiles resource not loading after upgrading to Spring 4.1
I was using Spring 3.1 Java 1.7 and Tiles 2. The Spring located and loaded the tiles resource fine. However, after upgrading to Spring 4.1 and Java 1.8 the tiles is not loading  up regardless of returning the string from the spring controller or using ModelAndView (It says ModelAndView is null when debugged).

I have given my configurations below:

DispatcherServlet contextConfiguration xml config:

```<code><property name="viewResolvers">
            <list>
                <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver" id="partialViewResolver"
                      p:contentType="application/partial-html">
                    <property name="order" value="1"/>
                    <property name="prefix" value="/WEB-INF/views/"/>
                    <property name="suffix" value=".jspx"/>
                </bean>
                <bean class="org.springframework.web.servlet.view.UrlBasedViewResolver" id="tilesViewResolver"
                      p:contentType="text/html">
                    <property name="order" value="2"/>
                    <property name="viewClass" value="org.springframework.web.servlet.view.tiles2.TilesView"/>
                </bean>
            </list>
        </property>
....
....

<bean class="org.springframework.web.servlet.view.UrlBasedViewResolver" id="tilesViewResolver">
        <property name="viewClass" value="org.springframework.web.servlet.view.tiles2.TilesView"/>
    </bean>
    <bean class="org.springframework.web.servlet.view.tiles2.TilesConfigurer" id="tilesConfigurer">
        <property name="definitions">
            <list>
                <value>/WEB-INF/layouts/layouts.xml</value>
                <!-- Scan views directory for Tiles configurations -->
                <value>/WEB-INF/views/**/views.xml</value>
            </list>
        </property>
    </bean>
</code>```

pom.xml

```<code><dependency>
            <groupId>org.apache.tiles</groupId>
            <artifactId>tiles-jsp</artifactId>
            <version>2.2.2</version>
        </dependency>

        <dependency>
            <groupId>org.apache.tiles</groupId>
            <artifactId>tiles-core</artifactId>
            <version>2.2.2</version>
        </dependency>
        <dependency>
            <groupId>org.apache.tiles</groupId>
            <artifactId>tiles-api</artifactId>
            <version>2.2.2</version>
        </dependency>
        <dependency>
            <groupId>org.apache.tiles</groupId>
            <artifactId>tiles-servlet</artifactId>
            <version>2.2.2</version>
        </dependency>

        <dependency>
            <groupId>org.apache.tiles</groupId>
            <artifactId>tiles-template</artifactId>
            <version>2.2.2</version>
        </dependency>

        <dependency>
            <groupId>org.apache.tiles</groupId>
            <artifactId>tiles-el</artifactId>
            <version>2.2.2</version>
        </dependency>
</code>```

Controller method code:

```<code>@RequestMapping(produces = {"text/html", "application/partial-html"})
public String list(Model uiModel) {

        uiModel.addAttribute("xxx", new XXX());

        return "xxx/list";
    }
</code>```

layouts.xml

```<code><?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE tiles-definitions PUBLIC "-//Apache Software Foundation//DTD Tiles Configuration 2.1//EN"
        "http://tiles.apache.org/dtds/tiles-config_2_1.dtd">

<tiles-definitions>

  <definition name="default" template="/WEB-INF/layouts/default.jspx">
    <put-attribute name="header" value="/WEB-INF/views/header.jspx" />
    <put-attribute name="menu" value="/WEB-INF/views/menu.jspx" />
    <put-attribute name="footer" value="/WEB-INF/views/footer.jspx" />
  </definition>

  <definition name="noLogin" template="/WEB-INF/layouts/noLogin.jspx">
        <put-attribute name="header" value="/WEB-INF/views/header.jspx" />
        <put-attribute name="menu" value="/WEB-INF/views/menu.jspx" />
        <put-attribute name="footer" value="/WEB-INF/views/footer.jspx" />
  </definition>

  <definition name="onlyContent" template="/WEB-INF/layouts/onlyContent.jspx">
  </definition>

  <definition name="public" template="/WEB-INF/layouts/default.jspx">
    <put-attribute name="header" value="/WEB-INF/views/header.jspx" />
    <put-attribute name="footer" value="/WEB-INF/views/footer.jspx" />
  </definition>

  <definition name="loginTemplate" template="/WEB-INF/layouts/default.jspx">
    <!--<put-attribute name="footer" value="/WEB-INF/views/footer.jspx" />-->
  </definition>

</tiles-definitions>
</code>```

views.xml

```<code><?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!DOCTYPE tiles-definitions PUBLIC "-//Apache Software Foundation//DTD Tiles Configuration 2.1//EN"
        "http://tiles.apache.org/dtds/tiles-config_2_1.dtd">
<tiles-definitions>
    <definition extends="default" name="xxx/list">
        <put-attribute name="body" value="/WEB-INF/views/xxx/list.jspx"/>
    </definition>
</tiles-definitions>
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I was using Spring 3.1 Java 1.7 and Tiles 2. The Spring located and loaded the tiles resource fine. However, after upgrading to Spring 4.1 and Java 1.8 the tiles is not loading  up regardless of returning the string from the spring controller or using ModelAndView (It says ModelAndView is null when debugged).

I have given my configurations below:

DispatcherServlet contextConfiguration xml config:

<property name="viewResolvers">
            <list>
                <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver" id="partialViewResolver"
                      p:contentType="application/partial-html">
                    <property name="order" value="1"/>
                    <property name="prefix" value="/WEB-INF/views/"/>
                    <property name="suffix" value=".jspx"/>
                </bean>
                <bean class="org.springframework.web.servlet.view.UrlBasedViewResolver" id="tilesViewResolver"
                      p:contentType="text/html">
                    <property name="order" value="2"/>
                    <property name="viewClass" value="org.springframework.web.servlet.view.tiles2.TilesView"/>
                </bean>
            </list>
        </property>
....
....

<bean class="org.springframework.web.servlet.view.UrlBasedViewResolver" id="tilesViewResolver">
        <property name="viewClass" value="org.springframework.web.servlet.view.tiles2.TilesView"/>
    </bean>
    <bean class="org.springframework.web.servlet.view.tiles2.TilesConfigurer" id="tilesConfigurer">
        <property name="definitions">
            <list>
                <value>/WEB-INF/layouts/layouts.xml</value>

                <value>/WEB-INF/views/**/views.xml</value>
            </list>
        </property>
    </bean>

pom.xml

<dependency>
            <groupId>org.apache.tiles</groupId>
            <artifactId>tiles-jsp</artifactId>
            <version>2.2.2</version>
        </dependency>

        <dependency>
            <groupId>org.apache.tiles</groupId>
            <artifactId>tiles-core</artifactId>
            <version>2.2.2</version>
        </dependency>
        <dependency>
            <groupId>org.apache.tiles</groupId>
            <artifactId>tiles-api</artifactId>
            <version>2.2.2</version>
        </dependency>
        <dependency>
            <groupId>org.apache.tiles</groupId>
            <artifactId>tiles-servlet</artifactId>
            <version>2.2.2</version>
        </dependency>

        <dependency>
            <groupId>org.apache.tiles</groupId>
            <artifactId>tiles-template</artifactId>
            <version>2.2.2</version>
        </dependency>

        <dependency>
            <groupId>org.apache.tiles</groupId>
            <artifactId>tiles-el</artifactId>
            <version>2.2.2</version>
        </dependency>

Controller method code:

@RequestMapping(produces = {"text/html", "application/partial-html"})
public String list(Model uiModel) {

        uiModel.addAttribute("xxx", new XXX());

        return "xxx/list";
    }

layouts.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE tiles-definitions PUBLIC "-//Apache Software Foundation//DTD Tiles Configuration 2.1//EN"
        "http://tiles.apache.org/dtds/tiles-config_2_1.dtd">

<tiles-definitions>

  <definition name="default" template="/WEB-INF/layouts/default.jspx">
    <put-attribute name="header" value="/WEB-INF/views/header.jspx" />
    <put-attribute name="menu" value="/WEB-INF/views/menu.jspx" />
    <put-attribute name="footer" value="/WEB-INF/views/footer.jspx" />
  </definition>

  <definition name="noLogin" template="/WEB-INF/layouts/noLogin.jspx">
        <put-attribute name="header" value="/WEB-INF/views/header.jspx" />
        <put-attribute name="menu" value="/WEB-INF/views/menu.jspx" />
        <put-attribute name="footer" value="/WEB-INF/views/footer.jspx" />
  </definition>

  <definition name="onlyContent" template="/WEB-INF/layouts/onlyContent.jspx">
  </definition>

  <definition name="public" template="/WEB-INF/layouts/default.jspx">
    <put-attribute name="header" value="/WEB-INF/views/header.jspx" />
    <put-attribute name="footer" value="/WEB-INF/views/footer.jspx" />
  </definition>

  <definition name="loginTemplate" template="/WEB-INF/layouts/default.jspx">

  </definition>

</tiles-definitions>

views.xml

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!DOCTYPE tiles-definitions PUBLIC "-//Apache Software Foundation//DTD Tiles Configuration 2.1//EN"
        "http://tiles.apache.org/dtds/tiles-config_2_1.dtd">
<tiles-definitions>
    <definition extends="default" name="xxx/list">
        <put-attribute name="body" value="/WEB-INF/views/xxx/list.jspx"/>
    </definition>
</tiles-definitions>


问:
FB sharing debugger not working for Dynamically created routes (nextjs13 app dir)
so I've been having the issue for the past couple of days that's driving me crazy where the og image tags for social media are not working for FB on dynamic routes for my site hosted on Vercel.

Using the app directory, if I put my tags on the head.tsx file for the homepage, FB crawls it just fine. However if i have something like /[posts], FB gives me a 500 internal server error, which is weird considering Twitter, and all of the other meta tag checker simulators scrape it perfectly fine dynamically.

FB had a section where they talked about how you could simulate their scraper with a certain CURL command. So I did that, and I got the same 500 internal server error. However, if I excluded the range header, I got the expected 200 response.

So I guess my question now that I've narrowed the issue down is how do I ignore the range header for requests coming through so FB can scrape my website correctly?

Thanks


问:
delete data from firebase database
There is no problem in transferring the data to the table, but the "sılmebtn" next to each data does not work. It is a bit confusing, but as I want, when the button next to the data is pressed, I want that data to be deleted from the database.

sılmebtn.addEventListener('click',(e) => {

 const zort = document.getElementById('sılmebtn');
   let key = ref.child("users").push().getKey();

firebase.database().ref('users/' + zort.value).set({
  full_name: "asasdasd",

}, (error) => {
  if (error) {
    // The write failed...
  } else {
    alert("ok")
  }
});

  });
```
<p><strong>I tried to do what I wanted here but it didn't work how can I do what I want</strong></p>
<pre class="lang-js prettyprint-override"><code>
  // read data
  getData.addEventListener('click',(e) => {

    $('#dataTbl td').remove();
    var rowNum = 0;
    const dbRef = ref(database, 'users/');

    onValue(dbRef, (snapshot) => {
      snapshot.forEach((childSnapshot) => {
      const childKey = childSnapshot.key;
      const childData = childSnapshot.val();
      // ...
      rowNum += 1;
      var row = " <tr><td>" + '<input type="checkbox" id="' + childKey + '" name="horns">'+ rowNum + "</td><td>" + childKey + "</td><td>" + childData.full_name + "</td><td>" + childData.create_acc + "</td><td>" + childData.email + "</td><td>" +  '<img src=\" ' + childData.profile_photo +  ' \" width=\"30px\" height=\"30px\">' + "</td><td>" + '<button id="sılmebtn" value="' + childKey + '" >sil</button>' + "</td></tr>"

      $(row).appendTo('#dataTbl');

      });
    }, {
       onlyOnce: true
    });

  });

  //

   sılmebtn.addEventListener('click',(e) => {

 const zort = document.getElementById('sılmebtn');
   let key = ref.child("users").push().getKey();

firebase.database().ref('users/' + zort.value).set({
  full_name: "asasdasd",

}, (error) => {
  if (error) {
    // The write failed...
  } else {
    alert("ok")
  }
});

  });

</code>```

Title: delete data from firebase database

Body:
There is no problem in transferring the data to the table, but the "sılmebtn" next to each data does not work. It is a bit confusing, but as I want, when the button next to the data is pressed, I want that data to be deleted from the database.

sılmebtn.addEventListener('click',(e) => {

 const zort = document.getElementById('sılmebtn');
   let key = ref.child("users").push().getKey();

firebase.database().ref('users/' + zort.value).set({
  full_name: "asasdasd",

}, (error) => {
  if (error) {
    // The write failed...
  } else {
    alert("ok")
  }
});

  });

I tried to do what I wanted here but it didn't work how can I do what I want

  // read data
  getData.addEventListener('click',(e) => {

    $('#dataTbl td').remove();
    var rowNum = 0;
    const dbRef = ref(database, 'users/');

    onValue(dbRef, (snapshot) => {
      snapshot.forEach((childSnapshot) => {
      const childKey = childSnapshot.key;
      const childData = childSnapshot.val();
      // ...
      rowNum += 1;
      var row = "
" + '<input type="checkbox" id="' + childKey + '" name="horns">'+ rowNum + "	" + childKey + "	" + childData.full_name + "	" + childData.create_acc + "	" + childData.email + "	" +  '' + "	" + '<button id="sılmebtn" value="' + childKey + '" >sil</button>' + "
"

      $(row).appendTo('#dataTbl');

      });
    }, {
       onlyOnce: true
    });

  });

  //

   sılmebtn.addEventListener('click',(e) => {

 const zort = document.getElementById('sılmebtn');
   let key = ref.child("users").push().getKey();

firebase.database().ref('users/' + zort.value).set({
  full_name: "asasdasd",

}, (error) => {
  if (error) {
    // The write failed...
  } else {
    alert("ok")
  }
});

  });


问:
Intel Graphics card for PyTorch acceleration
I have a HP laptop with an Intel graphics card (Iris Xe, I think, based on the following:

```<code>lspci -vnn | grep VGA
0000:00:02.0 VGA compatible controller [0300]: Intel Corporation TigerLake-LP GT2 [Iris Xe Graphics] [8086:9a49] (rev 01) (prog-if 00 [VGA controller])
</code>```

though I honestly don't know what all of that means). I would like to use this GPU for deep learning with PyTorch to avoid paying for online resources like Google Colab. I know PyTorch currently supports Nvidia GPUs with CUDA and Apple silicon. I found this page with instructions on how I could use directML to do this on WSL. The problem is that this laptop runs Linux (Mint, specifically). It seems to me that if something works on WSL, it should be easy to adapt to work on native Linux, but I'm not seeing any resources online for that and can't get it to work myself.

I also see many pages recommending OpenCL to use PyTorch with GPUs other than Nvidia, but based on what I've read, this would require a significant amount of work and would have a steep learning curve since I don't even know what OpenCL is.

TL;DR: The question, in sum, is: Can I (and how can I) use my Intel graphics card for PyTorch hardware acceleration?
Note: this question is not a duplicate of any questions I've found about using alternative GPUs than Nvidia ones for PyTorch, because I am specifically wondering how I can use directML or OpenCL on my operating system.

I'll add that when I installed torch_directml with pip, and tried to import it, I got this error:

```<code>In [1]: import torch_directml
---------------------------------------------------------------------------
OSError                                   Traceback (most recent call last)
Cell In[1], line 1
----> 1 import torch_directml

File /usr/lib/python3.10/torch_directml/__init__.py:13
     11 else:
     12     directml_dll = os.path.join(os.path.dirname(__file__), 'libdirectml.so')
---> 13 torch.ops.load_library(directml_dll)
     15 # import native apis
     16 import torch_directml_native

File ~/.local/lib/python3.10/site-packages/torch/_ops.py:573, in _Ops.load_library(self, path)
    568 path = _utils_internal.resolve_library_path(path)
    569 with dl_open_guard():
    570     # Import the shared library into the process, thus running its
    571     # static (global) initialization code in order to register custom
    572     # operators with the JIT.
--> 573     ctypes.CDLL(path)
    574 self.loaded_libraries.add(path)

File /usr/lib/python3.10/ctypes/__init__.py:374, in CDLL.__init__(self, name, mode, handle, use_errno, use_last_error, winmode)
    371 self._FuncPtr = _FuncPtr
    373 if handle is None:
--> 374     self._handle = _dlopen(self._name, mode)
    375 else:
    376     self._handle = handle

OSError: libd3d12.so: cannot open shared object file: No such file or directory

</code>```

even though the libd3d12.so file is present in the torch_directml folder. My guess is this is related to a problem with installation or with the fact that by all I can find, DirectML is intended for Windows or WSL, not native Linux.

Body:
I have a HP laptop with an Intel graphics card (Iris Xe, I think, based on the following:

lspci -vnn | grep VGA
0000:00:02.0 VGA compatible controller [0300]: Intel Corporation TigerLake-LP GT2 [Iris Xe Graphics] [8086:9a49] (rev 01) (prog-if 00 [VGA controller])

though I honestly don't know what all of that means). I would like to use this GPU for deep learning with PyTorch to avoid paying for online resources like Google Colab. I know PyTorch currently supports Nvidia GPUs with CUDA and Apple silicon. I found this page with instructions on how I could use directML to do this on WSL. The problem is that this laptop runs Linux (Mint, specifically). It seems to me that if something works on WSL, it should be easy to adapt to work on native Linux, but I'm not seeing any resources online for that and can't get it to work myself.

I also see many pages recommending OpenCL to use PyTorch with GPUs other than Nvidia, but based on what I've read, this would require a significant amount of work and would have a steep learning curve since I don't even know what OpenCL is.

TL;DR: The question, in sum, is: Can I (and how can I) use my Intel graphics card for PyTorch hardware acceleration?
Note: this question is not a duplicate of any questions I've found about using alternative GPUs than Nvidia ones for PyTorch, because I am specifically wondering how I can use directML or OpenCL on my operating system.

I'll add that when I installed torch_directml with pip, and tried to import it, I got this error:

In [1]: import torch_directml
---------------------------------------------------------------------------
OSError                                   Traceback (most recent call last)
Cell In[1], line 1
----> 1 import torch_directml

File /usr/lib/python3.10/torch_directml/__init__.py:13
     11 else:
     12     directml_dll = os.path.join(os.path.dirname(__file__), 'libdirectml.so')
---> 13 torch.ops.load_library(directml_dll)
     15 # import native apis
     16 import torch_directml_native

File ~/.local/lib/python3.10/site-packages/torch/_ops.py:573, in _Ops.load_library(self, path)
    568 path = _utils_internal.resolve_library_path(path)
    569 with dl_open_guard():
    570     # Import the shared library into the process, thus running its
    571     # static (global) initialization code in order to register custom
    572     # operators with the JIT.
--> 573     ctypes.CDLL(path)
    574 self.loaded_libraries.add(path)

File /usr/lib/python3.10/ctypes/__init__.py:374, in CDLL.__init__(self, name, mode, handle, use_errno, use_last_error, winmode)
    371 self._FuncPtr = _FuncPtr
    373 if handle is None:
--> 374     self._handle = _dlopen(self._name, mode)
    375 else:
    376     self._handle = handle

OSError: libd3d12.so: cannot open shared object file: No such file or directory

even though the libd3d12.so file is present in the torch_directml folder. My guess is this is related to a problem with installation or with the fact that by all I can find, DirectML is intended for Windows or WSL, not native Linux.


问:
How does a COM client parses Type Library from a EXE COM server?
Let's say we have a COM server EXE and COM client EXE running on the same machine.

COM server exposes IDispatch interface and carries a Type Library (.TLB file) into it's resource section.

COM client (something like PowerShell) wants to call a method and it does so via IDispatch::Invoke.

Before Client could make that call, If I understood it correctly, it must read Type Library of the COM class which can be done via the LoadTypeLib function

It's easy to digest if it were to be a COM server DLL, where client-server would be living in the same address space.

But what happens when the COM server is an EXE? Does the Client (which itself is an EXE) loads the server EXE (Not sure if that is even possible) ?

Remarks on MSDN has this

If the file is a DLL or an executable file, it is loaded. By default,
the type library is extracted from the first resource of type
ITypeLib.


问:
How to force useState hook to change the state inside the closure?
I have two parameters on the form : login and password.

When sending data from the form, the function is called:

```<code>const onRegister = (e) =>{
        e.preventDefault();
        validate();
        if (!loginError && !pwdError){
            const userData = {
                username: login,
                password: password,
            };
            axios.post("http://localhost:8080/api/auth/register", userData)
                .then(() => {
                    navigate("/auth",{ state: { previousUrl: location.pathname } });
                })
                .catch(error => {
                    setFieldError(error.response.data)
            })
        }
    };
</code>```

The first thing I want to do is validate the entered data:

```<code>const validate = () =>{

        if (!validLogin.test(login)) {
            setLoginError(true);
            console.log("after login err = ")
            console.log(loginError)
        }
        if (!validPassword.test(password)) {
            setPwdError(true);
            console.log("after pwd err = ")
            console.log(pwdError)
        }
    };
</code>```

And actually the problem is that setLoginError(true); and setPwdError(true); do not work.

```<code>    const [loginError, setLoginError] = useState(false);
    const [pwdError, setPwdError] = useState(false);
</code>```

That is, immediately after they are called false is still printed to the console and accordingly, the request is sent . I have not encountered these before, I will be glad to get help.

Body:
I have two parameters on the form : login and password.

When sending data from the form, the function is called:

const onRegister = (e) =>{
        e.preventDefault();
        validate();
        if (!loginError && !pwdError){
            const userData = {
                username: login,
                password: password,
            };
            axios.post("http://localhost:8080/api/auth/register", userData)
                .then(() => {
                    navigate("/auth",{ state: { previousUrl: location.pathname } });
                })
                .catch(error => {
                    setFieldError(error.response.data)
            })
        }
    };

The first thing I want to do is validate the entered data:

const validate = () =>{

        if (!validLogin.test(login)) {
            setLoginError(true);
            console.log("after login err = ")
            console.log(loginError)
        }
        if (!validPassword.test(password)) {
            setPwdError(true);
            console.log("after pwd err = ")
            console.log(pwdError)
        }
    };

And actually the problem is that setLoginError(true); and setPwdError(true); do not work.

    const [loginError, setLoginError] = useState(false);
    const [pwdError, setPwdError] = useState(false);

That is, immediately after they are called false is still printed to the console and accordingly, the request is sent . I have not encountered these before, I will be glad to get help.


问:
How to properly block and clear notifications in android?
I have made a notification blocker app with java around 6 months ago now. Here is the source code. It all works fine, the notifications are blocked and stored in the DB also. Yet there's one issue. I still can see the notifications coming as this image shows.

Since this is a notification blocker, this is not going to be very accurate. Therefore I need a way to block notifications from the view of the user in android.
If you have ever used focused mode, that is what I want. To block all the notifications and when they are unblocked again, I want to show them in the status bar. Any idea how to tackle this bug?


问:
python find how similar two strings with some NLP
So, I am happy to find any way to find if an answer is correct according to some string, unfortunately the correct answer strings are often in different formats and have do not accepts in built.

It is not practical for me to chagne all the correct answers becuase there are more than 100,000

Here is an example of an answerline: "integration with respect to time [accept logical equivalents which mention integration and time]"

I would want to accept anything that has integration and time

Here is another example: "Burials [accept funerals; prompt on death, do not accept cremation]"

I want to accept Burials, Funerals, and death but not cremation.

I would like this to be correct at least 80-90% of the time but there is nothing too important if it isn't correct.

What is the right approach to this? Should I be using things like Spacy, NLKT, Textblob, or some other library or should I just be using brute force. I tried using open ai but unfortunately the only openai model that could solve it was davinchi-003 which might be a bit expensive. If there is no other solutions that will work, I will do that if needed but if there are cheaper solutions or faster solutions, I would love to use those first.

Lastly here are some more examples of answers:

William Shakespeare

Katherine Mansfield (or Kathleen Beauchamp)

Second Great Awakening [prompt on "Great Awakening"]

Edward Morgan Forster

Kingdom ofÂ BactriaÂ (orÂ BactrianaÂ orÂ Zariaspa)

Egypt

Gottfried Wilhelm Leibniz

electrical resistance [or resistors; do not accept or prompt on "resistivity"]

Most of the time the do not accept's are in just a few varieties so I could probably hard code cases for that if I could find a way to split up something like
"electrical resistance [or resistors; do not accept or prompt on "resistivity"]"
into "electrical resistance", "resistors", and "do not accept "resistivity""

So far, I have been using this function

```<code>def find_correct(correct_answer,user_answer):
    correct_answer = re.sub(r'\([^)]*\)', '', correct_answer)
    correct_answer = re.sub(r'\[[^>]+]', '', correct_answer)
    correct_answer = re.sub(r'&lt[^>]+&gt','',correct_answer)
    correct_answer = re.sub(r'(\b[A-Z][A-Z]+|\b[A-Z]\b)','',correct_answer)
    correct_answer = re.sub(r'[Bb][oO][nN][uU][sS][eE][sS]','',correct_answer)
    correct_answer = re.sub(r'[Bb][oO][nN][uU][sS]','',correct_answer)
    correct_answer = correct_answer.strip()
    possible_answers = correct_answer.split()
    possible_answers.append(correct_answer)
    for a in possible_answers:
        distance = jellyfish.damerau_levenshtein_distance(user_answer.lower(), a.lower())
        print(distance)
        if distance<len(user_answer)*0.4:
            return [True, correct_answer]
    return [False, correct_answer]
</code>```

unfortunately this cannot do anything with do not accept and just gets rid of everything in parenthesis and square brackets just to make it work.

Body:
So, I am happy to find any way to find if an answer is correct according to some string, unfortunately the correct answer strings are often in different formats and have do not accepts in built.

It is not practical for me to chagne all the correct answers becuase there are more than 100,000

Here is an example of an answerline: "integration with respect to time [accept logical equivalents which mention integration and time]"

I would want to accept anything that has integration and time

Here is another example: "Burials [accept funerals; prompt on death, do not accept cremation]"

I want to accept Burials, Funerals, and death but not cremation.

I would like this to be correct at least 80-90% of the time but there is nothing too important if it isn't correct.

What is the right approach to this? Should I be using things like Spacy, NLKT, Textblob, or some other library or should I just be using brute force. I tried using open ai but unfortunately the only openai model that could solve it was davinchi-003 which might be a bit expensive. If there is no other solutions that will work, I will do that if needed but if there are cheaper solutions or faster solutions, I would love to use those first.

Lastly here are some more examples of answers:

William Shakespeare

Katherine Mansfield (or Kathleen Beauchamp)

Second Great Awakening [prompt on "Great Awakening"]

Edward Morgan Forster

Kingdom ofÂ BactriaÂ (orÂ BactrianaÂ orÂ Zariaspa)

Egypt

Gottfried Wilhelm Leibniz

electrical resistance [or resistors; do not accept or prompt on "resistivity"]

Most of the time the do not accept's are in just a few varieties so I could probably hard code cases for that if I could find a way to split up something like
"electrical resistance [or resistors; do not accept or prompt on "resistivity"]"
into "electrical resistance", "resistors", and "do not accept "resistivity""

So far, I have been using this function

def find_correct(correct_answer,user_answer):
    correct_answer = re.sub(r'\([^)]*\)', '', correct_answer)
    correct_answer = re.sub(r'\[[^>]+]', '', correct_answer)
    correct_answer = re.sub(r'&lt[^>]+&gt','',correct_answer)
    correct_answer = re.sub(r'(\b[A-Z][A-Z]+|\b[A-Z]\b)','',correct_answer)
    correct_answer = re.sub(r'[Bb][oO][nN][uU][sS][eE][sS]','',correct_answer)
    correct_answer = re.sub(r'[Bb][oO][nN][uU][sS]','',correct_answer)
    correct_answer = correct_answer.strip()
    possible_answers = correct_answer.split()
    possible_answers.append(correct_answer)
    for a in possible_answers:
        distance = jellyfish.damerau_levenshtein_distance(user_answer.lower(), a.lower())
        print(distance)
        if distance<len(user_answer)*0.4:
            return [True, correct_answer]
    return [False, correct_answer]

unfortunately this cannot do anything with do not accept and just gets rid of everything in parenthesis and square brackets just to make it work.


问:
Riverpod FutureProvider - passing result between screens
I'm learning Riverpod provider and stuck on a topic regarding passing values between screens.

As I learnt from Riverpod docs - it delivers a provider that enables values to be accessed globally... and here is my case.

I'm creating a service repo, that contains some methods delivering futures (e.g. network request to verify user):

```<code>class VerifyUser {

  Future<User> verifyUser(String input) async {

    await Future.delayed(const Duration(seconds: 2));

    print(input);

    if (input == 'Foo') {
      print('Foo is fine - VERIFIED');
      return User(userVerified: true);
    } else {
      print('$input is wrong - NOT VERIFIED');
      return User(userVerified: false);
    }
  }
}
</code>```

Next step is to create providers - I'm using Riverpod autogenerate providers for this, so here are my providers:

```<code>part 'providers.g.dart';

@riverpod
VerifyUser verifyUserRepo(VerifyUserRepoRef ref) {
  return VerifyUser();
}

@riverpod
Future<User> user(
    UserRef ref,
    String input
    ) {
  return ref
      .watch(verifyUserRepoProvider)
      .verifyUser(input);
}
</code>```

and there is a simple User model for this:

```<code>class User {

  bool userVerified;

  User({required this.userVerified});

}
</code>```

I'm creating a wrapper, that should take the user to Homescreen, when a user is verified, or take the user to authenticate screen when a user is not verified.

```<code>class Wrapper extends ConsumerWidget {

  @override
  Widget build(BuildContext context, WidgetRef ref) {

    String user = '';
    final userFromProvider = ref.watch(userProvider(user));

    if (user == 'verified') {
      print(userFromProvider);
      return MyHomePage();
    } else {
      return Authenticate();
    }
  }
}
</code>```

App opens on Authenticate screen because there is no info about the user.

On Authenticate screen I'm getting input and passing it to FutureProvider for verification.

```<code>final vUser = ref.watch(userProvider(userInput.value.text));
</code>```

When I'm pushing to Wrapper and calling provider - I'm not getting the value I initially got from future.

```<code>ElevatedButton(
     onPressed: () async {
     vUser;
     if (vUser.value?.userVerified == true) {
         print('going2wrapper');
         Navigator.of(context).push(MaterialPageRoute(builder: (context) => Wrapper()));
      }},
     child: const Text('Verify User'))
</code>```

Inside Wrapper it seems that this is only thing that I can do:

```<code>String user = '';
final userFromProvider = ref.watch(userProvider(user));
</code>```

But it makes me call the provider with a new value... and causing unsuccessful verification and I cannot proceed to homescreen.

As a workaround, I see that I can pass the named argument to Wrapper, but I want to use the provider for it... is it possible?

I hope that there is a solution to this.

Thx!
David

Body:
I'm learning Riverpod provider and stuck on a topic regarding passing values between screens.

As I learnt from Riverpod docs - it delivers a provider that enables values to be accessed globally... and here is my case.

I'm creating a service repo, that contains some methods delivering futures (e.g. network request to verify user):

class VerifyUser {

  Future<User> verifyUser(String input) async {

    await Future.delayed(const Duration(seconds: 2));

    print(input);

    if (input == 'Foo') {
      print('Foo is fine - VERIFIED');
      return User(userVerified: true);
    } else {
      print('$input is wrong - NOT VERIFIED');
      return User(userVerified: false);
    }
  }
}

Next step is to create providers - I'm using Riverpod autogenerate providers for this, so here are my providers:

part 'providers.g.dart';

@riverpod
VerifyUser verifyUserRepo(VerifyUserRepoRef ref) {
  return VerifyUser();
}

@riverpod
Future<User> user(
    UserRef ref,
    String input
    ) {
  return ref
      .watch(verifyUserRepoProvider)
      .verifyUser(input);
}

and there is a simple User model for this:

class User {

  bool userVerified;

  User({required this.userVerified});

}

I'm creating a wrapper, that should take the user to Homescreen, when a user is verified, or take the user to authenticate screen when a user is not verified.

class Wrapper extends ConsumerWidget {

  @override
  Widget build(BuildContext context, WidgetRef ref) {

    String user = '';
    final userFromProvider = ref.watch(userProvider(user));

    if (user == 'verified') {
      print(userFromProvider);
      return MyHomePage();
    } else {
      return Authenticate();
    }
  }
}

App opens on Authenticate screen because there is no info about the user.

On Authenticate screen I'm getting input and passing it to FutureProvider for verification.

final vUser = ref.watch(userProvider(userInput.value.text));

When I'm pushing to Wrapper and calling provider - I'm not getting the value I initially got from future.

ElevatedButton(
     onPressed: () async {
     vUser;
     if (vUser.value?.userVerified == true) {
         print('going2wrapper');
         Navigator.of(context).push(MaterialPageRoute(builder: (context) => Wrapper()));
      }},
     child: const Text('Verify User'))

Inside Wrapper it seems that this is only thing that I can do:

String user = '';
final userFromProvider = ref.watch(userProvider(user));

But it makes me call the provider with a new value... and causing unsuccessful verification and I cannot proceed to homescreen.

As a workaround, I see that I can pass the named argument to Wrapper, but I want to use the provider for it... is it possible?

I hope that there is a solution to this.

Thx!
David


问:
Assertion failed: new_time >= loop->time, file c:\ws\deps\uv\src\win\core.c, line 324
```<code>PS C:\xampp\htdocs\website> node -v
v18.12.1
PS C:\xampp\htdocs\website> npm -v
8.19.2
PS C:\xampp\htdocs\website> npm run dev

> dev
> vite

  VITE v3.2.5  ready in 1227 ms

  ➜  Local:   http://localhost:5173/
  ➜  Network: use --host to expose

  LARAVEL v9.43.0  plugin v0.7.2

  ➜  APP_URL: http://localhost
Assertion failed: new_time >= loop->time, file c:\ws\deps\uv\src\win\core.c, line 324
PS C:\xampp\htdocs\website> npm run dev

> dev
> vite

Assertion failed: new_time >= loop->time, file c:\ws\deps\uv\src\win\core.c, line 324
</code>```

I am running vite for laravel.
It works for a while.
After a few minutes it says ：Assertion failed
and I run "npm run dev" again
it's the same error

edit:
Currently my solution is
Replace Vite with Mix in Laravel 9.4

Body:
PS C:\xampp\htdocs\website> node -v
v18.12.1
PS C:\xampp\htdocs\website> npm -v
8.19.2
PS C:\xampp\htdocs\website> npm run dev

> dev
> vite

  VITE v3.2.5  ready in 1227 ms

  ➜  Local:   http://localhost:5173/
  ➜  Network: use --host to expose

  LARAVEL v9.43.0  plugin v0.7.2

  ➜  APP_URL: http://localhost
Assertion failed: new_time >= loop->time, file c:\ws\deps\uv\src\win\core.c, line 324
PS C:\xampp\htdocs\website> npm run dev

> dev
> vite

Assertion failed: new_time >= loop->time, file c:\ws\deps\uv\src\win\core.c, line 324

I am running vite for laravel.
It works for a while.
After a few minutes it says ：Assertion failed
and I run "npm run dev" again
it's the same error

edit:
Currently my solution is
Replace Vite with Mix in Laravel 9.4


问:
react-draft- wysiwyg (Post validation failed: body: Cast to string failed for value)
I have one problem when I try to use this  Markdown editor this error occurs again and again . but when i test another editor it just work without error

the problem is  I do not know why I can not set body and setBody to Editor and then send to  backend

this Body and setBody work in simple mde react but i do not know why I can not make it happen in react-draft-wysiwig

this is my code

```<code>import { EditorState } from 'draft-js';
import { Editor } from 'react-draft-wysiwyg';
import "react-draft-wysiwyg/dist/react-draft-wysiwyg.css";

const [body, setBody] = useState('');

<Editor
  // value={body}
     editorState={body}
     toolbarClassName="toolbarClassName"
     wrapperClassName="wrapperClassName"
     editorClassName="editorClassName"
     onEditorStateChange={setBody}
     textAlignment="right"
     placeholder="اینجا تایپ کنید"
 />;

</code>```

I tryyied value={body} and onChange={setBody} but still error

I am sure the Models file is ok because another markdown editor working

like this simple mde see this code works

```<code><SimpleMDE value={body} onChange={setBody} required />
</code>```

what is wrong with this code can not understand at all

thanks and  very sorry for my bad english

Body:
I have one problem when I try to use this  Markdown editor this error occurs again and again . but when i test another editor it just work without error

the problem is  I do not know why I can not set body and setBody to Editor and then send to  backend

this Body and setBody work in simple mde react but i do not know why I can not make it happen in react-draft-wysiwig

this is my code

import { EditorState } from 'draft-js';
import { Editor } from 'react-draft-wysiwyg';
import "react-draft-wysiwyg/dist/react-draft-wysiwyg.css";

const [body, setBody] = useState('');

<Editor
  // value={body}
     editorState={body}
     toolbarClassName="toolbarClassName"
     wrapperClassName="wrapperClassName"
     editorClassName="editorClassName"
     onEditorStateChange={setBody}
     textAlignment="right"
     placeholder="اینجا تایپ کنید"
 />;

I tryyied value={body} and onChange={setBody} but still error

I am sure the Models file is ok because another markdown editor working

like this simple mde see this code works

<SimpleMDE value={body} onChange={setBody} required />

what is wrong with this code can not understand at all

thanks and  very sorry for my bad english


问:
My webpack doesn't implement SVG inline, only like url
webpack config

```<code>const path = require('path')
const HtmlWebpackPlugin = require('html-webpack-plugin')
const HtmlWebpackInlineSVGPlugin = require('html-webpack-inline-svg-plugin')

module.exports = {
    mode: 'development',
    entry: {
        index: path.resolve(__dirname, './src/index.js'),
    },
    output: {
        path: path.resolve(__dirname, './'),
        filename: 'build/[name].budle.js',
    },
    plugins: [
        new HtmlWebpackPlugin({
            template: path.resolve(__dirname, './src/template.html'),
        }),
        new HtmlWebpackInlineSVGPlugin({
            runPreEmit: true,
            inlineAll: true,
        }),
    ],

    module: {
        rules: [
            {
                test: /\.css$/,
                use: ['style-loader', 'css-loader'],
            },
            {
                test: /\.svg$/,
                type: 'asset/source',
            },
        ],
    },
    watch: true,
}
</code>```

JS

```<code>    const imgCar = document.createElement('img')
    imgCar.setAttribute('src', carSvg)
    imgCar.classList.add('car-img')
    carBtnsMove.appendChild(imgCar)
</code>```

This is what I have:

This is what I want:

I am trying do this is pure js, I don't know where is problem.

Body:
webpack config

const path = require('path')
const HtmlWebpackPlugin = require('html-webpack-plugin')
const HtmlWebpackInlineSVGPlugin = require('html-webpack-inline-svg-plugin')

module.exports = {
    mode: 'development',
    entry: {
        index: path.resolve(__dirname, './src/index.js'),
    },
    output: {
        path: path.resolve(__dirname, './'),
        filename: 'build/[name].budle.js',
    },
    plugins: [
        new HtmlWebpackPlugin({
            template: path.resolve(__dirname, './src/template.html'),
        }),
        new HtmlWebpackInlineSVGPlugin({
            runPreEmit: true,
            inlineAll: true,
        }),
    ],

    module: {
        rules: [
            {
                test: /\.css$/,
                use: ['style-loader', 'css-loader'],
            },
            {
                test: /\.svg$/,
                type: 'asset/source',
            },
        ],
    },
    watch: true,
}

JS

    const imgCar = document.createElement('img')
    imgCar.setAttribute('src', carSvg)
    imgCar.classList.add('car-img')
    carBtnsMove.appendChild(imgCar)

This is what I have:

This is what I want:

I am trying do this is pure js, I don't know where is problem.


问:
How to test useRef and functions defined inside of useEffect (using Jest)?
I would like to ask for help to improve my skills about test and code quality.

I read a ton of guides and docs and I was not able to find an example of how to do a better code or test in a clean way.

My component has two useRef and it add some listeners to allow the user resize the div element. it works as expected! But I wish to ensure (by tests) that functions onMouseDownRightResize and onMouseMoveRightResize adjust the component using the correct data.

Could someone please show me:

how to test onMouseDownRightResize or onMouseMoveRightResize once the were defined inside the useEffect?

how to test if ref.current is null once he it is inside of the useEffect

Here is my code and a link to a code pen

https://codepen.io/getjv/pen/LYBZPrp

const { useState, useEffect, useRef } = React;

const App = () => {
    const ref = useRef(null);
    const refRight = useRef(null);

    useEffect(() => {
        const resizeableEle = ref.current;
        if (!resizeableEle) {
            return;
        }
        const styles = window.getComputedStyle(ref.current);
        let width = parseInt(styles.width, 10);
        let x = 0;

        const onMouseMoveRightResize = (event) => {
            const dx = event.clientX - x;
            x = event.clientX;
            width = width + dx;
            resizeableEle.style.width = `${width}px`;
        };
        const onMouseUpRightResize = (event) => {
            document.removeEventListener("mousemove", onMouseMoveRightResize);
        };
        const onMouseDownRightResize = (event) => {
            x = event.clientX;
            resizeableEle.style.left = styles.left;
            resizeableEle.style.right = "";
            document.addEventListener("mousemove", onMouseMoveRightResize);
            document.addEventListener("mouseup", onMouseUpRightResize);
        };

        const resizerRight = refRight.current;
        if (!resizerRight) {
            return;
        }
        resizerRight.addEventListener("mousedown", onMouseDownRightResize);

        return () => {
            resizerRight.removeEventListener(
                "mousedown",
                onMouseDownRightResize
            );
        };
    }, []);

    return (

move the green ->

    );
};

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


问:
ASP.NET 'FindByIdAsync' returns values but not passing values to variable?
I am trying to edit a list of Roles that I created via a Create page. However when I try to retrieve the role to edit using the FindByIdAsync(id), the role value/data is not being passed to the variable. The variable "role" is returning null and I don't understand why since I am retrieving the data successfully. Why is this happening?</p>
```<code>using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;

using System.ComponentModel.DataAnnotations;
using ThreeTierAdvisementApp.Data;

namespace ThreeTierAdvisementApp.Areas.Identity.Pages.Account.Administration
{

    public class EditRole : PageModel
    {
        private readonly RoleManager<IdentityRole> _roleManager;
        private readonly UserManager<DefaultUser> userManager;

        public EditRole(RoleManager<IdentityRole> roleManager, UserManager<DefaultUser> userManager)
        {
            _roleManager = roleManager;
            this.userManager = userManager;
            Users = new List<string>();
        }

        public int Id { get; set; }

        [Required(ErrorMessage = "Role Name is Required")]
        public string RoleName { get; set; }

        public List<string> Users { get; set; }

        [BindProperty]
        public IList<EditRole> CurrentRoles { get; set; }

        public async Task<IActionResult> OnGet(string id)
        {

            var role = await _roleManager.FindByIdAsync(id);
            if (role == null)
            {

                return NotFound();
            }

            var model = new EditRoles
            {
                Id = role.Id,
                RoleName = role.Name,
            };

            foreach (var user in userManager.Users)
            {
                if (await userManager.IsInRoleAsync(user, role.Name))
                {
                    model.Users.Add(user.UserName);
                };
            }
            return RedirectToPage("./Index");
        }
    }
    }
</code>```
```<code>using Microsoft.AspNetCore.Identity;
using System.ComponentModel.DataAnnotations;

namespace ThreeTierAdvisementApp.Data
{
    public class EditRoles:IdentityRole
    {
        public string Id { get; set; }
        [Required(ErrorMessage ="Role Name is required")]
        public string RoleName { get; set; }

        public List<string> Users { get; set; }
    }
}

**Identity Class**
using Microsoft.AspNetCore.Identity;

namespace ThreeTierAdvisementApp.Data
{
    public class DefaultUser:IdentityUser
    {
        public string FirstName { get; set; }
        public string LastName { get; set; }

    }
}

**Role Class**
    public class Roles : IdentityRole
    {
        [Required]
        public string RoleName { get; set; }
    }

**List of rolse view. When I click the edit button I want to edit the selected role**
@page
@using ThreeTierAdvisementApp.Areas.Identity.Pages.Account.Administration
@model ListRoleModel;
@{
    ViewData["Title"] = "All Roles";
}

<h1>All Roles</h1>
@if(Model.CurrentRoles.Any()){
@foreach (var item in Model.CurrentRoles)
    {

        <div class="card mb-3">
            <div class="card-header">
                @Html.DisplayFor(modelItem => item.Id)
            </div>
            <div class="card-body">
                <h5 class="card-title">@Html.DisplayFor(modelItem => item.RoleName)</h5>
            </div>
            <div class="card-footer">
                <a asp-page="EditRole" asp-route-Id="@Model.CurrentRoles" class="btn btn-warning">Edit</a>
                <a asp-page="./Delete" asp-route-id="@item.Id" class="btn btn-danger">Delete</a>
            </div>
        </div>

    }
}else{
    <div class="card">
        <div class="card-header">
            <h2>No Roles Yet</h2>
        </div>
        <div class="card-body">
            <h5 class="card-title">
                Use the button below to create a role
            </h5>
        </div>
        <a class="w-25 btn btn-lg btn-primary" asp-page="CreateRole">Create Role</a>

</div>
}

@section Scripts {
    <partial name="_ValidationScriptsPartial" />
}

</code>```

Body:
I am trying to edit a list of Roles that I created via a Create page. However when I try to retrieve the role to edit using the FindByIdAsync(id), the role value/data is not being passed to the variable. The variable "role" is returning null and I don't understand why since I am retrieving the data successfully. Why is this happening?

using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;

using System.ComponentModel.DataAnnotations;
using ThreeTierAdvisementApp.Data;

namespace ThreeTierAdvisementApp.Areas.Identity.Pages.Account.Administration
{

    public class EditRole : PageModel
    {
        private readonly RoleManager<IdentityRole> _roleManager;
        private readonly UserManager<DefaultUser> userManager;

        public EditRole(RoleManager<IdentityRole> roleManager, UserManager<DefaultUser> userManager)
        {
            _roleManager = roleManager;
            this.userManager = userManager;
            Users = new List<string>();
        }

        public int Id { get; set; }

        [Required(ErrorMessage = "Role Name is Required")]
        public string RoleName { get; set; }

        public List<string> Users { get; set; }

        [BindProperty]
        public IList<EditRole> CurrentRoles { get; set; }

        public async Task<IActionResult> OnGet(string id)
        {

            var role = await _roleManager.FindByIdAsync(id);
            if (role == null)
            {

                return NotFound();
            }

            var model = new EditRoles
            {
                Id = role.Id,
                RoleName = role.Name,
            };

            foreach (var user in userManager.Users)
            {
                if (await userManager.IsInRoleAsync(user, role.Name))
                {
                    model.Users.Add(user.UserName);
                };
            }
            return RedirectToPage("./Index");
        }
    }
    }

using Microsoft.AspNetCore.Identity;
using System.ComponentModel.DataAnnotations;

namespace ThreeTierAdvisementApp.Data
{
    public class EditRoles:IdentityRole
    {
        public string Id { get; set; }
        [Required(ErrorMessage ="Role Name is required")]
        public string RoleName { get; set; }

        public List<string> Users { get; set; }
    }
}

**Identity Class**
using Microsoft.AspNetCore.Identity;

namespace ThreeTierAdvisementApp.Data
{
    public class DefaultUser:IdentityUser
    {
        public string FirstName { get; set; }
        public string LastName { get; set; }

    }
}

**Role Class**
    public class Roles : IdentityRole
    {
        [Required]
        public string RoleName { get; set; }
    }

**List of rolse view. When I click the edit button I want to edit the selected role**
@page
@using ThreeTierAdvisementApp.Areas.Identity.Pages.Account.Administration
@model ListRoleModel;
@{
    ViewData["Title"] = "All Roles";
}

All Roles

@if(Model.CurrentRoles.Any()){
@foreach (var item in Model.CurrentRoles)
    {

                @Html.DisplayFor(modelItem => item.Id)

@Html.DisplayFor(modelItem => item.RoleName)

                Edit
                Delete

    }
}else{

No Roles Yet

                Use the button below to create a role

        Create Role

}

@section Scripts {
    <partial name="_ValidationScriptsPartial" />
}


问:
Cannot write to a HttpContext.Response in AuthenticationHandler
When in my custom AuthenticationHandler I want to write some data into HttpContext.Response like this:

```<code>protected override async Task<AuthenticateResult> HandleAuthenticateAsync()
{
    await Context.Response.WriteAsJsonAsync(new SomeObject(), Context.RequestAborted);
    return AuthenticateResult.Fail("something went wrong");
}
</code>```

I always get exception:

Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware[1]
An unhandled exception has occurred while executing the request.
System.InvalidOperationException: StatusCode cannot be set because the response has already started.

With these stack traces:

at Microsoft.AspNetCore.Server.Kestrel.Core.Internal.Http.HttpProtocol.ThrowResponseAlreadyStartedException(String value)
at Microsoft.AspNetCore.Server.Kestrel.Core.Internal.Http.HttpProtocol.set_StatusCode(Int32 value)
at Microsoft.AspNetCore.Authentication.AuthenticationHandler1.HandleChallengeAsync(AuthenticationProperties properties) at Microsoft.AspNetCore.Authentication.AuthenticationHandler1.ChallengeAsync(AuthenticationProperties properties)
at Microsoft.AspNetCore.Authentication.AuthenticationService.ChallengeAsync(HttpContext context, String scheme, AuthenticationProperties properties)
at Microsoft.AspNetCore.Authorization.Policy.AuthorizationMiddlewareResultHandler.<>c__DisplayClass0_0.<g__Handle|0>d.MoveNext()
--- End of stack trace from previous location ---

And:

at Microsoft.AspNetCore.Authorization.AuthorizationMiddleware.Invoke(HttpContext context)
at Microsoft.AspNetCore.Authentication.AuthenticationMiddleware.Invoke(HttpContext context)
at Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddlewareImpl.Invoke(HttpContext context)
at Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddlewareImpl.Invoke(HttpContext context)
at Microsoft.AspNetCore.Watch.BrowserRefresh.BrowserRefreshMiddleware.InvokeAsync(HttpContext context)
at Microsoft.AspNetCore.Server.Kestrel.Core.Internal.Http.HttpProtocol.ProcessRequests[TContext](IHttpApplication`1 application)

Thought with this error my request is aborted and I don't get any response. If after writing to response I call Response.CompleteAsync() then exception is still thrown, but I get response.

Additionally, I don't have any custom middleware. How can I fix this?

Body:
When in my custom AuthenticationHandler I want to write some data into HttpContext.Response like this:

protected override async Task<AuthenticateResult> HandleAuthenticateAsync()
{
    await Context.Response.WriteAsJsonAsync(new SomeObject(), Context.RequestAborted);
    return AuthenticateResult.Fail("something went wrong");
}

I always get exception:

Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware[1]
An unhandled exception has occurred while executing the request.
System.InvalidOperationException: StatusCode cannot be set because the response has already started.

With these stack traces:

at Microsoft.AspNetCore.Server.Kestrel.Core.Internal.Http.HttpProtocol.ThrowResponseAlreadyStartedException(String value)
at Microsoft.AspNetCore.Server.Kestrel.Core.Internal.Http.HttpProtocol.set_StatusCode(Int32 value)
at Microsoft.AspNetCore.Authentication.AuthenticationHandler1.HandleChallengeAsync(AuthenticationProperties properties) at Microsoft.AspNetCore.Authentication.AuthenticationHandler1.ChallengeAsync(AuthenticationProperties properties)
at Microsoft.AspNetCore.Authentication.AuthenticationService.ChallengeAsync(HttpContext context, String scheme, AuthenticationProperties properties)
at Microsoft.AspNetCore.Authorization.Policy.AuthorizationMiddlewareResultHandler.<>c__DisplayClass0_0.<g__Handle|0>d.MoveNext()
--- End of stack trace from previous location ---

And:

at Microsoft.AspNetCore.Authorization.AuthorizationMiddleware.Invoke(HttpContext context)
at Microsoft.AspNetCore.Authentication.AuthenticationMiddleware.Invoke(HttpContext context)
at Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddlewareImpl.Invoke(HttpContext context)
at Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddlewareImpl.Invoke(HttpContext context)
at Microsoft.AspNetCore.Watch.BrowserRefresh.BrowserRefreshMiddleware.InvokeAsync(HttpContext context)
at Microsoft.AspNetCore.Server.Kestrel.Core.Internal.Http.HttpProtocol.ProcessRequests[TContext](IHttpApplication`1 application)

Thought with this error my request is aborted and I don't get any response. If after writing to response I call Response.CompleteAsync() then exception is still thrown, but I get response.

Additionally, I don't have any custom middleware. How can I fix this?


问:
Google sheets chart has a white background on the app even though it is set to have no background
On google sheets I have the background color of my doughnut charts set to none. No background appears if I view my sheet on desktop or go to sheets using a mobile search engine. However, if I'm looking at the app the charts have a white background. Is there anyway to fix this by using api code, or am I just stuck with it?</p>


问:
Cannot change value of "/sys/class/power_supply/battery/input_suspend" on Android App
I'm trying to make Android app that stops battery charging.

My Android device runs Android 12, and the value of compileSdk in build.gradle of this app is 32.

Ofcource, my Android device is rooted.

I followed this question and disabled SELinux by runnning "setenforce 0" command.

I found that I can stop battery charging by changing value of "/sys/class/power_supply/battery/input_suspend" from 0 to 1.

I have confirmed by running the following command on the PC to which a Android device is connected that I can really stop battery charging by doing this:

```<code>adb shell su
echo 1 > /sys/class/power_supply/battery/input_suspend
</code>```

This worked well. So I started creating app that uses this method.

The MainActivity.java of this App:

```<code>package com.example.chargedisabler;

import static android.content.ContentValues.TAG;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.util.Log;

import java.io.IOException;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        try {
            Runtime.getRuntime().exec("su -c \"echo 1 > /sys/class/power_supply/battery/input_suspend\"");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
</code>```

This not worked.  Even if Root privileges were granted, charging was not stopped.

I changed the method and changed the MainActivity.java as follows:

```<code>package com.example.chargedisabler;

import static android.content.ContentValues.TAG;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.util.Log;

import java.io.IOException;
import java.io.OutputStream;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        try {
            Process p = Runtime.getRuntime().exec("su");
            OutputStream OStrm = p.getOutputStream();
            OStrm.write(("echo 1 > /sys/class/power_supply/battery/input_suspend\n").getBytes("UTF-8"));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
</code>```

This also not worked.

Next, on the PC to which the Android device is connected, I tried to stop battery charging in a different way than before:

```<code>adb shell su -c "echo 1 > /sys/class/power_supply/battery/input_suspend"
</code>```

Oddly enough, this command outputs the following:

```<code>/system/bin/sh: can't create /sys/class/power_supply/battery/input_suspend: Permission denied
</code>```

When I tried to read the contents in a similar way, somehow the file could be read successfully:

```<code>adb shell su -c "cat /sys/class/power_supply/battery/input_suspend"
</code>```

This command outputs "0".

It seems that unless the command is executed in some correct way, the file will be kept secret for writing.

How can I change the value of "/sys/class/power_supply/battery/input_suspend" from within the application?

Or is there a better way to stop charging that works with any device?

Body:
I'm trying to make Android app that stops battery charging.

My Android device runs Android 12, and the value of compileSdk in build.gradle of this app is 32.

Ofcource, my Android device is rooted.

I followed this question and disabled SELinux by runnning "setenforce 0" command.

I found that I can stop battery charging by changing value of "/sys/class/power_supply/battery/input_suspend" from 0 to 1.

I have confirmed by running the following command on the PC to which a Android device is connected that I can really stop battery charging by doing this:

adb shell su
echo 1 > /sys/class/power_supply/battery/input_suspend

This worked well. So I started creating app that uses this method.

The MainActivity.java of this App:

package com.example.chargedisabler;

import static android.content.ContentValues.TAG;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.util.Log;

import java.io.IOException;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        try {
            Runtime.getRuntime().exec("su -c \"echo 1 > /sys/class/power_supply/battery/input_suspend\"");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

This not worked.  Even if Root privileges were granted, charging was not stopped.

I changed the method and changed the MainActivity.java as follows:

package com.example.chargedisabler;

import static android.content.ContentValues.TAG;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.util.Log;

import java.io.IOException;
import java.io.OutputStream;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        try {
            Process p = Runtime.getRuntime().exec("su");
            OutputStream OStrm = p.getOutputStream();
            OStrm.write(("echo 1 > /sys/class/power_supply/battery/input_suspend\n").getBytes("UTF-8"));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

This also not worked.

Next, on the PC to which the Android device is connected, I tried to stop battery charging in a different way than before:

adb shell su -c "echo 1 > /sys/class/power_supply/battery/input_suspend"

Oddly enough, this command outputs the following:

/system/bin/sh: can't create /sys/class/power_supply/battery/input_suspend: Permission denied

When I tried to read the contents in a similar way, somehow the file could be read successfully:

adb shell su -c "cat /sys/class/power_supply/battery/input_suspend"

This command outputs "0".

It seems that unless the command is executed in some correct way, the file will be kept secret for writing.

How can I change the value of "/sys/class/power_supply/battery/input_suspend" from within the application?

Or is there a better way to stop charging that works with any device?