text:
Q: Как изменить размер Entry в tkinter То что я хотел сделать - калькулятор. Но я не могу изменять размер Entry(ans) в tkinter и не задевая других. Если не изменить размер то Entry будет очень маленьким для калькулятора. Проверьте пожалуйста. Иначе вы просто скажите "все норм же". Спасибо заранее!
Вот часть кода:
import tkinter as tk
wn = tk.Tk()
fnt = ('Arial',18)
fr = tk.Frame(bg = 'black')
fr.grid(sticky = 'nsew')
ans = tk.Entry(master = fr,width = 4,text = '',relief = 'sunken',borderwidth = 10,bg = 'black',fg = 'white')
ans.grid(row = 0, column = 1)
def check():
    if ans.get() == '0':
        ans.delete(0,tk.END)

def b1a():
    check()
    ans.insert(tk.END,'1')
def b2a():
    check()
    ans.insert(tk.END,'2')
def b3a():
    check()
    ans.insert(tk.END,'3')

wn.resizable(width=False, height=False)
b1 = tk.Button(master = fr,text = '1',width = 4,height = 2,command = b1a,bg = 'lightgreen')# Это кнопка
b2 = tk.Button(master = fr,text = '2',width = 4,height = 2,command = b2a,bg = 'lightgreen')#Это кнопка
b3 = tk.Button(master = fr,text = '3',width = 4,height = 2,command = b3a,bg = 'lightgreen')#Это кнопка

ans.configure(font = fnt)# Это просто изменяет размер и шрифт
b1.configure(font = fnt)# Это просто изменяет размер и шрифт
b2.configure(font = fnt)# Это просто изменяет размер и шрифт
b3.configure(font = fnt)# Это просто изменяет размер и шрифт

b1.grid(padx = 3,pady = 3,row = 1,column = 0)
b2.grid(padx = 3,pady = 3,row = 1,column = 1)
b3.grid(padx = 3,pady = 3,row = 1,column = 2)

A: Можно через параметр columnspan указать, чтобы текстовое поле занимало несколько колонок (3 в данном случае) и добавить sticky='ew', чтобы оно расширялось на всю доступную ширину:
ans.grid(row = 0, column = 0, columnspan=3, sticky='ew')

Результат:


text:
Q: Is the concept of a uniform space elementary? I'm self studying with Munkres's topology and he uses the uniform metric several times throughout the text. When I looked in Wikipedia I found that there's this concept of a uniform space.
I'd like to know what are it's uses (outside point set topology) and whether it's an important thing to learn on a first run on topology?

A: The concept of uniform space is designed to abstract the notions
of uniform continuity, Cauchy sequences, and completeness from
metric space theory.
What these concepts all have in common is that they require us to
be able to talk about a pair of points $x$ and $y$ being "sufficiently
close", where the notion of "sufficiently close" doesn't make explicit
reference to either $x$ or $y$.
In an arbitrary topological space, we can't do this: we can use the
system of n.h.s around a fixed point $x$ to measure "closeness to $x$",
but we can't make sense of the statement "$y$ is as close to $x$ as $y'$ is to $x'$" (if $x$ and $x'$ are different points) because there is no mechanism for comparing the size of a n.h. of $x$ to the size of a n.h. of $x'$.
In a metric space, we can do this, because we can talk about the $\epsilon$ n.h.s of any point, for fixed values of $\epsilon$.
In a topological group, we can also do this, because we can use translation by group elements to compare the system of n.h.s around any point to the system of n.h.s around some chosen base-point (usually the identity).
As Daniel Fischer indicates in his comment, the concept of uniform space
provides a language which generalizes these two examples.  I did find it useful to learn, since it clarifies results such as the theorem "closed and bounded implies compact" for subsets of Euclidean space, and since it provides a useful background language when studying topological vector spaces (and these sometimes come up in my research).  However, it is not used much in other areas of mathematics (in my experience), e.g. essentially not at all in algebraic topology or differenial topology, and so I wouldn't say there is any real need to learn it unless you feel highly motivated to do so.

A: Uniform spaces are right on the boundary of formalisms that are worth knowing.  Topological groups are definitely worth knowing, and are central to analysis and its applications.  The topology of a topological group is determined by the system of neighborhoods of the identity.  They also have a natural notion of uniform continuity.
In applications, the topology on a group is frequently given by a family of pseudometrics.  (An simple example is a Banach space -- a vector space is a kind of group, and the topology on the group is given by a single metric.)  Families of pseudometrics also have a notion of uniform continuity.
The axioms of a uniform space generalize these two cases — except that it's not a generalization.  The topology on a group always given by family of pseudometrics.  The interesting thing is that this proof — which can be phrased in terms of neighborhoods of the identity — immediately generalizes to all uniform spaces.  So while uniform spaces are not any more general, once you do the work of proving that theorem for topological groups, you get uniform spaces for free.
So if you don't like the definition of uniform spaces, or find it hard to understand, the idea is not strictly necessary.  But it's not much more work beyond understanding neighborhoods of the identity of a topological group.

A: Let me quote from Warren Page's Topological Uniform Structures:

This book aims to acquaint the reader with a slice of mathematics that is interesting, meaningful, and in the mainstream of contemporary [Ed: book originally published 1978] mathematical developments. Admittedly a number of excellent sources cover, in part, uniform spaces, topological groups, topological vector spaces, topological algebras, and abstract harmonic analysis.

and

The overall unifying theme of topologies compatible with increasingly enriched algebraic structures ... a number of striking results that combine and interlace algebraic, topological, and measure-theoretic properties associated with the structure under consideration.

As indicated, the subjects which most directly benefit from some background in uniform spaces are

*

*topological groups

*topological vector spaces

*topological algebras

*abstract harmonic analysis

But the uniform structure often only becomes apparent when you get quite far in the study of these objects. For example, while there is a rich and interesting theory of topological vector spaces, most of the TVS that are used commonly in other fields (in particular Banach and Frechet spaces) are in fact metrizable, so intuitions from metric spaces are "good enough" for everyday use for many mathematicians.
Let me give another example since you mentioned differential topology in your comments: any manifold is locally Euclidean, and hence locally metrizable. It is a theorem that locally metrizable topological spaces are metrizable if and only if it is Hausdorff and paracompact. When you study differential topology most of the time Hausdorff and paracompact are built-in assumptions for your manifolds. Hence for the most part, the study of smooth manifolds can be dispensed with using intuitions built up from metric spaces, without necessarily having to delve into intricacies associated with uniform structures.
On a first run through topology, I think it is safe to put-off learning about uniform spaces until later. By the time you really need it, you can probably pick it up relatively quickly. The one advantage to thinking a little bit about the uniform spaces (especially how they differ from metric spaces) is that it forces you to confront certain intuitive prejudices that we've grown accustomed to from working with $\mathbb{R}$ all the time, and allows you to overcome certain limitations that arises from thinking only about countable, instead of uncountable infinities. (This of course comes up also in the difference between nets and sequences.)

redpajama_set_name: RedPajamaStackExchange


text:
Q: Using Global Assembly Cache (GAC) - in the way it was designed to Is the following solution the only possibility to use libraries from GAC in code?
Assembly lib = Assembly.Load("MyLibrary, Version=1.0.0.0, Culture=neutral,
PublicKeyToken=31f5625abd53197f");

Console.WriteLine(lib.GetType("MyClass").GetMethod("Start").Invoke(obj, null));

I am a little bit confused - I've read quite much about GAC and I know how to sign an assembly, intall and uninstall assembly in GAC, but have no idea how to use it, and how does it help programmers (except that it stores different versions of same library safely). I wish I could normally create classes, not beeing forced to invoke methods presented above.
I don't want any work-arounds such as: "change windows registry" because I don't think GAC was designed for such manipulations. I want a simple answer: what the GAC is for, does runtime environment use it somehow?
What is the point of using GAC, when the code gets really ugly and difficult to manage? Or maybe I am missing something? Maybe I should manually copy an assembly into my local folder? But I heard it's also hard to do.

A: The GAC is there to help you have multiple versions of your (that's what the public key is for - preventing name clashes) assemblies installed side-by-side, and available to the whole machine, not just your application directory.
So yes, accessing assemblies from the GAC using the version number is pretty much exactly the way the GAC was designed for. ;-)
btw: You should not dynamically load stuff when you don't have to.
IOW: If you already know the class name and assembly version, you could just reference that assembly and skip the rather dramatic performance penalty of not only loading an assembly dynamically, but also invoking methods through reflection. (Instead of e.g. reusing them via interfaces or delegates)

A: If your assembly has been ngen'ed or GAC'd, then the application will use that automatically, if everything (hashes, etc) matches.

A: If you reference the assembly in your project, you can use it like a normally referenced DLL that is not in the GAC.


text:
Q: Writing array of objects to a file with Gson public boolean wirteJson(Passenger passenger[]){
    try {
        file = new FileWriter(System.getProperty("user.dir")+"/"+fileName);
        for (int i = 0; i < 10; i++) {
            String json =gson.toJson(passenger[i]);
            file.write(json);
        }
        file.flush();
        file.close();

    } catch (IOException ex) {
        return false;
    }
    return false;
}

I'm trying to write the passenger array to a file with Gson. I'm open to alternatives.

A: You don't have to serialize the given input array by each element:

*

*Gson can do it all itself;

*your method assumes the input array is exactly 10 elements long (thus, throwing ArrayIndexOutOfBoundsException if the input array has less elements, or writing only first 10 elements);

*your method does not write well-formed JSON: {},{},{} is invalid, whilst [{},{},{}] is;

*your method, as suggested by RealSkeptic, does not need intermediate string representations.

All you need are just two methods Gson.toJson and Gson.fromJson.
So, here is a simple example:
final class Passenger {

    final String name;

    Passenger(final String name) {
        this.name = name;
    }

}

public static void main(final String... args)
        throws IOException {
    final File file = createTempFile("q43439637_", "_q43439637");
    file.deleteOnExit();
    try ( final FileWriter fileWriter = new FileWriter(file) ) {
        final Passenger[] before = { new Passenger("Alice"), new Passenger("Bob") };
        gson.toJson(before, fileWriter);
    }
    try ( final FileReader fileReader = new FileReader(file) ) {
        final Passenger[] after = gson.fromJson(fileReader, Passenger[].class);
        for ( final Passenger p : after ) {
            System.out.println(p.name);
        }
    }
}

Output:

Alice
  Bob

P.S. Your out-of-catch return seems to have to return true rather than false. Also, flush() is unnecessary before close().


text:
Q: What is the difference between clearForm and resetForm in jQuery form plugin? In the jQuery form plugin, there are two options which look almost similar viz. clearForm and resetForm.
In their manuals, they have written
//clearForm: true        // clear all form fields after successful submit
//resetForm: true        // reset the form after successful submit

I really don't understand the actual difference between these two as they work identical.

A: If you check the source of the library you can see that the difference is that clearForm() empties the values in the fields, whereas resetForm() resets the value back to its default.


text:
Q: Qt Android Directories I am concerned about two questions regarding how Qt works with Android directories.

*

*For example, I want to download an archive via a library (QuaZip), but I need it to be downloaded along the path "/ storage / emulated / 0 / Android / data /", and then unzipped right there. But the problem is that the file is saved in the patch "/data/user/0/org.qtproject.example.NameApp". How can this be fixed? My code (it is unlikely that it works at all, but on Windows it would work for sure):

m_file.rename ("/storage/emulated/0/Android/data/cache.zip");

*Can I open a file in Android via QProccess?

A: On your first question about Android/data r/w
On Android 11 Android/data is forbidden for app access without root, see docs1 and docs2.
For read/write to other locations:

*

*The directory must exis or must be created (with QDir::mkpath() at once, or with QDir::mkdir() by subdirectories sequentally, because it can't create trees of directories).

*QFile must be closed before rename.

*App must have android.permission.READ_EXTERNAL_STORAGE and android.permission.WRITE_EXTERNAL_STORAGE permissions.

*At last, approve file access permissions manually in Android apps settings after app is deployed from Qt Creator. And you also may have to launch app manually, because there were reports about different app behavior when launched from IDE and and when launched manually from device.

This code worked for me (Android 11, Qt 5.15.2):
bool result;
QDir dir("/storage/emulated/0");
qDebug() << dir;
result = dir.mkdir("cache");
qDebug() << "mkdir(\"cache\") success: " << result;
QFile m_file(dir.path() + "/cache/cache.txt");
result = m_file.open(QFile::WriteOnly);
qDebug() << "open() success: " << result;
m_file.close();
result = m_file.rename(dir.path() + "/cache/cache.zip");
qDebug() << "rename() success: " << result;

On your second question about QProcess
This code worked for me:
QProcess process;
process.start("touch", QStringList() << "/storage/emulated/0/new_text_file.txt");
result = process.waitForFinished(1000);
qDebug() << "waitForFinished() success: " << result;
qDebug() << "errorString(): " << process.errorString();

The file new_text_file.txt appeared on my device storage. If you specify the type of file you want to launch, I can answer more precise.


text:
Q: Getting the data of Ancestor node + XQuery-Sql This is how my XML looks like :
 <Product sequence_number="1" number="1543448904" id="S1" unit_number="1">

     <consumer_narrative name="GLENN,GREGORY" date_filed="02/13/2009">
        <message type="Consumer Comments">THE CONSUMER STATES THIS WAS  NOT </message>
        <message type="Consumer Comments">THE PRODUCT REQUESTED.</message>
     </consumer_narrative></Product> <Product sequence_number="2" number="1543448905" id="S1" unit_number="1">

     <consumer_narrative name="JOHN,GORDON" date_filed="08/23/2009">
        <message type="Consumer Comments">THE CONSUMER STATES THAT</message>
        <message type="Consumer Comments">WRONG PRODUCT WAS SENT.</message>
     </consumer_narrative>  </Product>

My Query :
SELECT

    tab.col.value('../@number', 'varchar(30)')   [Claim Number],
    tab.col.value('../@name', 'varchar(30)')   [Name],
    tab.col.value('../@date_filed', 'varchar(30)')   [DateField],
    tab.col.value('@type', 'varchar(50)')   [Type],
    tab.col.value('.', 'varchar(250)')   [CustomerComments]

FROM XMLTABLE AS B
CROSS APPLY xmldocument.nodes('//Product/consumer_narrative/message') tab(col)
WHERE B.XMLId = 123

Gives me "null" for Claim Number. What should I have in the place of ../@number to get the claim number.

A: Another "../"
The first ../ has only taken you upto the consumer_narrative element


text:
Q: How do I force the "labeled intent" dropdown to accept my preferred intent On the intents page to the right of each utterance there is a dropdown with the labeled intent for the utterance.  If LUIS does not agree with the labeled intent it will be red.  In several cases LUIS is wrong and I want to force it to accept the intent I want.  How do I do this?

A: All you need to do is select the correct labeled intent from the drop down. The utterance will then move to that intent. After it has moved, click the 'Train' button in the top right of the window. This will train LUIS to recognize the utterance within the intent you re-categorized it to. At this time, the red border should disappear.
Utterance assigned to the wrong intent:

Training button:

Utterance now trained:


text:
Q: Group by and Sum for the list is the final aggregate result Table data is:
Info
-----------------------------------------------
num    name   age    expenseN    cost    group
1      a      20
2      b      21

InfoDetail
-----------------------------------------------
num    expenseN    cost       group
1      001         10.00      x
2      001         20.00      x
3      002         20.00      x
4      003         30.00      y

This is code:
public class _infoRepository
{
    public string name { get; set; }
    public int age { get; set; }
    public string expenseN { get; set; }
    public decimal cost { get; set; }
    public string group { get; set; }
}
public class _infoDetailRepository
{
    public string expenseN { get; set; }
    public decimal cost { get; set; }
    public string group { get; set; }
}

List<Info> result = new List<Info>();
var listInfoDetail = _infoDetailRepository.Query(p => p.group == "x").ToList();
var info1 = _infoRepository.Query(p => p.name = "a").FirstOrDefault();
for (int i = 0; i < listInfoDetail.Count; i++)
{
    result.Add(new Info()
    {
        name = info1.name,
        age = info1.age,
        expenseN = listInfoDetail[i].expenseN,
        cost = listInfoDetail[i].cost,
        group = listInfoDetail[i].group
    });
}
var info2 = _infoRepository.Query(p => p.name = "b").FirstOrDefault();
for (int i = 0; i < listInfoDetail.Count; i++)
{
    result.Add(new Info()
    {
        name = info2.name,
        age = info2.age,
        expenseN = listInfoDetail[i].expenseN,
        cost = listInfoDetail[i].cost,
        group = listInfoDetail[i].group
    });
}
return result;

After running this code, the result of the result variable is as follows:
result
--------------------------------------------------
num    name   age    expenseN    cost      group
1      a      20     001         10.00     x
2      a      20     001         20.00     x
3      a      20     002         20.00     x
4      b      21     001         10.00     x
5      b      21     001         20.00     x
6      b      21     002         20.00     x

However, that was not the result i wanted, the result i expected was like this:
result
--------------------------------------------------
num    name   age    expenseN    cost      group
1      a      20     001         30.00     x
2      a      20     002         20.00     x
3      b      21     001         30.00     x
4      b      21     002         20.00     x

After all, i want to group by and sum the result variable to give me the desired result. Someone please help me in this situation, thanks

A: var listInfoDetail = _infoDetailRepository.Query(p => p.group == "x").ToList();
You have 3 entries in your InfoDetail table with group == "x". As such listInfoDetail has 3 items. You do this twice so you end up with 6. Behavior is as expected.

i want to group by and sum the result variable to give me the desired result

If you don't want to make changes to the logic, you can take your result variable and do something like this where you are grouping by expenseN and name and then summing the cost
var resultGrouped = result
            .GroupBy(x => new { x.expenseN, x.name })
            .Select(y => new Info()
            {
                name = y.Key.name,
                age = y.FirstOrDefault().age,
                expenseN = y.Key.expenseN,
                cost = y.Sum(z => z.cost),
                group = y.FirstOrDefault().group
            }).ToList();

But this is a very inefficient use of LINQ. You should look to improve the following things:

*

*Duplicated code. You are repeating the same logic for p.name = "a" and p.name = "b"

*Unnecessary ToList(). Instead of storing listInfoDetail and info1 you could Join the two enumerations with a .Join()
Ultimately all this code could be archived with one chained LINQ statement and it would be much more efficient and shorter.

A: Following code will be helpful for you to simplify the existing code and also help you to get the desired result.
var result = from p in InfoDetails
             where p.groups == "x"
             group p by new { p.expenseN } into g
             from c in Info
             orderby c.name, g.FirstOrDefault().expenseN
             select new
             {
               name = c.name,
               age = c.age,
               expenseN = g.FirstOrDefault().expenseN,
               cost = g.Sum(x=>x.cost),
               groups = g.FirstOrDefault().groups
             };

or
var result = InfoDetails.Where(x=>x.groups=="x").GroupBy(x=>x.expenseN).SelectMany(t1 => Info.Select(t2 => new {
              name = t2.name,
              age = t2.age,
              expenseN = t1.FirstOrDefault().expenseN,
              cost = t1.Sum(x=>x.cost),
              groups = t1.FirstOrDefault().groups
              })).OrderBy(x=>x.name).ThenBy(x=>x.expenseN);


text:
Q: How to trigger input's property required on HTML5? My question is about how can I trigger the validation of required property without using the submit button
More or less I big a huge form, that is divide by a slider(steps), but is just one form. The point is, that form implement ajax at the end to submit the information that is serialize manually with javascript. So the problem is that the required (attribute, property) is not working, so you have to make the rule for empty input manually. I think is a waste, if you can do that with required.
So I want to bind every slide, to the required inputs.
Thank you in advance

A: Have you tried checkValidity() ( http://www.whatwg.org/specs/web-apps/current-work/multipage/association-of-controls-and-forms.html#dom-cva-checkvalidatity )?


text:
Q: Typescript Interface Properties with Index Signature for Defined Properties Only I am trying out an API using Typescript with local json file as storage (to test things out). I defined two interfaces, one for the DB model and one for the input from the request, with the model extending from the input interface, as the below.
export interface WorkoutInput {
    name: string;
    mode: string;
    equipment: string[];
    exercises: string[];
    trainerTips: string[];
}

export interface WorkoutModel extends WorkoutInput {
    id: string;
    createdAt: string;
    updatedAt: string;
}

However, when I had to update some fields in a WorkoutModel instance using the square brackets, I get an error since I haven't defined the index signature on either of the interfaces. I added the index signature, but this allows setting properties that aren't defined in the interface. For example:
export interface WorkoutModel extends WorkoutInput {
    [key: string]: string | string[];

    id: string;
    createdAt: string;
    updatedAt: string;
}

const workout: WorkoutModel = ...;
workout.hello = 'test';
workout['hello2'] = 'test2';

The last two lines don't throw any error, even though they are not part of the defined properties of the interface. As a workaround, I created a union type of the list of keys, and in the index signature, instead of making key's type as string, it would be this union type, however, this also produced an error saying to consider using a mapped object type instead, which after applying it changed the definition to the below.
type WorkoutModelKeys = 'id' | 'name' | 'mode' | 'equipment' | 'exercises' | 'trainerTips' | 'createdAt' | 'updatedAt';

export type WorkoutModel = WorkoutInput & {
    [key in WorkoutModelKeys]: string | string[];
} & {
    id: string;
    createdAt: string;
    updatedAt: string;
};

Indeed this gave an error when setting the keys hello and hello2 on the WorkoutModel instance and the code works fine with it, but I want to know if this is the only solution for this problem or is there another way this could have been solved without intersecting different types.
EDIT: Here is a reproducible scenario of the original issue.


text:
Q: Remove strings after match and also exclude null line breaks Input:
bta01524 Platinum drug resistance - Bos taurus (cow) (1)

  bta:514386 BIRC3

bta01522 Endocrine resistance - Bos taurus (cow) (2)

  bta:280795 FOS
  bta:281848 IGF1R

Desired output:
bta01524 BIRC3
bta01522 FOS
bta01522 IGF1R

I have been trying the following code, but not able to remove the bta:
sed 's%/\bta:/b[^ ]*%%g' output.txt

A: If row not starts with white space (/^[^ ]/) save first column to variable save. If row starts with a white space (/^ /) and contains columns (NF!=0) print variable save and content of column 2.
awk '/^[^ ]/ {save=$1}; /^ / && NF!=0 {print save,$2}' file

Output:

bta01524 BIRC3
bta01522 FOS
bta01522 IGF1R

A: In addition to sed, awk can provide a nice solution to your problem, e.g.
awk '/^\w/{lbl=$1;next} NF>1{print lbl,$NF}' file

Explanation

*

*rule 1 - /^\w{lbl=$1;next} if the 1st character is a \w (word character), set the label (lbl) to the first field and get the next record;

*rule 2 - NF>1{print lbl,$NF} if the number of fields (NF) is greater than 1, print the label and the last field.

(note: the '\w' word-character shorthand requires GNU awk and is equivalent to [a-zA-Z0-9_])
Example Use/Output
Using your input in file,
$ awk '/^\w/{lbl=$1;next} NF>1{print lbl,$NF}' file
bta01524 BIRC3
bta01522 FOS
bta01522 IGF1R

A: This might work for you (GNU sed):
sed -En '/^\S/h;//d;G;s/^.*\s(\S+)\n(\S+).*/\2 \1/p' file

If the current line begins with a non-whitespace, make a copy in the hold space and then delete it. Otherwise, append the hold space to the current line and using pattern matching and back references, fashion the desired format. If successful, print the result.
N.B. The option -n is set to prevent normal printing and replicate a grep-like nature.


text:
Q: Possibility of changing the signature for Embedded Users - DocuSign API We are trying to integrate with DocuSign using the DocuSign REST API. What we have observed is that when a user who is not registered with DocuSign and is coming into DocuSign from the partner system as an embedded user, he does not see the prompts to adopt or draw a signature and Sign (Adopt and Sign feature). Where as these prompts are always seen for external users i.e. when emails are triggered from DocuSign directly to the signers mail box and this user happens to be an unregistered user, he will always see these prompts to adopt a suggestion signature or draw a new signature.
The external users also see the prompts to 'register with DocuSign' once they have completed signing the Documents.
One more thing observed while making our portal users embedded users is that DocuSign does not shoot emails to their mailboxes when all parties have completed signing. but this email is sent to all the external users.
Are all these behavior expected when it comes to integrating using the API or is it there a way to achieve these prompts and notifications via the API too.
I would be more than grateful if anyone could help us with this information.
Thank you!

A: Short answer is that everything described above is expected under certain conditions/configurations. Users who do NOT have DocuSign user accounts will be prompted to adopt their signature each time (since there is no account to 'save' it). For embedded signing, as long as you pass the same name/email@/clientUserID for a specific individual, DocuSign will remember the signature they adopted and re-apply it for future signature events.

*

*If for some reason you want to clear the saved signature (https://www.docusign.com/p/RESTAPIGuide/RESTAPIGuide.htm#REST%20API%20References/Delete%20Captive%20Recipient%20Signature.htm?Highlight=delete%20captive)

The external users also see the prompts to 'register with DocuSign' once they have completed signing the Documents.

*

*This is configurable in your account as "Signer can create account" under Preferences -> Features.

One more thing observed while making our portal users embedded users is that DocuSign does not shoot emails to their mailboxes when all parties have completed signing. but this email is sent to all the external users.

*

*This is configurable in your account as "Use Envelope Complete Email for (non-suppressed) Embedded Signers" under Preferences -> Features.


text:
Q: Select the first row in a join of two tables in one statement I need to select only the first row from a query that joins tables A and B. On table B exist multiple records with same name. There are not identifiers in any of the two tables. I cannot change the scheme either because I do not own the DB.
TABLE A
NAME

TABLE B
NAME
DATA1
DATA2

Select Distinct A.NAME,B.DATA1,B.DATA2
From A
Inner Join B on A.NAME = B.NAME

This gives me
NAME       DATA1    DATA2
sameName   1        2
sameName   1        3
otherName  5        7
otherName  8        9

but I need to retrieve only one row per name
NAME       DATA1    DATA2
sameName   1        2
otherName  5        7

I was able to do this by adding the result into a temp table with a identity column and then select the minimum id per name.
The problem here is that I require to do this in one single statement.

A: Using a GROUP BY may get you part way there, but beware.  If you do something like this:
Select A.NAME, min(B.DATA1), min(B.DATA2)
From A Inner Join B on A.NAME = B.NAME
Group by A.NAME;

You will get the result you are looking for:
  NAME      DATA1   DATA2
  sameName   1        2
  otherName  5        7

But only because of the data you are testing with. If you change the data, so that instead of:
otherName  8        9

you had:
otherName  8        4

It would return:
  NAME      DATA1   DATA2
  sameName   1        2
  otherName  5        4

Note that otherName does not return DATA1 and DATA2 from the same record!
Update: A self-join with a comparison on one of the data values may help you, such as:
SELECT a.*, b.* FROM a,b
   LEFT JOIN b b2 ON b.name = b2.name AND b.data2 < b2.data2
   WHERE a.name = b.name AND b2.data2 IS NOT NULL;

However, this will only work if the values in DATA2 are unique per NAME.

A: This will work:
with temp as (
    select A.NAME, B.DATA1, B.DATA2,
        row_number() over (partition by A.NAME order by A.NAME) as rownum
    from TABLEA A inner join TABLEB B
    on A.NAME = B.NAME
)
select NAME, DATA1, DATA2 from temp where rownum = 1

If you want to select the least value of data1 and within it data2, then use this variation:
with temp as (
    select A.NAME, B.DATA1, B.DATA2,
        row_number() over (partition by A.NAME order by B.DATA1, B.DATA2) as rownum
    from TABLEA A inner join TABLEB B
    on A.NAME = B.NAME
)
select NAME, DATA1, DATA2 from temp where rownum = 1

Both the queries will give one row per name.

A: Not sure if this will solve your problem or not, but you could try using the GROUP BY clause and group by one of the name columns.
DB2 Group by tutorial

A: If you can add to a temp table and then query from that, you can do it in one go.
WITH T AS (temp table select), RN AS (select min row-numbers from T) SELECT T.NAME, T.DATA1, T.DATA2 FROM T INNER JOIN RN on T.row_number = RN.row_number

There are many other ways to write this, but that's how I've been doing similar things.

A: Try to dedupe B like this
SELECT  A.NAME, bb.DATA1, bb.DATA2
FROM    A
JOIN    B bb
ON      A.NAME = B.NAME
WHERE   NOT EXISTS (SELECT  *
                    FROM    B
                    WHERE   NAME = bb.NAME
                            AND (DATA1 > bb.DATA1
                                OR DATA1 = bb.DATA1 AND DATA2 > bb.DATA2))
Add more OR clauses if more DATAx columns exist.
If A contains duplicates too, simply use DISTINCT as in the OP.

A: SELECT  A.NAME, bb.DATA1, bb.DATA2
From A Inner Join B on A.NAME = B.NAME
WHERE B.DATA1 = (SELECT MIN(DATA1) FROM B WHERE NAME = A.NAME)

This will give your desired result, providing B.DATA1 values are unique within the set relating to table A.
If they're not unique, the only other way I know is using CROSS APPLY in MSSQL 2005 and above.

A: The tag of this question indicates that it would be a solution for DB2, but this is very similar to MS-SQL server, if so try these solutions:
Using CROSS, it will be possible to display what exists only in both tables
select A.*, B.DATA1, B.DATA2
from A
cross apply (select top 1 * from B where B.name = A.name) B

But it is possible to change to OUTER to display what exists in A without the obligation to exist in B
select A.*, B.DATA1, B.DATA2
from A
OUTER apply (select top 1 * from B where B.name = A.name) B

In the structure of the apply statement, it would also be possible to include an ORDER statement, since there is no indication of the order of exits in table B

A: You can use row number to get one row for each name, try something like below
Select name,data1,data2 from
(Select A.NAME,B.DATA1,B.DATA2,row_number() over(partitioj by a.name order by a.name) rn
From A
Inner Join B on A.NAME = B.NAME) where rn=1


text:
Q: How do I resolve this dependency conflict from when doing npm link When I do npm link like this in Window 10:
L:\git\notistack> npm link L:\react\Greta100Weeks\greta100weeks\node_modules\react

In my app when I do import { useSnackbar } from 'notistack'; then I can use the notistack ok, and it's the global notistack. I want to modify it debug it locally so I forked it and did the npm link but when I npm start the the App get the "You might have more than one copy of React in the same app " error. I also test this and it's true so that's why I do the npm link react and it's also recommended so I don't know what I do wrong here
To be able to debug notistack in VSCode and use the notistack in my app in VSCode. I do npm link. I get the Duplicate React error so must npm link the App react version and tell notistack to us the app react.
But I get this error: I do this npm link on other library's without problem but now this error:

I have tried to fixed this but it's not working.
I also do:
 L:\git\notistack> npm link L:\react\Greta100Weeks\greta100weeks\node_modules\react-dom

And that is resolving ok.
I fork the  notistack library and is using it ok in the app but only when I do npm link it fails. What is the problem here I guess it's in the package.json
Here is the package.json for the forked library notistack:
{
    "name": "notistack",
    "version": "1.0.10",
    "description": "Highly customizable notification snackbars (toasts) that can be stacked on top of each other",
    "main": "dist/index.js",
    "module": "dist/notistack.esm.js",
    "types": "dist/index.d.ts",
    "license": "MIT",
    "author": {
        "name": "Hossein Dehnokhalaji",
        "email": "hossein.dehnavi98@yahoo.com",
        "url": "https://github.com/iamhosseindhv/notistack"
    },
    "homepage": "https://www.iamhosseindhv.com/notistack",
    "repository": {
        "url": "git+https://github.com/iamhosseindhv/notistack.git",
        "type": "git"
    },
    "scripts": {
        "build": "tsdx build --transpileOnly --entry ./src/index.js",
        "prebuild": "npm run docs",
        "prepublishOnly": "npm run build",
        "docs": "rimraf typedoc.json && typedoc --tsconfig",
        "lint": "eslint . --ext .js,.jsx,.ts,.tsx"
    },
    "peerDependencies": {
        "@material-ui/core": "^4.11.2",
        "react": "^16.8.0 || ^17.0.0",
        "react-dom": "^16.8.0 || ^17.0.0"
    },
    "devDependencies": {
        "@babel/preset-react": "^7.8.3",
        "@material-ui/core": "^4.9.5",
        "@types/node": "^13.9.0",
        "@types/react": "^16.9.23",
        "@types/react-dom": "^16.9.5",
        "@types/react-is": "^16.7.1",
        "@typescript-eslint/eslint-plugin": "^3.9.1",
        "@typescript-eslint/parser": "^3.9.1",
        "babel-plugin-optimize-clsx": "^2.6.1",
        "eslint": "^7.7.0",
        "eslint-config-airbnb": "~18.2.0",
        "eslint-plugin-import": "~2.22.0",
        "eslint-plugin-jsx-a11y": "^6.3.1",
        "eslint-plugin-react": "^7.20.6",
        "react": "^16.8.0 || ^17.0.0",
        "react-dom": "^16.8.0 || ^17.0.0",
        "rimraf": "^3.0.2",
        "rollup-plugin-bundle-size": "^1.0.3",
        "rollup-plugin-copy": "^3.3.0",
        "tsdx": "^0.13.2",
        "typedoc": "^0.16.11",
        "typescript": "^3.8.3"
    },
    "dependencies": {
        "clsx": "^1.1.0",
        "hoist-non-react-statics": "^3.3.0"
    },
    "bugs": {
        "url": "https://github.com/iamhosseindhv/notistack/issues"
    },
    "funding": {
        "type": "opencollective",
        "url": "https://opencollective.com/notistack"
    },
    "contributors": [
        "Hossein Dehnokhalaji (https://www.iamhosseindhv.com/)"
    ],
    "keywords": [
        "notistack",
        "enqueueSnackbar",
        "snackbarprovider",
        "useSnackbar",
        "multiple",
        "react",
        "javascript",
        "material-ui",
        "toast",
        "redux",
        "snackbar",
        "stacked",
        "notification",
        "material design",
        "hossein",
        "dehnokhalaji",
        "iamhosseindhv"
    ]
}

Here is the package.json for the app using the library:
{
  "name": "greta-thunberg-fff",
  "version": "1.2.9",
  "private": true,
  "homepage": "https://greta.portplays.com",
  "main": "index.js",
  "module": "dist/index.js",
  "files": [
    "dist",
    "README.md"
  ],
  "dependencies": {
    "@material-ui/core": "^4.11.2",
    "@material-ui/icons": "^4.11.2",
    "@material-ui/lab": "^4.0.0-alpha.57",
    "@material-ui/styles": "^4.11.2",
    "axios": "^0.19.2",
    "bootstrap": "^4.5.2",
    "change-case": "^4.1.2",
    "classnames": "^2.3.1",
    "clean-tag": "^3.1.1",
    "clsx": "^1.1.1",
    "comma-separated-values": "^3.6.4",
    "crypto-js": "^4.0.0",
    "date-fns": "^2.23.0",
    "faker": "^5.5.3",
    "firebase": "^7.23.0",
    "formik": "^2.2.5",
    "framer-motion": "^2.9.5",
    "gsap": "^3.5.1",
    "history": "^5.0.0",
    "i": "^0.3.6",
    "lodash": "^4.17.19",
    "lodash.debounce": "^4.0.8",
    "mammoth": "^1.4.11",
    "material-table": "^1.69.2",
    "moment": "^2.27.0",
    "normalize-wheel": "^1.0.1",
    "notistack": "^1.0.10",
    "npm": "^7.11.2",
    "pdfjs-dist": "^1.8.357",
    "preval.macro": "^5.0.0",
    "prop-types": "^15.7.2",
    "react": "^17.0.2",
    "react-activity": "^1.2.2",
    "react-bootstrap": "^1.3.0",
    "react-chartjs-2": "^2.11.1",
    "react-data-grid": "^6.1.0",
    "react-detect-offline": "^2.4.0",
    "react-dom": "^17.0.2",
    "react-dropzone": "^11.3.4",
    "react-helmet": "^6.1.0",
    "react-motion": "^0.5.2",
    "react-perfect-scrollbar": "^1.5.8",
    "react-redux": "^7.2.5",
    "react-resize-detector": "^5.0.7",
    "react-router": "^6.0.0-beta.4",
    "react-router-dom": "^6.0.0-beta.4",
    "react-scripts": "^3.4.0",
    "react-slick": "^0.27.3",
    "react-spring": "^8.0.27",
    "react-transition-group": "^4.4.1",
    "react-visibility-sensor": "^5.1.1",
    "rebass": "^4.0.7",
    "recompose": "^0.30.0",
    "redux": "^4.0.5",
    "redux-logger": "^3.0.6",
    "redux-saga": "^1.1.3",
    "redux-thunk": "^2.3.0",
    "reselect": "^4.0.0",
    "sass": "^1.41.1",
    "simplebar-react": "^2.3.5",
    "slick-carousel": "^1.8.1",
    "styled-components": "^5.1.1",
    "styled-system": "^5.1.5",
    "three": "^0.85.2",
    "typescript": "^3.9.7",
    "uuid": "^8.3.1",
    "xlsx": "^0.10.1",
    "yup": "^0.32.1"
  },
  "scripts": {
    "start": "set PORT=6545&& react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test",
    "eject": "react-scripts eject",
    "predeploy": "npm run build",
    "deploy": "gh-pages -b master -d build"
  },
  "browserslist": [
    ">0.2%",
    "not dead",
    "not ie <= 11",
    "not op_mini all"
  ],
  "devDependencies": {
    "@typescript-eslint/eslint-plugin": "^4.1.1",
    "@typescript-eslint/parser": "^4.1.1",
    "axios": "^0.19.2",
    "babel-eslint": "^10.1.0",
    "clean-tag": "^3.1.1",
    "eslint": "^6.6.0",
    "eslint-config-airbnb": "^18.2.0",
    "eslint-config-prettier": "^6.11.0",
    "eslint-plugin-import": "^2.22.0",
    "eslint-plugin-jsx-a11y": "^6.3.1",
    "eslint-plugin-prettier": "^3.1.4",
    "eslint-plugin-react": "^7.20.6",
    "eslint-plugin-react-hooks": "^4.1.2",
    "gh-pages": "^2.0.1",
    "prettier": "^2.1.1",
    "react": "^16.4.2",
    "react-dom": "^16.4.2",
    "react-scripts": "^3.4.3",
    "rebass": "^4.0.7",
    "styled-system": "^5.1.5"
  }
}


text:
Q: Troubles implementing EEGNet convolution neural network according to paper I'm currently attempting to implement the a CNN for EEG classification using keras, specifically the one described in the paper here: https://arxiv.org/abs/2004.00077
It's all relatively straightforward until it states that they used a stride of 1 X 0 in the DepthConv2d layer. This throws an error with Keras, and according to all the sources I can find, none of the values in the stride parameter can be zero.
When I ignore that, and set the stride to 1 X 1, it doesn't match the expected parameters from the document. Is there something I'm missing about this?
This is an excerpt of the paper showing what I'm trying to emulate.
Fig. 3 and Table 1 from the paper


text:
Q: Add spaces around brackets in multiple files in Sublime Text 3 I'm wondering if it's possible to do a search and replace in Sublime Text 3 to add spaces around brackets in multiple files.
For example, I need to convert this in multiple files:
$var = function($par1, $par2);

to:
$var = function( $par1, $par2 );

Any ideas? If so, how can I do it?
Thanks in advance

A: After some fiddling around, I managed to come up with a regex to add spaces around brackets:
Find: \((.*?)\)
Replace: ( $1 )

UPDATE: The following regex is more precise because it matches ($var) but not ( $var ) nor ():
Find: \((?!\s)([^()]+)(?<!\s)\)
Replace: ( $1 )


text:
Q: Python HTML Parsing with BS4 I'm having the problem of trying to parse through HTML using Python & Beautiful Soup and I'm encountering the problem of which I want to parse for a very specific piece of data. This is the kind of code I'm encountering:

A

2213

B

215

C

253

There is a series of repeat HTML as you can see with only the values being different, my problem is locating a specific value. I want to locate the 253 in the last div. I would appreciate any help as this is a recurring problem in parsing through HTML.
Thank you in advance!
So far I've tried to parse for it but because the names are the same I have no idea how to navigate through it. I've tried using the for loop too but made little to no progress at all.

A: You can use string attribute as argument in find. BS docs for string attr.
"""Suppose html is the object holding html code of your web page that you want to scrape
and req_text is some text that you want to find"""
soup = BeautifulSoup(html, 'lxml')
req_div = soup.find('div', string=req_text)

req_div will contain the div element which you want.


text:
Q: Hiding a html table with knockout data-bind I know we can hide a table if no data is present like this: visible: Vehicles().length>0

0">

Brand	Model	Registration

The Vehicles is an observable object.
Now I have another scenario:

Brand	Model	Registration

As you can see, my Vehicles object which contains my data to fill the html table is contained in another object (observable) named chosenCategoryData.
I try to hide the table with visible: Vehicles().length>0 but I got an error, maybe because Vehicles is not observable.
How can I proceed?

A: IIRC, you can't use with and visible in the same data-bind. You can wrap it in another

...

or use the virtual syntax:

Take a look as this jsfiddle. Use Vehicles() if that is an observableArray.


text:
Q: Illegal mix of collations (utf8_general_ci,COERCIBLE) and (latin1_swedish_ci,IMPLICIT) Can anyone help me on how could i fix this error
Illegal mix of collations (utf8_general_ci,COERCIBLE) and (latin1_swedish_ci,IMPLICIT) for operation 'locate'

I have executed my stored procedure on the server1 and it's work fine, but it will throw an error on the server2. I've checked all the tables and stored procedure on both servers and it's all the same.
Can anyone help me on what is this problem and the resolution for it.
Here is the stored procedure.
DELIMITER $$

DROP PROCEDURE IF EXISTS `UPDATEPASSWORD` $$
CREATE DEFINER=`root`@`localhost` PROCEDURE `UPDATEPASSWORD`(IN empn CHAR(9), IN oldpassword VARCHAR(255), IN newpassword VARCHAR(255))
main:BEGIN
DECLARE diction INT;
DECLARE prevpass INT;
DECLARE len INT;
DROP TABLE IF EXISTS  passwordstatus;
CREATE TEMPORARY TABLE passwordstatus
(
    `passwordstatus` VARCHAR(127)
);

PREPARE stmt1 FROM "select count(seqid) into @diction
                    from dictionary where instr(?,word)>0 or instr(REVERSE(?),REVERSE(word))>0 ";
SET @a = newpassword;
SET @b = newpassword;
EXECUTE stmt1 USING @a,@b;
DEALLOCATE PREPARE stmt1;
IF @diction > 0 THEN
    START TRANSACTION;
    PREPARE stmt1 FROM "INSERT INTO passwordstatus VALUES (?)";
    SET @a = "PASSWORD CONTAINS COMMONLY USED WORDS";
    EXECUTE stmt1 USING @a;
    DEALLOCATE PREPARE stmt1;
    COMMIT;
    SELECT * FROM passwordstatus;
    LEAVE main;
END IF;

 PREPARE stmt1 FROM "select count(seqid) into @prevpass
                    from prevpass where (instr(sha1(?),passwd)>0 or instr(REVERSE(sha1(?)),REVERSE(passwd))>0)and empno = ?";
SET @a = newpassword;
SET @b =empn;
EXECUTE stmt1 USING @a, @a, @b;
DEALLOCATE PREPARE stmt1;
IF @prevpass > 0 THEN
    START TRANSACTION;
    PREPARE stmt1 FROM "INSERT INTO passwordstatus VALUES (?)";
    SET @a = "PASSWORD CONTAINS PREVIOUSLY USED PASSWORDS";
    EXECUTE stmt1 USING @a;
    DEALLOCATE PREPARE stmt1;
    COMMIT;
    SELECT * FROM passwordstatus;
    LEAVE main;
END IF;

PREPARE STMT1 FROM " SELECT COUNT(seqid) INTO @prevpass FROM prevpass where empno = ? ";
SET @a = empn;
EXECUTE STMT1 USING @a;
DEALLOCATE PREPARE STMT1;
START TRANSACTION;
IF @prevpass = 6 THEN
    PREPARE STMT1 FROM "DELETE FROM prevpass WHERE EMPNO = ? ORDER BY seqid LIMIT 1";
    SET @a = empn;
    EXECUTE STMT1 USING @a;
    DEALLOCATE PREPARE STMT1;
END IF;
PREPARE STMT FROM " UPDATE emppass SET passwd = sha1(?),lastupdate = now() WHERE empno = ? ";
SET @a = newpassword;
SET @b = empn;
EXECUTE STMT USING @a,@b;
DEALLOCATE PREPARE STMT;
PREPARE STMT1 FROM " INSERT INTO prevpass (empno,passwd,createdate) VALUES (?,sha1(?),now())";
SET @a = empn;
SET @b = newpassword;
EXECUTE STMT1 USING @a,@b;
DEALLOCATE PREPARE STMT1;
PREPARE stmt1 FROM "INSERT INTO passwordstatus VALUES (?)";
    SET @a = "PASSWORD UPDATED SUCCESSFULLY";
    EXECUTE stmt1 USING @a;
    DEALLOCATE PREPARE stmt1;
COMMIT;
SELECT * FROM passwordstatus;

END $$

DELIMITER ;

A: try to have a BINARY command before each parameter.
SHA1(BINARY ?)
BINARY passwd

A: Post query you are executing.
As i can see now, you can do this:
Check table collation of tables on both servers:
select table_name, table_collation
  from information_schema.tables
 where table_schema = database();

And check the collation of columns:
select *
from information_schema.columns
where table_schema = database()
  and collation_name is not null
  and collation_name not like 'utf8%';

Possibly this could help you.


text:
Q: C# System.Data.EvaluateException: 'Cannot perform 'Like' operation on System.Int64 and System.String.' I'm looking for a solution to your error please This method works when I enter text in the text box.However, when the "else if" block runs, it gives an error that I specified in the header.What can I do to solve this?
The problem happens only in the "else if" block. This problem doesn't work in other if,else etc. blocks.
        private void txt_box_urun_ara_TextChanged(object sender, EventArgs e)
    {
        if (urun_isim_radio.Checked == true)
        {
            (tablo_urunler.DataSource as DataTable).DefaultView.RowFilter = string.Format("UrunAdi LIKE '{0}%'", txt_box_urun_ara.Text);
        }
        else if (urun_id_radio.Checked == true)
        {
            (tablo_urunler.DataSource as DataTable).DefaultView.RowFilter = string.Format("UrunID LIKE '{0}%'", txt_box_urun_ara.Text);
        }
        else {
            urun_isim_radio.Checked = true;
            (tablo_urunler.DataSource as DataTable).DefaultView.RowFilter = string.Format("UrunAdi LIKE '{0}%'", txt_box_urun_ara.Text);

        }

A: Based on your code, I reproduced your problem. We can use Convert(ID, System.String) LIKE to perform the like operation about int type.
I make a code example and you can refer to it.
private void textBox1_TextChanged(object sender, EventArgs e)
    {
        if(radioButton1.Checked==true)
        {
            (dataGridView1.DataSource as DataTable).DefaultView.RowFilter = string.Format("Convert(Adi, System.String) LIKE '{0}%'", textBox1.Text);
        }
        else if (radioButton2.Checked == true)
        {
            (dataGridView1.DataSource as DataTable).DefaultView.RowFilter = string.Format("Convert(ID, System.String) LIKE '{0}%'",textBox1.Text);
        }
    }

    private void Form1_Load(object sender, EventArgs e)
    {
        DataTable dt = new DataTable();
        dt.Columns.Add("Adi", typeof(int));
        dt.Columns.Add("ID", typeof(int));
        dt.Rows.Add(123,1001);
        dt.Rows.Add(124,1002);
        dt.Rows.Add(125, 1003);
        dt.Rows.Add(135, 1004);
        dt.Rows.Add(167, 1101);
        dt.Rows.Add(196, 1102);
        dt.Rows.Add(193, 1103);
        dt.Rows.Add(186, 1104);
        this.dataGridView1.DataSource = dt;
    }

Result:


text:
Q: How to retrieve data through Foreign Key in Laravel? How to retrieve data in Laravel.
I am having table user in which I m having field parent_id in which I m showing information of its  user_id.
Now I want to show information of logged user
I tried this
 {{Auth::user()->parent_id}}

I get the selected parent_id, now I want the name of that user_id.
I'm trying this
{{(Auth::user()->parent_id)->value('name')}}

Its getting an error.
Please tell me how can I write this in my code to get name of that parent id.

A: Define the relationship to the parent user in the User modal.
User Modal
public function parent()
{
    return $this->belongsTo(User::class, 'parent_id');
}

blade
{{ Auth::user()->parent->name }}

A: There are (at least) two ways to do that.
1- Without relationship: you can select/find the user by parent_id and get its name. Something like this:
{{ App\User::find(Auth::user()->parent_id)->name }}

2- With relation: and I think it is easier. Define the relationship and set the parent_id as foreign key. Then you can get the parent user. Something like this:
{{ Auth::user()->parentUser->name }} // parentUser is the method created in User model

To define and use the relationship see the @Tharaka Dilshan answer.


text:
Q: Partial rendering failed with ajax I've an add_new_button which will create a new object in database and show the updated records with ajax. The code works well until I updated Mongoid from 2.4 => 3.0.0.rc (bundle update).
Now the problem is, when the button is clicked, the database is updated with new records, however the page won't be updated. I've checked the ajax request and it did render the partial page, but without the newly added record. While the second click will render the previously added record, yet without the latest record. Any ideas?
Updated with code snippets
It renders the _desktop.html.erb
#index.html.erb

    <%= render :partial => "desktop", :locals => { :items => @items } %>

*_desktop.html.erb* is rendered by the view and also for ajax update (This is the page which not updated with ajax)
#_desktop.html.erb
<%= form_tag(new_path, :remote => true) do %>

Select an item

        <%= select_tag "user_items", options_from_collection_for_select(services, "id", "name", :prompt => true) %>

        Close
        <%= submit_tag "Confirm", :id => "add-item_btn" %>

<% end %>

No problem in create a new item and it rendered _desktop.html.erb through json
# items_controller.rb
def new
    @user.items.create!(
        handle: 'name',
        content: 'body'
    )

    respond_to do |format|
        format.json { render :json => {:sucess => true, :html => (render_to_string '_items.html.erb', :locals => { :items => @items })} }
        format.html {}
    end
end

However it does not fetch the updated html with the newly added item..
    <%# new.js.erb %>
    $('#add-item_btn').live('ajax:success', function(event, data){
    if(data.success == true) { $('#columns').html(data.html); }
});

A: If the problem started with an update from a specific gem (in this case MongoID), then the first thing to consider is finding a CHANGELOG so see what could be the cause. In this case, it is a pretty long changelog, but it is still your best bet to find the cause by yourself.
Also, MongoID has a pretty good upgrading guide which might point you in the right direction.
One thing that did caught my eye, in ItemsController#new, you render _items.html.erb with local variables filled by @items. But where is @items set? With the code you provided, it looks like @items returns nil.


text:
Q: Sorting Parsed Data with jQuery I want to sort a list of clients (which is a list of keys from the variable "clients"), with a simple .sort().
I am unable to sort "clients", but I am able to sort "key_list" (they're in alphabetical order in my console).
So...
What I'm seeing with document.write is a list of clients with "Client: (client_name)" with a line break after each client, which is good. But it's in no particular order.
What I'm seeing with console.log is an alphabetical list of clients, which is good. But there each client is not shown as "Client: (client_name)" and there is no line break. It's one large list, with each item separated by a comma.
Why am I unable to sort the keys in "clients"? Is it the way I'm trying to access the parsed "data"?
$.ajax ({

  url: 'data.php?',
  type: 'GET',
  dataType: "json",
  success: function(data) {

  var clients = JSON.parse(data);

  for (var key in clients) document.write('Client:' + ' ' + key + '
');

  var key_list = Object.keys(clients);

  console.log(key_list.sort(clients));

  }

});

A: sort expects a callback function which takes two parameters, and also expects a return value based on a comparison between those two parameters.
.sort(function(a,b){ return a-b; });

You are sending sort an object from deserialized json, which is not a function that takes two parameters and returns a value based on comparison, so the sort does not work. By default, sort will use a lexicographical comparison.
This would be the default call
console.log(key_list.sort());

A: Because console.log() is only printing the key_list.sort(clients) object. So basically you are logging the object, not each element in the object.
So of course you are not getting the clients printed in the order you want in the document because you are doing that before you sort. Like Travis J said, you should use just .sort().
So you should do; console.log(clients.sort());
This will allow you to print the whole object and print out all the clients in sorted order.
EDIT:
$.ajax ({

  url: 'data.php?',
  type: 'GET',
  dataType: "json",
  success: function(data) {

  var clients = JSON.parse(data);
  var sortedClients = clients.sort();

  for (var key in sortedClients){
      document.write('Client:' + ' ' + key + '
');
      console.log('Client: ' + key);
  }

});


text:
Q: Disable HTML autofix in Chrome I am creating NODE.js app that use Nunjucks as view engine. I added tests to verify if the html created is valid (for now I just wanted to check if all tags are properly closed). In order to do this i spin up application, go to the site using headless chrome, making a snapshot and running validation code on output files.
The problem is that browsers try to fix HTML code automatically. They close tags by themself in order to create more or less valid HTML. Is there a way to disable this feature?
I would like to be sure that i created valid HTML document using nunjucks rather then counting that browser will fix it itself.

A: If you validate the source directly, Chrome will not change the HTML. Try this in your browser: view-source:https://stackoverflow.com/questions/65091531/disable-html-autofix-in-chrome
If you use the developer panel to inspect the DOM, Chrome tries to correct poor html.
You could maybe just do a GET request to the application, and validate the result, instead of using Chrome.


text:
Q: Regular expression in flask urls I want to write some urls in flask using regular expression. I have them in django like this
r'^v1/$'
r'^v1/(.+/)$'

I want to recreate them in flask
I have tried following
class RegexConverter(BaseConverter):
    def __init__(self, url_map, *items):
        super(RegexConverter, self).__init__(url_map)
        self.regex = items[0]
app.url_map.converters['regex'] = RegexConverter

api.add_resource(Handler1,'/<regex("^v1/$")>')
api.add_resource(Handler2,'/<regex("^v1/(.+/)$")>')

But it's not working.
Showing error
ValueError: malformed url rule: '/<regex("^v1/$")>'

A: You are not providing the url_map rule value. It should be:
class RegexConverter(BaseConverter):
    def __init__(self, url_map, *items):
        super(RegexConverter, self).__init__(url_map)
        self.regex = items[0]
app.url_map.converters['regex'] = RegexConverter

api.add_resource(Handler1,'/<regex("^v1/$"):just_v1>')
api.add_resource(Handler2,'/<regex("^v1/(.+/)$"):v1_plus>')

And, in your actual handlers (here Handler1 and Handler2); you'll receive those mapped values as parameters:
class Handler1(Resource):
    def get(self, just_v1):
        # you'll receive `v1/` as the value for `just_v1`


text:
Q: Do I have to add VIBRATE permission if I'm using Handheld.Vibrate() Do I have to add VIBRATE permission if I'm using Handheld.Vibrate() or is it added automatically?
If I do have to add it, how do I do it. How to edit the AndroidManifest. This is in Unity.

A: No, you don't have to add it manually. The permission will be added by Unity automatically if you use Handheld.Vibrate(). The-same thing applies when you use other Unity API for sensors like camera, accelerometer, gyro and GPS.

If I do have to add it, how do I do it. How to edit the
  AndroidManifest

1.Go to <UnityInstallationDirecory>\Editor\Data\PlaybackEngines\AndroidPlayer\Apk, Copy the AndroidManifest.xml file to your <ProjectName>Assets\Plugins\Android
2.Now open the copied Manifest file from <ProjectName>Assets\Plugins\Android  and add <uses-permission android:name="android.permission.VIBRATE"/> to it. Save, Build and Run.
But again, you don't have to add it manually.
Remember that Handheld.Vibrate() only do short vibration. If you need vibration with pattern, see here


text:
Q: How to determine the length (in pixels) of a string being rendered on a web page? If I know the font size (12) and the font family (calibri), is there a way to determine the length (in pixels) a given string will take after it will be rendered? I am absolutely certain about the font and size. Are there any lookup tables for this purpose to determine the length in PHP code itself? I am writing a PHP script to dynamically generate an SVG image which contains various boxes filled with data pulled out of a DB. The problem is that I need to manually wrap the text around and increase the size of the box if the string is big.
Thanks

A: Your title and actual post seem to say slightly different things. I'm guessing what you're really asking is whether it's possible to determine the width in pixels of text rendered on a web page in your PHP code (prior to web page being rendered).
If so, the answer is "NO". Said font may not be available on user's computer; s/he may have custom stylesheet applied; use large font sizes; etc...
What you can do is determine that width using javascript after the page is rendered (obviously, you can do that in some other page as well and hope nothing changes till then) and submit that back to PHP. With some clever AJAX-ing you can even do this on the same page.
Take a look at this question for details on how to do this in javascript.

A: Use jQuery,
$("text").each(function(){alert(this.innerHTML+" is "+$(this).width()+" pixels.");});

A: Use the PHP function imagettfbbox to get the size of the bounding box for the given string.
On the other hand you can use also javascript to manipulate SVG images in case you would like to handle it on the client side. That way it wouldn't even matter if the client had the specified font or not...

A: If you want to determine the string length of text, using PHP's Build-In-Fonts (e.g. if you are using imagestring()), you can use:
imagefontwidth()

$text = "Your text here"
$fontSize = 5;

$textLength = imagefontwidth($fontSize) * strlen($text);

If you do not use the Build-In-Fonts, use imagettfbbox(), like mentioned above.

A: You could use PHP GD to render out the string as a image and get the size of the resulting image.
If you use this, it should work:
   list($left,, $right) = imageftbbox( 12, 0, "arial.ttf", "Hello World");

   $width = $right - $left;


text:
Q: Is docker swarm loadbalancer enabled by default in traefik? I just need to know the answer on this question
If it is disabled by default is there any option to enabled it on all backends without adding label "traefik.backend.loadbalancer.swarm=true" on every service?

A: By exploiting a bug (issue 2138), I came to the conclusion that the default value is false (version v1.7.4).
I think you have to add that label for every service you use as an backend.
Take the example of enabling sticky session, in traefik.toml, you do:
[backends]
  [backends.backend1]
    # Enable sticky session
    [backends.backend1.loadbalancer.stickiness]

This is equivalent to add the following in the compose file,
  - "traefik.backend=backend1"
  - "traefik.backend.loadbalancer.stickiness=true"


text:
Q: What is the difference between a Kubernetes Controller and a Kubernetes Operator? As I understand the purpose of the Kubernetes Controller is to make sure that current state is equal to the desired state. Nevertheless, Kubernetes Operator does the same job.
The list of controller in the Control-plane:

*

*Deployment

*ReplicaSet

*StatefulSet

*DaemonSet

*etc

From the Google Search, I found out that there are K8s Operators such as

*

*etcd Operator

*Prometheus Operator

*kong Operators

However, I was not able to understand why it cannot be done using Controller?
Is Operator complementing the Controllers?
What's the difference between these two design as a purpose and functionality.
What certain things need to keep in mind to choose between Controller and Operator? ?

A: TL;DR:

*

*Controller == Works on vanilla K8s resources

*Operator == a Controller that adds custom resources (CRDs) required for it's operation

Change my mind but in my opinion the difference is negligible and the terms rather confuse people then actually adding value to a discussion. I therefore would use them interchangeablely.

A: In Kubernetes, most of the operations happen in an asynchronous manner.
For instance, when one creates a ReplicaSet object (picking a simpler object), this is the sequence that happens:

*

*We send the request to the Kube api-server.

*The kube-api server has a complex validation

*

*Ensures that the user has the RBAC credential to create the RS in the given namespace

*The request is validated by all the configured admission controllers

*Finally the object is just written to ETCD - nothing more nothing less

Now, it is the responsibility of the various Kubernetes controllers to watch the ETCD changes and actually execute the necessary operations. In this case, the ReplicaSet controller would be watching for the changes in ETCD (e.g. CRUD of ReplicataSets) and would create the Pods as per the replica count etc.
Now, coming to Operators, conceptually they are very similar to Kubernetes controllers. But they are used with third-party entities. In Kubernetes, there is a concept of CRDs, where vendors can define their own CRD which is nothing but a custom (e.g. Vendor specific) kubernetes object type. Very similar to the manner in which Kubernetes controllers read to the CRUD of Kubernetes objects, these operators respond to the operations on the corresponding CRDs. E.g. Kong operator can create new API entries in the Kong API server when a new API CRD object is created in the Kubernetes cluster.

A: I believe the term "kubernetes operator" was introduced by the CoreOS people here

An Operator is an application-specific controller that extends the Kubernetes API to create, configure and manage instances of complex stateful applications on behalf of a Kubernetes user. It builds upon the basic Kubernetes resource and controller concepts, but also includes domain or application-specific knowledge to automate common tasks better managed by computers.

So basically, a kubernetes operator is the name of a pattern that consists of a kubernetes controller that adds new objects to the Kubernetes API, in order to configure and manage an application, such as Prometheus or etcd.
In one sentence: An operator is a domain specific controller.
Update
There is a new discussion on Github about this very same topic, linking to the same blog post. Relevant bits of the discussion are:

All Operators use the controller pattern, but not all controllers are Operators. It's only an Operator if it's got: controller pattern + API extension + single-app focus.
Operator is a customized controller implemented with CRD. It follows the same pattern as built-in controllers (i.e. watch, diff, action).

Update 2
I found a new blog post that tries to explain the difference as well.

A: Controllers are innate objects to kubernetes that follows the control loop theory and ensures desired state matches the actual. ReplicatSet, daemonset, replication they all are pre-configured/pre-installed controllers
Operators also have controllers.  Operators are a means to customize or extend the functionality of kubernetes by means of CRD (Custom Resource Definition).  For eg, if you have a need to auto-inject specialized monitoring or initilization container, when a new app pod is created, then you will need write some customization (operators) as this functionality is not available in  kubernetes.
Operators can be written in any language with ability to communicate with Kubernetes API server; I have mostly seen them written in Golang.


text:
Q: How to refer to an Angular component's full template setting CSS without referring to any tags? My usual setup for each view is an outer DIV that I style as the base background etc.
<div class="outer">
  <!-- Actual stuff in here -->
</div>

Then, in the SASS, I refer to it like so.
div.outer { ... }

That adds one lever of indent and seems like an unnecessary (though minor) increment in complexity. So I wonder if it's possible to add a style to the template itself. Partly, to lower the complexity. Partly, because I'm going to have text-only elements with no tags at all.
Is it possible to set the style of template from SASS files if there are no tags, only text in it?

A: You can apply styling to the component host element with the :host selector:
:host {
  color: red;
}

See this stackblitz for a demo.


text:
Q: How to write php code insite double quotation of href in php? I am having difficulty to find out correct quote patterns to inside href to write PHP code. I checked other StackOverflow questions but did not get any idea. I am displaying data in PHP using table written inside PHP code rather then in HTML. Can anyone help me please? Thanks
"<a href='reps.php?id=<?php echo $data['userID']?>'". $data["userID"]. "
";


text:
Q: A question on the irreducible divisors and splitting field of $x^{p^n} - x\in \mathbb F_p[x]$. I need to prove that any irreducible polynomial $f$ of degree $d\,\big|\,n$ over $\mathbb F_p$ devides $x^{p^n} - x$. I know that the splitting field of the latter is the finite field with $p^n$ elements, and that if $\alpha$ is the root of $f$, then $[\mathbb F_p(\alpha):\mathbb F_p] = d$. I don't see, why all the roots of $f$ must lie in the splitting field of $x^{p^n} - x$. In fact, the splitting field of $f$ may have degree $d\,!$ over $\mathbb F_p$, which may well be greater than $n$.
Thank you.

A: Q: Why does $\mathbb{F}_{p^n}$ contain all the roots of an irreducible polynomial $f(x)\in\mathbb{F}_{p}[x]$ of degree $d$, $d\mid n$?

One way of seeing this is to observe that the extension $\mathbb{F}_{p^n}/\mathbb{F}_p$ is a Galois extension because it has $n$ distinct automorphisms (powers of the Frobenius automorphism). As a Galois extension it is normal, meaning exactly that any irreducible polynomial with coefficients in the prime field and a root in the bigger field splits there into a product of linear factors.

A possibly more concrete way of seeing the same thing is to observe that if $\alpha$ is a root of $f(x)$, then so are $\alpha^p$, $\alpha^{p^2}$ et cetera. The conjugates $\alpha^{p^i}$ must start repeating at some point, so we get, first $\alpha^{p^i}=\alpha^{p^j}$ for some integers $i,j$ such that $0<i<j$, and then (using injectivity of the $p$th power mapping) that $\alpha=\alpha^{p^{\ell}}$ with $\ell=j-i>0$. Without loss of generality we can assume that $\ell$ is the smallest positive integer with the property $\alpha^{p^\ell}=\alpha$.
At this point we know $\ell$ roots of $f(x)$, namely $\alpha^{p^i},0 \le i<\ell.$ Consider
the polynomial
$$
g(x)=\prod_{i=0}^{\ell-1}(x-\alpha^{p^i})=x^\ell+\sum_{i=0}^{\ell-1}a_ix^i
$$
for some coefficients $a_i\in\mathbb{F}_p[\alpha]$. Because $F:z\mapsto z^p$ is an automorphism of $\mathbb{F}_p[\alpha]$, we see that
$$
g^F(x):=x^\ell+\sum_{i=0}^{\ell-1}F(a_i)x^i=\prod_{i=0}^{\ell-1}(x-F(\alpha^{p^i}))
=\prod_{i=0}^{\ell-1}(x-(\alpha^{p^i})^p)=\prod_{i=1}^{\ell}(x-\alpha^{p^i})=g(x).
$$
Here in the last step we used the fact $\alpha^{p^\ell}=\alpha$. Therefore $F(a_i)=a_i$ for all $i$, in other words $g(x)\in\mathbb{F}_p[x]$. Because $g(x)$ is a non-trivial factor of $f(x)$ with coefficients in the prime field, we must have $g(x)=f(x)$, and hence also that $\ell=d$. This means that all the roots $\alpha_i$ of $f(x)$ are of the form $\alpha^{p^i}$ for some $i$. In particular they all satisfy the equation $\alpha_i^{p^d}=\alpha_i$. Consequently we also have $\alpha_i^{p^n}=\alpha_i$ for all $i$, which is what we wanted to show.


text:
Q: How to use regular expression in getElementsByTagName method of Java xml Parser I have multiple XMLs just varies tag names like this
sample1.xml
<Customer>
   <ns1:Account>
</Customer>

sample2.xml
<Customer>
   <ns3:Account>
</Customer>

sample3.xml
<Customer>
   <ns5:Account>
</Customer>

Account tag is constant but ns value is changing is each xml file. I want to give a regular expression inside doc.getElementsByTagName method like ".*child" to write a generic xml function using java xml parser but it is not working. Please help.
         File inputFile = new File("input.txt");
         DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
         DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
         Document doc = dBuilder.parse(inputFile);
         NodeList nList = doc.getElementsByTagName(".*Account");  // giving me null


text:
Q: Create PDF in PHP without manually creating HTML Can we really generate pdf files using php thro' some APIs without manually creating HTML. Beacuse I have got to create Invoices for some 50 groups and each having different HTML, so it would be a pain to create HTML for each of them and then create PDF using library from this HTML. Is there any other way?

A: yes of course, start learning from

http://www.fpdf.org/ or
  https://tcpdf.org/

It will definitely helps you


text:
Q: PDF does not work in Adobe Reader DC but all other Readers I am unable to get my pdf to work online with Adobe Reader DC.
http://www.okeechobeecountytaxcollector.com/Documents/FeeCalculatorRev0909.pdf
None of the buttons or functionality is working. (Like when you click motorvehicles, or Mobile homes or any of those buttons across the top a drop down of choices is supposed to appear) But if I open in any other reader it works fine. Does anyone know how I may be able to edit the document to work properly in Adobe Reader DC as well? Is there any settings in the document or anything that you have to change for things to work in DC?
I have tried changing the settings in the security section to Acrobat X and later but that did not fix it as well.


text:
Q: How to find the index of the center element of a 2d array using javascript? Let's say we have an image which a 2d array like this:
var img = [
    [
      { r: 255, g: 255, b: 255 },
      { r: 255, g: 255, b: 255 },
      { r: 255, g: 255, b: 255 }
    ],
    [
      { r: 255, g: 255, b: 255 },
      { r: 255, g: 255, b: 255 },
      { r: 255, g: 255, b: 255 }
    ],
    [
      { r: 255, g: 255, b: 255 },
      { r: 255, g: 255, b: 255 },
      { r: 255, g: 255, b: 255 }
    ]
  ];

We have a 3x3 matrix. Each record represents a pixel.
Now the middle element is the fifth record or Img[1][1].
I want to be able to find the index of the middle element in any odd number square matrix. How can I do this?
I have tried thinking about this and thought about using the modulus operator.
We would have let's a 5x5 matrix which means 25 pixels. I would then try to divide 25 by 2:
25/2 =  12 with a remainder 25 mod 2 = 1.
Therefore the middle element would be 12 + 1 = 13.
Because we have a 5x5 matrix this means that each line in the matrix contains 5 elements.
We would have to do:

*

*13/5 = 2 meaning we have to go through 2 lines of 5. Which mean we can skip directly from img[0][x] , img[1][x]  to [2][x]. (Skipping to the third line)

*13 mod 5 = 3 to get the index inside the line we're in meaning img[2][3] but this is wrong because 13 would be in the third spot but with index 2 because 0,1,2 so we would have img[2][2].
Doing for 7x7 matrix I notice a pattern for 3x3 we had img[1][1], for 5x5 we had img[2][2], for 7x7 we have img[3][3].
So my trouble with all of this is I do not now for sure if it applies for all even numbers and how to translate it to a javascript code.

A: const row    = img[Math.floor(img.length / 2)];
const result = row[Math.floor(row.length / 2)];

No need for modulo here


text:
Q: Textarea realtime update by multiple input values This is my form example:
<form action="" method="POST">
    <input type="text" name="firstTarget" />
    <input type="text" name="secondTarget" />
    <input type="text" name="thirdTarget" />
    <textarea name="result">I have this text and I want to update it using firstTarget. After that I want to use secondTarget and thirdTarget</textarea>
</form>

I want to update my textarea value in realtime by replacing the words firstTarget, secondTarget and thirdTarget with the actual values from firstTarget, secondTarget and thirdTarget inputs.

A: HTML:
<form action="" method="POST">
    <input type="text" name="firstTarget" onblur="tst(this);" />
    <input type="text" name="secondTarget" onblur="tst(this);" />
    <input type="text" name="thirdTarget" onblur="tst(this);" />
    <textarea style="width:500px; height: 100px;" name="result">I have this text and I want to update it using firstTarget. After that I want to use secondTarget and thirdTarget</textarea>
</form>

And javascript:
function tst(elm){
    var trgt=document.getElementsByTagName('textarea')[0];
    trgt.value=trgt.value.replace(elm.getAttribute('name'), elm.value);
}

Working jsfiddle demo here
EDIT:
should you want to update multple instances of your needles like firstTarget, then you need to create the regex on the fly so you can pass it the global flag.
function tst(elm){
    var trgt=document.getElementsByTagName('textarea')[0];
    trgt.value=trgt.value.replace(RegExp(elm.getAttribute('name'), 'g'), elm.value);
}

Working jsfiddle demo here

A: You can do something like this:
/* cache original value so we keep the keywords*/
var txt=$('textarea').val();

$('input').keyup(function(){
   var newText=txt;
    newText=newText.replace( this.name, this.value);
    $('textarea').val(newText);
});

One issue however is if textarea is not set as readonly and user changes anything within it this won't work as it relies on storing the original value and changing that. Would need to know more about use case for this setup to help advance it further.
Same issue exists in other solutions as well if user touches any of the keywords all will fail
DEMO
Here's a solution that stores the input value on every keyup so textarea can be edited by user as well.
$('input').keyup(function(){
    /* value to be replaced is stored in data object*/
    var regVal=$(this).data('replace');
   var newText=$('textarea').val().replace( regVal, this.value);
    /* store value that will get replaced*/
    $(this).data('replace', this.value)
    $('textarea').val(newText);
}).each(function(){
    /* on page load set initial replacement value as name of input*/
    $(this).data('replace', this.name);
});

Only limitation is it assumes no duplicate entries by user
DEMO

A: you can use this code to do it:
$('firstTarget').onChange(function(){
      var str =  $('result').val();
      str.replace(firstTarger, $( this ).attr('name'));
      $('result').text(str);
 }):

 $('secondTarget').onChange(function(){
      var str =  $('result').val();
      str.replace(firstTarger, $( this ).attr('name'));
      $('result').text(str);
 }):

$('thirdTarget').onChange(function(){
      var str =  $('result').val();
      str.replace(firstTarger, $( this ).attr('name'));
      $('result').text(str);
 }):

enjoy!!!


text:
Q: jQuery dialog on IFrame (containing PDF doc) overlapping in IE I am trying to display a jQuery dialog on top of PDF doc in IFrame. When I click a button in my Form, a jQuery dialog pops up. Problem is that the Popup is going behind the PDF doc instead of displaying at the top of the Viewport. This problem occurs only in IE (6,7 and 8). Firefox displays the elements correctly without any overlapping issue.
I tried setting the position: relative and z-index: , but no luck !
Please Help.
Thanks in advance !


text:
Q: 3 dependent multi dropdown list same select name how to insert into mysql using php? 3 dependent multi dropdown list same select name at the end of the select field each drop down. When i click portfolio level option based on the div display show one dependent dropdown list among three. When i click at showed dropdown list only posted to last selected value. In that i make every drop down list last select name same; i.e name=worklocation.
The html code below:
<form method="post" action="user-work.php" enctype="multipart/form-data">

                    <select name="pfLevel" id="portfolio_levels" class="form-control">
                        <option value="">Select Portfolio Level</option>
                    </select>

                    <select name="workLocation[]" id="counrey7" class="form-control">
                    <option value="">Select Country</option>
                    </select>

                    <select name="" id="country6" class="form-control">
                        <option value="">Select country</option>
                    </select>

                    <select name="workLocation[]" id="state6" class="form-control">
                        <option value="">Select State</option>
                    </select>

                    <select name="" id="country5" class="form-control">
                        <option value="">Select country</option>
                    </select>

                    <select name="" id="state5" class="form-control">
                        <option value="">Select state</option>
                    </select>

                    <select name="workLocation[]" id="city5" class="form-control">
                        <option value="">Select city</option>
                    </select>

                            <button class="btn btn-primary">Submit</button>
                            <button class="btn btn-secondry">Close</button>

                    </form>

php code
<?php

require 'inc/database.php';
if ( !empty($_POST)) {
    $pfLevel=$_POST['pfLevel'];
    $workLocation=$_POST['workLocation'];

    $pdo = Database::connect();
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

    $sql = "INSERT INTO userworkinfo (intWorkLocation,userPfLevel) values(?,?)";
    $q = $pdo->prepare($sql);
    $q->execute(array($workLocation,$pfLevel));
    Database::disconnect();
    echo '';
}
?>

A: Use select input name with index.
<select name="workLocation[0]" id="counrey7" class="form-control">
    <option value="">Select Country</option>
</select>

<select name="workLocation[1]" id="state6" class="form-control">
   <option value="">Select state</option>
</select>

<select name="workLocation[2]" id="city5" class="form-control">
   <option value="">Select city</option>
</select>


text:
Q: Spaces in java command line argument I've searched but still don't know how to resolve this. I am trying to setup a batch script to run this Java command:
"C:\Program Files (x86)\Java\jre1.8.0_60\bin\"java -cp "AddDocument.jar;Jace.jar;p8cel10n.jar;stax-api.jar;xlxpScanner.jar;xlxpScannerUtils.jar;log4j-1.2.15.jar" java -cp "AddDocument.jar;Jace.jar;p8cel10n.jar;stax-api.jar;xlxpScanner.jar;xlxpScannerUtils.jar;log4j-1.2.15.jar" com.ibm.labservices.AddDocument btd047e p8forHJ!Pecm FileNetP8WSI http://hjipuat/wsi/FNCEWS40MTOM HJIP Sample.iso image/jpeg.AddDocument userid password FileNetP8WSI http://hjipuat/wsi/FNCEWS40MTOM HJIP Sample.iso image/jpeg

Instead of the command running, I get the java help index.

A: Your second " is in the wrong place.  The first part of the command should be:
"C:\Program Files (x86)\Java\jre1.8.0_60\bin\java"

with the " after java not before it.  The complete, correct command is then:
"C:\Program Files (x86)\Java\jre1.8.0_60\bin\java" -cp "AddDocument.jar;Jace.jar;p8cel10n.jar;stax-api.jar;xlxpScanner.jar;xlxpScannerUtils.jar;log4j-1.2.15.jar" java -cp "AddDocument.jar;Jace.jar;p8cel10n.jar;stax-api.jar;xlxpScanner.jar;xlxpScannerUtils.jar;log4j-1.2.15.jar" com.ibm.labservices.AddDocument btd047e p8forHJ!Pecm FileNetP8WSI http://hjipuat/wsi/FNCEWS40MTOM HJIP Sample.iso image/jpeg.AddDocument userid password FileNetP8WSI http://hjipuat/wsi/FNCEWS40MTOM HJIP Sample.iso image/jpeg

If the command still misbehaves after the correction to the pathname, the problem lies with the syntax required by java.exe, not Command Prompt.


text:
Q: Java arrays error (not out of bounds) I'm working on Java via the Codefights website. This is the exercise:

After becoming famous, CodeBots decided to move to a new building and live together. The building is represented by a rectangular matrix of
  rooms, each cell containing an integer - the price of the room. Some
  rooms are free (their cost is 0), but that's probably because they are
  haunted, so all the bots are afraid of them. That is why any room that
  is free or is located anywhere below a free room in the same column is
  not considered suitable for the bots. Help the bots calculate the
  total price of all the rooms that are suitable for them. Example:
  For
matrix = [[0, 1, 1, 2],
          [0, 5, 0, 0],
          [2, 0, 3, 3]]

the output should be matrixElementsSum(matrix) = 9. Here's the rooms matrix with unsuitable rooms marked with 'x':
[[x, 1, 1, 2],
 [x, 5, x, x],
 [x, x, x, x]]

Thus, the answer is 1 + 5 + 1 + 2 = 9.

I understand that I've got to go through all the elements of the array, which is easy. The part I'm hung up on is checking on the "0" rooms above the current element in the array. I know that that position will be matrix[i-1][j], where the current position in the array is matrix[i][j]. But, I'm getting an error "InvocationTargetExeption" when I try to implement this.
My assumption is that I'm asking for negative numbers in the array address, but I'm not sure how to fix this. Here's my code:
int matrixElementsSum(int[][] matrix) {
    int sum = 0;
    for(int i = 0; i < matrix.length; i++){
        for(int j = 0; j < matrix[i].length; j++){
            if(matrix[i-1][j]==0){ sum += 0;}
            else{sum += matrix[i][j];}
                }
        }
    return sum;
}

A: It is an ArrayIndexOutOfBoundsException and you can fix it by replacing:
if(matrix[i-1][j]==0){ sum += 0;}

with:
if(i > 0 && matrix[i-1][j]==0){ sum += 0;}

You're getting it because you're trying to access: matrix[i-1][j] and when i=0 then i-1 = -1...
Running the fixed code on the matrix in the example you provided returned 9 as expected.
The only reason I can think of, that you're seeing an InvocationTargetException is if you invoke matrixElementsSum using reflection: then the method throws an ArrayIndexOutOfBoundsException which is wrapped by InvocationTargetException.
From Method.java docstring:
* @exception InvocationTargetException if the underlying method
*              throws an exception.


text:
Q: Cannot yield even though the return type is IEnumerable Consider the following trivial example:
class Filter<T, U>
    where T : IEnumerable<U>
    where U : IEquatable<U>
{
    private readonly U id;

    public Filter(U id) => this.id = id;

    public T Eval_A(T items)
    {
        foreach (var item in items)
            if (item.Equals(id))
                yield return item;
    }

    public IEnumerable<U> Eval_B(IEnumerable<U> items)
    {
        foreach (var item in items)
            if (item.Equals(id))
                yield return item;
    }
}

Even though T is of type IEnumerable<U>, an error still occurs for T Eval_A(T items) as follows.

The body of 'accessor' cannot be an iterator block because 'type' is not an iterator interface type

MSDN said:

This error occurs if an iterator accessor is used but the return type is not one of the iterator interface types: IEnumerable, IEnumerable<T>, IEnumerator, IEnumerator<T>. To avoid this error, use one of the iterator interface types as a return type.

I think the return type does conforms to the requirement.
What am I missing here?

A: The return type of the method has to be exactly one of IEnumerable, IEnumerable<T>, IEnumerator or IEnumerator<T>, and not T, which is some type that implements IEnumerable<U>.
This is because the way that iterator methods work, is that the compiler generates a type implementing one of the above interfaces, with the MoveNext and Current correctly implemented so that it matches the behaviour of your method, and then it rewrites your method to return an instance of that type instead.
For example, for:
public IEnumerable<int> GetSingleDigitNumbersLoop()
{
    int index = 0;
    while (index < 10)
        yield return index++;
}

The following is generated (seen using SharpLab.io):
[IteratorStateMachine(typeof(<GetSingleDigitNumbersLoop>d__0))]
public IEnumerable<int> GetSingleDigitNumbersLoop()
{
    return new <GetSingleDigitNumbersLoop>d__0(-2);
}

[CompilerGenerated]
private sealed class <GetSingleDigitNumbersLoop>d__0 : IEnumerable<int>, IEnumerable, IEnumerator<int>, IDisposable, IEnumerator
{
    private int <>1__state;

    private int <>2__current;

    private int <>l__initialThreadId;

    private int <index>5__2;

    int IEnumerator<int>.Current
    {
        [DebuggerHidden]
        get
        {
            return <>2__current;
        }
    }

    object IEnumerator.Current
    {
        [DebuggerHidden]
        get
        {
            return <>2__current;
        }
    }

    [DebuggerHidden]
    public <GetSingleDigitNumbersLoop>d__0(int <>1__state)
    {
        this.<>1__state = <>1__state;
        <>l__initialThreadId = Environment.CurrentManagedThreadId;
    }

    [DebuggerHidden]
    void IDisposable.Dispose()
    {
    }

    private bool MoveNext()
    {
        int num = <>1__state;
        if (num != 0)
        {
            if (num != 1)
            {
                return false;
            }
            <>1__state = -1;
        }
        else
        {
            <>1__state = -1;
            <index>5__2 = 0;
        }
        if (<index>5__2 < 10)
        {
            <>2__current = <index>5__2++;
            <>1__state = 1;
            return true;
        }
        return false;
    }

    bool IEnumerator.MoveNext()
    {
        //ILSpy generated this explicit interface implementation from .override directive in MoveNext
        return this.MoveNext();
    }

    [DebuggerHidden]
    void IEnumerator.Reset()
    {
        throw new NotSupportedException();
    }

    [DebuggerHidden]
    IEnumerator<int> IEnumerable<int>.GetEnumerator()
    {
        if (<>1__state == -2 && <>l__initialThreadId == Environment.CurrentManagedThreadId)
        {
            <>1__state = 0;
            return this;
        }
        return new <GetSingleDigitNumbersLoop>d__0(0);
    }

    [DebuggerHidden]
    IEnumerator IEnumerable.GetEnumerator()
    {
        return ((IEnumerable<int>)this).GetEnumerator();
    }
}

<GetSingleDigitNumbersLoop>d__0 is the type that implements IEnumerable<int> that GetSingleDigitNumbersLoop is rewritten to return instead.
Now, if GetSingleDigitNumbersLoop were declared to return some other type, like a type parameter T for example, the following wouldn't work:
public T GetSingleDigitNumbersLoop()
{
    return new <GetSingleDigitNumbersLoop>d__0(-2);
}

Because <GetSingleDigitNumbersLoop>d__0 is not necessarily a T. In fact it almost never would be, because it is a compiler generated type!
See also: yield statement implementation


text:
Q: What is the negative side of 'Remove-SPUser' in SharePoint 2010? I may have to cleanup the inactive users, so thought of using the 'Remove-SPUser' cmdlet as below.
Remove-SPUser -Identity "demo.net\karthik" -Web http://demo.net/testA/testA1/testA1a -Confirm:$false

What is the negative side of  'Remove-SPUser' in SharePoint 2010?

Quick Observations:
I observed that the user permission is removed from the entire site collection('demo.net') instead of the specific web('testA1a') which is fine in my case.
However, how does it differ from the below?
Get-SPSite "http://demo.net" | Get-SPWeb -Limit All | Remove-SPUser -Identity  "demo.net\karthik"

Also, It removes the user profile from the User information list however it does not affect the existing references(like created by/modified by etc)


text:
Q: I need help solving this javascript challenge In this challenge i have to Use arrow function syntax to compute the square of only the positive integers (decimal numbers are not integers) in the array realNumberArray and store the new array in the variable squared Integers .
https://learn.freecodecamp.org/javascript-algorithms-and-data-structures/es6/write-higher-order-arrow-functions
my code so far.
const realNumberArray = [4, 5.6, -9.8, 3.14, 42, 6, 8.34, -2];
const squareList = (arr) => {
  "use strict";
  realNumberArray.filter((arr) => arr !== null && parseInt())
  const squaredIntegers = arr;
  return squaredIntegers;
};

const squaredIntegers = squareList(realNumberArray);
console.log(squaredIntegers);

A: You could take three steps:

*

*Filter intger only numbers with Number.isInteger.

*Filter only positive values.

*Map squared values.

const isPositive = v => v > 0;

const squareList = (arr) => {
  "use strict";
  return realNumberArray
      .filter(Number.isInteger)
      .filter(isPositive)
      .map(v => v * v);
};

const realNumberArray = [4, 5.6, -9.8, 3.14, 42, 6, 8.34, -2];
const squaredIntegers = squareList(realNumberArray);
console.log(squaredIntegers);

A: The function parseInt() does not check if a number is an integer; it converts a string to an integer when applicable.
To check if a number is an integer, you can use Number.isInteger().
In the below snippet, we are filtering out non-integers and negative values, and then computing the squares of all the remaining elements using map() with an arrow function.

const realNumberArray = [4, 5.6, -9.8, 3.14, 42, 6, 8.34, -2];
const squareList = (arr) => {
  "use strict";
  //removing decimals from the passed array
  arr = arr.filter((elem) => Number.isInteger(elem) && elem >= 0);
  //computing the squares
  var squaredIntegers = arr.map((elem) => elem * elem);
  return squaredIntegers;
};

const squaredIntegers = squareList(realNumberArray);
console.log(squaredIntegers);

A: const realNumberArray = [4, 5.6,  -9.8,  3.14,   42, 6, 8.34,  -2];

const squareList = (arr) => {
      "use strict";
      const squaredIntegers = arr.filter( (num) => num > 0 && num % parseInt(num) === 0 ).map( (num) => Math.pow(num, 2) );
      return squaredIntegers;
    };

// test your code
const squaredIntegers = squareList(realNumberArray);
console.log(squaredIntegers)


text:
Q: Can't make a shortcut to work (properly) I made a shortcut for PyCharm following this instruction (created a *.desktop file; before that I launched the application via terminal by sudo sh pycharm.sh comand). However, the shortcut I made doesn't work properly - if I launch it from Dash the application will be launched but will not work and freeze. The same will happen if I launch application via terminal by sh pycharm.sh. But, if I launch the application via terminal with sudo sh pycharm.sh comand, close it and then use shortcut, everything will work smoothly.
How can I make the shortcut work properly?

A: Replace sudo in the .desktop file with gksudo.
This is because sudo cannot ask you the password outside the terminal, but the command needs sudo access so it freezes on the sudo step (apparently still waiting for the password).
gksudo will graphically prompt you for the password.
Update: To execute without password:
We need to set nopasswd on that script.

*

*Edit /etc/sudoers with the command sudo visudo /etc/sudoers

*Add the line:
%sudo ALL=NOPASSWD: /full/path/to/script.sh

Replacing /full/path/to/script.sh with the actual full path.

*Save (Ctrl+O) and quit (Ctrl+X).

Now you should be able to run it without password. Also, you can now even use sudo instead of gksudo.


text:
Q: Python socket, with proxy? I'm developing a function to check the ssl certificate of applications that we use. I developed the following function that is working, but I need it to work using a proxy server, because on the server where the app will be hosted I don't have direct connectivity to all the links I need to monitor. Would anyone know how I can do this connection created via socket go through a proxy?
import validators
from urllib.request import ssl, socket
from datetime import datetime
import logging

def verify_ssl(url):
    data_ssl = []
    dicio = {}
    try:
        test_url = validators.url("https://"+url)
        if test_url is True:
            hostname = url
            context = ssl.create_default_context()

            with socket.create_connection((hostname, "443")) as sock:
                with context.wrap_socket(sock, server_hostname = hostname) as ssock:
                    certificate = ssock.getpeercert()

                dicio ["url"] = hostname
                date = datetime.strptime(certificate["notAfter"], '%b %d %H:%M:%S %Y %Z')
                dicio ["notAfter"] = date.strftime("%d/%m/%Y")
                subjectAltName = certificate["subjectAltName"]
                y = 0
                san = []
                while y < len(subjectAltName):
                    san.append((subjectAltName[y][1]))
                    y += 1
                dicio ["subjectAltName"] = san
                dicio ["issuer"] = dict((y,z) for y,z in certificate["issuer"][len(certificate ["issuer"])-1])['commonName']
                dicio ["local"] = 'Manual'
                # dicio ["cadastrada"] = checkUrl(url,'prod')
            data_ssl.append(dicio)

        else:
            logging.error(f'{url}')
            dicio ["url"] = url
            dicio ["notAfter"] = 'Error'
            dicio ["subjectAltName"] = 'Error'
            dicio ["issuer"] = 'Error'
            dicio ["local"] = 'Manual'
            dicio ["cadastrada"] = 'Error'
            data_ssl.append(dicio)

    except Exception as e:
        logging.error(f'{url} - {e}')
        dicio ["url"] = url
        dicio ["notAfter"] = 'Error'
        dicio ["subjectAltName"] = 'Error'
        dicio ["issuer"] = 'Error'
        dicio ["local"] = 'Manual'
        dicio ["cadastrada"] = 'Error'
        data_ssl.append(dicio)
    return data_ssl