text:
Q: jQuery image slider not working with jQuery-cycle (ASP.NET) I am working on implementing an Obligatory image slider with jQuery on my ASP.NET web app. I can see the first picture, but when I press the next or previous buttons, it doesn't work.
I installed the jQuery.cycle plug in as well, but don't know what's wrong. Do I need another plug-in along with jQuery cycle?
Html

⟩

⟨

CSS

Javascript

A: Remove the duplicate
You already have it called (.min means minified version of the script.)
And wrap your call in a ready block

UPDATE:
I created a snippet using your exact code. it works perfectly.
this indicates that your other scripts are interfering.

    $('#slider').cycle({
        fx: 'scrollHorz',
        next: '#next',
        prev: '#prev',
        timeout: 3000,
        pause: 1
    });
    #slider-nav{
        width: 700px;
        height: 280px;
        position: relative;
        margin: 50px auto;
    }

    #slider{
        width: 700px;
        height: 280px;
        position: absolute;
        overflow: hidden;
    }

    #next {
        text-align: center;
        line-height: 50px;
        color: white;
        width: 50px;
        height: 50px;
        background-color: black;
        position: absolute;
        top: 120px;
        right: 0;
        z-index: 99;
        cursor: pointer;
        opacity: 0;
    }

    #prev {
        text-align: center;
        line-height: 50px;
        color: white;
        width: 50px;
        height: 50px;
        background-color: black;
        position: absolute;
        top: 120px;
        left: 0;
        z-index: 99;
        cursor: pointer;
        opacity: 0;
    }

    #slider-nav:hover #next {
        opacity: 1;
        transition: all .5s ease-out;
        -webkit-transition: all .5s ease-out;
    }

    #slider-nav:hover #prev {
        opacity: 1;
        transition: all .5s ease-out;
        -webkit-transition: all .5s ease-out;
    }

⟩

⟨


text:
Q: Modify only enabled checkboxes I have the below piece of code, whereby $(obj) is the main checkbox (select all/deselect all).
The function is working successfully, however I want to restrict the functionality to only enabled checkboxes.
Some checkboxes are disabled and I don't want it to be affected by the functionality.
Any idea on how to do so?
 if( $(obj).is(':checked') ) {
        $("#scrollableContent input[type='checkbox']").prop("checked", true);
    }else {
        $("#scrollableContent input[type='checkbox']").prop("checked", false);
    }

A: You can use the jQuery selector :enabled :
$("#scrollableContent input[type='checkbox']:enabled").prop("checked", true);

A: There are selectors to get only disabled elements :disabled or enabled elements :enabled
if( $(obj).is(':checked') ) {
    $("#scrollableContent input[type='checkbox']:not(:disabled)").prop("checked", true);
}else {
    $("#scrollableContent input[type='checkbox']:not(:disabled)").prop("checked", false);
}

A: As mentioned by the others, you can use :not selector, but you can also refactor your code into one line:
$("#scrollableContent input[type='checkbox']:not(:disabled)").prop("checked", $(obj).is(':checked'));

Or, using jQuery's not():
 $("#scrollableContent input[type='checkbox']").not(':disabled').prop("checked", $(obj).is(':checked'));

redpajama_set_name: RedPajamaStackExchange


text:
Q: Hand built w3c Document Text node causes odd behavior The following code causes output that resembles the following:
<parent>
  <child/>
  <secondChild/>  ...

I would anticipate it to look as follows:
<parent>
parent text
<child></child>
<secondChild>second child text</secondChild>

The code in question is as follows:
Element parentNode= document.createElement("parent");
Text textNode = document.createTextNode("parent text");
Element childNode = document.createElement("child");
parentNode.appendChild(childNode);
childNode.appendChild(textNode);
childNode = document.createElement("secondChild");
textNode = document.createTextNode("second child text");
parentNode.appendChild(childNode);
childNode.appendChild(textNode);

My question is is there something I am missing by re-referencing the textNode that causes an issue when building a Document?

A: yes, you cannot reuse any node. In a DOM, each node has a parent, and only one parent, once you attach a node (be it a text node or an element), that node is attached and should not be attached to any other parent node if not detached first.
DOM is rather ancient, and is not the easiest way to work with xml, not in java nor in any other platform (since it's a standard interface which is the same on almost all platforms).
Have you tried jdom or dom4j?

A: It works as expected for me. Maybe there's a problem with how you're printing it out? Try this:
import org.w3c.dom.*;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.*;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import java.io.StringWriter;

public class ThrowawayCode {
    public static void main(String[] args) throws Exception {
        Document document = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();
        Element parentNode = document.createElement("parent");
        document.appendChild(parentNode);
        Text textNode = document.createTextNode("parent text");
        Element childNode = document.createElement("child");
        parentNode.appendChild(childNode);
        childNode.appendChild(textNode);
        childNode = document.createElement("secondChild");
        textNode = document.createTextNode("second child text");
        parentNode.appendChild(childNode);
        childNode.appendChild(textNode);

        Source source = new DOMSource(document);
        StringWriter writer = new StringWriter();
        Result result = new StreamResult(writer);
        TransformerFactory.newInstance().newTransformer().transform(source, result);
        System.out.println(writer.toString());
    }
}

Output:
<?xml version="1.0" encoding="UTF-8" standalone="no"?><parent><child>parent text</child><secondChild>second child text</secondChild></parent>

Edit: If you really mean that you want the first text outside of the child instead of inside it, you need to change your code to:
Text textNode = document.createTextNode("parent text");
Element childNode = document.createElement("child");
parentNode.appendChild(textNode);
parentNode.appendChild(childNode);

but I assumed you had just mistyped the XML.


text:
Q: Como ordenar uma tabela de acordo com os dados de outra tabela Tenho duas tabelas
Tabela 1
 create table tb1
(
  cd_tb1 INT NOT NULL AUTO_INCREMENT PRIMARY KEY
);

Tabela 2
create table tb2
    (
      cd_tb2 INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
      cd_tb1 int,
      vl_avaliacao int,

      constraint fk_tb1
      foreign key (cd_tb1)
      references tb1 (cd_tb1),
    );

tb2 pode ter várias linhas com o mesmo código que pertencem a tb1. Preciso fazer uma média do campo vl_avaliacao e em seguida retornar os dados da tb1 ordenados por essa média. Gostaria de saber se tem alguma forma de fazer isso no Mysql ou se preciso retornar os valores desordenados e tentar de alguma forma ordenar na aplicação.

A: SELECT tb1.cd_tb1, AVG(tb2.vl_avaliacao) FROM
tb1 LEFT OUTER JOIN tb2 ON (tb1.cd_tb1 = tb2.cd_tb1)
GROUP BY tb1.cd_tb1
ORDER BY tb1.cd_tb1;

Talvez possa ser de seu interesse utilizar:
IFNULL(AVG(tb2.vl_avaliacao), 0)

A: Complementando a resposta do colega acima (order by por média):
SELECT tb1.cd_tb1, AVG(tb2.vl_avaliacao) as Media FROM
tb1 LEFT OUTER JOIN tb2 ON (tb1.cd_tb1 = tb2.cd_tb1)
GROUP BY tb1.cd_tb1
ORDER BY AVG(tb2.vl_avaliacao) desc;


text:
Q: Can I use PropertyPlaceholderConfigurer to perform replacement of properties on String at runtime? In one area of our Spring configuration we are using:
applicationContext.xml:
<bean class="org.springframework.cache.ehcache.EhCacheManagerFactoryBean" lazy-init="true">
    <property name="configLocation" value="classpath:ehcache.xml"/>
</bean>

However, ehcache.xml is not a standard spring bean configuration file but contains ${ehcache.providerURL} which we want to replace based on what we have configured with PropertyPlaceHolderConfigurer elsewhere:
ehcache.xml:
<cacheManagerPeerProviderFactory
   ...
   providerURL=${ehcache.providerURL}
   ...
</cacheManagerPeerProviderFactory>

I could use the Maven/profile/filter combination, but that would create a build that is specific to the environment it is being built for.  What I really want to do, is to pre-process the ehcache.xml at runtime performing substitutions based the properties read by PropertyPlaceHolderConfigurer and then pass the result of that into the EhCacheManagerBean.
At this point, I am thinking of somehow duplicating the functionality behind the @Value annotation since it can replace "bla bla bla ${property} bla bla bla" except I need to do this after reading a file from disk.
Any ideas on how to go about this?
Thanks.
-AP_

A: To manipulate strings directly, you could use the org.springframework.util.PropertyPlaceholderHelper
String template = "Key : ${key} value: ${value} "
PropertyPlaceholderHelper h = new PropertyPlaceholderHelper("${","}");
Properties p = new Properties();
p.setProperty("key","mykey");
p.setProperty("value","myvalue");
String out = h.replacePlaceholders(template,p);

It replaces values in a template with the corresponding property values.

A: After some searching, here is the essence of what I came up with.  I packaged this into a Factory which accepts a resource and converts it after replacing all the lines with ${propertyPlaceHolder} with actual values of the holder.
    final ConfigurableListableBeanFactory
        factory =
            ((ConfigurableApplicationContext) applicationContext).getBeanFactory();

    String line = null;
    while ((line = reader.readLine()) != null) {
        try {
            final String
                result = factory.resolveEmbeddedValue(line);
            writer.println(result);
        }
        catch (final Exception e) {
            log.error("Exception received while processing: " + line, e);
            throw e;
        }
    }

The benefit of this solution is that it is using the same facilities as Spring uses to resolve @Value("${fooBar}") annotations.  This means you can use SpEL and what ever else Spring would normally accept in the @Value annotation.  It is also integrated with PropertyPlaceholderConfigurer.
Hope this helps someone.
-AP_

A: PropertyPlaceholderConfigurer works to replace properties within Spring configuration files. It does not replace properties in external files. Your problem can not be resolved with PropertyPlaceholderConfigurer.
You can override org.springframework.cache.ehcache.EhCacheManagerFactoryBean.afterPropertiesSet() method and do whatever you want to do with xml before creating CacheManager.You know how clean it can be :)


text:
Q: Vectorize 3d operation in matlab Can you vectorize a operation where the columns of U are added to cwx and the result is stored in a 3d array?
A non-vectorized solution:
cwx =rand([500,100]);
U = rand([500 10]);

F = zeros([500 100 10]);
for y = 1:10
    F(:,:,y) = bsxfun(@plus,U(:,y),cwx);
end

A: It can be done with a single call to bsxfun, provided you first permute the second and third dimensions of U:
F = bsxfun(@plus, permute(U, [1 3 2]), cwx);


text:
Q: How to set custom community login page with aura to default login page? I created custom community login page via aura. I accessed to my community login page such as https://mycommunity url/communityname/login, but this URL is go to community experience builder's login page.I did the setting of redirect url at Site setting, but can't redirect to custom community login page.How can I solve it?

A: You can configure this from the administration page within the Community Workspace.

For a custom Aura Component, I'd recommend just updating the standard Login Page in the Community Builder to use your login component instead of the standard.


text:
Q: Parallel deployment of express nodejs application to multiple application servers I have a mean.io express/node js web application deployed on a Linode stack.
I have my 2 application servers running Ubuntu 14.04, which are accessed behind 2 Haproxy load balancers again running on Ubuntu 14.04.
Let us call Application server 1 => APP1 and Application server 2 => APP2
Currently, I deploy manually by

*

*Removing APP1 entry from haproxy.cfg of both the load balancers and restarting.

*Update the code on APP1

*Remove APP2 entry from haproxy.cfg of both the load balancers and put APP1 entry back

*Restart APP1

*Update code on APP2

*Put the APP2 entry back in both haproxy.cfg's and restart

*Restart APP2
I follow this process so that at any point of time the users of our web application get consistent data even during deployment, i.e both the instances of app server are not running a different copy of the code.
I am moving to automated deployment system and the 2 options I have looked at for deployment are Capistrano and Shipit JS.
They both provide ways to mention multiple servers in their configuration, for e.g in capistrano
role :app, "APP1", "APP2"

and in Shipit JS
shipit.config.servers = ['APP1', 'APP2']

*

*So, my question is how do these libraries make sure that both the servers are updated parallely before they are restarted? Is there a way by which they lock incoming requests to these servers during updation ?

*Do these deployment systems work only for simple Client - App Server architecture or they can used in systems where there is a load balancer?
Any explanation would be invaluable. I have tried my best to explain the situation here.If you need more input please mention below in the comments.


text:
Q: Как мне добавить Entry в мой код? Я пытался добавить Entry разными способами, но похоже нужно через canvas. Как мне это сделать? Добавил фрагмент кода с Tkinter

#=========================================================== Ход работы

error = 0
root = tk.Tk() # Задаем новое окно

root.geometry('400x500') # Определяем размеры
root.resizable(width=False, height=False) # Закрепляем размеры
root.title("Голосовой ассистент Юля")

#======= Непонятный код ======

image = Image.open("Background.png")
width = 500
ratio = (width / float(image.size[0]))
height = int((float(image.size[1]) * float(ratio)))
image = image.resize((width, height), Image.ANTIALIAS)
image = ImageTk.PhotoImage(image)
canvas = tk.Canvas(root, width=width, height=height)
canvas.pack(side="top", fill="both", expand="no")
canvas.create_image(0, 0, anchor="nw", image=image)

#==============================

canvas.create_text(200, 25, text="Юлия 0.1.5", fill="Purple", font='Helvetica 30') # Текст
canvas.create_text(200, 50, text="Голосовой помощник, созданный для общения", fill="Purple", font='Times 13') # Текст

button = tk.Button(root, text='Запуск', font="Times 30", bg=_from_rgb((189, 223, 249))) # Настройки для кнопки
canvas.create_window((125, 400), anchor="nw", window=button) # Вывод кнопки.
button.config(command=lambda: main()) # Вызов кнопкой функции main()
Program = tk.Entry(root, width=10) <-- ПРОБЛЕМНОЕ МЕСТО
Program.pack() <-- ПРОБЛЕМНОЕ МЕСТО

root = tk.mainloop() # Запуск окна

#==========================================================

Проблема в том, что поле для ввода не появляется. Почему canvas? Потому что код из области "Непонятный код" был взят с другого вопроса и менять что либо в нём я не желаю и не могу.

A: Текстовое поле у вас появляется ниже canvas, за пределами окна. Если убрать строку с указанием размера окна (root.geometry('400x500')), то его будет видно:

Если нужно добавить поле ввода поверх canvas, то добавляйте его аналогично добавлению кнопки button (в скобках (300, 400) - координаты, по которым будет расположено поле на canvas):
button = tk.Button(root, text='Запуск', font="Times 30") # Настройки для кнопки
canvas.create_window((125, 400), anchor="nw", window=button) # Вывод кнопки.
button.config(command=lambda: main()) # Вызов кнопкой функции main()

Program = tk.Entry(root, width=10)
canvas.create_window((300, 400), anchor="nw", window=Program)

Результат:


text:
Q: Swift Ambiguous type name import UIKit
import Foundation
import CollectionViewPagingLayout

public extension SnapshotTransformViewOptions {
    enum Layout: String, CaseIterable {
        case grid
        case space
        case chess
        case tiles
        case lines
        case bars
        case puzzle
        case fade
    }

    static func layout(_ layout: Layout) -> Self { //error: Ambiguous type name in 'SnapshotTransformViewOptions'

        switch layout {
        case .grid:
            return Self(
                pieceSizeRatio: .init(width: 1.0 / 4.0, height: 1.0 / 10.0),
                piecesCornerRadiusRatio: .static(1)

hello, I am trying to use an swift package to customize the paging about collection view, but I got "Ambiguous type name" error. What should I do here?

A: Try to use that Layout enum as SnapshotTransformViewOptions.Layout, that should fix the problem ( and I think that's the best practice for nested classes,enum, or structs )


text:
Q: Angular: How to refresh the view after data modification of list? I have a view with the following snippet:

{{item.position}}

{{item.text}}

In controller, I have the following snippet:
export class AppComponent implements AfterViewInit {
  step: StepInterface;
  stepId: number;
  orderedId: Array<number>;

  constructor(private api: ApiService) {

    this.stepId = 1 //Debug

    this.optionsSortable = {
      onUpdate: (event: any) => {
        this.api.organize(this.stepId, this.orderedId).subscribe((response) => {
          this.step = response;
          this.buildArray();
        });
      }
    };
  }

  ngAfterViewInit() {
    this.api.get(this.stepId).subscribe((data) => {
      this.step = data;

      this.buildArray();
    });
  }

  private buildArray() {
    this.orderedId = [];
    for (const item of this.step.items) {
      this.orderedId.push(item.id);
      console.log(clue.id);
    }
  }
}

In fact, I have sortable div and when user modify the position, data is updated with backend.
Problem is when the position is updated, so object "step" modified, {{item.position}} is not refreshed in view.
How can I update the position in view after position modification?
Thank you

A:

ChangeDetectorRef

if there is a case where any thing inside your component data has changed but it hasn't reflected the view, you might
  need to notify Angular to detect those changes ( detect local changes)
  and update the view.

import { Component, Input, ChangeDetectionStrategy,ChangeDetectorRef } from
   '@angular/core';
@Component({
  selector: 'app-child',
  templateUrl: './child.component.html',
  changeDetection: ChangeDetectionStrategy.OnPush
})

export class AppComponent implements AfterViewInit {
  step: StepInterface;
  stepId: number;
  orderedId: Array<number>;

  constructor(private api: ApiService,private cdr:ChangeDetectorRef) {

    this.stepId = 1 //Debug

    this.optionsSortable = {
      onUpdate: (event: any) => {
        this.api.organize(this.stepId, this.orderedId).subscribe((response) => {
          this.step = response;
          this.buildArray();
        });
      }
    };
  }

  ngAfterViewInit() {
    this.api.get(this.stepId).subscribe((data) => {
      this.step = data;

      this.buildArray();
    });
  }

  private buildArray() {
    this.orderedId = [];
    for (const item of this.step.items) {
      this.orderedId.push(item.id);
      console.log(clue.id);
    }
     this.cd.detectChanges();
  }
}


text:
Q: Redirecting localhost/xxx to localhost/xxx.php in WAMP In Ubuntu/Mac, going to, say, localhost/page automatically redirects to localhost/page.php.
But this doesn't work in Windows. How do you make stuff like localhost/asdf redirect to localhost/asdf.php?

A:
I am assuming that you know what an .htaccess file is.

You can achieve this by two methods:
Method 1:
`#1- Loads the page asdf.php but
     displays asdf in the address bar

RewriteBase   /site
RewriteRule ^([^/\.]+)?$ $1.php `

Method 2:
`#2- Loads the page asdf.php and
displays asdf.php in the address bar.
The R flag tells Apache to redirect to the
url.

RewriteBase   /site
RewriteRule ^([^/\.]+)?$ $1.php [R]`

I hope this will help you.


text:
Q: Getting dynamic date in oracle SQL query executed from python environment using cx_Oracle package I'm trying to write a query which fetches the current date and gets the relevant log data. Have written a nested query which works from PL/SQL but it isn't working from Python environment. Please advise.
Working query for PL/SQL:
SELECT * FROM TBLIRISVISITLOGS TLOG
WHERE TLOG.IVL_VISITDATE = (SELECT TO_CHAR(SYSTIMESTAMP,'DD-MON-YYYY') FROM DUAL)

When I execute this query in Python environment, it fetches an empty table.

A: seems like I've found the solution:
from pandas import Timestamp as tstamp
test_query = """
SELECT * FROM TBLIRISVISITLOGS T WHERE T.IVL_LATITUDE>0 AND T.IVL_VISITDATE = TO_DATE('{CURR_DATE}','YYYY-MM-DD')
""".format(CURR_DATE=str(tstamp.now().date()))


text:
Q: Given only the slope, find the shortest distance from a line to a point on the x-axis
I have the following amusing question.
Suppose that the red dot is the point $x = -1$
The blue line is the line crossing the origin with slope $-1/k, k > 0$
I wish to find the length of the purple line, which is the shortest distance from the blue line to the red dot.
Can this be done or do I need additional information?

A: Using the perpendicular distance formula: $d = \frac{ax_1 + by_1 + c}{\sqrt{a^2+b^2}}$ with $x_1 = -1, y_1 = 0$ (the coordinates of the given point) and $a = 1, b = k, c = 0$ (by writing the equation of the line in general form). This gives $d = \frac{1}{\sqrt{1+k^2}}$.
Note that this even works for $k < 0$ (but obviously not for $k = 0$).

A: Guide:

*

*Let the acute angle between the blue line and the negative $x$-axis be $\theta$. Since the slope is $-\frac1k$. Can you compute $\tan \theta$?

*The length of the purple line is $\sin \theta$.
$$\tan \theta = \frac{\sin\theta}{\sqrt{1-\sin^2\theta}}$$

A: You have a line
$$\bbox{ y(x) = - \frac{x}{k} }$$
We'll assume $0 \ne k \in \mathbb{R}$; i.e. $k$ may be any nonzero real.
The distance squared from point $(-1, 0)$ to $(x, y(x))$ is $(x-1)^2 + (y(x))^2$. As a function of $x$,
$$\bbox{ L_2(x) = (x - 1)^2 + \bigr( y(x) \bigr)^2 = \frac{k^2 + 1}{k^2} x^2 + 2 x + 1 }$$
Since this is continuous and differentiable, it reaches an extrema when its derivative,
$$\bbox{ \frac{d L_2(x)}{d x} = \frac{2 k^2 + 2}{k^2} x + 2 }$$
is zero:
$$\bbox{ \frac{2 k^2 + 2}{k^2} x + 2 = 0 } \quad \iff \quad \bbox{ x = - \frac{k^2}{k^2 + 1} }$$
Substituting that back to the distance squared, and taking a square root, we find that the minimum distance is
$$\bbox{ L_{min} = \sqrt{L_2\left(-\frac{k^2}{k^2 + 1}\right)} }$$
where the expression in the square root is $L_2(x)$ when $x = -k^2 / (k^2 + 1)$.
That simplifies to
$$\bbox{ L_{min} = \frac{1}{\sqrt{k^2 + 1}} }$$
We can make this cover all $k \in \mathbb{R}$, by noting that when $k = 0$, is passes via the point $(-1, 0)$, so then the distance is zero:
$$\bbox[#fffff7]{
\text{Minimum distance} = \begin{cases}
0, & k = 0 \\
\displaystyle \frac{1}{\sqrt{k^2 + 1}}, & k \ne 0
\end{cases} }$$


text:
Q: Bootstrap  borders are crooked I created a form on a cshtml page that has fillable field, and then I export it to PDF. I styled the Bootstrap rows and columns with a border so it looks like a form we are modeling. I noticed that some of the borders don't line up right and seem crooked.

I have a few css classes on the page to handle various borders that I turn on or off so the borders are not doubled up creating a thicker line

Here is a sample of my rows and columns code

RECORD OF WEIGHTED GUIDELINES APPLICATION

1. REPORT NO.

2. BASIC PROCUREMENT INSTRUMENT IDENTIFICATION NO.

3. SPIIN

4. DATE OF ACTION

                @Html.EJS().InPlaceEditor("textReportNo").Mode(Syncfusion.EJ2.InPlaceEditor.RenderMode.Inline).Type(Syncfusion.EJ2.InPlaceEditor.InputType.Text).ShowButtons(false).SubmitOnEnter().Render()

a. PURCHASING OFFICE

b. FY

c. TYPE PROC INST CODE

d. PRISN

                        @Html.EJS().InPlaceEditor("textPurchasingOffice").Mode(Syncfusion.EJ2.InPlaceEditor.RenderMode.Inline).Type(Syncfusion.EJ2.InPlaceEditor.InputType.Text).ShowButtons(false).SubmitOnEnter().Render()

                        @Html.EJS().InPlaceEditor("textFY").Mode(Syncfusion.EJ2.InPlaceEditor.RenderMode.Inline).Type(Syncfusion.EJ2.InPlaceEditor.InputType.Text).ShowButtons(false).SubmitOnEnter().Render()

                        @Html.EJS().InPlaceEditor("textTypeProcInstCode").Mode(Syncfusion.EJ2.InPlaceEditor.RenderMode.Inline).Type(Syncfusion.EJ2.InPlaceEditor.InputType.Text).ShowButtons(false).SubmitOnEnter().Render()

                        @Html.EJS().InPlaceEditor("textPrisn").Mode(Syncfusion.EJ2.InPlaceEditor.RenderMode.Inline).Type(Syncfusion.EJ2.InPlaceEditor.InputType.Text).ShowButtons(false).SubmitOnEnter().Render()

                @Html.EJS().InPlaceEditor("textSpiin").Mode(Syncfusion.EJ2.InPlaceEditor.RenderMode.Inline).Type(Syncfusion.EJ2.InPlaceEditor.InputType.Text).ShowButtons(false).SubmitOnEnter().Render()

                @Html.EJS().InPlaceEditor("dateOfAction").Mode(Syncfusion.EJ2.InPlaceEditor.RenderMode.Inline).Type(Syncfusion.EJ2.InPlaceEditor.InputType.Date).ShowButtons(false).SubmitOnEnter().Render()

5. CONTRACTING OFFICE CODE

                @Html.EJS().InPlaceEditor("textContractOfficeCode").Mode(Syncfusion.EJ2.InPlaceEditor.RenderMode.Inline).Type(Syncfusion.EJ2.InPlaceEditor.InputType.Text).ShowButtons(false).SubmitOnEnter().Render()

ITEM

COST CATEGORY

OBJECTIVE

I thought design would be flexible for variable rows and columns by using Bootstrap, but I am wondering it the styles would be easier and cleaner using tables.
Thanks for any help


text:
Q: Populate List from DataTable column I have a datatable dt with a single column and a list of strings. If I want to change this to a list (for example, to make it easier to compare with another list) I would default to something like:
var ls = new List<string>();
foreach (DataRow dr in dt.Rows)
{
    ls.Add(dr["COLUMN_NAME"].ToString());
}

I don't think it's possible to get more efficient than that, but is there shorter way to write this, maybe using LINQ?

A: As mentioned in the comment, the LINQ way might be shorter in code, but not more efficient.
Anyway, here is the one liner LINQ version.
var list = new List<string>(dt.Rows.Cast<DataRow>().Select(r => r["COLUMN_NAME"].ToString()));


text:
Q: imessage extension app group conversation send fails on first run I have an imessage extension app that works fine except on the first send to a group.
iOS 14.4 multiple devices 8, 8plus, 10...
Xcode 12.4
The code goes straight from the send closure (success) to didResignActive. The app is supposed to stay active. There is no dismiss called anywhere.  I've debugged w/ attached device stepped through the code, and it goes straight from the log line to didResignActive.
If I launch the app again on the same group it works fine. The app only fails if I start a new group conversation, then click on the app in tray, and send is called.
note: this only happens to group sends, and only on the first time a group is created.
       thisConversation.send(message) { error in
            if let error = error {
                os_log("submitMessage(%@): initial send error: %@", log: .default, type: .debug, type, error.localizedDescription)
            } else {
                os_log("submitMessage(%@): initial send success!", log: .default, type: .debug, type)
            }
        }

A: Edit:
Just an update...
I was told to file a bug report for this (which I did).
I also supplied a video which shows how to reproduce the bug.
This is the message sent back from support...

Hi,
Thank you contacting Apple Developer Technical Support (DTS).
There is no workaround DTS can provide for Feedback ID #FB9049862; it
is still under investigation. Please continue to track the problem via
the bug report.
...

I was able to create a test app that reproduces this problem, with what I think is the minimal amount of code to demonstrate.  Hope this invites a solution!
//
//  MessagesViewController.swift
//  testGroupSend MessagesExtension
//

import UIKit
import Messages
import os

class MessagesViewController: MSMessagesAppViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.
    }

    // MARK: - Conversation Handling
    func composeSelectionMsg(on conversation: MSConversation, in
        session: MSSession) -> MSMessage {

        let layout = MSMessageTemplateLayout()
        layout.caption = "caption..."

        let message = MSMessage(session: session)
        message.layout = layout
        message.summaryText = "summary text..."

        var components = URLComponents()
        var queryItems = [URLQueryItem]()

        queryItems.append(URLQueryItem(name: "MessageType1", value: "msgType"))
        queryItems.append(URLQueryItem(name: "Encode-Name", value: "Encode-Value"))

        components.queryItems = queryItems
        message.url = components.url!

        return message
    }

    func submitMessage() {
        guard let conversation = activeConversation else {
            os_log("submitMessage(): guard on conversation falied!", log: .default, type: .debug)
            return
        }
        var session : MSSession
        if let tSess = conversation.selectedMessage?.session {
            session = tSess
            os_log("submitMessage() got a session!...", log: .default, type: .debug)
        } else {
            os_log("###### submitMessage() did NOT get a session, creating new MSSession() #####", log: .default, type: .debug)
            session = MSSession()
        }
        var message: MSMessage

        message = composeSelectionMsg(on: conversation, in: session)

            //  conversation.insert(message) { error in
        conversation.send(message) { error in
                if let error = error {
                    os_log("submitMessage(): initial send error: %@", log: .default, type: .debug, error.localizedDescription)
                } else {
                    os_log("submitMessage(): initial send success!", log: .default, type: .debug)
                }
            }
    }

    fileprivate func loadContentView() {
        os_log("loadContentView()...", log: .default, type: .debug)
       let childViewCtrl = ContentViewHostController()

        childViewCtrl.delegate = self
        childViewCtrl.view.layoutIfNeeded() // avoids snapshot warning?

        if let window = self.view.window {
            childViewCtrl.myWindow = window
            window.rootViewController = childViewCtrl
        }
    }

    override func willBecomeActive(with conversation: MSConversation) {
        loadContentView()
    }

    override func didResignActive(with conversation: MSConversation) {
        os_log("didResignActive()...", log: .default, type: .debug)

    }
}
//
//
import SwiftUI
import Messages
import os

final class ContentViewHostController: UIHostingController<ContentView> {
    weak var delegate: ContentViewHostControllerDelegate?
    weak var myWindow: UIWindow?

    init() {

        super.init(rootView: ContentView())
        rootView.submitMessage = submitMessage
    }
    required init?(coder: NSCoder) {
        super.init(coder: coder, rootView: ContentView())
    }

    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
    }

    func submitMessage() {
        os_log("ContentViewHostController::submitMessage(): submit message...", log: .default, type: .debug)
        delegate?.contentViewHostControllerSubmitMessage(self)
    }
}

struct ContentView: View {
    @Environment(\.presentationMode) var presentationMode: Binding<PresentationMode>

    var submitMessage: (() -> Void)?

    var body: some View {
        VStack {
            VStack {
                HStack {
                    Button(action: { self.cancel() } ) { Image(systemName: "chevron.left") }
                        .padding()

                    Spacer()

                    Button(action: { self.submit() } ) {
                        Text("Send...")
                    }
                    .padding()

                } // HStack
            } // VStack
        } // outside most VStack

    } // body

    private func cancel() {
        presentationMode.wrappedValue.dismiss()
    }

    private func submit() {
        submitMessage!()
        presentationMode.wrappedValue.dismiss()
    }
} // ContentView

//
//

import SwiftUI
import Messages
import os

extension MessagesViewController: ContentViewHostControllerDelegate {
        // MARK: - ContenHost delegate

        func contentViewHostControllerSubmitMessage(_ controller: ContentViewHostController) {
            os_log("delegateSubmitMessage:...")

            submitMessage()
        }

}

//
//
import SwiftUI
import Messages

protocol ContentViewHostControllerDelegate: class  {
    func contentViewHostControllerSubmitMessage( _ controller: ContentViewHostController )
}


text:
Q: Call to undefined method Illuminate\Session\Store::getToken() I am trying to use excel package in my laravel 5.4 project following a tutorial I got online but I keep getting this error

Call to undefined method Illuminate\Session\Store::getToken() (View:
  C:\wamp64\www\Vidic\resources\views\file_import_export.blade.php) in
  HtmlServiceProvider.php (line 51)

here is my composer.json file
{
      "name": "laravel/laravel",
      "description": "The Laravel Framework.",
      "keywords": ["framework", "laravel"],
"license": "MIT",
"type": "project",
"require": {
    "php": ">=5.6.4",
    "laravel/framework": "5.4.*",
    "laravel/tinker": "~1.0",
    "maatwebsite/excel": "~2.1.0",
    "illuminate/html": "5.*"
},
"require-dev": {
    "fzaninotto/faker": "~1.4",
    "mockery/mockery": "0.9.*",
    "phpunit/phpunit": "~5.7"
},
"autoload": {
    "classmap": [
        "database"
    ],
    "psr-4": {
        "App\\": "app/"
    }
},
"autoload-dev": {
    "psr-4": {
        "Tests\\": "tests/"
    }
},
"scripts": {
    "post-root-package-install": [
        "php -r \"file_exists('.env') || copy('.env.example', '.env');\""
    ],
    "post-create-project-cmd": [
        "php artisan key:generate"
    ],
    "post-install-cmd": [
        "Illuminate\\Foundation\\ComposerScripts::postInstall",
        "php artisan optimize"
    ],
    "post-update-cmd": [
        "Illuminate\\Foundation\\ComposerScripts::postUpdate",
        "php artisan optimize"
    ]
},
"config": {
    "preferred-install": "dist",
    "sort-packages": true,
    "optimize-autoloader": true
}
}

and this is my app.php file
     'providers' => [
    /*
     * Laravel Framework Service Providers...
     */
    ...

    Illuminate\View\ViewServiceProvider::class,
    'Maatwebsite\Excel\ExcelServiceProvider',
    'Illuminate\Html\HtmlServiceProvider',

    'aliases' => [
    ...
    'View' => Illuminate\Support\Facades\View::class,
    'Excel' => 'Maatwebsite\Excel\Facades\Excel',
    'Form' => 'Illuminate\Html\FormFacade',
    'HTML' => 'Illuminate\Html\HtmlFacade',
],
];

and this is my view

Payments

        'xls']) }}">Download Excel xls |
        'xlsx']) }}">Download Excel xlsx |
        'csv']) }}">Download CSV

       {!! Form::open(array('route' => 'import-csv-excel','method'=>'POST','files'=>'true')) !!}

                    {!! Form::label('sample_file','Select File to Import:',['class'=>'col-md-3']) !!}

                    {!! Form::file('sample_file', array('class' => 'form-control')) !!}
                    {!! $errors->first('sample_file', '
:message
') !!}

            {!! Form::submit('Upload',['class'=>'btn btn-primary']) !!}

       {!! Form::close() !!}

I have renamed most of the methods in the HtmServiceProvider.php file such as the bindShared() to singleton() but that has not helped.
I have shortened the codes to make them easily understandable

A: This worked for me: changing getToken() to token()
Here is where I found my answer.

A: Try using this tutorial instead. Find it Here

A: 1 - In Your Project go to the following file;
vendor\laravelcollective\html\src\HtmlServiceProvider.php
2- In registerFormBuilder() method/function, change getToken() to token()
I hope it should work for you too.


text:
Q: Custom directive models do not work in ng-switch I am trying to use AngularJS to provide a toggable dropdown list, where the selection of various options will trigger different lists. ng-switch seemed like the right way to do it, but my ng-model is not binding while inside the ng-switch. The binding works fine if I do not use ng-switch, but I do not know how to toggle my dropdown lists if that's the case. What could be the issue here?
jsFiddle: http://jsfiddle.net/tanweihao88/LUzXT/3/
HTML:
<select ng-model="periodRangeModel" ng-options="item for item in items"></select>

    <period-selector items="monthOptions" ng-model="periodModel"></period-selector>
    <period-selector items="quarterOptions" ng-model="periodModel"></period-selector>

JS:
angular.module('myApp', [])
.controller("MyCtrl", function($scope) {
    $scope.items = ['Month', 'Quarter'];
    $scope.periodRangeModel = "Month";
    $scope.quarterOptions = ["Jan-Mar", "Apr-Jun", "Jul-Sept", "Oct-Dec"];
    $scope.monthOptions = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
    $scope.periodModel = $scope.monthOptions[0];
})
.directive('periodSelector', function() {
    return {
        restrict: 'E',
        replace: true,
        scope: { items: '=', ngModel: '='},
        template: "<select ng-options='period for period in items' ng-model='ngModel'></select>"
    }
});

A: The main reason the binding does not work as intended is ng-switch creates a new scope and when binding to a string primitive the original periodModel isn't being updated as you expect (since the new scope's periodModel is being updated).
This question has a lot more detail on what's going on behind the scenes and you can check out the Angular Batarang Chrome Extension to visually see the various scopes at play.
You can get around it by binding to an object value like in this updated fiddle. The main changes are:
1) Change periodModel to an object and set a property (in this example it's called value)
$scope.periodModel = {
    value: $scope.monthOptions[0]
};

2) Change any binding code to access periodModel.value instead of periodModel
<period-selector items="monthOptions" ng-model="periodModel.value"></period-selector>

Model: {{periodModel.value}} (this is supposed to change)


text:
Q: Geojson to json I need help trying to get a json file from the output of the QGIS2WEB plugin. There is only what appears to be a geojson output that has a .js extension and has this header:
var geojson_filename = {
"type": "FeatureCollection",
"crs": { "type": "name", "properties": { "name": "urn:ogc:def:crs:OGC:1.3:CRS84" } },

"features": [
....
]

Qgis itself only produces geojson files but I need a json format.
Some background: I need to get a json map to use in Power BI. I have the map in many formats; mapinfo tab, qgis shape, qgis geojson, html but for the life of me can't get a json format. Because of data sensitivity, I would like to avoid online converters.
Thanks for any help.


text:
Q: reminder emails from a sharepoint list I have a list of employees and columns of 10+ training courses they have to complete annually. I need to send out reminder emails when they are due but there could be more than 1 employee due a course on one day or one employee could have more than one course due on one day or lots of them could be due more than one course on one day. My workflow comes back with it will only return 1 result. How can I get it to check the whole list and send more than email reminder out. Thanks in advance

A: You could create the workflow that runs every day, checks for due courses and sends the appropriate emails to employees.
Easier said than done, of course. :)
How to do this:

*

*Create the site workflow in SharePoint designer.

*Add the loop that will contain all the
daily logic and the pause action at the end of the loop segment (set
pause for 1 day).

The logic should contain the following:

*

*Call the SharePoint REST api to get all the due courses for the day.
(This article shows how to call the web service from workflow and
this article shows how to create the query using SharePoint REST
api).

*Add another loop segment which should go through all the results of
the REST api call, and send the appropriate emails.

Depending on your data structure the queries could be more or less complex.
This is the high level picture of what should be done. It should be enough to start putting all the pieces together. After finishing the workflow, you should need to start it manually the first time, and it should run without ending.

A: You can create console application and schedule that console application inside widow task scheduler for onpremise and azure for online.It will run everyday and fetch all items from list then implement your logic and use SharePoint Utility.sendmail function for sending mail.


text:
Q: web.config transform from web.template.xml not working I'm trying to get web.config transformations working as described here. We've used this method on other projects and it works without issue, but not on this new project.
Here's what I've tried testing without success

*

*Changing name of wpp.targets file in case I got the project name wrong. I know the current one I'm using works since it's the only one that causes web.config to be rebuilt from web.template.xml this transform works. Only the sub templates don't work.

*Tried with xdt:Locator="Match(name)"

*Tried .config extension vs .xml, our other projects where this works use .xml

*Configuration manager is set to use the "Test" configuration for the project I'm working on.

*web.template.Test.xml has xdt:Transform="Replace" for the section I want to replace

*web.template.xml has the  placeholder

*Tried removing the "CopyWebTemplateConfig" section from wpp.targets as suggested on the stack question linked below. Our other projects have this and the "PropertyGroup" section commented out and I've tried both combinations.

I've read through the above link multiple times and this related stack question, but can't see what the problem is.
Note The publish transform does work in a way. It creates a web.template.xml file that contains the values from web.template.Test.xml, but does not create a web.config.xml as the wpp.targets instructs. So this is more of an issue with getting the build transform working it seems.
Anyone have an idea of what's missing?
wpp.targets
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">

  <!-- Make sure web.config will be there even for package/publish -->
  <Target Name="CopyWebTemplateConfig" BeforeTargets="Build">
    <Copy SourceFiles="web.template.xml"
          DestinationFiles="web.config"/>
  </Target>

  <PropertyGroup>
    <PrepareForRunDependsOn>
      $(PrepareForRunDependsOn);
      UpdateWebConfigBeforeRun;
    </PrepareForRunDependsOn>
  </PropertyGroup>

  <!-- This target will run right before you run your app in Visual Studio -->
  <Target Name="UpdateWebConfigBeforeRun">
    <Message Text="Configuration: $(Configuration): Web.template.$(Configuration).xml"/>
    <TransformXml Source="web.template.xml"
              Transform="web.template.$(Configuration).xml"
              Destination="web.config" />
  </Target>

  <!-- Exclude the config template files from the created package -->
  <Target Name="ExcludeCustomConfigTransformFiles" BeforeTargets="ExcludeFilesFromPackage">
    <ItemGroup>
      <ExcludeFromPackageFiles Include="web.template.xml;web.template.*.xml"/>
    </ItemGroup>
    <Message Text="ExcludeFromPackageFiles: @(ExcludeFromPackageFiles)" Importance="high"/>
  </Target>
</Project>

web.template.xml
<?xml version="1.0" encoding="utf-8"?>
<!--
  For more information on how to configure your ASP.NET application, please visit
  http://go.microsoft.com/fwlink/?LinkId=152368
  -->
<configuration>
  <configSections>
    <sectionGroup name="TestSettings"></sectionGroup>
    ....
  </configSections>
    ....
  <TestSettings>
  </TestSettings>
   ....
</configuration>

web.template.Test.xml
<?xml version="1.0"?>
<!-- For more information on using transformations
     see the web.config examples at http://go.microsoft.com/fwlink/?LinkId=214134. -->
<configuration xmlns:xdt="http://schemas.microsoft.com/XML-Document-Transform">
  <TestSettings xdt:Transform="Replace">
    ...
  </TestSettings>
</configuration>

MSBuild output
Target "UpdateWebConfigBeforeRun: (TargetId:143)" in file "C:\...\Project.wpp.targets" from project "C:\...\Project.csproj" (target "PrepareForRun" depends on it):
Task "Message" (TaskId:93)
  Configuration: Test: Web.template.Test.xml (TaskId:93)
Done executing task "Message". (TaskId:93)
Task "TransformXml" (TaskId:94)
  Transforming Source File: Web.template.xml (TaskId:94)
    Applying Transform File: Web.template.Test.xml (TaskId:94)
    Executing Replace (transform line 5, 18) (TaskId:94)
      on /configuration/TestSettings (TaskId:94)
      Applying to 'TestSettings' element (source line 121, 4) (TaskId:94)
      Replaced 'TestSettings' element (TaskId:94)
    Done executing Replace (TaskId:94)
    Output File: web.config (TaskId:94)
  Transformation succeeded (TaskId:94)
Done executing task "TransformXml". (TaskId:94)
Done building target "UpdateWebConfigBeforeRun" in project "Project.csproj".: (TargetId:143)

A: I had installed StyleCop and that was doing the overwrite for me.
So I uninstalled it and the issue was resolved.
Funny is that I re-installed the StyleCop and the transform was still working!
Also at some points I noticed that I should remove the CopyWebTemplateConfig target section as well.

A: I've got a solution to my problem, but not sure what the cause is, so not sure if this will solve it in other cases.
I reviewed the output of the MSBuild diagnostic and noticed that towards the end there was another section that copied web.template to web.config. Note that this is after the UpdateWebConfigBeforeRun target already ran and made its updates from the sub template transform file to web.config. It looked like this last step was overriding the web.config with the transform I wanted.
I wasn't sure where this last set of copy instruction was coming from, so I did a search for all files on my PC looking for other wpp.target files. I found another one in Slow Cheetah's extensions folder and saw some section up top that was setting a property "transformOnBuild" to false.
Thinking there was a conflict with SlowCheetah, I uninstalled it and the transformations started working as expected. This was still a bit odd since the other solutions worked with SlowCheetah enabled. On a whim I re-installed SlowCheetah and the transformation continued to work as expected.
So my solution ended up being a re-installation of SlowCheetah. I'm still confused about what the cause of this issue was, so if anyone else posts an answer to this I'll give them the bounty.

A: I've had a similar issue last week.
Turns out that whenever you add a project to a solution in VS 2010 the right project configuration doesn't get applied all the time.
So you think you have a configuration active but another is actually active on that project, thus the transformation you expect doesn't get applied.
Check the steps in last comment of this issue: Custom solution configuration not showing up in Visual Studio 2010

A: "I know the current one I'm using works since it's the only one that causes web.config to be rebuilt from web.template.xml this transform works. Only the sub templates don't work."
Does this mean, transformation works but TestSettings section alone does not get transformed?
Can you share build output with msbuild with verbosity set to diagnostic / detailed?

A: I wrote a blog post about this subject. I use it everyday in our web application. I wrote the blog post because the feature in slowcheetah isn't ready yet.
http://www.locktar.nl/general/use-config-transforms-when-debugging-your-web-application/


text:
Q: Issue with remote deployment of *.apk app using Airwatch I'm going through some hard times to remotely publish an in-house developed app over VMWare Airwatch application.
The application is published via Airwatch Console and then delivered to the smartphone...so far, so good. However when the user attempts to install it, android always raises the same message: "error during the package analysis" (in free translation to english. The original message language is Spanish, as you can see below).
The original message is raised in Spanish: "Se produjo un error durante el análisis del paquete".
Our mobile devices have the latest Airwatch Agent version 5.3.0.724 published to PlayStore. The only way our app can be deployed is over Airwatch, since it's a corporate mobile used by frontline employees, therefore access to apps has been supressed as well as data transfers (to preserve the 3G/4G franchises and avoid extra charges).
The issue reported happens both in smartphones factory restored (only with Airwatch app installed) and smartphones with the company required image.
The mobile devices are Moto-E 2nd generation using Lollipop 5.0.2
I'm looking for some help since I'm an IT project manager and this is a big risk to our corporate project.
I also have some logs from Airwatch console, which are quite long to post right. Should someone require, I can paste into the thread.
Thx and Brs,
Joao Kraemer.


text:
Q: Find sum of max integer in array with least space complexity I am new to programming and trying to learn by exploring. I was looking for a solution to find sum of maximum time repeating integer in an array with best space complexity. Suppose we have [1, 2, 3, 3] the result should be 6 with least space complexity, say O(n).
I came up with a solution but not sure about the complexity. Need some help to understand if below mentioned code has least complexity or it could be better(definitely!). Sorry if I made any mistake and thanks in advance.
public static int maxDuplicateSumSpaceBased(int[] a)
{
  int maxRepCount = 1, tempCount;
  int maxRepNum = a[0];
  int temp = 0;
  for (int i = 0; i < (a.length - 1); i++)
  {
    temp = a[i];
    tempCount = 0;
    for (int j = 1; j < a.length; j++)
    {
      if (temp == a[j])
        tempCount++;
    }
    if (tempCount > maxRepCount)
    {
        maxRepNum = temp;
      maxRepCount = tempCount;
    }
  }
  return maxRepNum * maxRepCount;
}

A: Actually the space of the input is usually not counted in the O notation so your program has a spatial complexity of O(6)=O(c)=O(1). c is a constant. In fact you always use 6 variables. If the amount of space used is dependent on the input given the situation is different but it's not your case because regardless of the length of you input you use always 6 variables.
If you want to count the input as occupied space (sometimes it's done) your space complexity would be O(6+n)=O(n) assuming that n is the length of the input.
It's impossible to do better as you can easly prove:
You can't have less memory occupied than the input (or you must memorize all the input). Since the input is the only thing that's not a constant you have that the maximum space used is the one needed to store the input that is n.

A: The space complexity1 of your solution is O(1).  You can't get better than that.
The time complexity of your solution is O(N^2).  You can improve on that in a couple of ways:

*

*If you can modify a, then you can sort it { time O(NlogN), spaceO(1) } then find / count the most frequent value { O(N) , O(1) }.  Overall complexity is { O(NlogN), O(1)}.

*If you cannot modify a, then copy it { O(N) / O(N) } and then proceed as above.  Overall complexity is { O(NlogN), O(N) }.

*If the range of the numbers (M) is less than the number of numbers, then you can use a bucket sort.  Overall complexity is { O(N), O(M) }.

*You can get better time complexity overall using a HashMap.  The overall complexity of that will be { O(N) on average, O(N)} ... with significantly larger constants of proportionality.  (Unfortunately, the worst case time complexity will be O(NlogN) or O(N^2) depending on the hash map implementation.  It occurs when all of the keys collide.  That is impossible for Integer keys and HashMap, but possible for Long keys.)

1 - I am referring to space in addition to the space occupied by the input array.  Obviously, the space used for the input array cannot be optimized.  It is a given.

A: I have understand your problem.. Now there could be a solution there are n integers and all integers k [1-n]. Then to find maxrepeatnumber takes O(n) time.
  public static int maxDuplicateSumSpaceBased(int[] a)
{
  int maxRepCount = 1, tempCount;
  int k=a.length();
  for (int i = 0; i <k; i++)
  {
        a[a[i]%k]+=k;
  }
    int maxRepnumber=0,temp=a[0];
    for (int j = 1; j < k; j++)
    {
      if (temp < a[j])
        {
           temp=a[j];
           maxRepnumber=j;
        }
    }

  }
  return maxRepNum;
}

Then you sum all that number and it take O(n)and O(1) space.


text:
Q: InvalidKeyException while encrypting data I know that there are many threads over this , but i am not able to find solution with them.
Problem Statement:
Need to encrypt data. Below is my code:
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.SecretKeySpec;
import java.nio.ByteBuffer;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.Base64;

import static java.nio.charset.StandardCharsets.UTF_8;

public class CryptoUtil {

    private static final String AES = "AES/ECB/PKCS5Padding";

    public String encryptMessage(final String message, final byte[] dataKey) throws Exception {
        SecretKeySpec secretKey = new SecretKeySpec(dataKey, AES);
        try {
            Cipher cipher = Cipher.getInstance(AES);
            cipher.init(Cipher.ENCRYPT_MODE, secretKey);
            byte[] encryptedMessage = cipher.doFinal(message.getBytes());
            return Base64.getEncoder().encodeToString(encryptedMessage);
        }
        catch (NoSuchPaddingException | NoSuchAlgorithmException | InvalidKeyException | BadPaddingException | IllegalBlockSizeException e) {
            throw new Exception("Error while encrypting application credentials", e);
        }
    }
}

I need to do it using BountyCastle service provider. So i followed the steps mentioned here and this. I am using JAVA 11, but i switched to JAVA 8 to follow mentioned link.
In my code i added static block to add BountyCastle as service provider
static {
    BouncyCastleProvider bouncyCastleProvider = new BouncyCastleProvider();
    Security.addProvider(bouncyCastleProvider);
  }

But, it is not getting added as verified providers. So i am getting the issue.
Any idea how to handle. How to add BouncyCastle as verified provider.
I am running on local machine , and need to create JAR.

A: Nobody has answered this, so I'll just post an answer with the comment I had above.  I have not tested it so I leave that part to you.
When you do Cipher.getInstance(), it is correct to have "AES/ECB/PKCS5Padding" (for some weird definition of "correct", where Java providers believe PKCS5 padding = PKCS7 padding, but never mind that).
But when you create the key, it is not correct to have the mode and padding in there.  Instead, they just want the algorithm.  So try:
SecretKeySpec secretKey = new SecretKeySpec(dataKey, "AES");

The change is the quotes around "AES", rather than using AES="AES/ECB/PKCS5Padding".
Not sure if that will fix your problem, but should be a step in the right direction (I hope).


text:
Q: Connection attempt from disallowed node 'ejabberdctl-1@localhost' The title is what appears in my ejabberd log files after an unsuccessful start.  I did some googling and have noticed it is probably related to my cookies..
Running get_cookie() in the erlang shell prints 'nocookie'.  Is this typical for a fresh install of erlang?  How should I ideally go about setting the cookie?

A: nocookie would likely mean that the node hasn't been started in distributed mode. All distributed nodes otherwise have a cookie.
You will have to make sure your node is started in distributed mode (through -name or -sname arguments) for things to work.
In case the node is already started and you have access to a shell, you can start the distributed kernel by hand with net_kernel:start([Name, shortnames]) or net_kernel:start([Name, longnames]).


text:
Q: TypeORM service name connection option for Oracle I'm trying to connect to a RAC environment, but I need to connect using the service name... It looks like this options isn't provided in the connection options provided by typeORM.
Here's the connection string on my SQL Client DBeaver

And this is my typeorm connection config.
@Module({
  imports: [
    TypeOrmModule.forRoot({
      type: "oracle",
      host: "localhost",
      port: 1521,
      extra: {
          "SERVICE_NAME": "node.localdomain"
      },
      username: "hr",
      password: "root",
      database: "orcl",
      entities: [Employee],
      synchronize: false,
    }),
    GraphQLModule.forRoot({
      debug: true,
      playground: true,
      autoSchemaFile: 'schema.gpl'
    }),
    EmployeesModule
  ],
  controllers: [],
  providers: [],
})
export class AppModule {}

A: So it looks like there is a property named serviceName, I guess it's part of oracle's database driver.


text:
Q: Variable elimination, Bayesian network
I'm self learning the topic variable elimination and try to solve some questions see if I fully understand the concept. But I'm stuck on this problem's second question for hours.
Base on my understanding, if we eliminate a variable then we need to create a new factor which is sum of product of all probabilities that the variable involved. Maybe I didn't describe it precisely but for instance, in question $1$ we have, $$P(A = T, B = T, C = T, E = T, F= T)$$ and since $D$ is missing, we have $$P(A = T, B = T, C = T, E = T, F= T) $$
$$= P(A=T)P(B=T|A=T)P(C=T) \times \sum_D P(D|A=T,B=T,C=T)P(E=T|D)P(F=T|D)$$
If we plug in the corresponding number we will get the solution $0.11088$, this seems straightforward to me. However I'm having tough time to calculate $P(E = T, F = T)$ by eliminating $B$, $A$,and $C$.
My approach as, $$P(E =T, F= T) = \sum_D P(E = T| D)P(F = T|D) \sum_C P(C)P(D|A, B ,C) \sum_A P(A)P(D|A,B,C) \sum_B P(B|A) P(D|A,B,C)$$
I don't know if it makes sense, but this looks like a extremely long computation to me, and I couldn't come up a solution as the answer shown. I wonder if anyone could find the same solution and express\explain the full computation would be highly appreciated.

A:
Base on my understanding, if we eliminate a variable then we need to create a new factor which is sum of product of all probabilities that the variable involved.

$\def\={\hspace{0.25ex}{=}\hspace{0.25ex}}\def\P{\operatorname{\sf P}}$Yes, this uses the Law of Total Probability, in your notation: $\P(X\=x,Z\=z)=\sum_{Y}\P(X\=x,Y,Z\=z)$
So $$\small{\P(A\=T,B\=T,C\=T,E\=T,F\=T)={{\P(A\=T)\P(B\=T\mid A\=T)\P(C\=T)\sum_D\P(D\mid A\=T,B\=T,C\=T)\P(E\=T\mid D)\P(F\=T\mid D)}}}$$
And likewise $$\small{\P(E\=T,F\=T)\\=\sum_D\P(E\=T\mid D)\P(F\=T\mid D)\sum_C\P(C)\sum_A\P(A)\sum_B\P(B\mid A)\P(D\mid A,B,C)}$$
Note: You must arrange the factors so all occurrences of the variable being eliminated are to the right of its summation symbol, and each factor only occurs exactly once.  Notably you had too many occurrences of $\P(D\mid A,B,C)$ which will surely have thrown off your calculations.
This will still be a tedious computation, as you will be summing sixteen terms, which are each products of five factors.  No helping that.


text:
Q: PHP SELECT query of array of named placeholders I would like to use name placeholder to pass the value of an array to a select statement, such as:
$keywords=("word1", "word2", etc);
$sql = "SELECT * FROM TABLE WHERE name LIKE :word1 AND name LIKE :word2 etc"

Below is the script that I am working on:
$symptoms=$_POST['search'];
$keywords = preg_split('/[\s]+/', $symptoms);
$totalKeywords = count($keywords);
$sql = "SELECT * FROM TABLE_3 WHERE MATCH (symptoms) AGAINST (:symptoms) ";
$like_placeholder = implode(' AND ', array_fill(0, $totalKeywords, 'symptoms LIKE ?'));
$sql .= " AND ({$like_placeholder})"; // build the query with placeholders
// prep input
$where_keywords = array_map(function($value) {
return "%{$value}%";
}, $keywords);
$stmt = $pdo->prepare($sql);
$stmt->bindValue(':symptoms', $symptoms);
$stmt->execute([$_POST['search']]);
$stmt->execute($keywords);
$results = $stmt->fetchAll();

A: You can't use both named and question-mark placeholders in the same query. Change the :symptoms placeholder to ? and insert $symptoms at the beginning of your $keywords array.
You're never using $where_keywords. You can concatenate the % wildcard in the SQL code itself.
$symptoms=$_POST['search'];
$keywords = preg_split('/[\s]+/', $symptoms);
$totalKeywords = count($keywords);
$sql = "SELECT * FROM TABLE_3 WHERE MATCH (symptoms) AGAINST (?) ";
$like_placeholder = implode(' AND ', array_fill(0, $totalKeywords, "symptoms LIKE CONCAT('%', ?, '%')"));
$sql .= " AND ({$like_placeholder})"; // build the query with placeholders
$stmt = $pdo->prepare($sql);
array_unshift($keywords, $symptoms);
$stmt->execute($keywords);
$results = $stmt->fetchAll();


text:
Q: Prevent SVG objects from overlapping I am currently working on a Drag and drop project that requires svg shapes to connect with each other but not pass through.  I have a jsfiddle with it working with divs but not the svgs. Any help would be appreciated.
JSFIDDLE
HTML

<svg height="100" width="100" class="draggable boundaries" >

<circle cx="50" cy="50" r="40" stroke="black" stroke-width="3" fill="green"/>
Sorry, your browser does not support inline SVG.

</svg>

<svg height="100" width="100" class="draggable boundaries" >
<circle cx="50" cy="50" r="40" stroke="black" stroke-width="3" fill="green"/>
Sorry, your browser does not support inline SVG.
</svg>

JS
$(".draggable").draggable({
obstacle:".boundaries",
preventCollision: true,
containment: "#container",
start: function(event,ui) {
    $(this).removeClass('boundaries');
},
stop: function(event,ui) {
    $(this).addClass('boundaries');
}
 });


text:
Q: My PHP form won't send e-mail to me and redirects to a blank page I have researched this question, but I don't think I will find an answer, because I'm guessing it is something wrong with my code personally. I have tried every combination of trying to get my PHP contact form to Submit & send me an e-mail but it does nothing, even when it has been uploaded to the server. It simply displays a blank page once I click submit, and I get no e-mail at all to the e-mail address I entered into the code. I don't know what I'm missing as I can't find an answer to my problem anywhere.
One thing I did notice was that I have some different fields in my HTML than specified in the PHP to be required fields. However, I don't know that this makes a difference as I'm not getting any error messages or anything else for these fields. Please let me know if you need any additional details. I appreciate your help in advance.
HTML
<form id="form_884913" method="post" action="send_form_email.php" class="appnitro">

This is where ALL of my fields are, so I omitted it since quite a large script. Please let me know if you need any of this to help me
Rest of HTML
<input type="hidden" name="form_id" value="884913" />
<input id="saveForm" class="button_text" type="submit" name="submit" value="Submit" />
<input type="reset" value="Reset">

    </form>

PHP
<?php
if(isset($_POST['email'])) {

// EDIT THE 2 LINES BELOW AS REQUIRED
$email_to = "myemailaddresswastyped@blank.com";
$email_subject = "Contact";

function died($error) {
    // your error code can go here
    echo "We are very sorry, but there were error(s) found with the form you submitted. ";
    echo "These errors appear below.

";
    echo $error."

";
    echo "Please go back and fix these errors.

";
    die();
}

// validation expected data exists
if(!isset($_POST['first_name']) ||
    !isset($_POST['last_name']) ||
    !isset($_POST['email']) ||
    !isset($_POST['telephone']) ||
    !isset($_POST['comments'])) {
    died('We are sorry, but there appears to be a problem with the form you submitted.');
}

$first_name = $_POST['first_name']; // required
$last_name = $_POST['last_name']; // required
$email_from = $_POST['email']; // required
$telephone = $_POST['telephone']; // not required
$comments = $_POST['comments']; // required

$error_message = "";
$email_exp = '/^[A-Za-z0-9._%-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4}$/';
if(!preg_match($email_exp,$email_from)) {
$error_message .= 'The Email Address you entered does not appear to be valid.
';
}
$string_exp = "/^[A-Za-z .'-]+$/";
if(!preg_match($string_exp,$first_name)) {
$error_message .= 'The First Name you entered does not appear to be valid.
';
}
if(!preg_match($string_exp,$last_name)) {
$error_message .= 'The Last Name you entered does not appear to be valid.
';
}
if(strlen($comments) < 2) {
$error_message .= 'The Comments you entered do not appear to be valid.
';
}
 if(strlen($error_message) > 0) {
died($error_message);
}
$email_message = "Form details below.\n\n";

function clean_string($string) {
  $bad = array("content-type","bcc:","to:","cc:","href");
  return str_replace($bad,"",$string);
}

$email_message .= "First Name: ".clean_string($first_name)."\n";
$email_message .= "Last Name: ".clean_string($last_name)."\n";
$email_message .= "Email: ".clean_string($email_from)."\n";
$email_message .= "Telephone: ".clean_string($telephone)."\n";
$email_message .= "Comments: ".clean_string($comments)."\n";

// create email headers
$headers = 'From: '.$email_from."\r\n".
'Reply-To: '.$email_from."\r\n" .
'X-Mailer: PHP/' . phpversion();
@mail($email_to, $email_subject, $email_message, $headers);
?>

Thank you for contacting me! I will be in touch with you very soon.

<?php
 }
 ?>

A: As mentioned by GaijinJim, if it isn't already a field you've posted, since you omitted some of the fields, make sure to add a field in HTML:
<input type="hidden" name="email" value="" />

Might also add for testing, but not for production, to the last line in PHP:
<?php
    } else {
        echo "$_POST['email'] is not set.";
    }
?>

A: If you want to use $_POST (Same with $_GET method) with a form in HTML&PHP you must name your field like so:
<input type="text" name="MyfieldName" value="1">

Only then you can call your $_POST['MyfieldName']
Now if you would echo $_POST['MyfieldName']; it would return 1

A: In your PHP-file you check whether all of the following input fields exist in your form,
// validation expected data exists
if(!isset($_POST['first_name']) ||
    !isset($_POST['last_name']) ||
    !isset($_POST['email']) ||
    !isset($_POST['telephone']) ||
    !isset($_POST['comments'])) {
    died('We are sorry, but there appears to be a problem with the form you submitted.');
}

Thus in order for your form to validate all of those fields must exist, you must have,
<input type="text" name="first_name" />
<input type="text" name="last_name" />
<input type="text" name="email" />
<input type="text" name="telephone" />
<input type="text" name="comments" />

If you do not want some of those fields, for example email, simply remove `!isset($_POST['email']) from your PHP's if-statement.

As per your comment I get the impression that the input field named email does not exists, which is the reason why you get a blank page. If you were to add that input field on your HTML-page you would see some sort of error message instead of a blank page :)


text:
Q: Cómo solucionar error 104 al consultar el servicio web de face Resulta que tengo a la hora de mandar el Request con el método de Enviar Factura, en la respuesta me da un código de error 104. Supuestamente lo estoy probando con SoapUI y a la hora de hacer la solicitud reemplazo los ? por mis valores, pero al ejecutar me da el error 104, la petición SOAP no está bien construida: no se encuentra el SOAP Header

Que me falta para que funcione bien
Gracias

A: Falta configurar WS-Security. El Manual de Uso de Servicios -
facturasspp dice:

Las peticiones deben ir firmadas
tal y como se indica en el apartado Implementación o con un formato válido de WS-Security 1.0
X.509 Token Profile.

El mismo manual muestra una petición de ejemplo que incluye un extenso contenido de la etiqueta <soapenv:Header> y que en las imágenes de la pregunta se observa que está vacía. También menciona cómo obtener un archivo PEM (que debería incluir una llave pública y una llave privada) para firmar las peticiones:

Para poder utilizar los servicios web de FACe deberá darse de alta previamente en el portal
web de FACe, en el menú de Integradores – Gestión de Certificados
(https://face.gob.es/es/proveedores), donde informará del PEM del certificado con el que firmará las
llamadas a los servicios web.

De la petición de ejemplo del manual se puede deducir la siguiente configuración para la Outgoing WS-Security Configuration de SoapUI:

*

*Must Undestand: ✅ (chequeado)

*Key Identifier Type: Binary Security Token

*Signature Algorithm: http://www.w3.org/2000/09/xmldsig#rsasha1

*Signature Canonicalization: http://www.w3.org/2001/10/xml-excc14n#

*Digest algorithm: http://www.w3.org/2000/09/xmldsig#sha1
Otros enlaces útiles:

*

*Área Descargas - FACe - Punto General de Entrada de Facturas Electrónicas de la AGE. En la sección «Documentación para integradores» se encuentra el manual mencionado arriba, manuales de otros servicios e información de los certificados de los servicios web de pruebas y producción.

*WS-Security Settings de SoapUI (inglés).

*KeyStore Explorer. Herramienta para gestionar keystores de Java, como la que se necesita configurar en la Outgoing WS-Security Configuration de SoapUI.

A: a mi también me ha servido tu respuesta, aun que hay varias cosillas de esa cabecera de ejemplo que no estoy seguro de como tengo que rellenarlas.

*

*Lo primero que se rellena es el BinarySecurityToken que se llena con
el certificado digital (ese lo tengo claro)

*Luego hay otro campo que se podría tener que rellenar que es el
SignedInfo que dentro tiene el campo DigestValue con un valor ya
relleno, y no se si este seria necesario el modificarlo.

*y por ultimo el campo SignatureValue que tengo claro que tengo que
rellenar, pero no se con que.
entiendo que a través de algún algoritmo con el que consigo dichos valores, pero no termino de enterarme bien.
Gracias y un saludo!


text:
Q: Why can't we change the order of statements in insertion sort's while loop? As shown below is the basic insertion sort algorithm taught at school. if you change the order of while loop parameters, it doesn't work.
public static int[] insertionSort(int[] A){
    for(int i =1; i<A.length;i++){
        int key = A[i];
        int j = i;
        while(j>0&&A[j-1]>key){
            A[j]=A[j-1];
            j--;
        }
        A[j]=key;
        }
    return A;
}

After the change (Now the code wont work and it will give  java.lang.ArrayIndexOutOfBoundsException: -1 expection):
public static int[] insertionSort(int[] A){
    for(int i =1; i<A.length;i++){
        int key = A[i];
        int j = i;
        while(A[j-1]>key&&j>0){
            A[j]=A[j-1];
            j--;
        }
        A[j]=key;
        }
    return A;
}

If there any other way to implement the same algorithm so that the order of the conditional loop statements doesn't matter?

A: Because of short-circuit evaluation.
If the first half of an && is false, the second half will not be evaluated at all (since the result cannot possibly be true).
Therefore, you can write j > 0 && A[j - 1]..., and A[j - 1] will only be evaluated if j > 0.

A: You can improve the above code as follow. Now the while loop will never fail for arr[-1] condition as every time j==-1 the loop will break out.
public static void InsertionSort()
    int j, temp;
    Scanner sc = new Scanner(System.in);
    System.out.println("enter the size");
    int n = sc.nextInt();
    int arr[] = new int[n];
    System.out.println("enter the elements");
    for (int i = 0; i < n; i++)
    {
        arr[i] = sc.nextInt();
    }
    for (int i = 1; i < n; i++)
    {
        temp = arr[i];
        j = i - 1;
        while (arr[j] > temp && j >= 0)
        {
            arr[j + 1] = arr[j];
            j = j - 1;
            if (j == -1)
                break;
        }
        arr[j + 1] = temp;
    }
    System.out.println("Array Sorted through Insertion Sort");
    for (int i = 0; i < n; i++)
    {
        System.out.println(arr[i]);
    }
}


text:
Q: How scroll table to down? LibGDX I have Table in ScrollPane, I want Scroll down table when add items. When i make that:
table.add(...);
scrollPane.setScrollY(table.getHeight());

It scrolls on the penultimate element. How fix it?

A: Try this:
scrollPane.setScrollPercentY(100);


text:
Q: SVG renders improperly after scroll and on different pages I have converted a badge/image from PNG to SVG in order to be able to re-use the asset in various sizes etc.
The problem is that depending on the specific webpage i'm embedding the SVG on, it either looks super crisp (as intended) or looks bad with some sort of anti-aliasing gone horribly wrong.
Even on the pages where the SVG looks crisp after load, I only have to scroll the page a bit until it looks horrible as well.
Please look at the screenshots below to see the exact difference on the BADGE (SVG):

It seems the browser only messes with the SVG right where the SVG meets the image behind it. The SVG is only slightly transparent in the gray center, so that should not be the cause of it.
I have tested in Chrome, Edge, Safari which all do the same thing.
Does anybody know what might be the cause of this?

A: I found a fix to what clearly seems to be a somehow undiscovered big bug in all modern browsers in regards to handling SVG through CSS as a background on an element overlapping another element with background/image.
The fix for my case was simply adding a background-color to the element. Since the element is completely round I can simply make a border-radius as well, so the background will never appear.
If the element however was not a complete round circle, this would not be a workable fix.


text:
Q: I Need to Discard Days of Month and Make Duplicate Months as Distinct SELECT  e.firstName,t.setDate, w.wageAmount
         FROM TimeSheet t
         INNER JOIN Employee e
         ON e.employeeID = t.employeeID
         INNER JOIN Salary s
         ON s.salaryID = t.salaryID
         INNER JOIN Wage w
         ON w.wageID = s.wageID
         INNER JOIN EmpHiringInfo ehf
         ON ehf.EmpHiringInfoID = s.EmpHiringInfoID
         INNER JOIN WageType wt
         ON wt.wageTypeID = w.wageTypeID
         WHERE (wt.wageTypeID = 19) AND (ehf.isActive = 1 AND s.isActive = 1
         AND ehf.employeeID = 300) AND (CONVERT(varchar, t.setDate, 23) BETWEEN '2000-08-02' AND '2020-08-04')

By the way, the wage is only one for every month, so the wage is repetitive. So for the month 11,2010 wage is 3600 regardless how many days in 11,2010 ...
The above sample produce the following sample code:

I need to gather all similar month/year into one cell discarding days and time. For example
2010-11-12 and 2010-11-26 has to be contracted to one cell as 2010-11 (in any format).
Any help is appreciated.

A: To Unify all the dates to months you can do something like this:
dateadd(mm,datediff(mm,0,t.setDate),0)

But you will need to group by this is you want to do aggregations:
select e.firstName,dateadd(mm,datediff(mm,0,t.setDate),0), sum(w.wageAmount)
from ...
group by e.firstName, dateadd(mm,datediff(mm,0,t.setDate),0)

A: You can try something like the following:
SELECT  e.firstName
,CONVERT(CHAR(7),t.setDate,102)
,SUM(w.wageAmount)
FROM ...

GROUP BY e.firstName,
,CONVERT(CHAR(7),t.setDate,102)

A: There is a DatePart function in T-SQL that is able to retrieve the date and the year of a specific date.
Your query could look something like this :
SELECT  e.firstName,
DATEPART(yy, t.setDate) AS Year,
DATEPART(mm, t.setDate) AS Month,
MAX(w.wageAmount) AS wageAmount
FROM TimeSheet t
     INNER JOIN Employee e
     ON e.employeeID = t.employeeID
     INNER JOIN Salary s
     ON s.salaryID = t.salaryID
     INNER JOIN Wage w
     ON w.wageID = s.wageID
     INNER JOIN EmpHiringInfo ehf
     ON ehf.EmpHiringInfoID = s.EmpHiringInfoID
     INNER JOIN WageType wt
     ON wt.wageTypeID = w.wageTypeID
     WHERE (wt.wageTypeID = 19) AND (ehf.isActive = 1 AND s.isActive = 1
     AND ehf.employeeID = 300) AND
     (CONVERT(varchar, t.setDate, 23) BETWEEN '2000-08-02' AND '2020-08-04')
GROUP BY e.firstName, DATEPART(yy, t.setDate), DATEPART(mm, t.setDate)


text:
Q: Can I override the toString method of an anonymous function in Scala? I tried to override the toString of an anonymous function in Scala like this:
scala> ()=>{def toString="yes"; 1}
res1: () => Int = <function0>

Which does not work - I want res1 to be "yes" somehow.
Is this possible?

A: You can't do that with anonymous function literals, you will need to extend the Function trait. E.g.
val f = new (() => Int) {
  override def toString = "yes"
  def apply() = 1
}

or
val f = new Function0[Int] {
  override def toString = "yes"
  def apply() = 1
}


text:
Q: How to change image based on textfiled input I have a credit card number input and I am trying to add an image of the credit card brand next to the text field based on the number the user entered. whether that may be visa, master card, etc.
I have created a struct for the credit cards:
struct CreditCard: Identifiable, Codable {
    var id: String = UUID().uuidString
    var type: String
    var prefix: [Int]
    var length: Int
}

and I have added the credit card data locally:
let cardTypes: [CreditCard] = [
    CreditCard(type: "American Express", prefix: [34, 37], length: 15),
    CreditCard(type: "Visa", prefix: [4], length: 16),
    CreditCard(type: "Master Card", prefix: [51, 52, 53, 54], length: 16),
    CreditCard(type: "Discover", prefix: [6011], length: 16),
    CreditCard(type: "JCB", prefix: [3, 2131, 1800], length: 15)
]

I have imported the data into my view using the following:
var creditCards: [CreditCard] = cardTypes

So for instance, I'd like to display an image saved in my assets folder with the name "Master Card" only when the first numbers in the text input are 51, 52, 53 or 54.
I am using a swiftui textfield
Any help is appreciated, thank you!

A: Here is a solution for SwiftUI.
Add your logo in the Asset folder. Then store the name of the Image inside your CreditCard model like this
struct CreditCard: Identifiable, Codable {
    var id: String = UUID().uuidString
    var type: String
    var prefix: [Int]
    var length: Int
    var imageName: String
}

Here I created sample data for two credit cards with their imageName.
let cardTypes: [CreditCard] = [
    CreditCard(type: "Visa", prefix: [4], length: 16, imageName: "visa"),
    CreditCard(type: "Master Card", prefix: [51, 52, 53, 54], length: 16, imageName: "mastercard")
]

And then use ProxyBinding to check the typed text and set the image.
struct ContentView: View {
    @State var string: String = ""
    var creditCards: [CreditCard] = cardTypes

    @State var imageName: String = ""

    var body: some View {
        HStack(spacing: 8) {

            if imageName != "" {
                Image(imageName)
                    .resizable()
                    .frame(width: 32, height: 25)
            } else {
                Rectangle()
                    .foregroundColor(.gray)
                    .frame(width: 32, height: 25)
            }

            TextField("Card Number", text: Binding<String>( get: {
                return string
            }, set: {
                string = $0

                let trimmedText = string.trimmingCharacters(in: .whitespaces)

                guard string.count >= 1,
                      trimmedText != "" else {
                    imageName = ""
                    return
                }

                for card in creditCards {
                    for prefix in card.prefix {
                        if trimmedText.hasPrefix(String(prefix)) {
                            imageName = card.imageName
                            return
                        }
                    }
                }

                imageName = ""
            }))
        }
        .padding(.horizontal, 16)
    }
}


text:
Q: How to apply filters automatically based on search term? Is it possible to apply filters/facets automatically based on search term?
For example, If there are two facets called "Category" and "Material" ,and If user searches for the term "plastic water bottles" where bottle is one of the category
(Catergory=bottle) and plastic is one of the material facet(Material = Plastic).
I am looking for the option to enable/force search engine to filter based on category=bottle and material=plastic automatically when it has matching terms in the query.
Please help.

A: This is not possible.  It is possible to trigger oneboxes, keymatches and related queries based on keywords.


text:
Q: How to encrypt a file and store it on LFS? I know how to encrypt a file on my repository, via git-crypt:
echo "*.crypt.* filter=git-crypt diff=git-crypt" > .gitattributes
echo "supersecret info" > somethingTo.crypt.txt
git add .gitattributes somethingTo.crypt.txt
git crypt status   # somethingTo.crypt.txt results encrypted
git commit
git push

and I know how to store a file with git-lfs (on a self-hosted GitLab; LFS enabled in the project settings):
git lfs track somethingTo.crypt.txt
git add .gitattributes    # updated LFS rule for tracked file
git commit
git push

... but, how does one use them both on the same file?

Even if .gitattributes has the git-filter for encrypting before the filter for storing on LFS, the file doesn't get encrypted (git crypt status | grep somethingTo reports "not encrypted"). All the other *.crypt.* files that are not tracked by LFS get encrypted correctly.
I guess that the issue is with my somethingTo.crypt.txt now being just a reference object in the repository, instead of the actual (encrypted) file. But I would expect (thanks to the git-filters) that the file gets filtered/encrypted before being pushed to the LFS Store.

Are the two filter extension compatible with each other? How do I make them work together?

A: Composing filters you get to do yourself.  You'll have to make your own combined filter (and whatever other attributes those mods install) that has the effect you want, git doesn't know how to make third-part hooks cooperate with each other,

Even if .gitattributes has the git-filter for encrypting before the filter for storing on LFS, the file doesn't get encrypted

that would be because attributes don't accumulate, they overwrite.  You get one value for each attribute, the one specified in the last match.  If you want a filter that combines the effect of two third-party tools, you have to write a filter that combines the effect of those two third-party tools.


text:
Q: AngularJS recursive ng-repeat variable binding with ng-include I'm having a problem while programming a dynamic structure with AngularJS. I have basically a tree structure, which can go potentially down recursively to infinity. I need to build an HTML page according to this tree, where every node of the tree needs to be displayed by a specific HTML template, according to its type. By using ng-repeat and ng-include I can do this quite easily, apart from the fact that problems related to the variable binding arise.
To better explain the situation, I'll use a simplified example.
This is my controller:
function testController($scope,$http,$timeout,$window,$state, Data) {
  $scope.blocks = []

  block1 = {
    "type":"block",
    "id":1,
    "innerblocks":[],
    "html":"block1.html"
  }

  block21 = {
    "type":"block",
    "id":21,
    "innerblocks":[],
    "html":"block2.html"
  }
  block22 = {
    "type":"block",
    "id":22,
    "innerblocks":[],
    "html":"block2.html"
  }

  block1.innerblocks.push(block21);
  block1.innerblocks.push(block22);

  $scope.showFromBlock1 = function () {
    $scope.blocks = [];
    $scope.blocks.push(block1);
  }

  $scope.showFromBlock2 = function () {
    $scope.blocks = [];
    $scope.blocks.push(block21);
    $scope.blocks.push(block22);
  }
}

where $scope.blocks represents the root of my tree, which has 1 inner node (block1) and 2 leafs (block21 and block22).
index.html is:

    <button ng-click="showFromBlock1()" >From Block1</button>
    <button ng-click="showFromBlock2()" >From Block2</button>

whereas my templates are:
block1.html

    BLOCK 1 TYPE: {{block.id}}

block2.html

      BLOCK 2 TYPE: {{block.id}}

`

As you can see if you run this example, when "From Block2" is pressed (meaning that the html should display the tree starting from blocks on level 2), the ids are displayed correctly, as the block variable in the index is bound correctly to the one in block2.html. If you press instead "From Block1", you will see that the block variable inside block2.html is bound again the one in index.html, instead of being bound to the innerblock variable in block1.html, displaying thus the "wrong" id. I understand that this is due to the naming, but how can I manage these recursive situations, when there are templates that can be nested on into another, an they should use a general variable name?
(of course, this is a small example of something that might be much more complex)

A: Instead of using ng-include create a directive with the isolated scope that will use templates from your blocks. This way you'll be able to use generic naming without any conflicts.

A: Working a little bit I found my solution. It is enough to use ng-init in every ng-include inside a ng-repeat to re-bind the loop variable. According to this, the repeat in index.html will look like

while the one in block1.html will be

`


text:
Q: css selector - select every div in between first and last How do you select the div elements after the first and before the last div in a container, so your selecting everything in between
I have this in my css
&--marker {
        background: green;
        width: 20px;
        height: 20px;
        border-radius: 100%;
        position: absolute;
        top: 50%;
        transform: translate3d(0, -50%, 0);

        &:first-child {
            left: calc((100% / var(--index)));
        }

        // selector below doesn't work
        &:nth-of-type():not(:first-of-type):not(:last-of-type) {
            left: calc((100% / (var(--index) + 1)) - (var(--width)/2));
        }

        &:last-child {
            left: calc((100%  - var(--width));

        }
    }

A: you can try this:
.container div:not(:first-child):not(:last-child) {
       /* css here */
}

A: As your question doesn't have any HTML structure, so I have created a test and apply the color to all inside and then update for 1st and last-child, are you looking for the same?

div.container *{
  color: red;
}
div.container div:first-child,
div.container div:last-child{
  color: green;
}

1

2

3

4

5

6

A: Simply
.someParentClass div:not(:first-child):not(:last-child) {
 //your css
}


text:
Q: HtmlUnit WebClient method getPage always returns the same page I am currently working on a solution to scrape data from a specific website (return list of prices from a html table from a website by using css selectors). In order to do this, I decided to use the HtmlUnit library as I saw that it supports a lot of features.
After I finished the code, and tested it against the same page (with same search parameters) I thought that I was done but everything changed after starting multiple threads for multiple pages. The issue is that basically below code is always returning the same old page for all threads and I simply don't understand this behavior:
page = client.getPage(webPageURL); // always returns the same old page source

I am using the same website and I am only changing some search parameters.
These are some parts of my code:
final WebClient client = new WebClient(BrowserVersion.CHROME);
            client.getOptions().setCssEnabled(false);
            client.getOptions().setJavaScriptEnabled(true);
            client.setAjaxController(new com.gargoylesoftware.htmlunit.NicelyResynchronizingAjaxController());
            client.getOptions().setThrowExceptionOnFailingStatusCode(false);
            client.getOptions().setThrowExceptionOnScriptError(false);
            client.addRequestHeader("Cache-Control", "no-cache, no-store, must-revalidate");
            client.addRequestHeader("Pragma", "no-cache");
            client.addRequestHeader("Expires", "0"); //
            client.getCache().clear();
            client.getCache().clearOutdated();
            client.getCache().setMaxSize(0);

            // enable sessions
            client.getCookieManager().setCookiesEnabled(true);

Place where the page is retrieved:
HtmlPage page = null;

            try{
                //client.closeAllWindows();
                page = client.getPage(webPageURL);
                WebResponse response = page.getWebResponse();
                pageAsString= response.getContentAsString();

As you noticed, I tried to play a lot with the cache (because I assume that this is the issue right?) and did some debugging by printing the page as String (pageAsString).
No matter how many times I changed the search parameters in the page url, no change whatsoever. I always got same old page.
I also tried some stuff with removing all jobs or cleaning up the page. Needless to say that none of it worked:
finally {
                client.getCurrentWindow().getJobManager().removeAllJobs();
                page.cleanUp();
                client.close();
                client.getCurrentWindow().getJobManager().shutdown();
                //client.closeAllWindows();
                //System.gc();
                }

Do you have any ideas how I messed up with the code, that I always get the same cached page?
Thank you in advance,
n23

A: Seems to be a proxy issue not related to HtmlUnit (see https://github.com/HtmlUnit/htmlunit/issues/327 for more details)


text:
Q: Post to user's facebook stream using Java I'm writing a java application whereby I'd like to post the a user's facebook stream without using the facebook API.
I thought it was possible to just send a POST containing the appropriate details to https://graph.facebook.com/me/feed but this has not proved successful.
Do I definitely need to set the access token in the POST? Can I get away without it if I've chosen to have "offline_access" privileges?
Thanks

A: In order to post anything to Facebook, you'll need to be posting from a particular account, which must have authorized your app to post on their behalf.  This is what the access token signifies.  It is how Facebook knows who you are.
Without the access token, FB would have no idea who was doing the posting, and there would be no way to verify that person had given you permission to post on their behalf.
You can post to https://graph.facebook.com/SOME_USER_ID/feed, but that only determines whose feed you are posting to, and does not specify who is doing the posting.
So in short, you need to do the whole OAuth2 thing to get a token, to post to someone's feed.  If a user grants you the offline_access privilege, then you can do this using a stored token without that user being logged in.
All this makes using a library, either the Javascript or some Java library quite attractive.


text:
Q: CoreBluetooth and External Accessory not working in iOS10 I am using external hardware device using Bluetooth i getting this error and I am unable to get the permission of Bluetooth it is working until iOS9 but I don't no why this change affect in iOS10 ?
Error :

[CoreBluetooth] API MISUSE:  has no restore identifier but the delegate implements the centralManager:willRestoreState: method. Restoring will not be supported
2016-09-17  Couldn't find the "com.apple.private.externalaccessory.showallaccessories" entitlement

Update :
I have seen this bug here
https://forums.developer.apple.com/thread/61646

A: In my case it worked when I enabled "Uses Bluettoth LE accessories".
Project -> Capabilities -> Background Modes -> Uses Bluetooth LE accessories.
Location of "Uses Bluetooth LE accessories"

A: I had to whitelist all accessories, that I was planing to use in my application. It is done by adding 'protocol names' for each accessory to the info.plist. search for needed array type key for text 'Supported external accessory protocols' or add by key 'UISupportedExternalAccessoryProtocols'.
Once this is done, you should stop receiving this issue.


text:
Q: Rearranging columns with pandas: Is there an equivalent to dplyr's select(..., everything())? I'm trying to rearrange columns in a DataFrame, by putting a few columns first, and then all the others after.
With R's dplyr, this would look like:
library(dplyr)

df = tibble(col1 = c("a", "b", "c"),
            id = c(1, 2, 3),
            col2 = c(2, 4, 6),
            date = c("1 Feb", "2 Feb", "3 Feb"))

df2 = select(df,
             id, date, everything())

Easy. With Python's pandas, here's what I've tried:
import pandas as pd

df = pd.DataFrame({
    "col1": ["a", "b", "c"],
    "id": [1, 2, 3],
    "col2": [2, 4, 6],
    "date": ["1 Feb", "2 Feb", "3 Feb"]
    })

# using sets
cols = df.columns.tolist()
cols_1st = {"id", "date"}
cols = set(cols) - cols_1st
cols = list(cols_1st) + list(cols)

# wrong column order
df2 = df[cols]

# using lists
cols = df.columns.tolist()
cols_1st = ["id", "date"]
cols = [c for c in cols if c not in cols_1st]
cols = cols_1st + cols

# right column order, but is there a better way?
df3 = df[cols]

The pandas way is more tedious, but I'm fairly new to this. Is there a better way?

A: You can use df.drop:
>>> df = pd.DataFrame({
    "col1": ["a", "b", "c"],
    "id": [1, 2, 3],
    "col2": [2, 4, 6],
    "date": ["1 Feb", "2 Feb", "3 Feb"]
    })

>>> df

  col1  id  col2   date
0    a   1     2  1 Feb
1    b   2     4  2 Feb
2    c   3     6  3 Feb

>>> cols_1st = ["id", "date"]

>>> df[cols_1st + list(df.drop(cols_1st, 1))]

   id   date col1  col2
0   1  1 Feb    a     2
1   2  2 Feb    b     4
2   3  3 Feb    c     6

A: Usually, the best translation between R and Python Pandas is with base R which follow the same semantics such as logical indexing on a vector, here being column names. Notice the similarity below with negation and in functions:
# R
mycols <- c("id", "date")
df2 <- df[c(mycols, colnames(df)[!colnames(df) %in% c(mycols)])]

# PANDAS (OLDER, NON-RECOMMENDED WAY)
mycols = ["id", "date"]
df2 = df[mycols + df.columns[~df.columns.isin(mycols)].tolist()]

# PANDAS (CURRENT, RECOMMENDED WAY WITH reindex)
df2 = df.reindex(mycols + df.columns[~df.columns.isin(mycols)].tolist(),
                 axis='columns')

A: As easy as you do it in R with datar:
>>> from datar.all import c, f, tibble, select, everything
>>> df = tibble(col1 = c("a", "b", "c"),
...             id = c(1, 2, 3),
...             col2 = c(2, 4, 6),
...             date = c("1 Feb", "2 Feb", "3 Feb"))
>>>
>>> df2 = select(df,
...              f.id, f.date, everything())
>>>
>>> df2
       id     date     col1    col2
  <int64> <object> <object> <int64>
0       1    1 Feb        a       2
1       2    2 Feb        b       4
2       3    3 Feb        c       6

I am the author of the package. Feel free to submit issues if you have any questions.


text:
Q: jquery store locator plugin icon and arrow issue Hello my problem is i dont see the arrow in the address box the way it should be seen

and it should be seen like this http://bjornblog.com/storelocator/default-location-example.html
here's my file, im using bootstrap btw

http://jsfiddle.net/3eKaA/
any idea?
ty in advance

A: here is the solution Twitter Bootstrap CSS affecting Google Maps i think the problem with my question is that i wasnt able to explain my problem in a better way