text:
Q: Selection of Object not working with context Menu I have created a little MessageBox that shows messages like an email-client.
Just like in an email-client the user should be able to mark messages as read or unread using a context menu. Building that one up is not a problem. Displaying messages in the messages window based on selection neither.
But when i use the context menu to mark messages as read or unread, it is always the last message that is highlighted.
I was unable to find a solution for that so far. Couldn't find and answer or hint neither on ddg nor on SO.
A small overview for the program flow:
- messages are displayed / represented via MessageObjects.
- they are stored inside a list called self.__messages inside the InBox-Object
- selection is done by left-clicking a message object, context menu is opened using right-click.
- the selection is done inside the InBox object in order to allow only single selection
- the context menu is registered and run only inside the MessageObject.
Unfortunately i was not able to strip the example below more to get a still working code.
Any help, hints or ideas are very welcome as i cannot figure out where the error comes from.
    from sys import hexversion, modules

    if hexversion>0x03000000:
        import Tkinter
        modules['Tkinter'] = tkinter
        modules['ttk']     = tkinter.ttk

    import Tkinter as tk
    import ttk

    __DEBUG__=2

    class MessageObject(ttk.Frame):
        def __init__(self, master=None, **options):
            ttk.Frame.__init__(self, master, **options)
            self.pack(expand=True, fill=tk.BOTH)

            self.master=master
            self.takefocus=True

            self.read=tk.BooleanVar()
            self.sender=tk.StringVar()
            self.date=tk.StringVar()
            self.text=tk.StringVar()
            self.subject=tk.StringVar()
            self.mID=tk.IntVar()

            self.__loadUI()

        def __loadUI(self, event=None):
            self.grid_columnconfigure(0, weight=1)
            self.grid_columnconfigure(0, weight=1)

            self.Labels=[]

            self.Labels.append(ttk.Label(self, text="Subject:", justify=tk.LEFT))
            self.Labels.append(ttk.Label(self, text="Sender:", justify=tk.LEFT))

            self.Labels.append(ttk.Label(self, textvariable=self.subject, justify=tk.RIGHT))
            self.Labels.append(ttk.Label(self, textvariable=self.sender, justify=tk.RIGHT))

            self.Labels[0].grid(row=0, column=0, sticky=tk.N+tk.SW)
            self.Labels[1].grid(row=1, column=0, sticky=tk.N+tk.SW)

            self.Labels[2].grid(row=0, column=1, sticky=tk.N+tk.SE)
            self.Labels[3].grid(row=1, column=1, sticky=tk.N+tk.SE)

            #Context Menu
            self.__cMenu=tk.Menu(self, tearoff=0)
            self.__cMenu.add_command(label="Mark as read", command=lambda: self.Read(True))
            self.__cMenu.add_command(label="Mark as unread", command=lambda: self.Read(False))

            self.bind_all("", self.__showContextMenu)

        def __showContextMenu(self, event=None):
            self.__cMenu.post(event.x_root, event.y_root)

        def Read(self, value=False):
            self.read.set(value)
            if value:
                self.config(style='Read.TFrame')
                for Label in self.Labels:
                    Label.config(style='Read.TLabel')
            else:
                self.config(style='Unread.TFrame')
                for Label in self.Labels:
                    Label.config(style='Unread.TLabel')

        def Selected(self, value=False):
            #TODO: keep Font, only change for- and background
            if value:
                self.config(style='Selected.TFrame')
                for Label in self.Labels:
                    Label.config(style='Selected.TLabel')
            else:
                for Label in self.Labels:
                    if self.read.get():
                        Label.config(style='Read.TLabel')
                        self.config(style='Read.TFrame')
                    else:
                        Label.config(style='Unread.TLabel')
                        self.config(style='Unread.TFrame')

    class InBox(ttk.Frame):
        def __init__(self, master=None, **options):
            ttk.Frame.__init__(self, master, **options)
            self.pack(expand=True, fill=tk.BOTH)

            self.master=master

            self.grid_columnconfigure(0, weight=2)
            self.grid_columnconfigure(1, weight=0)
            self.grid_columnconfigure(2, weight=0)
            self.grid_columnconfigure(3, weight=0)

            self.grid_rowconfigure(0, weight=0)
            self.grid_rowconfigure(1, weight=1)
            self.grid_rowconfigure(2, weight=1)
            self.grid_rowconfigure(3, weight=1)

            self.__text=tk.StringVar()
            self.__currentSubject=tk.StringVar()
            self.__currentTimestamp=tk.StringVar()

            self.__itemCount=0
            self.__messages=[]

            self.__loadUI()

        def __loadUI(self):
            ttk.Label(self, text="Inbox:", anchor=tk.W).grid(row=0, column=0, sticky=tk.NW+tk.SE)
            ttk.Label(self, text="Selected Message:", anchor=tk.W).grid(row=0, column=1, sticky=tk.NW+tk.SE)

            ttk.Label(self, textvariable=self.__currentSubject).grid(row=0, column=2, sticky=tk.NW)
            ttk.Label(self, textvariable=self.__currentTimestamp).grid(row=0, column=3, sticky=tk.NW)

            self.InBoxList=ttk.Frame(self)
            self.InBoxList.grid(row=1, rowspan=3, column=0, sticky=tk.NW+tk.SE)

            self.TextDisplay=tk.Text(self)
            self.TextDisplay.grid(row=1, rowspan=3, column=1, columnspan=3, sticky=tk.NW+tk.SE)

            self.__messages=[]

        def insert(self,index=0, mID=0, sender=None, subject=None, message=None, date=None, Read=False):
            if sender!=None and subject!=None and  message!=None:
                self.InBoxList.grid_rowconfigure(self.__itemCount, weight=0)

                self.__messages.append(MessageObject(self.InBoxList))
                self.__messages[-1].mID.set(mID)
                self.__messages[-1].text.set(message)
                self.__messages[-1].sender.set(sender)
                self.__messages[-1].subject.set(subject)
                self.__messages[-1].date.set(date)
                self.__messages[-1].Read(Read)
                self.__messages[-1].grid(row=self.__itemCount, column=0, sticky=tk.NE+tk.SW)
                self.__messages[-1].bind_all("", self.__selectionChanged)

                self.__itemCount=self.__itemCount+1
                return 0
            else:
                return 1

        def Messages(self):
            return self.__messages

        def __selectionChanged(self, event):
            try:
                item=event.widget

                #Empty Message Display
                self.TextDisplay.delete(1.0, tk.END)
                self.__currentSubject.set("")
                self.__currentTimestamp.set("")

                #Deactivate all but the selected one (the one calling)
                for i in range(0,len(self.__messages)):
                    print("EventItem: %s"%item)
                    print("Message:   %s"%self.__messages[i])
                    found=False

                    if "%s"%self.__messages[i] in "%s"%item :
                        self.__messages[i].Selected(True)

                        #Refresh Message Display
                        self.TextDisplay.insert(tk.END, self.__messages[i].text.get())
                        self.__currentSubject.set(self.__messages[i].subject.get())
                        self.__currentTimestamp.set(self.__messages[i].date.get())
                    else:
                        self.__messages[i].Selected(False)

            except Exception as ex:
                #Not in clickable Area?
                if __DEBUG__>1: print("Got click but cannot link it to item - %s"%ex)
                pass

        def delete(self, index=0, messageObject=None):
            self.__logger.debug("")
            if messageObject!=None:
                for i in range(len(self.__itemCount)):
                    if self.__messages[i]==messageObject:
                        self.__messages[i].destroy()
            else:
                self.__messages[index].destroy()
            self.__itemCount=self.__itemCount-1

    if __name__=="__main__":
       # Styling
        __msg_style=ttk.Style()

        __msg_style.configure('Read.TFrame', background='#ffffff')
        __msg_style.configure('Read.TFrame', foreground='#000000')
        __msg_style.configure('Read.TFrame', font='Segue\ UI 8 normal')

        __msg_style.configure('Unread.TFrame', background='#fafafa')
        __msg_style.configure('Unread.TFrame', foreground='#0000ff')
        __msg_style.configure('Unread.TFrame', font='Segue\ UI 8 bold')

        __msg_style.configure('Selected.TFrame', background='#8888ff')
        __msg_style.configure('Selected.TFrame', foreground='#ffffff')
       #__msg_style.configure('Selected.TFrame', font='Segue\ UI 8 italic')

        __msg_style.configure('Read.TLabel', background='#ffffff')
        __msg_style.configure('Read.TLabel', foreground='#000000')
        __msg_style.configure('Read.TLabel', font='Segue\ UI 8 normal')

        __msg_style.configure('Unread.TLabel', background='#fafafa')
        __msg_style.configure('Unread.TLabel', foreground='#0000ff')
        __msg_style.configure('Unread.TLabel', font='Segue\ UI 8 bold')

        __msg_style.configure('Selected.TLabel', background='#8888ff')
        __msg_style.configure('Selected.TLabel', foreground='#ffffff')
       #__msg_style.configure('Selected.TLabel', font='Segue\ UI 8 italic')

        app=InBox()
        app.insert(sender="Hans Dampf", subject="Read Subject", message="Lorem ipsum Read", date="14/01/2013", Read=True)
        app.insert(sender="Test Name", subject="UnRead Subject", message="Lorem ipsum UnRead", date="14/01/2016", Read=False)

        app.bind_all("", app.destroy)
        app.mainloop()

A: I managed making it working. It seems I did not get the documentation properly.
The widget that raised the Event was not the instance of the widget MessageObject but the whole application as bind_all was used.

But Tkinter also allows you to create bindings on the class and application level; in fact, you can create bindings on four different levels:

*

*the widget instance, using bind.

*the widget's toplevel window (Toplevel or root), also using bind.

*the widget class, using bind_class (this is used by Tkinter to provide standard bindings).

*the whole application, using bind_all.

I slightly adapted the code to:
self.bind("<Button-3>", self.__showContextMenu)
for label in self.Labels:
    label.bind("<Button-3>", self.__showContextMenu)

Now the instance of the widget calls the handler and everything works.


text:
Q: How to change variable values that are in other project from a select form in other proyect on the same server? So I'm developing a web app that based on the selected images it has to change the variables values from other project that stores the path of the images, its like interface to configure the main project that shows the images.
I have the images stored in a folder inside the web app that im developing.
So my approach to solving this is to save the selected images paths to mysql or maybe not use mysql at all i don't know which will be better, then store the paths to an array or variables and then dump them in the main project`s code that is in the same server. Ill show you my form and how the main project gets the images.
I'm kinda new to laravel and web development in general but im not new to coding or mysql im on my last semester of systems engineering and this is for my social service but i really never done anything like this or close to it.
Thanks in advance.
I have read about how to store the images paths and view the images but i just don't know how to update other projects on the same server.
This is my select form

 Imagen 1

         Imagen

    <select id = "imgPreview" class="custom-select" >
     <option selected value="{{ asset('multimedia/1.jpg') }}">Imagen1</option>
     <option value="{{ asset('multimedia/2.JPG') }}">Imagen2</option>
     <option value="{{ asset('multimedia/3.jpg') }}">Imagen3</option>
     <option value="{{ asset('multimedia/4.jpg') }}">Imagen4</option>
     <option value="{{ asset('multimedia/5.jpg') }}">Imagen5</option>

</select>

and here is how the main proyects gets its images:

all of this variables are statics values and the goal is to change this values from my project.
I just have to update the var values to the selected ones in my project.

A: Just create an identical model in both projects, connect to the same database and use them as you normally would.
The catch is - they need to use the same database in .env file, but you can also use raw queries and use database_name, but it would require some tinkering.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Making custom column in WordPress dashboard for custom taxonomy SORTABLE I'm tearing my hair out trying to figure out what's wrong with this code. I've already read and tried every single question on this topic on StackOverflow - I'm hoping someone can spot a small bug and figure it out.
I have a custom post type called "books" with custom taxonomy "book-series". The "book-series" taxonomy has a custom meta value of "series-index-number" associated with it (used to display series in a certain order).
I want to display "series-index-number" as one of the columns on the main taxonomy page and also have it be sortable.
DISPLAYING the values is WORKING.
SORTING by the column is NOT WORKING.
Here's the full code:
UPDATE: I found the solution - use pre_get_terms to add on an action that will attach a meta class the term query. The code below is updated to reflect the working version.
...
// display the series index numbers on the main series list page
add_filter('manage_edit-book-series_columns', 'add_series_index_column' );
add_filter('manage_book-series_custom_column', 'add_series_index_column_content', 10, 3 );
add_filter('manage_edit-book-series_sortable_columns', 'add_series_index_column_sortable' );
add_action( 'pre_get_terms', 'series_orderby' );

// add series index column to series page
function add_series_index_column( $columns ){
    $columns['series_index'] = 'Order Number';
    return $columns;
}
// add actual series index values to the table
function add_series_index_column_content( $content, $column_name, $term_id ){

    if( $column_name !== 'series_index' ){
        return $content;
    }

    $term_id = absint( $term_id );
    $display_index = get_term_meta( $term_id, 'series-index-number', true );

    if( !empty( $display_index ) ){
        $content .= esc_attr( $display_index );
    }

    return $content;
}
// make series index column sortable
function add_series_index_column_sortable( $sortable ){
    $sortable[ 'series_index' ] = 'series_index';
    return $sortable;
}

function series_orderby( $query ) {
  global $pagenow;

  if(!is_admin()) {
    return $term_query;
  }

  // WP_Term_Query does not define a get() or a set() method so the query_vars member must
  // be manipulated directly
  if(is_admin() && $pagenow == 'edit-tags.php' && $term_query->query_vars['taxonomy'][0] == 'book-series' && (isset($_GET['orderby']) || $_GET['orderby'] == 'series_index')) {
    // set orderby to the named clause in the meta_query
    $term_query->query_vars['orderby'] = 'order_clause';
    $term_query->query_vars['order'] = isset($_GET['order']) ? $_GET['order'] : "DESC";

    // the OR relation and the NOT EXISTS clause allow for terms without a meta_value at all
    $args = array('relation' => 'OR',
       'order_clause' => array(
        'key' => 'series-index-number',
        'type' => 'NUMERIC'
      ),
      array(
        'key' => 'series-index-number',
        'compare' => 'NOT EXISTS'
       )
    );
    $term_query->meta_query = new WP_Meta_Query( $args );
  }
  return $term_query;
}

...

A: I found an answer! Here in this post:
https://wordpress.stackexchange.com/questions/159330/custom-taxonomy-custom-sortable-column/203834
The solution is to use pre_get_terms to attach a new meta query to the core term query.
I've updated the code in the original request to show the actual functioning solution.


text:
Q: "Update Model From Database" does not work in .edmx Entities file. My Database is DB2 I am trying to reflect new changes or add a new table to my model in EDMX file using 'Update Model From Database.' Then i get this error message in Update Wizard saying "Error retrieving Database information. An Item with the same key has already been added."
I am using DB2 database and VS 2010.
Please let me know how i can add a new table or reflect the changes to my model with the changes made to the database. Right now i am deleting the entire model and recreating the new one.
Any help is appreciated.

A: I was getting this same error. In my case with DB2 9.5 LUW the solution was to remove duplicate named stored procedures on the server. DB2 lets you have multiple stored procs with the same name but different definitions (ie different parameters). But apparently this isn't compatible with Entity Framework. Fortunately for me the duplicates were actually unused old versions.
An alternative is to edit your EDM file in XML editor mode.

A: I have followed the solution provided by vikrantislav. And in addition to that, I made one more change. By default EF tool brings objects from all the exiting schemas. So make sure you don't have duplicate store procedures in any of those schemas or change the connection properties to filter out by a specific schema. In my case I have filtered out by specific schema as I don't want to mess up with someone else's store procedures in other schemas. And now "update model from database" wizard started working. what a relief.
Schema filter in connection properties window


text:
Q: Are there any wikis that use BlueSpice? My problem is that I cannot find any BlueSpice wikis to check out how they look like so I can make my mind up about implementing this software in my MediaWiki too
I keep trying to find examples of BlueSpice wikis without any results.

A: I don't have a reference site but this may help.

*

*BlueSpice MediaWiki is seemingly well established.

*MidiaWiki provides a BlueSpice profile.

*The BlueSpice.com site site also includes some things that may help you:

*

*The 'Our customers' section and its View all references link identifies existing implementations. You might reach out to them.

*The SourceForge: BlueSpice free Discussion has resources and forums with which you might be able to answer your questions, or contact existing users.


text:
Q: How to use GDK with Quickly I trying to use the library gdk for scale down an image and apply it to a GdkImage.
This is the code
pixbuf = Gdk.pixbuf_new_from_file(fileName)
 pixbuf = pixbuf.scale_simple(100, 100, Gdk.INTERP_BILINEAR)

The problem is that python can't find Gdk even if I use everything in lowercase
Error:
pixbuf = Gdk.pixbuf_new_from_file(fileName)
NameError: global name 'Gdk' is not defined
I don't know what should I do because I tried to import Gdk but nothing is changed

A: Try importing it like this:
 from gi.repository import Gtk
 from gi.repository.GdkPixbuf import Pixbuf, InterpType

then:
 pixbuf = Pixbuf.new_from_file(filename)
 pixbuf = pixbuf.scale_simple(100, 100, InterpType.BILINEAR)

I would recommend using the command below because it automatically scales it when it reads it in. Just specify how big (pixels) you want the image to be:
 pixbuf = Pixbuf.new_from_file_at_size(size_x, size_y, filename)

*

*Using scale_simple() does not preserve aspect ratio.

*Using new_from_file_at_size() preserves aspect ratio

A: I had the same problem. Your answer almost worked for me, but I got the following errormessage:
AttributeError: 'gi.repository.Gdk' object has no attribute 'INTERP_BILINEAR'

But I found the definition of it here gtkmm:gdkmm Enums and Flags:
Gdk::InterpType {
  Gdk::INTERP_NEAREST,
  Gdk::INTERP_TILES,
  Gdk::INTERP_BILINEAR,
  Gdk::INTERP_HYPER
}

So for me it worked when I called the function like this:
from gi.repository import Gtk, Gdk
from gi.repository.GdkPixbuf import Pixbuf
...
pixbuf = Pixbuf.new_from_file('mypic.gif')
pixbuf = pixbuf.scale_simple(desired_width, desired_height, 2) # 2 := BILINEAR

...maybe this helps someone with the same problem ;)


text:
Q: Python: Write a subclass of "property" with special setting behavior I would like to write a subclass of Python's property which already has a setter on board which does a specific check on the value before setting.
Background: I have a class with many attributes which all must not be negative. So I would like to make them all to properties and check if they are set with non-negative values. But I don't want to write the same setter multiple times.
Please have a look at the following example:
class Body(object):
  _mass = 0.
  _size = 0.

  @nonnegative
  def mass(self):
    return self._mass

  @nonnegative
  def size(self):
    return self._size

Now I would like to define "nonnegative" which should inherit from "property". My ansatz was overwriting the __set__ method, but I'm stuck:
class nonnegative(property):
  def __set__(self, obj, value):
    if value < 0:
      raise ValueError, 'value must not be negative'
    ### then set the attribute to value, but how?
    ### how can I know the name of the attribute?

Or maybe I should overwrite fset? Or setter? Can somebody help?

A: isn't simplier like this:
class Body(object):
def __init__(self):
    self._mass = 0.
    self._size = 0.

    self.last = True

def __setattr__(self, name, val):
    if 'last' in self.__dict__:
        if val < 0:
            raise ValueError('value must not be negative')
            return
    self.__dict__[name] = val

def mass(self):
    return self._mass

def size(self):
    return self._size

The "last" is there only to skip values that you provide on init. Keep it ... last.
Obviously, you may check if the attr name is not a reserved/special one or else
if val < 0

will check all that you set after init.
EDITED: this will check for non negative when you set value, not when you get. If you want to allow negative values, but rise error only on retrieval, use
__getattr__

Or (for abarnert) in classic way, but you have to write setter/getter for every property:
class Body(object):
    def __init__(self):
        self._mass = 0.
        self._size = 0.

    @property
    def mass(self):
        return self._mass

    @mass.setter
    def mass(self, value):
        if value < 0:
            raise ValueError('value must not be negative')
        self._mass = value

    @mass.getter
    def mass(self):
        return self._mass


text:
Q: Azure Data Factory - Dynamic Skip Lines Expression I am attempting to import a CSV into ADF however the file header is not the first line of the file. It is dynamic therefore I need to match it based on the first column (e.g "TestID,") which is a string.
Example Data (Header is on Line 4)
Date:,01/05/2022
Time:,00:30:25
Test Temperature:,25C
TestID,StartTime,EndTime,Result
TID12345-01,00:45:30,00:47:12,Pass
TID12345-02,00:46:50,00:49:12,Fail
TID12345-03,00:48:20,00:52:17,Pass
TID12345-04,00:49:12,00:49:45,Pass
TID12345-05,00:50:22,00:51:55,Fail

I found this article which addresses this issue however I am struggling to rewrite the expression from using an integer to using a string.
https://kromerbigdata.com/2019/09/28/adf-dynamic-skip-lines-find-data-with-variable-headers
First Expression
iif(!isNull(toInteger(left(toString(byPosition(1)),1))),toInteger(rownum),toInteger(0))

As the article states, this expression looks at the first character of each row and if it is an integer it will return the row number (rownum)
How do I perform this action for a string (e.g "TestID,")
Many Thanks
Jonny

A: I think you want to consider first line that starts with string as your header and preceding lines that starts with numbers should not be considered as header. You can use isNan function to check if the first character is Not a number(i.e. string) as seen in the below modified expression:
iif(isNan(left(toString(byPosition(1)),1))
    ,toInteger(rownum)
    ,toInteger(0)
   )

Following is a breakdown of the above expression:

*

*left(toString(byPosition(1)),1): gets first  character fron left side of the first column.

*isNan: checks if the character is "not a number".

*iif: not a number, true then return rownum, false then return 0.

Or you can also use functions like isInteger() to check if the first character is an integer or not and perform actions accordingly.
Later on as explained in the cited article you need to find minimum rownum to skip.
Hope it helps.


text:
Q: Stdout and flush? It's appending and not flushing What I'm trying to do is have some 'progress text' on the bottom of a script that I've creating. If I for loop a list [1,2,3,4,5] and print i, then it simply prints 1,2,3,4, and 5 on separate lines. How about if I want to print 1 out to the screen, sleep 5 seconds, clear that out and then print 2?
I've tried using stdout.write("text"), sleep, flush, stdout.write("aetlkjetjer"), sleep, and it just simply adds on to that "text" statement instead of flushing the output.
Am I misunderstanding something with the way stdout.flush works? Isn't it supposed to flush/erase the output of the previous print?

A: In computer science, the term "flush" doesn't mean to erase what's already in a buffer; rather, it means to take the unwritten contents of a buffer in memory (like the stdout buffer) and write it, in this case to the screen. So when you tell the program to "flush stdout", you're really just telling it to "take what's in stdout and make sure it's all displayed on the screen."

A: All .flush() does is flush out the buffer. What you actually want is to write backspace(\b) to stdout.
import time, sys

for i in [1,2,3,4,5]:
    sys.stdout.write(str(i))
    sys.stdout.flush() #flush the buffer because python buffers stdout
    time.sleep(5)
    sys.stdout.write("\b") #literally "write backspace".
    sys.stdout.flush()

It gets more complicated if you want to count up to numbers with more than one digit.


text:
Q: Does JLex include a yymore function? Lex includes a function yymore() that concatenates the next recognized input expression to the current input string.
JLex, which implements Lex for Java (and is not the same package as jflex, to my knowledge), does not mention yymore() in its documentation. Does  yymore() work in JLex?

A: No.
From a Coursera forum (this was also my experience):

The middle of section 4 of the Lex manual shows the use of a yymore() method to ease parsing of string literals. This method does not seem to be available in JLex.

https://class.coursera.org/compilers-003/forum/thread?thread_id=223, Tim McIver


text:
Q: Graphical proof of variance decomposition for linear regression Suppose we aim to predict $Y$ from $X$ using the linear regression model $Y = mX + b$.  There is a standard variance decomposition:
$$\operatorname{Var}[Y] = \operatorname{Var}[\widehat{Y}] + \operatorname{Var}[R],$$
where $\widehat{Y}=mX+b$ is the model's prediction at $X$ and $R=Y-\widehat{Y}$ is the residual.  Thus, the variance of the $Y$'s is equal to the sum of the variance of the predictions and the variance of the residuals.
I can derive this algebraically.  But is there a simple graphical proof?  Or some other way to see why this is true, in a way that doesn't require much in the way of formulas or algebraic derivations?

A: How about simply:

$Var[Y] = Var[red] + Var[blue]$
Code:
x <- rnorm(10)
y <- rnorm(10, x)
plot(x, y, pch=19, col="blue", bty="n")
m <- lm(y ~ x)
abline(m, col="red")
ypred <- predict(m, newdata=data.frame(x=x))
segments(x, ypred, x, y, col="blue")


text: Q: Is there a way to view passwords in plaintext? I need to figure out a password, but I'm not supposed to change the password itself. Is there anyway, perhaps through the common-password file or a command to show the plaintext password of a user?


text:
Q: How to interpret correlation heatmaps? I've noticed that correlation heat maps are a popular method of visualising data, but I'm not sure what insights they provide. I can understand why we're interested in the relationship between different predictors and the target, but what do the correlations between the predictors themselves tell us? How do they help us to choose which variables will be useful for a model?

A: As ever it depends on the question at hand but often the interesting variables are those which are not correlated with each other but are both correlated with the target.
Collinearity between variables is often insightful because sometimes surprisingly different things end up related to each other and it teaches you something about the domain.
Collinearity increases the variance of a regression fit, so spotting variables that are correlated with each other gives you cause to do something about it. I.e. pick one of them or some linear combination of them to maximise the information you can get.
Finally, when you're preparing your data and transforming it with something more uncorrelated n mind, a correlation heatmap may be a good way to see how good a job you've done and where there is still work to do.

A: The heatmap may also show a clustering structure according to correlations, in which case it may be a good idea to represent the clusters by single variables (this could be a principal component of the variables in the cluster, or one "central" variable to represent them all, or some kind newly defined index that puts together the information in the variables in the cluster in a way meaningful from a subject matter perspective).


text:
Q: Check function if event has an accepted offer? I need to check if an event has an offer and i have made this function
public function hasAcceptedOffer()
{
    foreach ($this->offers as $offer) {

        if( $offer->accepted == 1 ){
        return true;

    } else {

        return false;

    }
}

But i think this can be made better, more optimized. Because if there are a lot of offers i don't want to go through all of them. What i want is that if a function finds an offer that is accepted it should stop further iteration.

A: I think you did good here.
You can remove the else part by doing this
public function hasAcceptedOffer()
{
    foreach ($this->offers as $offer) {

        if( $offer->accepted == 1 ){
           return true;

        }
    }
    return false;
 }

A: Assuming you only care if any offer was accepted, and you don't need to know which one, I like to do it like this:
public function hasAcceptedOffer()
{
    foreach($this->offers as $offer) {
        if($offer->accepted !== 1)
            continue;

        return true;
    }

    return false;
}

Each iteration of the loop will quickly skip to the next one if it doesn't match your desired criteria, it will return immediately when it finds the first positive result and skip processing the others (since you don't care anyway) and return false if no matches are found.
If you want to collect the offers that were accepted, you can amend it like so:
public function getAcceptedOffers()
{
    $results = array();

    foreach($this->offers as $offer) {
        if($offer->accepted !== 1)
            continue;

        $results[] = $offer;
    }

    return $results;
}


text:
Q: Redirection rules in codeigniter I want to create location pages in my codeigniter site. So I have one contrller named locations and index method. So all the requests http://mysite.com/location_name should be landed to http://mysite.com/index.php/locations/index. And all other should work as it is like http://mysite.com/login should be landed to http://mysite.com/index.php/home/login. Contact us http://mysite.com/contact-us should be landed to http://mysite.com/index.php/home/contact.
I tried to achieve this by writing following line route rule (route.php):
$route['(:any)'] = 'locations';  //location name can be anything around the world

So locations are working fine, but http://mysite.com/login and http://mysite.com/contact-us are not working, they redirecting continuously in infinite loop.
Please suggest the solution. Thank.

A: The routes are applied from top to bottom, so you need to have your more specific rules listed first, then your more generic rules last:
$route['login'] = 'home/login';
$route['contact-us'] = 'home/contact';
$route['(:any)'] = 'location/index';

I see that you mentioned you've tried changing the order of rules in your route file. So If you have done this and it's not working - you have something else going on.
I would check these things:

*

*.htaccess file (if you're using it)

*controllers that are causing the infinite loop (any redirections in there, _remap method, etc. )


text:
Q: Method dispose functionality C# Is there a way to dispose method variables without using try-finally block in C# 2010 (.Net 4)?
The story:
I have few files handler methods. Each handler (method) can abort in the middle of execution.
I like to dispose all method's object before exiting the method.
The option to compose dispose method for each handler is not an option.
Thank you
This demonstrate the general idea:
`public static class Comparison
    {
        private static bool CompareXmls(...)
        {
            //has 7 object to be disposed in 3 exit points acordding to 4 conditions
        //General method flow:

        //1. init part of the object

        //2. if(!<condition1>)
                //disposed objects
                //exit method

        //3. perform some actions

        //4. init some of the other objects

        //2. if(!<condition2>)
                //disposed objects
                //exit method

        //and so on...
    }

    private static bool CompareJpgs(...)
    {
        //has 12 object to be disposed in 10 exit points acordding to 4 conditions
    }

    private static bool CompareBitMaps(...)
    {
        //has 5 object to be disposed in 3 exit points acordding to 4 conditions
    }

    private static bool CompareTxts(...)
    {
        //has 12 object to be disposed in 10 exit points acordding to 4 conditions
    }
}`

I have another 7 comparison methods

A: using? Refer here for the full description on how and why to use http://msdn.microsoft.com/en-us/library/yh598w02(v=VS.100).aspx. A sample would be
using (MyDisposableType disposable1 = GetDisposable1(), disposable2 = GetDisposable2() /*,...*/)
{
    //your actions
}

after exiting from the using block, all disposable objects declared in its header will be disposed.
If your disposable objects are of different types, you can use nested usings:
using (MyDisposableType1 disposable1 = GetDisposable1())
{
    using (MyDisposableType2 disposable2 = GetDisposable2())
    {
        //more usings if needed, and then your actions
    }
}

A: I would put the method on an object that impiments idisposible and call this.dispose() in a finally block


text:
Q: Spring-Integration-SFTP download and process files I have used the below suggestion and able to download the files from the remote server. If I want to process the files after the download completes then how do I proceed? Can someone please guide me on how/where to get the control once the files are downloaded to my local system
spring integration + cron + quartz in cluster?
ApplicationContext.xml
<?xml version="1.0" encoding="UTF-8"?>

<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:int="http://www.springframework.org/schema/integration"
    xmlns:int-sftp="http://www.springframework.org/schema/integration/sftp"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/integration http://www.springframework.org/schema/integration/spring-integration.xsd
        http://www.springframework.org/schema/integration/sftp http://www.springframework.org/schema/integration/sftp/spring-integration-sftp.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.1.xsd">

    <context:component-scan base-package="com.reports"/>

    <context:property-placeholder location="classpath:reports.properties"/>

    <bean class="org.springframework.integration.sftp.session.DefaultSftpSessionFactory"
        id="sftpSessionFactory">
        <property name="host" value="${sftp.host}"/>
        <property name="privateKey" value="${sftp.key.location}"/>
        <property name="port" value="${sftp.port}"/>
        <property name="user" value="${sftp.user}"/>
    </bean>

    <int-sftp:inbound-channel-adapter
        id="sftpInboundAdapter"
        auto-startup="false"
        auto-create-local-directory="false"
        channel="receiveChannel"
        delete-remote-files="false"
        filter = "customfilter"
        remote-file-separator="/"
        local-directory="${local.directory}"
        remote-directory="${remote.directory}"
        session-factory="sftpSessionFactory"
        preserve-timestamp="true"
        local-filter="acceptAll">

        <int:poller trigger="sftp-trigger"/>
    </int-sftp:inbound-channel-adapter>

    <int:channel id="receiveChannel">
        <int:queue/>
    </int:channel>

    <bean id="customfilter" class="com.reports.filters.ReportsFileListFilter"/>
    <bean id="acceptAll" class="org.springframework.integration.file.filters.AcceptAllFileListFilter" />
    <bean id="sftp-trigger" class="com.reports.jobs.ReportsTrigger"/>

    <!-- Quartz job -->
    <!--  (1) Trigger - This is used in the Scheduler below -->
    <bean id="ReportCronTrigger" class="org.springframework.scheduling.quartz.CronTriggerFactoryBean">
        <property name="jobDetail" ref="ReportsJob"/>
        <property name="cronExpression" value="${cron.expression}"/>
    </bean>

    <!-- (2) Job -->
    <bean name="ReportsJob" class="org.springframework.scheduling.quartz.JobDetailFactoryBean">
        <property name="jobClass" value="com.reports.jobs.ReportsJob"/>
        <property name="name" value="ReportsJob" />
        <property name="durability" value="true" />
    </bean>

    <!-- (3) Scheduler -->
    <bean class="org.springframework.scheduling.quartz.SchedulerFactoryBean">
        <property name="schedulerContextAsMap">
            <map>
                <entry key="inputEndpoint"><ref bean="sftpInboundAdapter" /></entry>
                <entry key="inputEndpointTrigger"><ref bean="sftp-trigger" /></entry>
            </map>
        </property>
        <property name="dataSource" ref="dataSource" />
        <property name="overwriteExistingJobs" value="true" />
        <property name="quartzProperties">
            <props>
                <prop key="org.quartz.scheduler.instanceName">ReportsBatchScheduler</prop>
                <prop key="org.quartz.scheduler.instanceId">AUTO</prop>
                <prop key="org.quartz.jobStore.misfireThreshold">60000</prop>
                <prop key="org.quartz.jobStore.class">org.quartz.impl.jdbcjobstore.JobStoreTX</prop>
                <prop key="org.quartz.jobStore.driverDelegateClass">org.quartz.impl.jdbcjobstore.StdJDBCDelegate</prop>
                <prop key="org.quartz.jobStore.tablePrefix">dbo.QRTZ_</prop>
                <prop key="org.quartz.jobStore.isClustered">true</prop>
                <prop key="org.quartz.threadPool.class">org.quartz.simpl.SimpleThreadPool</prop>
                <prop key="org.quartz.threadPool.threadCount">1</prop>
                <prop key="org.quartz.threadPool.threadPriority">5</prop>
                <prop key="org.quartz.jobStore.selectWithLockSQL">SELECT * FROM {0}LOCKS UPDLOCK WHERE LOCK_NAME = ?</prop>
            </props>
        </property>
        <property name="triggers">
            <list>
                <ref bean="ReportCronTrigger" />
            </list>
        </property>
    </bean>

    <bean id="dataSource" class="org.springframework.jndi.JndiObjectFactoryBean">
        <property name="jndiName"><value>java:/MSSQLDS_APP</value></property>
    </bean>

</beans>

Custom Filter
public class ReportsFileListFilter extends AbstractFileListFilter<LsEntry> {
    SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
    @Override
    protected boolean accept(LsEntry file) {
        if (".".equals(file.getFilename()) || "..".equals(file.getFilename())) {
            return false;
        }
        String dt = sdf.format(new Date());
        if (file != null && file.getFilename().contains(dt)) {
            Log.logDebug(ReportsFileListFilter.class, "Downloading File :: "+file.getFilename());
            return true;
        }
        return false;
    }
}

Trigger
public class ReportsTrigger implements Trigger {
    boolean done;

    public Date nextExecutionTime(TriggerContext triggerContext) {
        if (done) {
            return null;
        }
        done = true;
        Log.logDebug(ReportsTrigger.class, "Job started for date :: "+new Date());
        return new Date();
    }

    public void reset() {
        Log.logDebug(ReportsTrigger.class, "Reset is called");
        done = false;
    }
}

Quartz Job
public class ReportsJob extends QuartzJobBean {

    private AbstractEndpoint inputEndpoint;
    private ReportsTrigger inputEndpointTrigger;

    public void setInputEndpoint(final AbstractEndpoint pInputEndpoint) {
        this.inputEndpoint = pInputEndpoint;
    }
    public void setInputEndpointTrigger(final ReportsTrigger pInputEndpointTrigger) {
        this.inputEndpointTrigger = pInputEndpointTrigger;
    }
    @Override
    protected void executeInternal(final JobExecutionContext pParamJobExecutionContext)
    throws JobExecutionException {
        inputEndpoint.stop();
        inputEndpointTrigger.reset();
        inputEndpoint.start();
        Log.logDebug(ReportsJob.class, "Job runnnnnnning");
    }
}

A:
Actually I want to parse the downloaded files and insert them into database tables

Well. Since FTP adapter polls the remote directory, stores those files to local one and sends the one by one as Message.payload (File object), there is no stops to do some custom process for each of them in the downstream flow.
E.g. you can use <int-file:file-to-string-transformer> and provide some further custom parser as <transformer ref="">.
In the end there is just enough to get deal with <int-jdbc:outbound-channel-adapter> to store the data from payload to the DB.


text:
Q: Use commandline to launch Chrome with POST data I have a script at the end of some test data that launches Chrome. Unfortunately I can't seem to find the switch to launch a url in POST or to include POST data.
I know you can possibly do javascript: in chrome's url bar to make it execute javascript, and then I could probably simulate a POST request, however when trying a test script, Chrome is just launching a blank page. I think it has something to do with the security feature. Is there a Chrome switch for disabling this security feature for that one webpage launch?
test script (found it here: https://productforums.google.com/d/msg/chrome/CLDQ5KhXfFk/x0r7PGY1CooJ, kind of nice)
javascript:W7=open('','A','width=320,height=240,resizable');W7.focus();with(W7.document){write('<title>Javascript Tester</title><form><textarea name=X rows=10 cols=34 wrap>javascript:</textarea>
<input type=button value=Run onclick=opener.location=X.value>');void(close())}


text:
Q: under hange root environment: error while loading shared libraries: libjli.so: cannot open shared object file: No such file or directory Actually I have solved the problem but I don't understand why it works.
I have been developing under a change root environment, which was configured by someone else. I tried to use java command, but got that error message in the title.
After searching for solutions to this problem, I found no one works for my situation. Then I downloaded the newest java package from Oracle website and put it somewhere in my change root environment. By running ./java in .../jre.../bin, I tried test whether this new one works and it did work.
Then the thing I cannot understand happened. After testing the new jre, the old java command is fixed and I don't get the error message any more. I have used "java -version" to check the version of the java command and it was the old version.
Can someone explain?


text:
Q: Singular or plural when referring to an event and a specific case of that event In sentences in which a verb references an event, and a particular case of that same event, should i use the singular or plural form for the verb?
for example:
"milk production, and in particular white milk production, is/are subject to severe scrutiny"

A: The phrase is saying that milk production (just one noun) is subject to severe scrutiny. The way in which the second noun is added is just adding emphasis to the first noun, like "all balls (especially bouncy ones) bounce" (please excuse the bad example here, I can't think of a better one at this time...


text:
Q: If $A$ is normal, show that $A$ and $A*$ are simultaneously diagonalizable. If $A$ is a normal matrix, show that $A$ and $A^*$ (conjugate transpose) are simultenously diagonalizable over the field of complex numbers.
I know:

*

*$AA^* = A^*A$

*If $A$ and $B$ are simultaneosly diagonalizable then $AB=BA$.

*If there exists an invertible P such that $P^{-1}AP$ and $P^{-1}A^*P$
are both diagonal, then $A$ and $A^*$ are simultanously diagonalizable.

*Every normal matrix is diagonalizable.
but I couldn't be able to solve the problem. Thanks for any help.


text:
Q: My meta viewport doesn't work I'm working at a website(Revogue).I'm trying to disable zoom for mobile phones and it doesn't work.I tried many metaviewports...Please help me((
<meta name="viewport" content="user-scalable=0, initial-scale=1, maximum-scale=1, width=device-width, height=device-height, target-densitydpi=device-dpi" />
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no">
<meta name="viewport" content="user-scalable=no, initial-scale=1, maximum-scale=1, minimum-scale=1, width=device-width, height=device-height, target-densitydpi=device-dpi" />
<meta name="HandheldFriendly" content="true" />

A: This should be all you need to disable zoom:
<meta name="viewport" content="user-scalable=no" />

If your browser is still zooming make sure there's no "force zoom" accessibility settings enabled. In Chrome it's under "three dot menu"->settings->accessibility.

A: You must config in css file to works, something like this
<style>
@-ms-viewport{
    user-zoom:fixed;
    max-zoom:2;
    min-zoom:2;
}

body, html{
    margin:0;
    overflow:hidden;
    -ms-content-zooming:none;
    -ms-overflow-style:none !important;
    background-color: #ccc;
    width:720px;
    height:480px;
}

</style>


text:
Q: Cordova error when using angular to get remote json I develop a little mobile app with cordova + onsen ui platform, i develop on a macbook pro, all things works perfectly but when i try to get remote json i get following error :
Uncaught Error: Module     org.apache.cordova.file.resolveLocalFileSystemURI does not exist.

I search on google but not found similar issue, anyone can help me please?
Thank you.
Below is latest detail :
I deleted all angular json call and "Uncaught Error: Module org.apache.cordova.file.requestFileSystem does not exist." remain, so i think it's not an angular problem but cordova issue

Thanks all for your question, this is my code to get json from angular :
Note : i use onsen UI framework for the UI
ons.ready(function(){

    myapp.controller("PostsCtrl", function($scope, $http) {
        $http.get('http://www.e-sysoft.fr/myicc/?get=events').
        success(function(data, status, headers, config) {
            $scope.posts = data;
            alert(data)
        }).
        error(function(data, status, headers, config) {
            // log error
        });
    });

})

When i run this code nothing happens could you help me?


text:
Q: Getting started with Visual Basic I'm getting started with learning visual basic and was wondering if I should download the visual studio community or the visual studio code? What's the difference?

A: If you own a Windows machine, Visual Studio Community is the best. But only if you have a Windows machine.
If you use some other OS like macOS you will have to use Visual Studio Code, but it is not as easy to set up.
macOS does have a Visual Studio for Mac, but it is not the same as Visual Studio for Windows. Instead, it is used for Unity3d programming and Xamarin for mobile applications.
Coming from 2 years of classroom experience, Visual Studio Community is the BEST way to begin learning Visual Basic.

A: VS Code uses .NET Core, a limited Open-Source Version of the .NET Framework.
VS Community uses the full .NET Framework and allows you to use e.g. Windows Forms.
VS Code is more lightweight than VS Community, but for a beginner it's usually simpler to use VS Community if you just want
to learn programming. There is also more information about VS Community so I recommend you to use it.
Visual Studio Community is only available for Windows, so if you are on Linux or MacOS X you'll have to use VS Code.


text:
Q: How do I add tailwindcss to vite? I'm using vite 0.16.6 and wanted to migrated a vuepress site to using vite.
However I was unsure how to configure vite to using tailwindcss.
in my index.css
@tailwind base;
@tailwind components;
@tailwind utilities;

#app {
  font-family: Avenir, Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  text-align: center;
  color: #2c3e50;
  margin-top: 60px;
}

A: After some digging, looks like that we have to include a postcss.config.js in the root directory of the application
module.exports = {
  plugins: [
    // ...
    require('tailwindcss'),
    require('autoprefixer'),
    // ...
  ]
}

A: yarn add tailwindcss @tailwindcss/typography @tailwindcss/ui -D

yarn tailwind init note : you can use npm
crate file : postcss.config.js and add :
module.exports={
 plugins: [
  require('tailwindcss'),
  require('autoprefixer'),
  ]
 }

Replace the contents of src/index.css file with:
@import "tailwindcss/base";
@import "tailwindcss/components";
@import "tailwindcss/utilities";

A: I wrote a vite tailwind plugin https://github.com/axe-me/vite-plugin-tailwind
it enabled the jit compiler by default and it also have a tailwind config viewer

A: If you want to create a vite project that includes tailwind, the create-vite-tailwind initializer package is what you want.
$ npm create-vite-tailwind
...
$ npm run dev


text:
Q: How to validate server's ssl certificate in python? I have configured my server to serve only https creating a self-signed certificate. I have a client that I has to validate the server's certificate and after that will download a file from the server.
How do I implement the validation in client? Is there any code example?
My question is similar with this one: How can the SSL client validate the server's certificate?
but although the fine explanation, I didn't find any help.
So far, in my code I create a directory and then I download the file with urllib2:
[...] #imports

def dir_creation(path):
try:
    os.makedirs(path)
except OSError as exception:
    if exception.errno != errno.EEXIST:
        raise

def file_download(url):
ver_file = urllib2.urlopen(url)
data = ver_file.read()
with open(local_filename, "wb") as code:
    code.write(data)

dir_creation(path)
file_download(url)

A: Rather than configuring your server to present a self-signed certificate, you should use a self-signed certificate as a certificate authority to sign the server certificate.  (How to do this is beyond the scope of your question, but I'm sure you can find help on Stack Overflow or elsewhere.)
Now you must configure your client to trust your certificate authority.  In python (2.7.9 or later), you can do this using the ssl module:
import ssl

...  # create socket

ctx = ssl.create_default_context(cafile=path_to_ca_certificate)
sslsock = ctx.wrap_socket(sock)

You can then transmit and read data on the secure socket.  See the ssl module documentation for more explanation.
The urllib2 API is simpler:
import urllib2

resp = urllib2.urlopen(url, cafile=path_to_ca_certificate)
resp_body = resp.read()

If you wish to use Requests, according to the documentation you can supply a path to the CA certificate as the argument to the verify parameter:
resp = requests.get(url, verify=path_to_ca_certificate)


text:
Q: Qt Linguist, macro and preprocessor Since moc object works with macro, is it possible to use the Qt Linguist with macro?
Basically, I want to achieve that :
#define TR1(x) QObject::tr(#x)
#define TR2(x) QObject::tr(x)
#define TR3(x) x
#define TR4 QObject::tr("Lolita4")

auto a = TR1(Lolita1);
auto b = TR2("Lolita2");
auto c = TR3(QObject::tr("Lolita3"));
auto d = TR4;

Here we only have the TR3 and TR4 that works. Is it possible to have TR1 and TR2 also?
Thanks

A: I'm using a "tr()" macro to cheat on Qt Linguist in QObject subclass.
#define tr(str) QStringLiteral(str)
QString str = tr("Lolita1");
#undef tr

And every time you use this variable
QString translation = tr(str.toUtf8());

These two steps should be in one class.


text:
Q: Eleminar elementos repetidos en un archivo .txt tengo un archivo llamado digamos ejemplo.txt en el que tengo los siguientes numeros.
1323
7445
1323
5345
3455
1323

Y me preguntaba como podria eliminar los repetidos, en este caso el numero 1323 y dejar que solo quede uno, que quede de esta forma:
7445
5345
3455
1323

Muchas gracias.

A: Una alternativa es usar Streams que nos brinda Java 8.
public class Main {

    public static void main(String[] args) {

        try (Scanner sc = new Scanner(new File("/home/crack81/Desktop/file.txt"))) {

            List<String> numbers = new ArrayList<>();

            while(sc.hasNext()){
                numbers.add(sc.nextLine());
            }

            List<String> filtered = numbers.stream().distinct().collect(Collectors.toList());

            filtered.forEach(System.out::println);

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
    }
}

A: Otra alternativa (con streams) seria usar HashSet, ya que no permite duplicados.
Main:
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
import java.util.stream.Collectors;
import java.util.stream.Stream;

public class Main {

    public static void main(String[] args) throws IOException {

        String fileName = "pathtofile.txt";
        Set<String> list = new HashSet<String>();
        Path path = Paths.get(fileName);

        try (Stream<String> lines = Files.lines(path)) {
            list = lines
                    .collect(Collectors.toSet());

        } catch (IOException ex) {
          //capturar la excepción
        }

        //imprimir en consola
        list.forEach(e -> System.out.println(e));

        //Reemplazar archivo
        BufferedWriter out = new BufferedWriter(new FileWriter(fileName));
        Iterator<String> it = list.iterator();
        while(it.hasNext()) {
            out.write(it.next());
            out.newLine();
        }
        out.close();

    }
}

Finalmente este seria el archivo txt reemplazado:
1323
3455
7445
5345


text:
Q: Import declarations may only appear at top level of a module and trying type="module" just gives me a new error I'm working with fairly simple code. I'm making a todo list and using webpack because I'm following The Odin Project. I have my index.js in my src folder where I create the UI elements. I have another js file, projects.js  where you can actually add new projects. I want to import the add project function so when you click on the +project button you can add a new project. But whenever I try to import on either js files I have, it gives me the "" error. I googled, some people said to add type="module" to the scripts I'm using. So I did that and now I get an error in the firefox console when I open my html:
"Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resources at file: todo-list/src/index.js (Reason: CORS request not http)" and "Modules source URI is now allowed in this document todo-list/src/index.js"
I'm not advanced enough to understand what this means even after googling these errors. I literally just made another project, and had 0 issues importing things from other js files. I'm very confused. Can anyone help me? ):
my import looks like this:
import addProject from '.projects.js'

A: So I figured it out - for both errors, when I was following the webpack tutorial here (https://webpack.js.org/guides/getting-started/) I forgot to create the webpack.config.js file. I started from scratch, and made sure I used this first command, which I skipped on accident when I first started the project:
npx webpack --config webpack.config.js

Also, me being dumb, and not remembering how things worked with webpack as described in TOP, I don't need to actually add the <script> tags for all the scripts I'm using besides the main.js (the stuff that looks like spaghetti code) since I'm guessing it knows what to do with the index.js and goes from there, as index.js is referenced as the entry: in the webpack.config.js file.
I'm fairly new at working with webpack, so hopefully that makes some sense if someone else comes across this issue like me. I had to go back and look at my restaurant page project and see how it was set up. (^:


text:
Q: Fetch data from mysql with xiaomi device I'm developing an app that fetchs data from mysql database. When I run the app with my samsung device, data will be fetched from database and showing up but if I run the app with my xiaomi device, nothing comes from server. here are my permissions:
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<uses-permission android:name="android.permission.CHANGE_NETWORK_STATE"/>

what am I doing wrong?

A: I found the problem wasn't about samsung or xiaomi. It was about Android version of device. Android 9 and upper versions dont allow php mysql connection. We need to add,
android:usesCleartextTraffic="true"

to Manifest file and it works.


text:
Q: Ubuntu installation hangs at partition menu Hello guys I'm trying to dual boot ubuntu on my ssd with windows 7 64 installed. I had already reserved 40gb free space for it in advance. I tried to install both 14.04.1 and 12.04 with no success. The both  hang at the partition menu. Any suggestions?
edit:
Ok so I managed to get this during an installation attempt.
http://oi61.tinypic.com/rlidqe.jpg

A: If you are installing Ubuntu desktop, it will sense the windows partition, then ask you if you want to keep the windows partition, and install Ubuntu alongside, or delete the windows partition, and use the whole disk for Ubuntu. After answering this question, you should be able to use the default disk partition it provides, and not go into the partition menu at all.


text:
Q: ¿Cuál es la función real del operador "<<" en JavaScript? En diferentes páginas me han dado diferentes ejemplos y aún no entiendo realmente el funcionamiento del operador <<

var a = 4 << 3;
var b = 4 << 5;

console.log("a = "+a + " y b = " +b);

A: Este operador << se llama ShiftLeft y >> es ShiftRight lo que hace es que en notacion binaria ShiftLeft desplaza el numero binario de la izquierda tantos ceros hacia la izquierda como diga el numero de la derecha e inversamente lo hace ShiftRight:
4 << 2 es 100 << 2 lo cual queda en binario 10000 que es 16.
Esto servia antes ya que la ALU(Unidad Aritmeticologica) solo podia sumar,restar, hacer AND Logico y dejar el valor Del buffer principal igual que como habia ingresado y cuando se necesitaba usar multiplicacion y division como te daras cuenta, con solo esas operaciones, eran muchas las iteraciones necesarias y por lo tanto mucho uso de CPU, pero esto es tema de arquitecturas de computadoras que es solo sirve para explicarte que estos dos simbolos previamente mencionados sirven para:
multiplicar un numero N por 2^M en el caso de shiftleft:
N << M -> 4<<2 -> (4*(2^2)) = 16.
O dividir N por M^2 en el caso de shiftRight
N>>M  -> 8>>3 == 8/(2^3) = 1.
1000 >> 3 == 1.

A: Justo como lo dice este enlace, desplaza el número de posiciones (indicado con el número de la derecha) del binario del numero de la izquierda, por ejemplo:
El número 4 en binario es 100 con el operador << hacemos que el binario se desplace agregando ceros al binario del número, entonces:
(Se agregan 3 ceros a la derecha del binario de 4 que es 100 )
4 << 3 == 100000 que  si lo convertimos  por el valor 1 en la posición 5 del binario es igual a:

32

(Se agregan 5 ceros a la derecha del binario de 4 que es 100 )
4 << 5 == 10000000 que si lo convertimos por el valor 1 en la posición 8 del binario es igual a:

128

Un ejemplo mas sencillo el 1 en binario seria 01, con el operado quedaría  de la siguiente forma:
1 << 1 == 2 == 10
1 << 2 == 4 == 100
1 << 3 == 8 == 1000

...
Ejemplos:

var a = 4 << 3;
var b = 4 << 5;
var c = 1 << 1;
var d = 1 << 2;
var e = 1 << 3;
console.log("a = "+a)
console.log("b = "+b)
console.log("c = "+c)
console.log("d = "+d)
console.log("e = "+e)

A: Son operadores a nivel de bits
Observa el siguiente ejemplo:

¿Te preguntaras, para que sirve esto?
Una de sus principales utilidades era para optimizar el trafico de datos en la red con el metodo de Bitwise mediante el cual puedes lograr a tener o emular tipos de datos de hasta un bit.
Existen varios operadores de bit:
Operadores de Bits Javascript

A: Los valores son almacenados en memoria en base binaria, lo que significa que cada bit tiene un peso de 2^N, así:
| 2^N | ... | 2^0 |

Para 8 bits:
   N  |   7 |  6 |  5 |  4 | 3 | 2 | 1 | 0 |
Peso  | 128 | 64 | 32 | 16 | 8 | 4 | 2 | 1 |

Así tendriamos como ejemplos:

*

*1 es representado en binario como 0000 0001 = (2^0)

*4 es representado en binario como 0000 0100 = (2^2)

*42 es representado en binario como 0010 1010 = (2^5 + 2^3 + 2^1)

Ahora, el operador << N desplaza los bits N posiciones hacia la izquierda, teniendo el mismo ejemplo del post:

*

*4 << 3, en version binario 0000 0100 << 3, y se obtiene 0010 0000, que es 32

*4 << 5, en version binario 0000 0100 << 3, y se obtiene 1000 0000, que es 128

*13 << 3, 0000 1101 << 3 = 0110 1000 = 104

Desde otro punto de vista, desplazar un numero a la izquierda N posiciones equivale a multiplicarlo por 2^N.

A: var a = b << c; convierte b en un número entero de 32 bits (entre -2147483648 y 2147483647) y lo desplaza   binariamente hacia la izquierda c posiciones. Como binario es base 2 cada desplazamiento equivale a multiplicarlo por 2: var a = 4 << 3; es equivalente a var a = parseInt(4) *2 *2 *2; ó también  var a = parseInt(4) * Math.pow(2,3);

var a = 4 << 3;
console.log("var a = 4 << 3;", a);

var a = parseInt(4) *2 *2 *2;
console.log("var a = parseInt(4) *2 *2 *2;", a);

var a = parseInt(4) * Math.pow(2,3);
console.log("var a = parseInt(4) * Math.pow(2,3);", a);

var a = 4.5 << 3;
console.log("var a = 4.5 << 3;", a);

var a = parseInt(4.5) *2 *2 *2;
console.log("var a = parseInt(4.5) *2 *2 *2;", a);

var a = parseInt(4.5) * Math.pow(2,3);
console.log("var a = parseInt(4.5) * Math.pow(2,3);", a);


text:
Q: Why File can be moved when file lock acquired by FileChanel.open() instead of RandomAccessFile.getChannel() I am testing NIO File Lock acquired by FileChannel.open() and RandonAccessFile.getChanel().
It is found that the file that FileLock acquired by FileChannel.open() can be move while FileLock acquired by RandonAccessFile.getChanel() do not.
FileChannel.open()
        File file = new File("../tmp/test.txt");
        FileChannel fileChannel = FileChannel.open(file.toPath(), StandardOpenOption.WRITE);
        FileLock fileLock = fileChannel.lock();
        System.out.println("file locked");
        boolean result = file.renameTo(new File("../tmp/test2.txt"));
        System.out.println("rename result " + result);
        fileLock.release();
        fileChannel.close();

RandonAccessFile.getChanel()
        File file = new File("../tmp/test.txt");
        RandomAccessFile randomAccessFile = new RandomAccessFile(file, "rws");
        FileChannel newChannel = (randomAccessFile).getChannel();
        FileLock fileLock = newChannel.lock();
        System.out.println("File locked");
        boolean result = file.renameTo(new File("../tmp/test2.txt"));
        System.out.println("rename result " + result);

A: Behavior of Java file locks are highly platform specific, and so is the behavior of renameTo, including its interaction with files that are explicitly locked or are "in use" in other ways.
In the case of Windows, some file "open" operations will lock the entire file, and rename doesn't work on locked file.  (Indeed, I suspect that the version of your code using getChannel() would fail even if you commented out the lock() call.  But I don't have a Windows machine to test this.)
By contrast, Linux doesn't lock files when you open them, and you can rename an open file.
How to deal with this?

*

*If you want your code to be cross-platform, you need to be extremely conservative.  For example, don't attempt to rename a file that your application currently has open.  Close all file "handles" before you rename.

*Alternatively, write your code to be aware of the platform, and do different things on different platforms as required.  (I can't advise precisely what, because your example doesn't tell us what you are actually trying to achieve.)


text:
Q: How does chef resolve core resources? Using chef-apply, It seems to me that this line is what triggers resource resolution and adds it to the resource collection of the run_context.
I have tried to dive into and follow where the code goes but I cannot find where it resolves a resource and then adds the instance of the resource to resource collection.
Where does chef add the resource into the run_context?


text:
Q: accurate method to compare the s3 object and local object I saved the modified time in ms and file size into the object's metadata in s3.  I realized even if I did not change anything for my file if I open it then just save the file without editing.  The modified time will be changed and in this case it will update the s3 object.  I thought of using size but size wouldn't be as accurate too because there are chances for the size to be the same even after modified.  I also used the Binary got back from s3.getObject and locally's file Binary but without any changes.  The Binary wont be the same too.  What would be a better more accurate way to track changes?
I have something like this in my code which saves the file modified ms and file size
fs.readFile(path, async (err, fileBinary) => {
      if (err) throw err;

      const s3 = new AWS.S3();
      const Key = path.replace(process.env.WATCH_PATH, '');
      const filename = Key.split('/').pop();

      // if filename is within the regex, ignore the file.  Do nothing.
      if (new RegExp(IGNORE_FILES_TO_S3()).test(filename)) return false;

      const getStat = await getFileStat(path);
      // console.log(getStat, 'getstatsssssssssssssss');
      const s3PutParams = {
          Body: fileBinary,
          Bucket: process.env.S3_BUCKET,
          Key,
          Metadata: {  // thought of saving these two as comparison in future usage, which works but really really accurate though
              mtimeMs: String(getStat.mtimeMs),
              size: String(getStat.size)
          }
      };
// rest of the code here just do comparisons and decide if `s3.putOjbect` should be done or not.
});

my getFileStat()
exports.getFileStat = (path) => {
    /*
    SAMPLE: success
    {
    dev: 2097,
    mode: 33204,
    nlink: 1,
    uid: 1000,
    gid: 1000,
    rdev: 0,
    blksize: 4096,
    ino: 5639856,
    size: 2,
    blocks: 8,
    atimeMs: 1545952029779.866,
    mtimeMs: 1545952020431.9802,
    ctimeMs: 1545952020439.98,
    birthtimeMs: 1545952020439.98,
    atime: 2018-12-27T23:07:09.780Z,
    mtime: 2018-12-27T23:07:00.432Z,
    ctime: 2018-12-27T23:07:00.440Z,
    birthtime: 2018-12-27T23:07:00.440Z
    }
    */
    return new Promise((res, rej) => {
        fs.stat(path, (err, stat) => {
            if (err) rej(err);
            res(stat);
        });
    });
};

Thanks in advance for any suggestions and help.
PS.  This is not saving anything into the DB so no info will be saved at all in case there's an idea of saving something into DB for comparison purpose

A: To compare the contents of a local file with an Amazon S3 object, use the ETag, which is a checksum on the contents. The ETag is available when retrieving information about an S3 object.
See: All about AWS S3 ETags - Teppen.io
Also, please note that an object uploaded via multi-part upload has a slightly more complex calculation. See: What is the algorithm to compute the Amazon-S3 Etag for a file larger than 5GB?


text:
Q: Which formatter is used when I send a multipart request to a Web API Controller in ASP.NET CORE? Checking the ASP.NET Core built-in formatters there seems to be no multipart formatter. Yet a multipart request is model bound, so there needs to be some kind of input formatter, that creates the key-value pairs, which are then model bound. Which formatter is that?

A: Model is bound during model binding. Model binder in its turn uses IValueProvider to get values from request. There is FormValueProvider for multipart content, which in its turn gets values from FormValueProviderFactory provided by request.ReadFormAsync() call. Default implementation of HttpRequest redirects the call to FormFeature's ReadFormAsync. So you can find all the logic for reading multipart content values there.


text:
Q: Toggle a td tag on click Here's my problem. I have a table with 3 rows. Within each row there's a hidden 'check' icon tag that toggles on and off when you click a table's row. I've gotten that to work successfully so far. What i'm trying to do now is to only have one checkmark showing at a time. So if one row is already checked and you click on another row, it'll uncheck the previously checked row and show the checkmark in the newly selected row. Here's the HTML and js that I have currently.

$(document).ready(function () {
    var tr = $('#eventListings').find('tr');
    $(tr).click(function () {
        if ($(this).find('td i').hasClass('hide')) {
        $(this).find('td i').removeClass('hide');
    } else {
        $(this).find('td i').addClass('hide');
    }
    });
});

          10/19 @ 4:30 PM
          Denver Broncos v San Francisco 49ers

           10/23 @ 4:25 PM
          Denver Broncos v San Diego Chargers

           11/23 @ 6:30 PM
          Denver Broncos v Miami Dolphins

A: You can hide the visible checked items using :visible selector and then toggle the clicked item using toggleClass() as follows:

$(document).ready(function () {
    var tr = $('#events').find('tr');
    $(tr).click(function () {
        $("td i:visible").addClass('hide')
        $(this).find('td i').toggleClass('hide');
    });
});
/*For Demo Purpose*/

i::after{
  content:"checked";
}
i.hide{
  display:none;
}

          10/19 @ 4:30 PM
          Denver Broncos v San Francisco 49ers

           10/23 @ 4:25 PM
          Denver Broncos v San Diego Chargers

           11/23 @ 6:30 PM
          Denver Broncos v Miami Dolphins


text:
Q: Why is the last element of the list not shuffled in the Fischer-Yates algorithm? On the Wikipedia, it gives the amended Fischer-Yates shuffle algorithm as:
-- To shuffle an array a of n elements (indices 0..n-1):
for i from 0 to n−2 do
     j ← random integer such that i ≤ j < n
     exchange a[i] and a[j]

Why is the last element of the array not shuffled?

A: Putting @CollinD's comments as an answer:
If i == n-1, then it can only possibly be swapped with j = n-1 so why bother running an extra iteration?
At a given i, there is a 1/(n-i) chance to swap with any element in [i, n) (including i itself)


text:
Q: Framer Motion StaggerChildren Animation on Child Removal do not Trigger Animation I have a list (ParentBox.tsx) that contains many items (Box.tsx). When clicking the Add button, the ParentBox has one additional unique Box. The animation works fine. However, there are two scenarios where it does not:

*

*When I click on the Box, it removes the item from the list. Framer Motion removes the Box from the user interface without exit animation.

*When clicking "Remove All", the whole list of items is removed. There is no exit stagger effect.

I want to have an individual element of the list animated out, and when the whole list is cleared, have them one by one animated out.
Full Repro in CodeSanbox
Parent Box
const variantsBoxContainer: Variants = {
  hidden: {
    transition: {
      staggerChildren: 0.1,
      delayChildren: 0.3,
      staggerDirection: -1
    }
  },
  show: {
    transition: {
      staggerChildren: 0.1,
      delayChildren: 0.3,
      staggerDirection: 1
    }
  }
};

let id = 3;
export const ParentBox = (props: ParentBoxProps) => {
  const [items, setItems] = useState<Item[]>([
    { id: 1, text: "Test #1" },
    { id: 2, text: "Test #2" }
  ]);
  return (
    <motion.div
      className="parentbox"
    >
      <button
        onClick={() => {
          id++;
          setItems([...items, { id: id, text: `Click to delete id ${id}` }]);
        }}
      >
        Add
      </button>
      <button
        onClick={() => {
          id++;
          setItems([]);
        }}
      >
        Remove All
      </button>

      <motion.ol
        variants={variantsBoxContainer}
        initial="hidden"
        animate="show"
        exit="hidden"
      >
        <AnimatePresence mode="popLayout">
          {items
            .sort((a, b) => a.id - b.id)
            .map((d) => (
              <Box
                key={d.id}
                data={d}
                onRemove={(item) => {
                  const newList = items.filter((i) => i.id !== item.id);
                  console.log(newList);
                  setItems(newList);
                }}
              />
            ))}
        </AnimatePresence>
      </motion.ol>
    </motion.div>
  );
};

Box
const variantBox: Variants = {
  hidden: { opacity: 0, top: -100, transition: { duration: 2 } },
  show: { opacity: 1, top: 0, transition: { duration: 2 } }
};
export const Box = (props: BoxProps) => {
  return (
    <motion.li
      className="box"
      variants={variantBox}
      onClick={() => {
        props.onRemove(props.data);
      }}
    >
      {props.data.text}
    </motion.li>
  );
};

What I have tried so far:

*

*Adding/Removing the explicit mention of initial, animate, exit on the Box component.

*Adding/Removing the when option.

*Tried all mode in the AnimatedPresence

*Try to add a function for the hidden (exit) variant to have a custom delay per index

*Ensure all Box all have unique key
Let me know if you have any idea what I am missing to have the animation on Box removal (children).
CodeSanbox

A: Exit animations will work if you explicitly indicate which variant to use for the animation states:
export const Box = (props: BoxProps) => {
  return (
    <motion.li
      custom={props.index}
      className="box"
      variants={variantBox}
      exit="hidden"
      initial="hidden"
      animate="show"
      onClick={() => {
        props.onRemove(props.data);
      }}
    >
      {props.data.text}
    </motion.li>
  );
};

I believe AnimatePresence is conflicting with the staggerChildren prop since it appears between the parent and children. See this issue on GitHub.
Quickest workaround is probably to use dynamic variants and manually set a delay in the variants for the Box component (based on the index in the items array.


text:
Q: Will my bluetooth keyboard/mouse autoconnect on a reboot without any extra work? I'm very new to Linux so I apologize if this is a very rudimentary question. That being said, I am planning on buying Bluetooth peripherals. (Microsoft Designer Compact Keyboard & Microsoft Bluetooth Ergonomic Mouse) And I need to know before I get them, if they will automatically connect to my computer on boot. I'm running Ubuntu 20.04.2 LTS aarch64 with the Ubuntu Mate environment. All help is appreciated, thank you!

A: Short answer, yes. Hardware is automatically discovered on boot, so no additional steps than having your Bluetooth USB dongle plugged in is required.

A: I don't think the question concerned a Bluetooth dongle, it concerned a bluetooth mouse and keyboard. The following worked for me:
Switch on the devices and put them in pairing mode. Open the bluetooth settings and click on the + sign at the bottom. Select your devices and pair them. Note their bluetooth addresses (6 pairs of hexadecimal digits separated by colons e.g. 0F:1E:2D:3C:4B:5A)
Now open a terminal e.g. with Ctrl+Alt+T
Enter bluetoothctl
Enter trust 0F:1E:2D:3C:4B:5A (i.e. the bluetooth address you noted earlier)
When the system responds that it trusts your device, repeat trust 0F:1E:2D:3C:4B:5A with the next device's address.
When you're finished, enter Exit.
Now your devices should connect automatically next time you boot.


text:
Q: How to avoid splitting tables between sections I have 5 tables and a section after them. After creation of an output file I have two tables on one page, then a section and last 3 tables on next page.
What I want to achieve is to put tables and section below them.
\begin{table}[ht]\footnotesize
\centering
\begin{tabular}{|ll|}
......
\end{tabular}
\label{tab:result}
\end{table}

\section{Section below tables}

A: or you can change \begin{table}[ht] to \begin{table}[H] and add \usepackage{float} to your preamble. the H means "absolutely do not float this, and put it right here."

A: If you're using memoir, it includes functionality from placeins. It allows you, for example, to do this:
\setFloatBlockFor{section}

which is equivalent to \usepackage[section]{placeins}

A: You can use the \FloatBarrier macro from the placeins package. This prevents floats from floating across the barrier. Alternatively, you can use the section option to that package to prevent floats from leaving the section.

A: The easiest way is to use the placeins package:
\usepackage[section]{placeins}

A: The simple \clearpage command just before the new section (after the table) seems to work nicely. (in this case \clearpage does not insert an empty page)
\afterpage{...} worked OK but hid the section from the contents section of my thesis.
\section{Name1}
Stuff
\begin{table}[h]
...
\end{table}[h]
\clearpage
\section{Name2}
Stuff 2
\begin{table}[h]
...
\end{table}[h]


text:
Q: Product of two absolutely convergent improper integrals is absolutely convergent Let $f$ and $g$ be such that $\int_{1}^{\infty}f(x)\,dx$ and $\int_{1}^{\infty}g(x)\,dx$ are absolutely convergent. I need to prove that $\int_{1}^{\infty}f(x)g(x)\,dx$ is absolutely convergent.
It's sufficient to prove that if $\int_{1}^{\infty}f(x)\,dx$ absolutely converges then $\int_{1}^{\infty}f^{2}(x)\,dx$ converges. I think this is easier to prove. However, I don't have an idea how to start out yet.
Any hints would be greatly appreciated.


text:
Q: Xamarin Forms Navigation stucks on WebService SomeMethodAsyncCompleted Event Hi everyone i am using a WCF Soap Webservice and consuming it inside a Xamarin.Forms MVVM Client. (Mvvm light with MvvmLightNavigationExtension.
The Problem is when i use the Async Methods from the Webservice and corresponding Completed Event in my ViewModel the Navigation stucks / the screen is not changing.
When i debug the current Navigation Page says to be my second page but the first Page is still showing.
I Also tried it with Messengers but that wont work eather.
Down Below is some example Code.
Fun fact: When i make a second Button/Command and navigate to my second page after i called the GetLoginResponseCommand i can navigate Back two times to the first page.
Its Probably some weird Threading/UI Thread thing but i don't get it.
public LoginViewModel(INavigationService navigationService, MyWebService service)
{
    _navigationService = navigationService;
    _myWebService = service;

    _myWebService.GetLoginInfoCompleted += MyWebServiceOnGetLoginInfoCompleted;
}

public RelayCommand GetLoginResponseCommand
{
    get
    {
        return _getLoginResponseCommand ?? (_getLoginResponseCommand = new RelayCommand(
            () =>
            {
                _orkaWebService.GetLoginInfoAsync(request);
            }));
    }
}

private void MyWebServiceOnGetLoginInfoCompleted(object sender, GetLoginInfoCompletedEventArgs e)
{
    _navigationService.NavigateTo(VmKeys.ArtikelBestandKey);
}

A: Try to use async/ await in your async methods.
return _getLoginResponseCommand ?? (_getLoginResponseCommand = new RelayCommand(
        async () =>
        {
            await _orkaWebService.GetLoginInfoAsync(request);
        }));

A: I Got it myself.
The MyWebServiceOnGetLoginInfoCompleted runs in an own Thread. But the _navigationService needs to be run on the UIThread.
(Same for ContentPage.DisplayAlert or ContentPage.DisplayActionSheet)
When you run it like Device.BeginInvokeOnMainThread(() => _navigationService.NavigateTo(VmKeys.ArtikelBestandKey)); it works like a charm!
private void MyWebServiceOnGetLoginInfoCompleted(object sender, GetLoginInfoCompletedEventArgs e)
{
   Device.BeginInvokeOnMainThread(() => _navigationService.NavigateTo(VmKeys.ArtikelBestandKey));
}

Thanks to Rohit for leading me to the right solution.


text:
Q: PHP Rename and illegal filename I have a strange problem with renaming an existing file:
I have on my server a series of html files that need to be selected via a file selection dialog and then renamed.
The form that opens the dialog is called via JavaScript and correctly opens the dialog, allows a file to be selected, and renames it, right up until I come across a file with some (presumably) illegal characters in it. At this point I get a file not found error.
The source and destination for the rename are the same, it is only the filename that needs to be changed.
My code, which works on other files is as follows (with variables renamed for some clarity):
$dest_path = realpath(dirname(dirname(__FILE__))) . $miDestination ;
$targefile = $dest_path  .  basename( $_FILES["thesrcfile"]["name"]);
$newName = $dest_path . $anewname . ".html";
rename($targefile,$newName);

As mentioned this works fine until I reach a file with a name such as:
These are "very" strangely-named file's!.html

From this I get a file not found error. All permissions are correct and this code has been working fine with more sensibly named files. By the way, I have no control over the names of the files and they can quite literally contain any characters.
Can anyone suggest a way to get the rename function to recognise these files as existing, and to rename them accordingly?
many thanks
Max

A: trim() and str_replace() all illegals char into $anewname var


text:
Q: .NET Core WEB API - Return 400 if user includes an unrecognized query parameter in the GET URL Pretty much as the title says - I want to throw a 400 bad request with a message something along the lines of Unexpected Query Param: someParam.
This would help consumers of the API greatly when trying to debug why their calls aren't working, e.g. if they've misspelled a parameter.
I've done a little searching and haven't found anything like this.

A: Some might say you're not trying hard enough:
return BadRequest("some error or object");


text:
Q: Improving Mass Update Query Performance I'm looking to run some remediation on my database which requires adding some new fields to a table and backfilling them based on specific criteria. There are a LOT of records and I'd prefer the backfill to run relatively fast, as my current query is taking forever to run.
I attempted updating via subqueries, but this doesn't seem to be very performant.
Query below is edited to show general process (so syntax might be a little off). Hopefully you can understand what I'm trying to do./
I'd like to update every single record in the accounts table.
I'd like to do this by goin through each record and running a number of checks against the ID of that record prior to updating. For any records that don't match up in the join, I just want to set them to 0.
Doing this over the course of a few hundred thousand records seems to take forever. I'm sure there is a faster more efficient way to go about doing this. Using Postgres.
UPDATE

    accounts

SET

    account_age = a2.account_age,

FROM

    (

    with dataPoints as (

        select

            COALESCE(account__c.account_id as account_id,
account__c.account_age, 0) as account_age

        from account__c

        OUTER LEFT join points on points.account_id = account__c.id

        OUTER LEFT join goal__c on goal__c.id = scores.goal_id

    group by account_id, account__c.account_age

     )

       select

       account_id,

            max(dataPoints.account_age) as account_age,

        from scores

        join account on accounts.id = scores.account_id

        group by account_id

    ) as a2

WHERE accounts.id = a2.account_id;


text:
Q: Segfaulting while finding path through maze I am trying to print out the coordinates of the maze as I am trying to solve using depth first search algorithm, however, it prints out the initial position, but it seg faults. Is there something I am doing wrong??? Here is my code :
#include "mazegen.h"
#include "stack.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#define  BUFFERSIZE 500
#define  FLAG

void mazeSolution(char maze[100][100], int counter, int counter2)
{
   stack*currentCell;

   int i;
   int j;

   currentCell = create();

  for(i=0; i<counter; i++)
  {
      for(j=0; j<counter2; j++)
      {

          if(maze[i][j] == 'S')
          {
              push(currentCell,i,j);
              currentCell->visited = true;
          }

      }
  }

   printStack(currentCell);

   while(currentCell != NULL)
   {
      pop(currentCell);

      if(maze[i][j] == 'F')
      {
           break;
      }
      if(i != 0)
      {
          if(maze[i-1][j] == ' ' && currentCell->visited != true)
          {
              currentCell->visited = true;
              push(currentCell,i-1,j);

          }
      }
      if(maze[i+1][j] == ' ' && currentCell->visited != true)
      {
          currentCell->visited = true;
          push(currentCell,i+1,j);
      }
      if(j != 0)
      {
          if(maze[i][j-1] == ' ' && currentCell->visited != true)
          {
              currentCell->visited = true;
              push(currentCell, i,j-1);
          }
      }
      if(maze[i][j+1] == ' ' && currentCell->visited != true)
      {
           currentCell->visited = true;
            push(currentCell, i, j+1);
      }

 }

  printf("No solution\n");

  printStack(currentCell);

}

I think it has something to do with my pop function and with the way I have implemented it
void pop (stack*theStack)
{
    node*theHead;

    if(theStack == NULL)
    {
        printf("Empty Stack. Error\n");
         exit(0);
    }

    theHead = removeFromFront(theStack->list);

    theStack->list = theHead;

}
node*removeFromFront(node*theList)
{
    node*temp;

    temp = theList->next;

    if(temp == NULL)
    {
        printf("pop Error\n");
        return NULL;
    }

    theList = theList->next;

    return theList;
}.

A: Look at this portion of your code:
while(currentCell != NULL)
{
      pop(currentCell);

      if(maze[i][j] == 'F')
      {
           break;
      }
   ...
}

You are popping a value from the stack - this is ok. But you need to assign the popped value toi and j. In your code, the value of i and j remain unchanged, so you have an infinite while loop. You are continuously pushing values in the stack inside this loop, which ultimately leads to segfault.

A: Keeping a visited status on the stack is useless - you need to check if the specific position has been visited when you try to access it from some new direction, which may happen if there is a loop in your maze. So the proper place for this attribute is a maze itself, not a stack.
You don't need separate stack and node structures - the stack is actually a list of nodes.
Building a stack is quite easy, but you need to imagine it's structure and behaviour before you start encoding. There are two basic (plain C) solutions: use a pre-allocated array or dynamically linked list. Let's use an array.
A stack's item will be
typedef struct node {
    int i, j;
} Node;

a stack itself:
Node stack[ 10001];

and a number of items currently stacked:
int stkptr = 0;

Now we can test if the stack contains any data:
int StackNonEmpty() { return stkptr; }

push new position onto the stack:
void Push(int i, int j) {
    stack[ stkptr].i = i;
    stack[ stkptr].j = j;
    stkptr ++;
}

read a position from the stack's top (assuming StackNonEmpty() != 0):
void Fetch(int *pi, int *pj) {
    *pi = stack[ stkptr - 1].i;
    *pj = stack[ stkptr - 1].j;
}

and remove it from the stack:
void Pop() { stkptr --; }

We also need to define a marker for visited positions:
int VISITED = '.';

or
#define VISITED '.'

and we're ready to write the algorithm:
for(i=0; i<counter; i++)
    for(j=0; j<counter2; j++)
        if(maze[i][j] == 'S')
        {
            Push(i,j);   // set the Start position
            i = counter; // this is to break the outer loop
            break;       // and this breaks the inner loop
        }
while( StackNonEmpty())
{
    Fetch(& i, & j);             // get a current position
    if( maze[i,j] == 'F')              // Finish found?
        break;
    if( maze[i,j] == ' ')              // empty cell?
        maze[i,j] = VISITED;
    // find next possible step
    if( i > 0 && maze[i-1,j] == ' ')   // cell to the left is empty
        Push(i-1,j);                   // step left
    else
    if( j > 0 && maze[i,j-1] == ' ')   // cell above is empty
        Push(i,j-1);                   // step up
    else
    if( i+1 < counter && maze[i+1,j] == ' ')
        Push(i+1,j);                   // step right
    else
    if( j+1 < counter2 && maze[i,j+1] == ' ')
        Push(i,j+1);                   // step down
    else                               // dead end - no way out
        Pop();                         // step back
}
if( StackNonEmpty())      // exited with break, so 'F' found
    PrintStack();
else
    PrintFailureMessage();  // could not reach 'F'

To show the results just print all items of the stack array until the stkptr position:
void PrintStack() {
    for(i = 0; i < stkptr; i ++)
        printf( "%d,%d\n", stack[i].i, stack[i].j);
}

EDIT
'VALID' status assignment corrected (was == instead of =), PrintFailureError replaced with PrintFailureMessage.


text:
Q: Is it possible to turn off eclipselink version increment for particular update? There is a similar question here for Hibernate with an answer by Palladium explaining how to merge a detached object back to the entity cache without increasing the version. Is the same also achievable with eclispelink? How?
I am aware how to achieve to goal with native queries, but that has drawbacks.


text:
Q: Function doesn't change value of the object attributes I need to write my own set function for the object. But it does not change the value of an attribute. I call the function in another js file.
function parameterSet(ifFloat, variable, newValue, max){
  if(newValue >= 0 && newValue <= max){
     if(ifFloat)
        variable = newValue;
     else
        variable = Math.floor(newValue);
     }
 }

 exports.lightObject.prototype.changeLightStartTime = function(newValue){
     parameterSet(true, this.lightStartTime, newValue, 23);
 };
 exports.lightObject.prototype.changeLightDurationTime = function(newValue){
     parameterSet(true, this.lightDurationTime, newValue, 23);
 };

socket.on('newLightParam', function(data){
   light.lightStartTime = data.newLightStart;           // this one works
   light.changeLightDurationTime(data.newLightLength);  // this one doesn't
});

A: This occurs because when you do that, you lose the reference to the object.
You can pass object to the function, and change lightDurationTime attribute inside that function.
function parameterSet(ifFloat, variable, newValue, max){
  if(newValue >= 0 && newValue <= max){
     if(ifFloat)
        variable.lightStartTime = newValue;
     else
        variable.lightStartTime = Math.floor(newValue);
     }
 }
 exports.lightObject.prototype.changeLightStartTime = function(newValue){
     parameterSet(true, this, newValue, 23);
 };

Or you if you want to make it more generic:
function parameterSet(ifFloat, variable, attribute, newValue, max){
  if(newValue >= 0 && newValue <= max){
     if(ifFloat)
        variable[attribute] = newValue;
     else
        variable[attribute] = Math.floor(newValue);
     }
 }
 exports.lightObject.prototype.changeLightStartTime = function(newValue){
     parameterSet(true, this, 'lightStartTime', newValue, 23);
 };

socket.on('newLightParam', function(data){
   light.lightStartTime = data.newLightStart;           // this one works
   light.changeLightDurationTime(data.newLightLength);  // this one doesn't
});

A: First, note that on the next line:

parameterSet(true, this.lightDurationTime, newValue, 23);

this.lightDurationTime will be a primitive value and passed by value to the parameterSet() method. So, you will lost the reference to this. You are not passing the memory reference to a value as you may think. However, a simple fix, could be passing the reference to this and the property you want to change:

parameterSet(true, this, "lightDurationTime", newValue, 23);

Example:

function parameterSet(ifFloat, obj, property, newValue, max)
{
    if (newValue >= 0 && newValue <= max)
    {
        if (ifFloat)
            obj[property] = newValue;
         else
            obj[property] = Math.floor(newValue);
    }
}

var lightObject = function()
{
    this.lightStartTime = 0,
    this.lightDurationTime = 0
};

lightObject.prototype.changeLightStartTime = function(newValue)
{
    parameterSet(true, this, "lightStartTime", newValue, 23);
};

lightObject.prototype.changeLightDurationTime = function(newValue)
{
    parameterSet(true, this, "lightDurationTime", newValue, 23);
};

let light = new lightObject();
light.lightStartTime = 5;
console.log(light.lightStartTime);
light.changeLightDurationTime(10);
console.log(light.lightDurationTime);


text:
Q: Использование переменных в $_POST Можно ли в $_POST[name] вместо name поместить переменную?

A: Итог.
$_POST - это ассоциативный массив данных, переданных скрипту через HTTP метод POST.
В документации написано, что ключом для ассоциативного массива может быть:

либо типа integer, либо типа string

Значит следующий код будет работать и для $_POST
$intKey = 1;
$_POST[$intKey] = "test"

$stringKey = "key";
$_POST[$stringKey] = "test 2"