text:
Q: How to Quickly Replace a Parameter in a Piped Command Chain Question
Let's say I just entered this command to get a count of how many lines contain a particular string:
me@machine $ command-producing-multi-line-output | grep -i "needle" | wc -l

Now how could I quickly replace "needle" with some other word?

Current Inefficient Solution
Right now I:

*

*Press Up on the keyboard to load the last command.

*Press Left or Ctrl+Left until I reach "needle".

*Press Backspace or Ctrl+w to delete the word.

*Type or paste in the new word.

*Hit Enter.

This seems pretty inefficient.

Attempted Non-working Solutions
I've tried to research history shortcuts like !!:sg/needle/new-needle; but there are a few problems with this:

*

*You can't press Up to put !!:sg/needle/new-needle back on the command line. Doing this will just show what it expands to (running right back into the original problem).

*Repeating this with yet another new needle requires you to replace both needle and new-needle (i.e. !!:sg/new-needle-from-before/yet-another-new-needle).

*You need to type the entire needle instead of using something like !:4 or $4 (i.e. !!:sg/!:4/new-needle or !!:sg/$4/new-needle) to save time/keystrokes on however long the needle was.

I've also found things like !:^-3 "new-needle" !:5-$ but that also has issues:

*

*It expands in history so it can't be re-used quickly.

*Even if it didn't expand, you run into the original problem of needing to replace a word in the middle of a command chain.

I believe there has to be some super fast way to do what I want to do, and that some linux gurus out there know it. I would be very grateful for any input or suggestions on this.

EDIT:
Background
Just a bit of background, I work a lot with OpenStack on the command line and I find myself often needing to replace a parameter in several places within a long command chain of piped commands.
The way our OpenStack environments are configured, several engineers share a single stack user on any number of servers, and there are several clusters within multiple environments. So a function declared within .bashrc or .profile file isn't really possible.
I'm hoping for something portable that can be used quickly with no or very minimal setup required. Otherwise I may just need to resort to using a solution outside of the shell entirely (such as clipboard replacement in AutoHotKey/Keyboard Maestro/AutoKey, etc.).

A: A useful alias in bash is
alias r='fc -s'

The r command is often found in other shells by default1, and repeats the most recent command in history.  The bash manual even refers to this as a useful alias to define:
[...]  A useful alias to use with this is ``r="fc -s"'',
so that typing ``r cc'' runs the last command beginning with
``cc'' and typing ``r'' re-executes the last command.

It will also allow you to do replacements in the text of the last command.
Here I'm running your command, then I use the above alias to replace the word needle with the word haystack:
$ command-producing-multi-line-output | grep -i "needle" | wc -l
bash: command-producing-multi-line-output: command not found
       0

$ r needle=haystack
command-producing-multi-line-output | grep -i "haystack" | wc -l
bash: command-producing-multi-line-output: command not found
       0

When I use r needle=haystack on the command line, the shell print out the command it's going to run and then immediately runs it.  As you can see, it also replaces the word.
The errors are obviously due to me not having a command-producing-multi-line-output command, but that's not important in this exercise.

The fc command won't get saved to your history, but you can make it get saved by creating it as a shell function like this:
fc() {
    command fc "$@"
    history -s fc "$@"   # append the given fc command to history
}

You may then do
$ command-producing-multi-line-output | grep -i "needle" | wc -l
bash: command-producing-multi-line-output: command not found
       0

Rerun the most recent command starting with comm and replace needle using r needle=haystack comm:
$ r needle=haystack comm
command-producing-multi-line-output | grep -i "haystack" | wc -l
bash: command-producing-multi-line-output: command not found
       0

Rerun the most recent command, but replace haystack, using r haystack=beeswax:
$ r haystack=beeswax
fc -s needle=beeswax comm
command-producing-multi-line-output | grep -i "beeswax" | wc -l
bash: command-producing-multi-line-output: command not found
       0

Note the double call that gets made to fc in that last line, first through our alias r and then through our function fc.
Obviously, saving the fc command to history makes you run the risk of accidentally calling fc -s recursively.

1In zsh it's a built-in command, in OpenBSD ksh it's a default alias for fc -s, in ksh93 it a default alias for hist -s, etc.

A: The OP says that a function declared in .bashrc is not practical, but there is nothing stopping declaring one interactively. As this is for just the current session a single letter name is suitable, e.g. q.
Starting with
$ command-producing-multi-line-output | grep -i "haystack" | wc -l

press Up ;} to end a function, edit the haystack to $1, Control+aq(){Space to get
q(){ command-producing-multi-line-output | grep -i "$1" | wc -l;}

then you can use q needle, q haystack, q something. I prefer this over the while solution in the currently accepted answer as it allows other commands in-between the searching/counting.
For this particular case I would actually define
q(){ command-producing-multi-line-output | grep -i "$@";}

as I would probably want to see the actually matching lines at some stage, so I could use q needle | wc -l or the better q -c needle to count, and q needle to see the lines.
As the function definition is going to be stored in the bash history, it is usually possible to reload the definition if it is needed in a future session.

A: Summary: Ctrl+R nee Alt+D haystack Enter
Press Ctrl+R to start a reverse incremental search and type a few characters of the text you want to replace (or some text very close to it) until the desired part of the desired command line appears (it doesn't have to be the previous command line). Press Ctrl+R to search for the previous occurrence. Press Ctrl+S to go forward if you've gone back too far. Press Backspace if you've mistyped a character.
Once you've reached the place you want, you can use keys like Delete, Alt+D or Alt+Backspace to start deleting text around the cursor, or just Escape to exit the incremental search at the point you've reached.
Press Enter only when you've finished editing the command line. Note that Enter during an incremental search has its normal meaning to execute the current command line as it is: it doesn't just exit search mode (press Escape to just exit search mode).

A: That's exactly what history expansion is for:
$ command-producing-multi-line-output | grep -i "needle" | wc -l
...
$ ^needle^nipple
command-producing-multi-line-output | grep -i "nipple" | wc -l
...

A: I've run into a similar situation and present my solution here just in case it's a useful pattern.
Once I realize that I'm repeatedly changing one piece of data that's annoying to replace interactively, I'll stop and write a little while loop:
$ command-producing-multi-line-output | grep -i "needle" | wc -l
0
$ command-producing-multi-line-output | grep -i "haystack" | wc -l
0
$ while read needle; do

Up-Arrow to the previous command-producing-multi-line-output line and replace "haystack" with "$needle"
command-producing-multi-line-output | grep -i "$needle" | wc -l; done
something
0
something else
0
gold
1

(ending with Control+D)
Or the slightly fancier variation:
$ while read needle; do
printf 'For: %s\n' "$needle"
command-producing-multi-line-output | grep -i "$needle" | wc -l; done

If I see a future for this command-line beyond "today", I'll write it into a function or script.

A: Open a proper editor which is built for this stuff. By default, you can do this with Ctrl-x Ctrl-e, though if you have enabled vi editing mode (one way is set -o vi), you can also use Esc v.
Once there, use your editor's substitution command. In vi(m), e.g.,
:%substitute/needle/haystack/g

A: In these situations I often use an environment variable for the parameter as follows:
ARG1=needle; command-producing-multi-line-output | grep -i "${ARG1}" | wc -l

The first assignment sets an environment variable which can then be used in subsequent commands.  This serves as the parameter which can be changed as needed.  Note this will set an environment variable for the life of this shell, but I have found for quick, specific commands this is ok. The usual rules apply for variable expansion, such as single quotes '${ARG1}' will not expand the variable.  General information can be found on this (here is one) https://www.gnu.org/software/bash/manual/html_node/Quoting.html

A: I find myself using fzf for this.
If you're willing to install something like fzf, and your output is normally less than a screen, try this:
echo | fzf -q 'shuf < /usr/share/dict/words | grep needle | head' --preview-window=up:99% --preview="eval {q}"

Once the output pops up, cursor to the end of the word "needle", hit Ctrl-W and type haystack.  Then hit Ctrl-W again and type some other word.  And so on.
However, I would not advise this for any commands that change the system :-)  You're using fzf's preview feature to run the command, and fzf attempts to run it as soon as anything changes.  For example, when you hit Ctrl-W you'll see grep showing it's usage message because momentarily, until you type the first character of the replacement word, there is no argument to it.
I use this so often I have a script called try, which is basically this:
#!/bin/bash

export FZF_DEFAULT_COMMAND=echo
fzf -q "$*" --preview-window=up:99% --preview="eval {q}"


text:
Q: Why in IntentService super.OnCreate delete a notification startForeground() I'm continuing in the Android studies and i've a questions.
I'have this intentService:
public class SystemService extends IntentService{
    public SystemService() {
       super("SystemService");
    }

    public int onStartCommand(Intent intent, int flags, int startId) {
       super.onStartCommand(intent, startId, startId);
       return(START_NOT_STICKY);
    }

    @Override
    public void onCreate(){
        super.onCreate();
        startForeground();
    }

    @TargetApi(Build.VERSION_CODES.JELLY_BEAN)
    private void startForeground(){
    Intent notificationIntent = new Intent(this, DashboardActivity.class);
    PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);
    Notification noti = new Notification.Builder(getApplicationContext())
            .setContentTitle("Foregroundservice")
            .setContentText("foreground is active")
            .setSmallIcon(R.mipmap.ic_launcher)
            .setContentIntent(pendingIntent).build();
    startForeground(1337, noti);
    }
}

Why, in onCreate() function,  if I put the function startForeground() so, ne initializing foregroundservice before the super.onCreate(), the foreground notify disappear But if a put after seem work?

redpajama_set_name: RedPajamaStackExchange


text:
Q: How the non-sticky format properties are reset? Consider the following code:
class C{};

std::ostream &operator <<(std::ostream &o, const C &) {
    o.fill('!');
    o.width(8);
    return o << 42;
}

int main() {
    std::cout << C{} << '\n';
    std::cout << 42 << '\n';
    return 0;
}

It outputs:

!!!!!!42
42

I was expecting !!!!!!42 twice because I've changed the state of the provided std::ostream o calling fill and width inside the operator <<, so I used to think that the fill character and the width setted into the operator would leak outside the operator call as if they were sticky properties.
As you can see I don't flush the stream nor re-set the fill character or width so, why (and how) the original behaviour is preserved?
So the question is: How the properties of the ostream are setted back to the previous state after the call to my operator<< for class C?

This doesn't bothers me, I'm happy with this behaviour but I want to understand how it works.

A: As underscore_d mentioned: width isn't sticky. But actually there is no such attribute stickiness for the iostream classes and their manipulators.
Though, if width would not have been reset by the previous << operator call, the width would also affect the output of \n:
std::cout << std::setw(10) << std::setfill('!') << 42 << '\n';
std::cout << std::setw(10) << std::setfill('!') << 42 << std::setw(10) << '\n';

gives
!!!!!!!!42
!!!!!!!!42!!!!!!!!!

.


text:
Q: How to make a gridView command field button into an ajax update panel PostBackTrigger I have a gridview in an ajax  update panel. I have set the different button events as AsyncPostBackTriggers but I want the select button to open a child web page so it has to be a postback. I tried the following:
<Triggers>
      <asp:AsyncPostBackTrigger ControlID="gvClients" EventName="RowCancelingEdit" />
      <asp:AsyncPostBackTrigger ControlID="gvClients" EventName="RowEditing" />
      <asp:AsyncPostBackTrigger ControlID="gvClients" EventName="RowUpdated" />
      <asp:AsyncPostBackTrigger ControlID="gvClients" EventName="RowUpdating" />
      <asp:AsyncPostBackTrigger ControlID="gvClients" EventName="Sorted" />
      <asp:AsyncPostBackTrigger ControlID="gvClients" EventName="Sorting" />
      <asp:PostBackTrigger ControlID="gvClients" />
</Triggers>

I recieved the following error:" System.ArgumentException: Control with ID 'gvClients' cannot be registered through both RegisterAsyncPostBackControl and RegisterPostBackControl. This can happen if you have conflicting triggers associated with the target control."
I tried accessing the select button from code behind and setting it as a trigger.
This is the code:
   protected void gvClients_RowDataBound(object sender, GridViewRowEventArgs e)
    {
       if (e.Row.RowType == DataControlRowType.DataRow)
        {
            Button btnDtls = (Button)e.Row.Cells[0].Controls[2];
            string btnDtlsId = btnDtls.ID;
            PostBackTrigger trigger = new PostBackTrigger();
            trigger.ControlID = btnDtlsId;
            UpdatePanel1.Triggers.Add(trigger);
        }
    }

In debugging I saw that the ID for the button is "ctl01" but I'm getting this error: "A control with ID 'ctl01' could not be found for the trigger in UpdatePanel 'UpdatePanel1'". Is there a way of accessing a control field select button and setting it as a PostBackTrigger?

A: Since the button is inside a template, its final id is different and you can get it from the UniqueID property.
http://msdn.microsoft.com/en-us/library/system.web.ui.control.uniqueid.aspx


text:
Q: Javascript function: use newlines as \n instead of actually rendering them I am working on a function that receives text from a textarea input with an aim of retaining newline characters. The function then takes the text as an argument to the function, for example: function get_text(val){ ... }.
The value being received from the textarea is:
$('#textarea').val();

Such that on the click of a button, the value in the textarea is passed to the get_text() function, for example:
$('#button').click(function(){
    get_text($('#textarea').val());
});

Then the function is meant to use the newline characters which are retained since the value is from a textarea.
But here is where the problem comes in, when I pass the value of the textarea to the get_text() function, I get an error in the console stating: Unexpected identifier because the argument has been split over a few lines, for example:
If the text in the input is:
(Line 1)My
(Line 2)text
(Line 3)is
(Line 4)here
The function takes the text and outputs the newline characters:
get_text("My   --- (×)Error appears here
text
is
here");

I'm trying to use the newline characters from the textarea in the function which performs some task after every newline character is encountered, so getting rid of the newlines is not an option unless there is another way to perform the task.
The only problem here is actually passing the text into the function, for example:
get_text($('#textarea').val());
--- should result to ---
get_text('My\ntext\nis\nhere');
--- instead of actually outputting the newlines ---

Which works well with the function.
Is there a way to pass the text to the function without printing the newlines but instead show them as \n ?
This is the get_text function:
function get_text(val){
let n = /[\n]/;
let i;
let inner = [];
for(i = 0; i < val.length; i++){
inner.push('' + val[i] + '';
if(n.test(val[i]) == true){
inner.push('' + val[i] + '';
}
}
return inner.join("");
}

And again, the problem is not even in the function, it is only when the value is passed to the function, it gets split into lines ... and no, I am not using eval
Yes I get the error only after getting it from a form

A: MDN Template Literals
Template literal syntax allows your string to span multiple lines using the ` backticks as the container, which should avoid your problem.  I would still recommend escaping the string and/or not mixing the server-side templating code and JavaScript code like that, especially not embedding form data as JS code verbatim.  You can at least serialize it with json_encode or something similar.
You could also use JSON.stringify of the form data, and then JSON.parse it afterwards.
let val = `My
test
is
here`;

get_text(`My
text
is
here`);

You're missing parens and you're not using .test right.  It takes the string, not a boolean comparison, and returns a boolean if it matches.
Also, if you want line breaks you should be using
.  Putting a newline in a  will  just collapse.  It will not insert a line break in the rendered output.  Unless you're using some CSS style like a float break that does the line break for you.

function get_text(val) {
  let n = /[\n]/;
  let i;
  let inner = [];
  for (let i = 0; i < val.length; i++) {
    inner.push('' + val[i] + '');
    if (n.test(val[i])) {
      inner.push('' + val[i] + '');
    }
  }
  return inner.join("");
}

console.log(
  content.innerHTML = get_text(`My
text
is
here`)
)
.newline::after {
  content: '\\n'
}

A: You can simply replace them with the backslash (\) and n characters literally.
To create a \ in a literal, escape it with itself, i.e. \\.
So,
$('#textarea').val().replace(/\n/g, '\\n')


text:
Q: Unable to access hivemq broker from raspberry pi I want to use hivemq
as an online broker for my IOT projects BUT the problem is I am unable to connect with hiveMQ from my raspberry pi. I am even unable to open hiveMQ website from my raspberry pi.
I tried subscribing to hiveMQ broker using this basic python script

import paho.mqtt.client as mqtt

MQTT_HOST = "broker.mqttdashboard.com"

MQTT_PORT = 1883

MQTT_KEEPALIVE_INTERVAL = 5

MQTT_TOPIC = "testTopic"

def on_connect(mosq, obj, rc):
    mqttc.subscribe(MQTT_TOPIC, 0)

def on_subscribe(mosq, obj, mid, granted_qos):
    print("Subscribed to MOTT Topic...")

def on_message(mosq, obj, msg):
    print(msg.payload)

mqttc = mqtt.Client()

mqttc.on_message = on_message

mqttc.on_connect = on_connect

mqttc.on_subscribe = on_subscribe

mqttc.connect(MQTT_HOST, MQTT_PORT, MQTT_KEEPALIVE_INTERVAL)

mqttc.loop_forever()

BUT IT IS THROWING AN ERROR:
Traceback (most recent call last):

File "subscriber.py", line 23, in <module>
    mqttc.connect(MQTT_HOST, MQTT_PORT, MQTT_KEEPALIVE_INTERVAL)

File "/usr/local/lib/python3.4/dist-packages/paho/mqtt/client.py", line 686, in connect
    return self.reconnect()

File "/usr/local/lib/python3.4/dist-packages/paho/mqtt/client.py", line 808, in reconnect

    sock = socket.create_connection((self._host, self._port), source_address=(self._bind_address, 0))

File "/usr/lib/python3.4/socket.py", line 509, in create_connection
    raise err

  File "/usr/lib/python3.4/socket.py", line 500, in create_connection
    sock.connect(sa)

OSError: [Errno 113] No route to host

on the other hand i also subscribed to my local MOSQUITTO broker using the same python script just by changing the HOST to the ip of my local machine and it was working fine...


text:
Q: Why does empty Bitbucket repo "contain work" that I "do not have locally"? I have a project on my system that I want to store on Bitbucket. I created the empty project on Bitbucket (with a Readme), and then did the following commands in the root of my project:
git init
git add --all
git commit -m "Initial commit"
git remote add origin <path-to-repo>
git push -u origin --all

I got these commands from this link
It gave me the error that Updates were rejected because the remote contains work that you do not have locally. It suggests doing git pull but I'm worried that if I do that it will erase the work I have locally.
What should I do here?

A:
It gave me the error that Updates were rejected because the remote contains work that you do not have locally. It suggests doing git pull. What should I do here?

Do what it says. git pull.

I'm worried that if I do that it will erase the work I have locally.

Well, stop worrying. This is git. Once committed, nothing is ever, ever lost.

Why does empty Bitbucket repo "contain work" that I "do not have locally"?

Well, you told us the answer to that yourself: It isn't empty! "With a Readme," you said. Do you have the Readme locally? No, you don't. So the Bitbucket repo contains work you do not have locally.

EDIT So the problem with the instructions you tried to follow is that those instructions assume your Bitbucket repo is empty — and we have already established that it isn't. Well, in git push -u, the point of the u is to associate your master branch with Bitbucket's master branch. You need to do that in order to push or pull, and you are allowed to do it the first time you push. Okay, but git push -u only works if you can push. But you can't push because you have not pulled the Readme. And you can't pull the Readme because git push -u didn't succeed! Catch-22!!
The solution is to intervene manually by saying (while on master):
git branch -u origin/master

Now you have formed the necessary association, and so you can just git pull and git push plain and simple and all will be well.


text:
Q: Inserting elements with foreign keys to Database by bulk insert with SqlBulkTools I use SqlBulkTools   library for inserting and updating lot of data to my database.
It works great when used with classes like in the example shown in documentation:
Example class:
public class Book {
    public int Id { get; set; }
    public string ISBN { get; set; }
    public string Description { get; set; }
}

And inserting to the database:
bulk.Setup<Book>(x => x.ForCollection(books))
    .WithTable("Books")
    .AddColumn(x => x.ISBN)
    .AddColumn(x => x.Title)
    .AddColumn(x => x.Description)
    .BulkInsert()

but my class is not so simple and it has foreign keys to another elements, eg. it could looks like this:
public class Book {
    public int Id {get; set;}
    public string ISBN {get; set;}
    public string Description {get; set;}
    public Author BookAuthor (get;set;}
}

and in database I have column Author_KeyId and separate table Author.
I was trying to insert it like this:
bulk.Setup<Book>(x => x.ForCollection(books))
        .WithTable("Books")
        .AddColumn(x => x.ISBN)
        .AddColumn(x => x.Title)
        .AddColumn(x => x.Description)
        .CustomColumnMapping(x => x.BookAuthor.KeyId, "Author_KeyId")
        .AddColumn(x=>x.BookAuthor.KeyId)
        .BulkInsert()

but it not works. It looks like only property can be added...
maybe someone already used this very useful library and can help me with this problem?

A: That's because the insert query SqlBulkTools is building likely looks something similar to this:
INSERT INTO Books
(
    ISBN,
    Title,
    Description,
    Author_KeyId
)
SELECT
    ISBN,
    Title,
    Description,
    KeyId
FROM #Temp;

...with the query breaking on the second-to-last line, because class Book doesn't have a KeyId property. You're giving CustomColumnMapping() an expression evaluating to an integer; it's not going to have any clue where it came from.
The best solution would be to create a data transfer object representation of Book that has the Author_KeyId property, then translate your collection to that new class.
BookDTO:
public class BookDTO {
    public int Id { get; set; }
    public string ISBN { get; set; }
    public string Description { get; set; }
    public int Author_KeyId { get; set; }
}

Translate (using LINQ; this is just one possible method):
List<BookDTO> bookDtos = (from b in books
                         select new BookDTO
                         {
                             Id = b.Id,
                             ISBN = b.ISBN,
                             Description = b.Description,
                             Author_KeyId = b.BookAuthor.KeyId
                         }).ToList();

Finally, the bulk insert:
bulk.Setup<BookDTO>(x => x.ForCollection(bookDtos))
    .WithTable("Books")
    .AddAllColumns()
    .BulkInsert();


text:
Q: Autosave content of TinyMce editor on change event (with laravel 7)? I want to autosave the content of tinyMce editor
I'm using tinmce version 5.2.2 with laravel V7
tinymce configuration in app.js
require('./bootstrap');
require('tinymce/themes/silver');
require('tinymce/plugins/image');
require('tinymce/plugins/code');
require('tinymce/plugins/save');

import tinymce from 'tinymce';
tinymce.init({

        selector:'textarea#inputQuestionTitle',
        height:400,
        setup: function(editor) {
                editor.on('Change Keyup', function () {
                            editor.save();
                            //tinyMCE.triggerSave()   <-- also tried
        });
    }

With following View
@extends('dashboard.layout')
@section('content')

<form id='addQ' action="{{route('questions.store')}}" method="post" enctype="multipart/form-data" >
@csrf

        Title
        <textarea  name="title" class="form-control mb-2 " id="inputQuestionTitle" placeholder="Question Title"> </textarea>

        <button type="submit" class="btn btn-primary mb-2">Add new category </button>

</form>

@endsection

Outputs

I had using jquery to show input request with console.log
As showed in output title field does not returns any value
Please tell me how i autosave the content of tinymce editor and send it with input request ..
I had also tried to tinymce.triggerSave() before serialize() method of  ajax so that input request will take tinymce content but not works

A: Instead of trying to update the textarea via the triggerSave() or save() methods while someone is editing the content I would just place tinymce.triggerSave() at the very beginning of the function that submits the page.  This will ensure that the triggerSave() is called directly before you grab the content from the textarea.


text:
Q: Problem using the prependTo() in jQuery I am having a problem trying to use the prependTo() function in jQuery... for some reason I can't get this to work
$("

1 minute ago

ñasdas dasdasdasd conclusión

").prependTo(".notes").fadeIn("slow");

Although when doing it like this, it works fine
$.ajax({
  url:'/chart-notes/show/<cfoutput>#chartnote.id#</cfoutput>',
  success: function(data) {
   $(data).prependTo(".notes").fadeIn("slow");

   // Scroll to the top of the annotations
   $('html, body').animate({scrollTop: $(".notes").offset().top}, 1000);

   // Clear the form
   $('#chartnote-notes').val("");
  }
 });

The "data" response from that success function is the same

1 minute ago

ñasdas dasdasdasd conclusión

As before

A: Also, IIRC, you have to set "display: none" for #note178 before calling fadeIn, otherwise you won't see any fade effect.

A: Try this one.
$("
 "+
"

 "+
"
1 minute ago
 "+
"
ñasdas dasdasdasd conclusión
  "+
"
").prependTo(".notes").fadeIn("slow");

You need to escape the double quotes and you cannot have literal new lines in javascript strings. thus the following syntax which concatenates multiple strings.
"..." +
"..." +
"..."

A: Try changing all of the double quotes inside of the main $("...") to single quotes. For example, 'note178'

A: A JavaScript string cannot literal newlines.
alert("12
       34");

Gives the error: unterminated string literal


text:
Q: How to create multiple borders on an img? I want to add multiple borders on a single image. Is this possible through CSS?
Example: http://imageshack.us/photo/my-images/31/multiplebg.jpg/

A: At the moment it's not possible to make more than one border in CSS. You can kind of fake having three borders by using some clever css3 shadowing techniques.
div
{
    margin: 10px;
    border: 2px solid #f00;
    box-shadow:inset 0px 0px 2px 2px #0f0, 0px 0px 2px 5px #00f;
}

But I'd just go with adding the borders to the image as this isn't supported by IE. (Maybe IE9 supports it.)

A: Nest your   inside multiple container and apply border to each

Then apply border to each like
#b1 { border: 1px #000 solid; }
#b2 { border: 1px #f00 solid; }
#b3 { border: 1px #0f0 solid; }
img { border: 1px #00f solid; }

Or
Use a image that has multiple border on it and using border-image property

A: Easy, using CSS3 this is a very simple problem to solve.
If using 'outline' fits your particular situation don't be afraid to use it.
http://tinkerbin.com/tCGF0mfW

A: yes possible mite....
See Here
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>

A: Shadow is not yet cross-browser friendly.
The simplest (and cross-browser friendly) way is to use a combination of padding and border.
Example:
<img src="<path>" class="doubleBorder" />

And the CSS:
.doubleBorder {
padding: 10px; background: orange;
border: 5px solid green;
}

Hope this helps.


text:
Q: Update dataTable (using lazy loading) from another component I'm using lazy loading with pagination in a dataTable, and works fine. The problem is that I have an advanced search functionality in the same html page, and when I click on the search button, I want my dataTable to be updated according to the values I entered in the advanced search fields (this functionality is implemented at DaoFactory.getDocumentoDao().buscarLazy(first, pageSize),
the code is below. But the update attribute at my button doesn't seem to do anything becouse the load method of the lazy model is not called. So the question is: can I somehow call the load method of the lazy model from outside of the model in order to have my dataTable updated?
FORM:
<h:form id="frmCli">
    <p:commandButton value="Buscar"
                     update="frmCli:panelResultadosDoc"/>
    <h:panelGroup id="panelResultadosDoc">
        <div class="dataTable">
            <p:dataTable id="documentos"
                         value="#{documentoBuscadorBean.lazyModel}"
                         lazy="true"
                         var="varDocBean"
                         paginator="true"
                         paginatorPosition="bottom"
                         paginatorAlwaysVisible="false"
                         rows="5">
                <p:column>
                   <f:facet name="header">Código</f:facet>
                   <h:outputText value="#{varDocBean.documento.id}"/>
                 </p:column>
            </p:dataTable>
        </div>
    </h:panelGroup>
</h:form>

BEAN CONTAINING THE MODEL:
@ManagedBean
@SessionScoped
public class DocumentoBuscadorBean {

   private LazyDataModel<DocumentoBean> lazyModel;

   @SuppressWarnings("serial")
   public DocumentoBuscadorBean() {

      lazyModel = new LazyDataModel<DocumentoBean>() {

      public List<DocumentoBean> load(int first, int pageSize, String sortField, boolean sortOrder, Map<String,String> filters) {
            List<DocumentoBean> lazyListDocumentos = new ArrayList<DocumentoBean>();
               try {
                  lazyListDocumentos = DaoFactory.getDocumentoDao().buscarLazy(first, pageSize);
             } catch (DocumentoException e) {
                e.printStackTrace();
             }
               return lazyListDocumentos;
           }
         };
         lazyModel.setRowCount(DaoFactory.getDocumentoDao().rowCount());
         lazyModel.setPageSize(5);
   }
   public LazyDataModel<DocumentoBean> getLazyModel() {
      return lazyModel;
   }

}

A: If I'm not missing something, you could just use action:
<p:commandButton value="Buscar"
                 action="#{documentoBuscadorBean.lazyModel.load(0,10,...)}"
                 process="@form"
                 update="frmCli:panelResultadosDoc"/>

It would be better to add parameterless version of load so you don't mix logic in your view. This is even mandatory if you cannot use EL 2.2 for some reason (I strongly recommend EL 2.2 though, saves you a lot of ugly f:param handling).

A: What does it mean #{varDocBean.documento.id}? varDocBean is a DocumentoBean - so documento is a property of DocumentoBean?
Also, what commandButton doesn't do anything? I see only one commandButton but without action method.
You should take a look(again) at the lazy dataTable in Primefaces lab showcase: http://www.primefaces.org/showcase-labs/ui/datatableLazy.jsf


text:
Q: Use count() operator en SQL Query I do a query in the following way:
SELECT * FROM frequency WHERE docid = '10398_txt_earn' AND count = 1
UNION
SELECT * FROM frequency WHERE docid = '925_txt_trade' AND count = 1;

With a correct output
docid   term    count
10398_txt_earn  100     1
10398_txt_earn  11340   1
10398_txt_earn  12  1
10398_txt_earn  1204    1
10398_txt_earn  198485  1
10398_txt_earn  20  1
10398_txt_earn  27  1
10398_txt_earn  28  1

And now I want to compute the number of rows in the result with the COUNT() operator but I don't know to apply it.  Thanks in advance
Ubuntu14.04
SQLite with XAMPP

A: Are you looking for this?
select count(*)
FROM (SELECT * FROM frequency WHERE docid = '10398_txt_earn' AND count = 1
      UNION
      SELECT * FROM frequency WHERE docid = '925_txt_trade' AND count = 1
     ) t;

By the way, you can write your original query more efficiently as:
SELECT *
FROM frequency
WHERE count = 1 and (docid in  '10398_txt_earn', '925_txt_trade');

The count is then:
SELECT count(*)
FROM frequency
WHERE count = 1 and (docid in  '10398_txt_earn', '925_txt_trade');

A: You can do:
SELECT COUNT(1)
FROM
(
  SELECT * FROM frequency WHERE docid = '10398_txt_earn' AND count = 1
  UNION
  SELECT * FROM frequency WHERE docid = '925_txt_trade' AND count = 1
) a

Since you used a 'UNION', your results will remove duplicates. If you want to include all records (including any duplicates), then use a UNION ALL instead of a UNION.


text:
Q: Expectation of a Standard Normal Variable Let Y be a standard normal variable, and $b$ a non-random real number. Calculate
$E((Y − b)^+)$ , where $(Y − b)^+$ is the positive part of $Y − b$
So $(Y - b)^+ = (Y - b)$ if $Y ≥ b$ ;
$0$ if $Y < b$

A: Let $Y$ be a random variable with density $f_Y$ then for each measurable function $g$ it holds: $$E[g(Y)] = \int_{-\infty}^\infty g(x)\,f_Y(x) dx$$
In your case $g(x) = (x-b)^+$ and $f_Y(x) = \frac{1}{\sqrt{2\pi}} e^\frac{-x^2}{2}$
So you have to calc:
$$E[(Y-b)^+] = \frac{1}{\sqrt{2\pi}}  \int_{-\infty}^\infty (x-b)^+ \frac{1}{\sqrt{2\pi}} e^\frac{-x^2}{2} dx = \int_b^\infty (x-b) e^\frac{-x^2}{2}dx$$
You can solve that integral by your own…


text:
Q: Adding links in Excel with macro i have script which is doing wright thing for me, but I can use it just in single cell.
    Sub Macro1()
'
' Macro1 Macro
'
Dim CName As String

CName = ActiveCell
'
    ActiveSheet.Hyperlinks.Add Anchor:=Selection, Address:= _
        "SWFdataEN\DOKUMENTE\C00\04%20TB031\" & CName, TextToDisplay _
        :=CName
End Sub

It is adding link to filename which is written in this cell (CName) and sets TextToDisplay in same name (CName).
How can I apply this macro in next cell in column (like i hit enter and run macro again) automatically? I tried with For-Next loop, but no good results. Script always puts link of same first filename, but TextToDisply is correct.
Help please

A: I've worked out this:
In a public module, you insert your macro:
Sub sofMacro1()
'
  Dim CName As String

  CName = ActiveCell
'
  If (CName <> "") Then
    ActiveSheet.Hyperlinks.Add Anchor:=Selection, Address:= _
      "SWFdataEN\DOKUMENTE\C00\04%20TB031\" & CName, TextToDisplay _
      :=CName
  End If
'
End Sub

Then in the current Worksheet, you add an event handler:
Private Sub Worksheet_SelectionChange(ByVal Target As Range)
  sofMacro1
End Sub

It adds a Hyperlink to any cell that contains text (not empty), when you move your cursor anywhere in the ActiveSheet.


text:
Q: NodeJS: Auto-catch errors in Promise and call reject I recently found myself in a situation very difficult to debug.
Imagine the following very simple situation:
function somePromise() {
    return new Promise((resolve, reject) => {
        SomeModule.someMethod();
        AnotherModule.somePromise().then(resolve).catch(reject);
    });
}

Resolve was never called, but I didn't get an error in the console - this was difficult to debug!
Turns out that I forgot to require SomeModule. After requiring it, the code worked as expected.
Is there a way to automatically try/catch every Promise in my code with an error handler? I don't want to surround the body of my Promises with a try/catch block just to be able to find such errors more easily in the future.
Thanks in advance for opinions!

A:
Is there a way to automatically try/catch every Promise in my code with an error handler?

This is implicitly done by the Promise constructor already. If the callback throws an exception synchronously, the promise will reject.
However, you really should avoid the Promise constructor antipattern! Use
function somePromise() {
    SomeModule.someMethod();
    return AnotherModule.somePromise();
}


text:
Q: База данных MNIST Работаю над нейронной сетью по распознованию цифр, для обучение использую базу данных MNIST, требуется доучить нейронною сеть - не могу найти как самому написать похожую базу со своими обучающими примерами как в MNIST. Желательно с полным объяснением как устроены данные в MNIST

A: Данные устроены очень просто. Если откроете файлик mnist_train.csv в блокноте, то каждая текстовая строка - это изображение размером 28*28, развёрнутое построчно в одну текстовую строку. Числа - яркость пикселей, первое число - правильный ответ. в каждой строке 28*28+1 значений. Всего в базе 60000 изображений - 60000 строк в файле.

A: MNIST содержит коллекцию из  70 000 изображений 28 x 28  рукописных цифр от  0 до 9.
Набор данных разделен на наборы для обучения и тестирования. Загрузка
from tensorflow.keras.datasets import mnist #Библиотека с базой Mnist
(x_train_org, y_train_org), (x_test_org, y_test_org) = mnist.load_data() #Загрузка данных Mnist
x_train_org - 60000 тренировочных картинок 28 x 28  рукописных цифр от  0 до 9 в бело -серых тонах
y_train_org - цифры на картинках в виде чисел 0-9
то-же самое для тестирования-проверки обученной нейронной сети  10000 тестовых картинок
x_test_org, y_test_org
Как написать похожую базу:

*

*На бумаге рисуем произвольную цифру. Небольшого размера ( клетка тетради).

*Фотографируем

*Загружаем фото

*С помощью функции image.load_img(path, target_size=(28, 28), color_mode = 'grayscale') загружаем картинку в переменную.


text:
Q: Bootstrap 4.3.1 dropdown login form redirect upon success I am building a site where users can login via a Bootstrap Dropdown, i did have it working, it would log user in and refresh the whole page with login session BUT if user entered wrong creds it wouldn't stay open and alert them.  I got around this by putting the login form in an iframe in the dropdown but it's no longer starting the session - any ideas please?  I'm trying to not be vague so here is the code in the iframe and the actual URL below that - thank you :)

Login

  <form name="login" action="" method="post" class="form">

      Email
      <input type="email" class="form-control" id="lopc_username" placeholder="email@company.com" name="lopc_username">

      Password
      <input type="password" class="form-control" id="lopc_password" name="lopc_password">

      Forgot password

    <button type="submit" name="submit" class="btn btn-primary login_btn">LOGIN</button>

      New customer?  Register here

      <?php

if (isset($_POST['submit']))

{

include('../265451/92631043.php');

$lopc_username = mysqli_real_escape_string($conn,$_POST['lopc_username']);
$lopc_password = mysqli_real_escape_string($conn,(md5($_POST['lopc_password'])));
$lopc_last_login = date("Y-m-d H:i:s");

$query = "SELECT * FROM lopc_reg_users WHERE lopc_username = '$lopc_username' AND lopc_password = '$lopc_password' ";

$result = mysqli_query($conn,$query);

if(mysqli_num_rows($result) == 1)

{

    $_SESSION['lopc_username'] = $_POST['lopc_username'];
    $lopc_username = $_SESSION['lopc_username'];

    $query2 = "UPDATE lopc_reg_users SET lopc_last_login = '$lopc_last_login' WHERE lopc_username = '$lopc_username' ";
        $result2 = mysqli_query($conn,$query2);

    //header("Location: ".$_SERVER['PHP_SELF']);
    ?>

      <?php
    exit;
}
    else
    {
        echo '
Username or password does not exist.
';
    }

}
      ?>

  </form>

https://littleorangeprinting.co.uk/2021
Login:     test@test.com
Pass:      testing4321


text:
Q: Try / Except does not work on UnicodeEncodeError: 'UCS-2' when reading json I want to read one json file with python. JSON file contains emojis so I get the error:
UnicodeEncodeError: 'UCS-2' codec can't encode characters in position 96-96: Non-BMP character not supported in Tk

I want to skip the rows that has emoji, to continue the loop without that row. I have tried to use try except statement but I still get the same error:
I have used:
try:
    url = "https://api.instagram.com/v1/media/" + str(postid) + "/comments?" + token_id  # api link
    r = requests.get(url) #getting the data
    json_comment = r.json() # converting to json

    if json_comment.get("data") != []:
        json_comment = json_comment["data"][0]["text"] #taking values from json

        list_of_rows.append([client_id, postid, json_comment]) #ubacujem komentare u listu

except:
    continue

But the error is the same. I have tried to do except UnicodeEncodeError: continue and except UnicodeEncodeError: pass but the error is the same

A: Change your code to this
try:
    #your code here

#You can use
except UnicodeEncodeError as e:
    pass
#or
except Exception as e:
    pass


text:
Q: Using OR operator in a regular expression How can I use OR in a Java regex? I tried the following, but it's returning null instead of the text.
Pattern reg = Pattern.compile("\\*+|#+ (.+?)");
Matcher matcher = reg.matcher("* kdkdk"); \\ "# aksdasd"
matcher.find();
System.out.println(matcher.group(1));

A: The regex syntax for searching for X or Y is (X|Y). The parentheses are required if you have anything else in the pattern. You were searching for one of these patterns:

a literal * repeated one or more times

OR

a literal # repeated one or more times, followed by a space, followed by one or more of any character, matching a minimum number of times

This pattern matches * using the first part of the OR, but since that subpattern defines no capture groups, matcher.group(1) will be null. If you printed matcher.group(0), you would get * as the output.
If you want to capture the first character to the right of a space on a line that starts with either "*" or "#" repeated some number of times, followed by a space and at least one character, you probably want:
Pattern.compile("(?:\\*+|#+) (.+?)");

If you want everything to the right of the space, you want:
Pattern.compile("(?:\\*+|#+) (.+)");


text:
Q: How do I use cocoapods 0.33.1 on Yosemite? Because of the breaking changes cocoapods 0.34.x introduces, I need to continue using 0.33.1 following my upgrade to Yosemite.
Unfortunately, running pod install produces this output:

$ pod install
/System/Library/Frameworks/Ruby.framework/Versions/2.0/usr/lib/ruby/2.0.0/rubygems/core_ext/kernel_require.rb:55:in `require': cannot load such file -- xcodeproj/prebuilt/universal.x86_64-darwin14-2.0.0/xcodeproj_ext (LoadError)
    from /System/Library/Frameworks/Ruby.framework/Versions/2.0/usr/lib/ruby/2.0.0/rubygems/core_ext/kernel_require.rb:55:in `require'
    from /Library/Ruby/Gems/2.0.0/gems/xcodeproj-0.17.0/lib/xcodeproj/ext.rb:6:in `rescue in <top (required)>'
    from /Library/Ruby/Gems/2.0.0/gems/xcodeproj-0.17.0/lib/xcodeproj/ext.rb:3:in `<top (required)>'
    from /System/Library/Frameworks/Ruby.framework/Versions/2.0/usr/lib/ruby/2.0.0/rubygems/core_ext/kernel_require.rb:55:in `require'
    from /System/Library/Frameworks/Ruby.framework/Versions/2.0/usr/lib/ruby/2.0.0/rubygems/core_ext/kernel_require.rb:55:in `require'
    from /Library/Ruby/Gems/2.0.0/gems/xcodeproj-0.17.0/lib/xcodeproj.rb:30:in `<top (required)>'
    from /System/Library/Frameworks/Ruby.framework/Versions/2.0/usr/lib/ruby/2.0.0/rubygems/core_ext/kernel_require.rb:55:in `require'
    from /System/Library/Frameworks/Ruby.framework/Versions/2.0/usr/lib/ruby/2.0.0/rubygems/core_ext/kernel_require.rb:55:in `require'
    from /Library/Ruby/Gems/2.0.0/gems/cocoapods-0.33.1/lib/cocoapods.rb:2:in `<top (required)>'
    from /System/Library/Frameworks/Ruby.framework/Versions/2.0/usr/lib/ruby/2.0.0/rubygems/core_ext/kernel_require.rb:55:in `require'
    from /System/Library/Frameworks/Ruby.framework/Versions/2.0/usr/lib/ruby/2.0.0/rubygems/core_ext/kernel_require.rb:55:in `require'
    from /Library/Ruby/Gems/2.0.0/gems/cocoapods-0.33.1/bin/pod:32:in `<top (required)>'
    from /usr/bin/pod:23:in `load'
    from /usr/bin/pod:23:in `<main>'

I have Xcode 6.1 and latest command line tools.  The answer to the following question no longer works: Can't get to work CocoaPods and Yosemite

A: Alright, it seems the easiest solution is to install a Ruby environment manager.  This allows the appropriate Ruby version to be loaded when cocoapods asks for it.  I haven't dug too deep, but it seems the version CP is looking for is incompatible. (???)  Anyway, installing rbenv immediately solved my problem.
I chose rbenv but there's another called RVM.  rbenv did a good job explaining the differences between the two, however.


text:
Q:  section is not being encrypted in app.config Following the MS guide, I am trying to encrypt entire <connectionString> section in app.config file. While the program is running, I can open bin/Debug/MyApp.vshost.exe.config and see that <connectionString> is encrypted. However, if I let the program run, finish up and exit normally, nothing get saved in the file, as if it flushes all the settings.
  Dim config As Configuration =
    ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None)
    Dim section As ConnectionStringsSection =
    DirectCast(config.GetSection("connectionStrings"), ConnectionStringsSection)
    If section.SectionInformation.IsProtected Then
        'Remove encryption
        section.SectionInformation.UnprotectSection()
    Else
        'Encrypt
         section.SectionInformation.ProtectSection("DataProtectionConfigurationProvider")
    End If
        section.SectionInformation.ForceSave = True
        config.Save(ConfigurationSaveMode.Full)
    Dim sectionXmlas As String = 'result of encryption
                    section.SectionInformation.GetRawXml()

A: To make this work Programmatically, you would have to call
config.refreshsection

The call to Save will adjust the physical file but it will be cached in memory until the above call is made.


text:
Q: (...) Show that $f(x) ≤ f(b)$ for all $x \in [a,b]$ and that $f(a) = f(b)$ Can someone help me with this proof?

Let $a,b \in\mathbb{R}$ with $a < b$. Furthermore let $f: [a,b] \rightarrow \mathbb{R}$ be continuous with the following conditions:

*

*For $\forall x \in (a,b)$ there $\exists y \in (x,b]$ so that $f(y) > f(x)$.

*For $x=a$ the first condition (1) is not fulfilled.
Show that $f(x) ≤ f(b)$ for $\forall x \in [a,b]$ and that $f(a) = f(b)$.

Hints and solutions are both appreciated.
As suggested, I'm going to post my try here:

To show: $f(x) ≤ f(b) \forall x \in [a,b]$
$f$ is continuous $\rightarrow \lim_{x \to b}f(x) = f(\lim_{x \to b}x) = f(b)$.
Now assume that $\exists x \in (a,b]$ so that $f(x) > f(b)$.
Then there $\exists y \in (x,b]$ so that $f(y) > f(x) > f(b)$ using the first condition.
However, it follows that $f(b) < \lim_{y \to b}f(y) = f(b)$, which is a contradiction.
Hence $f(x) ≤ f(b) \forall x \in (a,b)$.

Is that OK?

A: Outline :
As $f$ is continuous, $f([a;b])=[c;d]$ for some $c$ and $d$. therefore $\exists x$ : $f(x)=d$. applying condition 1 to that $x$ would give a contradiction, therefore $x=a$ or $x=b$
if $x=b$, condition $2$ gives that $f(a)\geq f(b)$, and since $f(b)$ is the maximum...
if $x=a$, Assume $f(a)>f(b)$. then there exists $y$ close to $a$ such that $f(y)>f(b)$ (continuity). Then $f([y;b])=[m;M]$, and this time (using condition 1. again) the only choice is $f(b)=M$, witch contradicts $f(y)>f(b)$. Therefore $f(a)=f(b)$.

A: Hint: Assume that there exists $w\in[a,b]$ with $f(w)>f(b)$. Consider $x=\sup\{z\in[a,b]\mid f(z)=f(w)\}$. What is $f(x)$? If there is a $y\in[x,b]$ a promised by the first property, then use the Intermediate Value Theorem to reach a contradiction.


text:
Q: Checkboxes in PySide using for loop connects unexpected on stateChanged What I'm trying to do is to create checkboxes using for loop and connect a function to them ,which is called with different argument for every checkbox.
Here is some code:
for video in videos:
    video_cb = QtGui.QCheckBox(video['title'])
    video_cb.toggle()
    video_cb.stateChanged.connect(lambda: self._toggle_video_cb(video))
    videos_checkboxes_container.addWidget(video_cb)

and _toggle_video_cb function:
def _toggle_video_cb(self, video):
    print(video['title'])
    video['is_for_download'] = not video['is_for_download']

Here video is a dictionary whith keys: title: (str) , is_for_download: (boolean)...
The print is just for checking the argument and it is the same for every checkbox.No matter which checkbox I click it gives me it prints the same video title.
Why is that so? Is that the right way to do it?
Thanks in advance !
Best regards :)


text:
Q: Need synchronization for an increment-only counter? I use an integer as counter. The integer will only be increased, and surely more than one thread will increase it at the same time. The value of this counter is read at the end of program execution when no other thread will try to access its value.
I assume that I don't have to use a lock or any kind of synchronization for this kind of increment-only counter. Is this right?
I code in Java if that makes any difference.

A: If you just used an int or long variable then you would need synchronization - incrementing involves read / increment-locally / write, which is far from an atomic operation. (Even if the variable is volatile to avoid memory model concerns of staleness, you'd still have three distinct operations, with the possibility of being pre-empted between any pair of them.)
Fortunately Java provides AtomicInteger and AtomicLong which can be used without any synchronization:
private final AtomicLong counter = new AtomicLong();

...

counter.incrementAndGet(); // No need for synchronization


text:
Q: Correct way to use get_or_create on model object I know how get or create work with the values like
Car.get_or_create(name="Canro", model=2012 ... .. many other fields)

but when I have adding or Updating the car object using django forms, how can I check if user have entered a car who is already in the db?
One way could be,
have_in_db = Car.objects(name=user_entered.name)
if have_in_db:
  have_in_db.model!=user_entered.model
  # many other fields.

i want to try somthing like that.
Car.get_or_create(**user_entered)

can i have anyway in django to do that?

A: I put this logic in my view's form_valid like so:
def form_valid(self, form):
    self.object, created = Car.objects.get_or_create(
        **form.cleaned_data
    )
    return super(CarCreateView, self).form_valid(form)

To put that in context, I have a complaints case management system that registers new complaints in stages. When someone wants to complain their details are stored in a Complainant model that creates a new complainant for someone's first complaint but doesn't for subsequent ones. They are then redirected to a Case model form along with their id value, which is automatically added as the Case object's foreign key to the Complainant object. That model form looks like this:
class ComplainantCreateView(PermissionRequiredMixin, CreateView):
    model = Complainant
    form_class = ComplainantForm
    login_url = "/login/"
    permission_required = "complaints.add_complainant"

    def form_valid(self, form):
        self.object, created = Complainant.objects.get_or_create(
            **form.cleaned_data
        )
        return HttpResponseRedirect(
            reverse(
                'select_case',
                args=[self.object.pk],
            )
        )

A: Do it in form's clean method:
from django.forms import ModelForm
from myapp.models import Car

class CarForm(ModelForm):
    class Meta:
        model = Car

    def clean(self):
        if self._meta.model.objects.filter(**self.cleaned_data).count() > 0:
            raise forms.ValidationError('Car already exists')
        return self.cleaned_data


text:
Q: Searching for good open source web based log viewer My web site runs on Azure machines, using IIS8. I'm looking for a good open source web based log viewer for logs written in the DB using NLog, obviously I prefer an ASP.NET application.
I wanted to try ELMAH but it seems too basic, and I wanted to try Graylog2 and Logstash, but I can't host them on IIS.


text:
Q: how can I create a new variable with the same data type of a specific variable in C#? I want to create a new variable in the same data type of my variable Message. How can I do that?
I tried the following code. but I got an error.
MessageDTO Message;
var Message2 = new Message.GetType();

Error:

Message is a variable but is used like a type.

Here is my code:
public string Send(MessageDTO message)
{
     MessageDTO Message2 = new MessageDTO();
     if (message is Email)
     {
         Message2= new Email();
     }else if(message is SMS)
     {
         Message2= new SMS();
     }
    // rest of code ...
 }

Where
 public class MessageDTO
 {
        public int Id { get; set; }
        public MessageType Type { get; set; }
        public string? Subject { get; set; }
        public string? TextBody { get; set; }
        public string? HTMLBody { get; set; }
        public DateTimeOffset SendDate { get; set; }
        public DateTime SendTime { get; set; }
 }

public class Email : MessageDTO
{
   public string From{ get; set; }
   public string To{ get; set; }
}

 public class SMS : MessageDTO
 {
   public string SenderLine{ get; set; }
   public string[] To{ get; set; }
 }

I want to make my code open for extension, but closed for modification (i.e. If I add other types of messages, the Send method remains unchanged.). The Send method becomes shorter like this:
public string Send(MessageDTO message)
{
     MessageDTO Message2 = new Activator.CreateInstance(Message.GetType());
     // rest of code ...
 }

A: Its not clear to me why you need to make a new object in Send(). Knowing that, maybe another solution would be better. But I'll just go with the assumption that it is necessary.
One approach is to have MessageDTO be responsible for creating a new object of the correct type:
public class MessageDTO
{
    public abstract MessageDTO CreateAnother();
}

public class Email : MessageDTO
{
   public override MessageDTO CreateAnother() => new Email();
}

...

public string Send(MessageDTO message)
{
   MessageDTO Message2 = message.CreateAnother();
}

The CreateAnother() function could also do something more sophisticated, depending on what you need. For instance it could clone the existing object, not just create a default new one. (In that case I'd probably name it differently!)


text:
Q: p-calendar popup modal is not closing after choose date and time I'm using p-calendar like below
<p-calendar showTime="showTime" placeholder="Start Date & Time" hourFormat="24" [minDate]="minDate" [defaultDate]="minDate" (click)="onPickDate()" formControlName="pick_up_datetime" [touchUI]="true"></p-calendar>

its working fine. This calendar displaying both Date & Time . Here my Question is on selecting Date and Time in the primeng  calendar  it should be hide when click on button. Is there any way to do this?

A: Go to primeng in node_modules and open primeng->components->calendar and open calendar.js and add function
Calendar.prototype.onSetButton = function (clickedElement) {
        this.disableModality();
    };

and add a button in template (you can find template line around 1700 to 1710)
 <button id=\"set-button\" type=\"button\"  (click)=\"onSetButton(this)\">Set</button>

Hope it will solve your problem

A: There is an issue if you are using showTime="true", remove the [showTime] and it perfectly works fine.


text:
Q: How to summon an Angry Zombified Piglin in Minecraft Java 1.19 I'm making a minecraft map with some of my friends and we're looking to make Zombie Piglins automatically angry upon summoning them.
I've looked into it a bit and there are a few things I've found. In versions prior to 1.19 (or at least around 1.8), the nbt tag {Angry:100} would allow you to make them mad.
However now the tag is split in 2: it's now {AngerTime: *x*}, the amount of time the entity is angry for, and the actual issue, {AngryAt: []}, which is a list of the UUIDs of entities it's mad at. The problem is that when spawning a zombie piglin, you can't do something like
summon zombified_piglin ~ ~ ~ {AngerTime:100,AngryAt:@a} or anything, you need the actual UUID of the player entity, but since this is a map I don't know what the ID is. Is this a thing I can do, or am I just barking up the wrong tree?

A: First, summon a normal zombified piglin, then run the command /data modify <piglin> AngryAt set from entity <player> UUID to copy the player's UUID to the piglin.


text:
Q: Equivalent definition of normalizer of a group. Need help in proof. The definition of normalizer of a non-empty set $A$ in group $G$ is given by $$N_G(A) = \{g\in G\:|\:gAg^{-1} = A\}$$
This definition is from Abstract Algebra by Dummit and Foote.
Another definition I have seen around the internet (here and in this video) is $$N_G(A)=\{g\in G\:|\:gag^{-1}\in A\:\forall\: a\in A\}$$
I try to prove these equivalent. So we need $$gAg^{-1}=A \iff gag^{-1}\in A \:\forall\: a \in A$$
Here is my partial proof:
Assume $gAg^{-1}=A$. Then $gag^{-1}\in gAg^{-1}=A \:\forall \:a \in A$.
Conversely, assume $gag^{-1}\in A \:\forall\: a \in A$. Let $x\in gAg^{-1}$. Then, $\exists\:a_x \in A$ such that $x=ga_xg^{-1}\in A$. It follows that $gAg^{-1}\subseteq A$.
Now , let $y \in A$. This implies $gyg^{-1} \in A$. (This is where I'm stuck).
If I could somehow prove $y \in A \implies g^{-1}yg\in A$, then the result would from the hypothesis. Please let me know if I'm headed in the wrong direction.
I have seen this MathSE post. The definition of the normalizer is a slightly modified version of the first one stated here. However, I would like to know how I can proceed from where I'm stuck.

A: $gAg^{-1}$ = {$gag^{-1} : a\in A$}
Therefore, $gAg^{-1} = A$ occurs iff $g^{-1}Ag=A$ which both imply $\forall a\in A\; gag^{-1},g^{-1}ag\in A$
Now, assume $\forall a\in A\; gag^{-1}\in A$. From this we have $gAg^{-1}\subset A$. Choose $b\in A$ and note that $y=g^{-1}bg\in A$ and therefore $$b=gyg^{-1}\in gAg^{-1}$$
implying $A\subset gAg^{-1}$. Therefore, $gAg^{-1} = A$ iff $\forall a\in A\; gag^{-1}\in A$


text:
Q: Correct way of linking raw github file? In my github repo's Readme.md, I'd like to link to several raw html files.
I can do that by
[](./output_HTML/marham.html)

But in my github page, the HTML cannot be rendered directly. For example, for my file (https://github.com/cqcn1991/Wind-Speed-Analysis/blob/master/output_HTML/marham.html), it will display:

What would be a good way to link my file, so the HTML can be directly rendered?
I know one alternative is to use rawgit. That is, to manually change the link into
[](https://cdn.rawgit.com/cqcn1991/Wind-Speed-Analysis/master/output_HTML/marham.html)

But I'm not sure if this is the right approach? Or if there are better way than to manually do this?

A: Since rawgit.com is shutting down you want to use combinatronics.com it is an alternative for rawgit.com
It is a drop in replacement, so for your example:
[](http://cdn.combinatronics.com/cqcn1991/Wind-Speed-Analysis/master/output_HTML/marham.html)


text:
Q: String and value object In php we can assign a method name to a variable and then use that variable to call the method. For example:
$image_create_func = 'ImageCreateFromGIF';
$newImage = $image_create_func($oldImage);

But can we do this in Flex?
In flex, I have the string public var key:String = "email"
And I also have a value object searchTerm:SearchTermVO which has a public property "email" (searchTerm.email).
Now I want to do searchTerm.email by doing something like in php: searchTerm.key but it's not possible.
Can anybody help me with this plz?
Thank you.

A: You can use the square brackets:
var email:String = SearchTErm[email];


text:
Q: Problema para contar los días hasta la fecha C Tengo un problema en la función "fecha".
El enunciado me pide que dado un dia, mes y año, devuelva los días que pasaron de ese año, por ejemplo, el 3 de marzo sería 31 dias de enero + 28 dias de febrero + 3 días de marzo.
El problema es que la función no está devolviendo la cantidad de días que debería.
#include <stdio.h>

int bis(int ano);
int fecha(int dia, int mes);

int main()
{
    int a,b,c,d;
    int cardinal, bisiesto;
    printf("\n\nIntroduzca una fecha en formato aa(dia), bb(mes), cccc(ano): \n\n");
    scanf("%i %i %i",&a, &b, &c);
    bisiesto = bis(c);
    cardinal = fecha(a,b);
    printf("\n\n%i\n\n", cardinal);

}

int bis(int ano) {

    int c;
    if (ano%4==0 && ano%100!=0) {
        c = 1;
    }
    else if (ano%400==0){
        c = 1;
    }
    else {
        c = 0;
    }

    return c;

}

int fecha(int dia, int mes) {

    int v[13] = {0,31,28,31,30,31,30,31,31,30,31,30,31};
    int total = 0;
    int dias_mes = 0;
    int m;
    for (m=1; m<=mes; m++) {
        if (m==1) {
            total = dia;
        }
        else {
            dias_mes = dias_mes + v[m];
            total = dia + dias_mes;
        }
    }

    return total;
}

A: En el for sumas el día varias veces, excepto en el mes de enero.
total = dia + dias_mes;

Esa línea deberías moverla afuera del ciclo.
Se supone que deberías sumar los meses que ya pasaron. Pero como la condición del for es m <= mes también cuentas el mes que no pasó.
Por ejemplo, si mes es 3, la suma que está haciendo es 31 + 28 + 31.
Entonces la condición que buscas es m < mes.
El código te quedaría así:
int fecha(int dia, int mes) {

    int v[] = { 0, 31,28,31,30,31,30,31,31,30,31,30,31};
    int total = dia;

    for (int m = 1; m < mes; m++) {
        total += v[m];
    }

    return total;
}


text:
Q: Word that describes control over opacity/exchange? I'm looking for a word, could be a noun or verb or adjective, that describes something with varying degrees of opacity/exchange/transfer, possibly that could be controlled. An example that comes to my mind is, 'aperture', which could be opened or closed to either allow light/exchange. Or 'veil' which could either hide or reveal.
Thank you for your answers! I think 'filter' is quite nice.
To clarify, this is for an architectural concept. I'm looking for a one-word marketing-style concept for my project. I will be designing a gay space (a sauna) that challenges societal norms relating to sexuality and private/public by exposing some of the program to the public at varying degrees at different parts of the building (through varying glass opacities, etc)
Hopefully that makes it more clear what I'm trying to achieve.

A: In terms of physical examples, it sounds like you're talking about something like a lighting gel/color gel, on which tack you might also use the nouns film, filter, aperture, or shutter.  Light can also be filtered, obscured, shrouded or occluded.  ('Occluder' is also a valid noun but usually refers to an optometrist's tool, so probably isn't what you're looking for.)
Diaphragm and membrane are also closely related words (the apertures of most cameras use iris diaphragms).  Note however that a diaphragm is usually a separator, and without the specific context of an optical diaphragm it doesn't imply permeability or exchange, for which 'membrane' is a better match.
If you're looking more generic words about controlling rates or transference, there are also: regulate/regulator, limiter, screen (noun or verb), police (verb)

A: I agree with the commenter Xanne that "filter" is a possibility, and I think it is the best: it is short, neutral, technical, and adaptable to all kinds of qualities or qualities. (You do not make it clear enough what it is that is being controlled. If "filter" does not help you, you should clarify the kind of the thing-to-be-controlled.)
If you prefer a less latinate, more metaphorical word, try a creative metaphor like

*

*rubber bottleneck

But beware: this could remind some of rubberneck.

A: I am thinking through your question.
I will enter ideas that come to mind:

*

*Adaptive configuration

*Appropriates to conditions

*Auto-temper

*Self-adjust

*Configures accordingly

*conforms as required

*Malleable to needs

Another approach:
Idiom: Like water it seeks its own level.

*

*Other ways to use water metaphors

A word came to me but it's not exactly what you ask, but:
Diaphanous.
So alliteration with: dense, direct, diligent,deferrent.
Depending (pardon pun) on the particular use.
Since I don't know where you want it applied these ideas might trigger your own.


text:
Q: Why doesn't SendMessageTimeout update the environment variables? Question: I have an installer, and it installs some native dll's along with the program.
The dll's are in a separate folder, which I added to the path environment variable.
That was done successfully, and the variable shows up in path if I check the windows system settings.
However, if I start the command line program/service, it says dll's not found...
I check the environment variable path with the set command, and my folder is not in there.
If I do
SET path = %path%;my/folder/here/

And start my program after that, then it works.
According to this MS KB article this is because the computer would need to be restarted.
unless I do
SendMessageTimeout(HWND_BROADCAST, WM_SETTINGCHANGE, 0, (LPARAM) "Environment", SMTO_ABORTIFHUNG, 5000, &dwReturnValue);

Now I did just that, using the below code, but the error message persists. My folder in %path% is correctly spelled, I checked that.
What am I doing wrong ?
' http://www.pinvoke.net/default.aspx/Enums/SendMessageTimeoutFlags.html '
<Flags()> _
Public Enum SendMessageTimeoutFlags
    SMTO_NORMAL = 0
    SMTO_BLOCK = 1
    SMTO_ABORTIFHUNG = 2
    SMTO_NOTIMEOUTIFNOTHUNG = 8
End Enum

' http://ghouston.blogspot.com/2005/08/how-to-create-and-change-environment.html '
Public Const HWND_BROADCAST As Integer = &HFFFF
Public Const WM_SETTINGCHANGE As Integer = &H1A

' http://pinvoke.net/default.aspx/user32.SendMessageTimeout '
<System.Runtime.InteropServices.DllImport("user32.dll", SetLastError:=True)> _
Public Shared Function SendMessageTimeout(ByVal windowHandle As IntPtr, ByVal Msg As Integer, ByVal wParam As IntPtr, ByVal lParam As IntPtr, ByVal flags As SendMessageTimeoutFlags, ByVal timeout As Integer, ByRef result As IntPtr) As IntPtr
End Function

' http://support.microsoft.com/?kbid=104011 '
' http://blog.jtbworld.com/2005/11/set-environment-variable-using-vbnet.html '
Sub UpdatePath()
    Dim result As Integer
    ' SendMessageTimeout(HWND_BROADCAST, WM_SETTINGCHANGE, 0,(LPARAM) "Environment", SMTO_ABORTIFHUNG,5000, &dwReturnValue); '

    ' CType("Environment", System.IntPtr) '
    Dim s As String = New String("Environment")
    Dim ptr As IntPtr = Runtime.InteropServices.Marshal.StringToHGlobalUni(s)

    'SendMessageTimeout(CType(HWND_BROADCAST, System.IntPtr), WM_SETTINGCHANGE, 0, ptr, SendMessageTimeoutFlags.SMTO_BLOCK Or SendMessageTimeoutFlags.SMTO_ABORTIFHUNG Or SendMessageTimeoutFlags.SMTO_NOTIMEOUTIFNOTHUNG, 5000, result) '
    SendMessageTimeout(CType(HWND_BROADCAST, System.IntPtr), WM_SETTINGCHANGE, 0, ptr, SendMessageTimeoutFlags.SMTO_ABORTIFHUNG, 5000, result)
End Sub

A: I suspect it has to do with Unicode/ANSI processing; the base system seems to want "Environment" in ANSI but most apps including the shell want Unicode, if they acknowledge it at all. In C I just send it as:
SendMessageTimeout(HWND_BROADCAST, WM_SETTINGCHANGE, 0, (LPARAM) "Environment", SMTO_ABORTIFHUNG, 1000, NULL );
SendMessageTimeout(HWND_BROADCAST, WM_SETTINGCHANGE, 0, (LPARAM) L"Environment", SMTO_ABORTIFHUNG, 1000, NULL );

Which gets the job done nicely.
In VB.Net I suppose the equivalent for you would be:
Dim s As String = New String("Environment")
Dim ptrA As IntPtr = Runtime.InteropServices.Marshal.StringToHGlobalAnsi(s)
Dim ptrU As IntPtr = Runtime.InteropServices.Marshal.StringToHGlobalUni(s)
SendMessageTimeout(CType(HWND_BROADCAST, System.IntPtr), WM_SETTINGCHANGE, 0, ptrA, SendMessageTimeoutFlags.SMTO_ABORTIFHUNG, 5000, result)
SendMessageTimeout(CType(HWND_BROADCAST, System.IntPtr), WM_SETTINGCHANGE, 0, ptrU, SendMessageTimeoutFlags.SMTO_ABORTIFHUNG, 5000, result)

(And don't forget to free your memory if you're going to use unmanaged code.)


text:
Q: gcloud CLI: running bq mk command requires a step using the browser I am running the following command from a local terminal:
bq mk --transfer_config --target_dataset=mydataset --display_name='mytransfer' --params='{
"data_path": "s3://mys3path/*",
"destination_table_name_template": "mytable",
"file_format": "JSON",
"max_bad_records":"0",
"ignore_unknown_values":"true",
"access_key_id": "myaccessid",
"secret_access_key": "myaccesskey"
}' --data_source=amazon_s3

Now, every time I run this, I get the following:
/opt/google-cloud-sdk/platform/bq/bq.py:41: DeprecationWarning: the imp module is deprecated in favour of importlib and slated for removal in Python 3.12; see the module's documentation for alternative uses
  import imp
Table '<mytablehere>' successfully created.
/opt/google-cloud-sdk/platform/bq/bq.py:41: DeprecationWarning: the imp module is deprecated in favour of importlib and slated for removal in Python 3.12; see the module's documentation for alternative uses
  import imp

https://www.gstatic.com/bigquerydatatransfer/oauthz/auth?client_id=***********.apps.googleusercontent.com&scope=https://www.googleapis.com/auth/bigquery&redirect_uri=urn:ietf:wg:oauth:2.0:oob&response_type=version_info
Please copy and paste the above URL into your web browser and follow the instructions to retrieve a version_info.
Enter your version_info here:

So, every time I run this, I need to open this link, sign-in my account, authorize Google data transfer service to "View and manage your data in Google BigQuery and see the email address for your Google Account" and then copy/paste back to the terminal a string that I get in the browser.
Is there any way to persist the version configuration so that I don't have to perform this step every time?
Thank you in advance

A: In order to have your Service Account's credentials to persist within the BigQuery command line tool, so that you can use it after logging out then logging in again, you will need to set the CLOUDSDK_PYTHON_SITEPACKAGES environment variable by running the following command:

export CLOUDSDK_PYTHON_SITEPACKAGES=1

You can then run the following command to see the accounts the tool has credentials for, which should include your Service Account:

gcloud auth list

I hope that the above information would be helpful. If it does not, make sure that you try out the steps followed in the Stackoverflow case.
Make sure to try out the .bigqueryrc solution provided by Michael Sheldon.


text:
Q: Proj4js: Is this correct implementation of Azimuthal Equidistant relative to an arbitrary center? If I wanted to interpolate points along a Great Circle Arc, it makes sense that either endpoint of the Great Circle is a satisfactory starting place. Next, I suppose I'll need a projection to preserve distances along the Great Circle. Unless someone corrects me, I think an Azimuthal Equidistant projection centered on either endpoint of the Great Circle would work.
From Wikipedia, with respect to an Azimuthal Equidistant projection "all points on the map are at proportionately correct distances from the center point", and additionally, it's "useful for showing airline distances from [the] center point of projection".
I suspect I can implement the Azimuthal Equidistant in Proj4js, but I've never really customized a projection before, so basically I'm just curious whether I'm doing it properly..
Now if I go to SpatialReference.org and search for Azimuthal Equidistant, I see both north and south pole-centered customizations of the projection. Respectively, they're implemented in Proj4js like so:
North Pole Azimuthal Equidistant:
Proj4js.defs["ESRI:102016"] = "+proj=aeqd +lat_0=90 +lon_0=0 +x_0=0 +y_0=0 +ellps=WGS84 +datum=WGS84 +units=m +no_defs";
South Pole Azimuthal Equidistant:
Proj4js.defs["ESRI:102019"] = "+proj=aeqd +lat_0=-90 +lon_0=0 +x_0=0 +y_0=0 +ellps=WGS84 +datum=WGS84 +units=m +no_defs";
It follows that the only value changing in either projection is the latitude, itself, +lat_0=, which changes from 90 to -90. So I'm pretty sure I just need to set these +lat_0 and +lon_0 appropriately, and bingo--the Azimuthal Equidistant is properly defined.
So with all of this said..
Is this a valid way to define an Azimuthal Equidistant projection relative to a specific place, like Columbia, South Carolina? (Lon: -81.020742, Lat: 34.008654)
Proj4js.defs["CUSTOM:10001"] = "+proj=aeqd +lat_0=34.008654 +lon_0=-81.020742 +x_0=0 +y_0=0 +ellps=WGS84 +datum=WGS84 +units=m +no_defs";
I hate to ask such a Yes or No question, so please note the additional opportunity to remark on whether this is a wise choice of projection considering the scenario (interpolating points at fixed distances along a Great Circle Arc).

A: This looks ok. If you run into reprojecting problems, try the spherical version, as I explained here:
Manipulating Azimuthal Equidistant Projections in QGIS


text:
Q: Why are nonstatic global variables defined in shared objects referenced using GOT? I mean nonstatic global variables that are defined in the module, not externally.
Why does it have to be referenced through GOT? Why no use relative address?(since the distance between the global variable in the .data section and the reference in the .text section is a constant, it's also position-independent)

A: Since your variable isn't static, on ELF it can be interposed (think of LD_PRELOAD).

A: I also have the same confusion.
If there is one global variable with same name defined in both two DSOs and they are dynamically linked into one executable, will both libraries access the same copy of the variable?
And which library(library's data section) the variable locates depends on the order of libraries loading?


text:
Q: Not able to see debug values in quick watch or in Add watch or when i move mouse pointer over the variable, for C++ project in VS2015 I am having a C++ project build using vs2015. The problem is when I debug the application created,  I put few break points and started debugging.,
 it was hitting the brake point, step into and step over is working,
 but the values are not getting shown up when
 I move the mouse over the variables. and in "Add watch" or "quick watch" for the variable, it says Internal error in the expression evaluator.
Any suggestion
Thanks
Arjun Reddy


text:
Q: How to use feathersjs-primus to setup websocket connection I am trying to setup websocket by feathers js + primus following from this link: https://docs.feathersjs.com/real-time/primus.html.
But I don't know how to get spark instance from primus in server side. Below is my server code:
  class SocketService {
      create(data, params, callback){
          ...
      }
  }

module.exports = function(){
  const app = this
  let ss = new SocketService()
  app.use('socket-shell', ss);
}

In above code, server can get the message from client in create() method. But how can I get spark instance from primus in that method? I want to use spark.write method to send message back to the client.
Below is the server code for configuring feathers services:
app
  .use(compress())
  .options('*', cors())
  .use(cors())
  // .use(favicon(path.join(app.get('public'), 'favicon.ico')))
  .use('/', serveStatic(app.get('public')))
  .use(bodyParser.json())
  .use(bodyParser.urlencoded({extended: true}))
  .configure(hooks())
  .configure(rest())
  .configure(primus({
    transformer: 'websockets',
    timeout: false,
  }, (primus) => {
    app.use('socket-shell', function(socket, done){
      // Exposing a request property to services and hooks
      socket.request.feathers.referrer = socket.request.referrer;
      done();
    });
  }))
  .configure(services)
  .configure(middleware);

Below code is used  to registering a event listener on server side but it can't receive event from client:
class SocketService {

  constructor(options) {

    this.events = [ 'someevent','serverevent' ]

  }

  setup(app) {
    this.app = app;

    let socketService = app.service('socket-shell')
    socketService.addListener('serverevent', this.serverevent)
  }

  serverevent(msg){
    console.log('serverevent', msg)
  }

In client code, I use below code to emit message to server:
var primus = new Primus('http://localhost:3030');
  var app = feathers()
    .configure(feathers.hooks())
    .configure(feathers.primus(primus));

  var messageService = app.service('/socket-shell');
messageService.emit('serverevent', {msg:'this is client'})

what wrong with above code?

A: Ideally you wouldn't use the socket connection directly in your service. A service shouldn't know about how it is being accessed. There are two options:

*

*Set up and send your own events in app.configure(primus(

*Have the service emit its own custom events
--
class SocketService {
  constructor() {
    this.events = [ 'someevent' ];
  }

  create(data, params, callback){
      this.emit('someevent', 'data');
  }
}


text:
Q: AlpineJS trigger magic function programatically I've been using this notification magic

It is working when you load the page. My goal is to trigger it by calling via javascript function.
I'm looking for ideas on how to implement that. Thanks a lot.

A: Use default events or custom events. Code is untested but something like this will work.
<button x-on:click="$notification({text: 'clicked', variant: 'info'})">
    Click me
</button>

<button x-on:click="$dispatch('add-error', {message: 'Something went wrong'})">
    Click me
</button>


text:
Q: wgs84 and maxscaledenom on mapserver &mode=tile&tilemode=gmap&tile={x}+{y}+{z}.png http://mapserver.org/mapfile/layer.html
MAXSCALEDENOM 24000
For me this only seem to work when using UNITS dd and wgs84 and using qgis, as soon as i use leaflet and &mode=tile&tilemode=gmap&tile={x}+{y}+{z}.png i need to useUNITS meters and mercator. &mode=tile&tilemode=gmap&tile={x}+{y}+{z}.png doesn't work using MAXSCALEDENOM in combination with UNITS dd and wgs84 everything else works.
Debug message tells me scale is to small when using wgs84
Is this a bug or related to something else? Below example works until you switch everything to wgs84 then you need to comment out MAXSCALEDENOM 24000 or you get a empty png in leaflet at any zoom level.
MAP
  NAME "TEST"
  SHAPEPATH "/wms"
  CONFIG  "MS_ERRORFILE" "stderr"
  UNITS METERS
  # UNITS dd
  # EXTENT 6.024789 47.513195 15.008623 54.838047
  STATUS ON
  DEBUG 0

  PROJECTION
    # "init=epsg:4326"
    "init=epsg:3857"
  END

  WEB
    METADATA
      "wms_enable_request" "*"
      "wms_title" "TEST"
      # "wms_onlineresource" "..."
      # "wms_srs" "EPSG:4326"
      "wms_srs" "EPSG:3857"
      "wms_format" "image/png"
      "tile_map_edge_buffer" "10"
      "tile_metatile_level" "0"
    END
  END

  OUTPUTFORMAT
    NAME "AGGPNG"
    DRIVER "AGG/PNG"
    EXTENSION "png"
    MIMETYPE "image/png"
    IMAGEMODE RGBA
  END

  LAYER
    NAME test
    DATA test
    TYPE line
    MAXSCALEDENOM 24000

    CLASS
      STYLE
        width 8
        color "#000000"
        offset 0 -99
      END
    END

  END

END


text:
Q: TypeScript - property does not exist on object after parsing with toml My TypeScript project is modular and has several config files.
I chose TOML for the configuration files as it's a really intuitive language.
Also, I got a main.toml where you can enable/disable the modules.
My config class looks like this. It's made for creating multiple configs from it that are automatically parsed.
import { parse } from 'toml';
import { readFileSync } from 'fs';
import { join } from 'path';

export class Config {
    private readonly _name: string;
    private readonly _path: string;
    private _config: object;

    constructor(name: string) {
        this._name = name;
        this._path = join(__dirname, '..', '..', 'config', `${name}.toml`);
        this._config = this.load();
    }

    public load(): object {
        let config: object = {};
        try {
            config = parse(readFileSync(this._path).toString());
        } catch (error) {
            if (error.code === 'ENOENT') {
                throw new Error(`config ${this._name}.toml was not found!`);
            } else {
                throw new Error(error);
            }
        }
        return config;
    }

    get config(): object {
        return this._config;
    }
}

This is how my main file looks where I want to use the main.toml to activate other modules:
import { Config } from './init/config';

let config: object = {};
try {
    config = new Config('main').config;
} catch (error) {
    console.log(error.stack);
    process.exit(1);
}

for (const key in config.modules) {
    if (Object.prototype.hasOwnProperty.call(config.modules, key) && config.modules[key]) {
        require(`./modules/${key}/${key}`);
    } else {
        zoya.info(`skipping module ${key}...`);
    }
}

Now I have the problem that the typescript compiler gives me the following error each time I use config.modules:
TS2339: Property 'modules' does not exist on type 'object'.

I could just suppress it with @ts-ignore which works fine by the way but I think that's some bad practice and I want to know if I can somehow prevent this.
I also tried other TOML parsers like this one which I hoped would make a difference but I get the exact same problem.

A: Typescript can't infer what the structure of your parsed config is. Remember that Typescript exists at compile-time, but not runtime, and your parsed config object exists at runtime but not at compile time.
You're telling Typescript that your parsed config is of type object, but object doesn't have a modules property.
You have two options here:

*

*Define _config as any rather than object. This will tell Typescript that that object can be of any type, which means it will essentially not be typechecked.

*Define interfaces for your config objects, so Typescript knows what types it should expect from them. Trivially:

interface ConfigDef {
   modules: SomeType[]
}

let config: ConfigDef = { modules: [] };
try {
    config = new Config('main').config as ConfigDef;
} catch (error) {
    console.log(error.stack);
    process.exit(1);
}

Or, more strictly, using generics (which is probably better):
export class Config<T> {
    private readonly _name: string;
    private readonly _path: string;
    private _config: T;

    constructor(name: string) {
        this._name = name;
        this._path = join(__dirname, '..', '..', 'config', `${name}.toml`);
        this._config = this.load();
    }

    public load(): T {
        let config: T = {};
        try {
            config = parse(readFileSync(this._path).toString()) as T;
        } catch (error) {
            if (error.code === 'ENOENT') {
                throw new Error(`config ${this._name}.toml was not found!`);
            } else {
                throw new Error(error);
            }
        }
        return config;
    }

    get config(): T {
        return this._config;
    }
}

// ...

let config: ConfigDef = { modules: [] };
try {
    config = new Config<ConfigDef>('main').config;
} catch (error) {
    console.log(error.stack);
    process.exit(1);
}


text:
Q: Lucene sort by date descending I am trying to sort a Lucene search firstly by a boolean field and then by a datetime. I have this:
SortField[] sortFields = new SortField[]
  {
    new SortField(LuceneMedia.IndexFields.IsPrivate, SortField.STRING, true),
    new SortField(LuceneMedia.IndexFields.DateAdded, SortField.STRING, true)
  };
Sort sort = new Sort(sortFields);

The boolean field is being sorted correct, but the date seems a bit random.
SortField[] sortFields = new SortField[]
  {
    new SortField(LuceneMedia.IndexFields.IsPrivate, SortField.STRING, true),
    new SortField(LuceneMedia.IndexFields.DateAdded, SortField.LONG, true)
  };
Sort sort = new Sort(sortFields);

But now it seems to ignore the date and is ordering by the document title, which isn't part of the sort at all.


text:
Q: python open directory error Wrote some code to go through a folder of 200 images to get the value of the minimum number of pixels in an image  (i.e. min  width and height)
But I keep getting this error :
File "pixelSizeCheck.py", line 9, in get_num_pixels
width, height = Image.open(open(filepath)).size
IsADirectoryError: [Errno 21] Is a directory:

when I run this code :
from PIL import Image
import os.path

def get_num_pixels(filepath):
    heightMin= 10000
    widthMin= 10000
    for filename in os.listdir(filepath):
        if filename.endswith(".jpg") :
            width, height = Image.open(open(filepath)).size
            if width< widthMin:
                widthMin = width
                return widthMin

            if height < heightMin:
                heightMin = height
                return heightMin

print (heightMin, widthMin)

get_num_pixels("filepath")

However i have tested the code with print statement and i know the directory i have been putting in is correct because it reaches the for loop correctly but then crashes when i try and won line 9 :
Image.open(open(filepath)).size

also I'm relatively new to python so any advice on how to improve the code would be much appreciated. Apologies in advance if any of the code is sloppy or poor.

A: you're trying to open the directory you're scanning: In Image.open call:
open(filepath)

should be (the second error is that you have to open in binary mode too)
open(os.path.join(filepath,filename),"rb")

a better way would be to use glob.glob to filter and get absolute path at the same time:
for filename in os.listdir(filepath):
    if filename.endswith(".jpg") :
        width, height = Image.open(open(os.path.join(filepath,filename),"rb")).size

would become (with, added, a context manager to make sure the file is closed):
for filename in glob.glob(os.path.join(filepath,"*.jpg")):
    with open(filename,"rb") as f:
        width, height = Image.open(f).size


text:
Q: What are distinguishable and indistinguishable particles in statistical mechanics? What are distinguishable and indistinguishable particles in statistical mechanics? While learning different distributions in statistical mechanics I came across this doubt; Maxwell-Boltzmann distribution is used for solving distinguishable particle and Fermi-Dirac, Bose-Einstein for indistinguishable particles. What is the significance of these two terms in these distributions?

A: Assume you have two particle A and B in states 1 and 2. If the two particle are distinguishable, then by exchanging the particles A and B, you will obtain a new state that will have the same properties as the old state i.e. you have degeneracy and you have to count both states when calculating the entropy for example. On the other hand, for indistinguishable particles, exchanging A and B is a transformation that does nothing and you have the same physical state. This means that for indistinguishable particles, particle labels are unphysical and they represent a redundancy in describing the physical state and that is why you would have to divide by some symmetry factor to get the proper counting of states.

A: On the deepest level, particles are indistinguishable if and only if they have the same quantum numbers (mass, spin, and charges).
However, in statistical mechanics one often studies effective theories where there are additional means of distinguishing particles. Two important examples:

*

*In modeling molecular fluids, two atoms on the same molecule are distinguishable if and only if there is no molecular symmetry interchanging the two atoms, and two atoms in different molecules are distinguishable if and only if there is no congruent matching of the two molecules such that the two atoms correspond to each other.

*In modeling the solid state, one typically assumes that the atoms are confined to lattice sites, and that each site is occupied at most once.. In this case, the position in the lattice is a distinguishable label, which makes all atoms distinguishable.
The computational relevance of the distinction is that permutations of (in)distinguishable particles (don't) count towards the weighting factor.
For an expanded discussion see my article at PhysicsForums.

A: Suppose you have two distinct particles. If they are distinguishable (Like a helium-3 atom and a helium-4 atom), then you can switch their positions and the system changes. If they are indistinguishable (Like two protons), switching the two particles' positions makes no physical change because we do not know whether particles switched at all. I haven't studied advanced quantum mechanics, so I can't give a better explanation, but Wikipedia can http://en.wikipedia.org/wiki/Identical_particles#Distinguishing_between_particles.
The number of permutations of the distinguishable particles is n! more than that of indistinguishable ones, so quantities like entropy can change depending on whether we can distinguish particles in our system. All three distributions can be derived from the grand partition function, but the derivations for Bose-Einstein and Fermi-Dirac distributions uses indistinguishability..

A: Since there is no way in which the molecules can be labeled, the particles are indistinguishable.
On the other hand, if the assembly is a crystal, the molecules can be labeled in
accord with the positions they occupy in the crystal lattice and can be considered
distinguishable.

A: In classical mechanics, one can keep track of individual particles. For example, if you have two particles in a system, you can color these particles red and blue and follow them. Notice this, for classical mechanics, dynamical variables are $(q_i,p_i)$ with $i=1,2$. There is nothing classical mechanics that prevents you from specifying more variables e.g $c_i\in \{r,b\}$.
In quantum mechanics, however, the maximum you can do is specify a complete set of commuting observables for each of the particles. There is also this problem of following the trajectory in quantum mechanics. There is no trajectory, owing to Heisenberg's Uncertainty. So, there will be regions in the system, where you will be blind and the two particles exchange their positions. If you look too carefully, the system would be disturbed, thus making your measurements useless.
P.S. I have channeled my answer from the first paragraph of J.J. Sakurai's Modern Quantum Mechanics. Look at the Chapter Identical Particles to get an answer with a picture.


text:
Q: How to make sure sp_xml_removedocument is always run I would like to run a query to release the space held by XML parsing created by sp_xml_preparedocument before the session is killed. My code is like:
DECLARE @idoc INT, @result XML

SELECT @result = Result
FROM XmlFieldTable

EXEC sp_xml_preparedocument @idoc OUTPUT, @result

-- some query in the middle

EXEC sp_xml_removedocument @idoc;

I want to make sure the handle is removed before the session is killed, or the internal cache may overflow, what should I do?
I have already tried to use a try/catch statement or transaction, but it doesn't help.

A: I would have expected it to rollback the handle with a transaction on error. At least according to the docs it seems to say the handle is only valid for a single session. But if it doesn't work, I suggest you report this as a bug on Azure Feedback. It does seem from here that others have had the same problem.
As a workaround, catch errors client-side and check for open handles:
SELECT document_id FROM dm_exec_xml_handles (@@spid)
Loop through the results and pass to sp_xml_removedocument
You may want to close all handles periodically, even for other sessions, as the whole connection may get closed. So pass 0 to the function. You could do this as an Agent Job periodically.


text:
Q: How to full-text filter with admin-on-rest on loopback server I want to use a fulltext filter with admin-on-rest to query data from my loopback server.
I have tried to implement the example from the documentation (AOR-doc), but I have unfortunately only managed to query single fields:
const CatFilter = (props) => (
  <Filter {...props}>
    <TextInput label="Search" source="CatCode" alwaysOn />
  </Filter>
);

How can I use a loopback backend to perform a full text search across multiple fields that will search for "contains" string if possible.

A: There are 2 ways to do this, I am outlining both below.
1) Loopback fulltext search needs a custom Remote Method that does a Regex search.
https://loopback.io/doc/en/lb3/Where-filter.html
jump to the section for regular expressions.
This was the best way I could find for doing text searches in LB.
This is my filter
const AdminFilter = (props) => {
  return (<Filter {...props}>
    <TextInput label="Name Or Email" source="userNameOrEmailId" alwaysOn />
  </Filter>)
}

This generates a filter of the following form in the API side.
const findUsersByNameOrEmail = (filter) => {
    const regex = '^' + filter.where.userNameOrEmailId
    filter.where.or = [{name: {'regexp': regex}}, {email: {'regexp': regex}}]
    delete filter.where.userNameOrEmailId
    return findAllUsersByFilter(filter)
}

const findAllUsersByFilter = (filter) => {
    return AppUser.find(filter)
}

A minor hackyness here I guess would be assigning a dummy source in the filter like userNameOrEmail in above. Though it isnt really overriding any default concerns. Just helping us set appropriate filters.
2) You can also achieve the same thing by doing something like the filter construction that is being done by function findUsersByNameOrEmail above in a custom Rest Wrapper or your own Rest Client. So something like below in your rest Client or wrapper.
 if (type === 'GET_LIST' && resource === 'appUser') {
  const regex = '^' + params.userNameOrEmailId
  const url =  `URLroot/filter={where: [or: {name: {'regexp': regex}}, {email: {'regexp': regex}}]
  options.method = 'GET';
  return handleRequestAndResponse(url, options)
}

The idea is to intercept the call to your API and fix things as you need beforehand.

A: In the end, I think I found a solution that seems to work well. I hope I have not overlooked any problem so that the solution can help someone else or make me aware of the mistake.
First I created a Text Index in MongoDB
db.collection.createIndex( { "$**": "text" } )

In Loopback I created an access operation-hook in die model-name.js that catches the full-text query "q" and makes a direct database query:
Clinic.observe('access', function logQuery(ctx, next) {
    console.log('Accessing %s matching %s', JSON.stringify(ctx.Model.modelName), JSON.stringify(ctx.query.where));

    if (ctx && ctx.query && ctx.query.where && ctx.query.where.q) {
      ctx.query.where =
      {$text:
      {
        search: ctx.query.where.q,
        language: "de",
        caseSensitive: false,
        diacriticSensitive: false
      }
    }
    }
    next();
  });

The Filter in the admin-on-rest code has remained as in the example:
const CatFilter = (props) => {
  return (<Filter {...props}>
    <TextInput label="Full Text Search" source="q" alwaysOn />
  </Filter>)
}


text:
Q: What's my mistake on Design Twitter problen on Leetcode? the problem:
https://leetcode.com/problems/design-twitter/
my solutiion:
class Twitter:

    def __init__(self):
        self.tweet_posted = []
        self.follow_users = []

    def postTweet(self, userId: int, tweetId: int) -> None:
        self.tweet_posted.insert(0, [userId, tweetId])

    def getNewsFeed(self, userId: int) -> List[int]:
        #lst = [ls[1] for ls in self.tweet_posted if ls[0] == userId or list([userId, ls[0]]) in self.follow_users]
        lst = []
        for i in self.tweet_posted:
            if list([userId, i[0]]) in self.follow_users or i[0] == userId:
                lst.append(i[1])
        return lst

    def follow(self, followerId: int, followeeId: int) -> None:
        self.follow_users.append([followerId, followeeId])

    def unfollow(self, followerId: int, followeeId: int) -> None:
        unfollow_user = [followerId, followeeId]
        if unfollow_user in self.follow_users:
            self.follow_users.remove(unfollow_user)

No error, but wrong answer by leetcode:
enter image description here
it seems that my solution should be right since the function getNewsFeed must contain ALL the tweets of the user...


text:
Q: This code displays an number of li inside an ol This is what I should have posted in the first place.
This code displays an number of li inside an ol. Each li is represented on the page with a number(1 thru ...). Is there any way that I can access the current li number value with HTML, C#, Razor or JavaScript so that I can display it myself elsewhere on the page?

    @foreach(var row in data)
    {

                @row.Name, @row.ReleaseYear, @row.Genre

                    @{displayCount++;@displayCount;}

                    <select style="background-color:ThreeDFace">
                        <option>Choose Action</option>
                        <option onclick="window.location='dataMovies.cshtml?id=@row.id'">Google it</option>
                        <option onclick="window.location='EditMovie.cshtml?id=@row.id'">Edit Movie</option>
                        <option onclick="window.location='DeleteMovie.cshtml?id=@row.id'">Delete Movie</option>
                    </select>

    }

A: I assume you mean the numbering that is automatically allied by the browser when ol or Ordered List is used.
With JQuery you could use .index()
In CSS3 you can use the nth-child pseudo-selector to style specific elements:-
http://reference.sitepoint.com/css/pseudoclass-nthchild

A: If you want to display it yourself, use ul and a counter. However, you can slightly modify the automatically displayed numbers as well.

A: This post will help you to achieve this.