text:
Q: meteor js how to write a file to disk from the server I am writing a meteor package 'myPackage' which needs to write a file onto disk using Npm FileSystem and Pah modules.
The file should end up in the example-app/packages/myPackage/auto_generated/myFile.js, where example-app project
has myPackage added.
fs = Npm.require( 'fs' ) ;
path = Npm.require( 'path' ) ;

Meteor.methods( {
    autoGenerate : function( script ) {
        var myPath = '/Users/martinfox/tmp/auto-generated' ;
        var filePath = path.join(myPath, 'myFile.js' ) ;
                    console.log( filePath ) ;    // shows /Uses/martinfox/tmp/auto-generated/myFile.js
        var buffer = new Buffer( script ) ;
        fs.writeFileSync( filePath, buffer ) ;
    },
} );

When I run the code above (server side only) I get
Exception while invoking method 'autoGenerate' Error: ENOENT,
no such file or directory '/Uses/martinfox/tmp/auto-generated/myFile.js'

Note /Uses/martinfox/tmp/auto-generated folder does exist

*

*Any ideas what is going wrong?

*Is it possible to obtain the absolute path to the meteor projects directory?

A: If you are just looking for the absolute path for your app, you could simply do var base = process.env.PWD, which yields: /Users/[username]/[app-name]
This would avoid the extra stuff .meteor/local/build/programs/server

A: To get the path of your project you can do this :
from main.js stored in the root of your app
var fs = Npm.require('fs');
__ROOT_APP_PATH__ = fs.realpathSync('.');
console.log(__ROOT_APP_PATH__);

You can also check if your folder exists :
if (!fs.existsSync(myPath)) {
    throw new Error(myPath + " does not exists");
}

Hope it will help you


text:
Q: What are efficient algorithms for immutable dictionaries/sets? What are efficient algorithms for immutable dictionaries/sets? By efficient I mean they either have better or comparable time and/or memory performance compared to their mutable versions. I don't necessarily mean this in the context of functional programming, where I've seen immutability equated to persistent data structures.
A concrete example is Guava, where I have seen memory savings when used with sets that don't need to be modified.

A: There are data structures that a easy to read and (relatively) slow to build, so they tend to be more suitable for immutable data structures.
Just for example, for a mutable set, you'd typically use some sort of tree structure (e.g., red-black tree or AVL tree). Such a tree has reasonable complexity for both lookups and modifications (typically O(log N) for either). A tree, however, has two (or three) pointers per data item. That reduces the data density, so you get relatively poor cache usage.
If your dictionary is immutable, you can use a sorted array instead. This eliminates the pointers, increasing the data density, so you get (at least somewhat) better cache usage.
In a typical case, using a sorted array will let you go a step further than that though. A tree supports binary searching to find the item of interest. If your keys have a reasonably predictable distribution (most often roughly uniform, but other distributions can be handled as well), you can use an interpolating search instead.
For example, consider looking up a word in a (physical) dictionary. If you're looking for "cab", you know you want to look somewhere close to the beginning; if you're looking for "yes", you know you want to look close to the end.
An interpolating search does roughly the same--uses the key to compute a decent approximation of the starting location for the search, rather than always starting at the middle (and the same on subsequent searches).
Assuming the key distribution is at least somewhat predictable, this will typically improve your lookup complexity to roughly O(log log N), which is often referred to as "pseudo-constant", because it really is essentially constant for almost any size of collection encountered in reality.
For example, let's assume common (base 10) logarithms. Every size from 100 through 109 has log log N = 1. Every size from 1010 through 1099 has log log N = 2.
For any practical purpose, N=2 is already well past the maximum we can ever expect to deal with--to get to N=3, we'd need a collection of at least 10100 items. To put that in perspective, there are about 1057 atoms in the solar system, so if you could store each item using only a single atom, you'd still need the atoms from approximately 1043 solar systems to store a collection of 10100 items.

A:
By efficient I mean they either have better or comparable time and/or
  memory performance compared to their mutable versions.

Strictly speaking I don't believe this can exist, because you can always show me an immutable data structure and I can find ways to make something cheaper if it could be made mutable. For example, I might be able to eliminate the requirement for garbage collection or reference-counting if it was mutable.
There are data structures that are well-suited to become immutable though where the costs are relatively cheap. Most of the non-trivial ones are typically at least partially contiguous. That allows the costs of ref-counting or GC to be trivialized if the nodes are unrolled and store multiple elements each, not one element per node.
There's also often a balancing act between shallow copying more pointers vs. deep copying fewer non-unique elements because any data structure can be made immutable if you just copy the whole freaking thing every time you want to change anything, but that could be explosive in memory and processing requirements. On the flip side, if you shallow reference every single individual element, that could be explosive in memory and processing requirements with all the extra pointers, all the extra indirection and potential memory fragmentation, the cost of ref-counting or GC having to be paid for every single element, etc.
So often I think the most efficient immutable data structures for sets and dictionaries are going to be partially contiguous ones, like a hash table using open addressing but instead of using one giant array for the whole table, it uses unrolled blocks storing, say, 64 keys each. Another example would be an n-ary tree storing many keys in one node.
Of course a hash table using separate chaining is really straightforward to make immutable since making singly-linked LIFO lists immutable just requires storing a different head pointer per immutable list. However, it's straightforward but not very cheap since that implies, again, reference-counting or GC paid on a per-element level.
Also chances are that you'll need something like a "builder" or "transient" to express what you want to do with it, since you don't want to pay the cost of generating a new immutable instance every single time you just insert or remove one key.

A concrete example is Guava, where I have seen memory savings when
  used with sets that don't need to be modified.

Here perhaps it's not so much about immutability but just a data structure being able to work off the assumption that elements will simply be inserted to it and known in advance and not having to deal with dynamic removal and insertion of elements after it's built.
In that case, for example, you can use a sequential memory allocator as one optimization because you don't have to handle freeing memory for individual elements since elements are never going to be individually removed from the data structure. All you have to be able to do is purge all the memory for all elements when the data structure is destroyed.
Also if the elements are all known in advance, you might be able to avoid having to do reallocations to expand the size of the structure. You can make it perfectly-sized upfront since you know all the elements you're going to be inserting to it upfront so you don't have to reserve any additional memory for future insertions.
Data structures which only need fulfill these types of "static" and not "dynamic" requirements also provide plenty of room for post-processing after they're built. A binary tree might be post-processed to reallocate its nodes in a cache-friendly access pattern, for example. You can afford that with a static kind of data structure that doesn't deal with dynamic insertions and removals since there's a clear build phase which leaves room for post-processing, after which you no longer have to deal with changes to the data structure.
Ex: Mutable "Clear" Method
Any data structure which has fewer functional requirements to deal with will generally have more room to optimize. But here it's not about immutable data structures so much as data structures which can just be built in advance and don't have to deal with dynamic insertions and removals. Such data structures could still be made mutable and stay just as cheap. For example, such a data structure might still provide a mutable clear method to clear the entire contents of the set/dictionary, and providing such a mutable method would not require it to lose those potential optimizations described above. So there's no case as far as I see where immutability makes anything cheaper, since immutability imposes more functional requirements on a data structure, so to speak, not less.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Can Hibernate generate tables without Spring? I have Hibernate on my project,
but no Spring yet.
I wonder if:
Question 1:
Hibernate annotations and dialect propert in persistence.xml is enough for Hibernate to generate tables?
Question 2:
Also i guess, there must be something like Spring to look for annotations and fire a generation event and start some other things?
EDIT:
My persistence.xml file
<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.1" xmlns="http://xmlns.jcp.org/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence http://xmlns.jcp.org/xml/ns/persistence/persistence_2_1.xsd">
    <persistence-unit name="Kutuphane2" transaction-type="RESOURCE_LOCAL">
        <non-jta-data-source>kutuphaneDS</non-jta-data-source>
        <properties>
            <property name="javax.persistence.jdbc.url" value="jdbc:mysql://localhost:3306/kutuphane"/>
            <property name="javax.persistence.jdbc.user" value="root"/>
            <property name="javax.persistence.jdbc.password" value="root"/>
            <property name="javax.persistence.jdbc.driver" value="com.mysql.jdbc.Driver"/>
            <property name="hibernate.show_sql" value="true"/>
            <property name="hibernate.format_sql" value="true"/>
            <property name="hibernate.hbm2ddl.auto" value="create"/>
            <property name="hibernate.dialect" value="org.hibernate.dialect.MySQL5InnoDBDialect"/>
        </properties>
    </persistence-unit>
</persistence>

A:
Hibernate annotations and dialect propert in persistence.xml is enough for Hibernate to generate tables?

Yes, Hibernate works by itself, Spring just helps Hibernate to provide a data source and help you to access to the Hibernate API.

there must be something like Spring to look for annotations and fire a generation event and start some other things?

Nope, that's Hibernate work as well, just by adding hibernate.hbm2ddl.auto property. This is explained here:

*

*Hibernate 4.3.5 Documentation. Chapter 3. Configuration. Table 3.7. Miscellaneous Properties

*Hibernate: Automatically creating/updating the db tables based on entity classes

*Hibernate hbm2ddl.auto possible values and what they do?


text:
Q: how to get the name of a JMenu when a JMenuItem is clicked How would one get the name of the JMenu holding a clicked JMenuItem? I tried doing this:
public void actionPerformed(ActionEvent arg0) {
    JMenu menuthing = (JMenu)(arg0.getSource());
    String menuString =  menuthing.getText();
    JMenuItem source = (JMenuItem)(arg0.getSource());
    String colorType = source.getText();

But it gives me this error:
Exception in thread "AWT-EventQueue-0" java.lang.ClassCastException: javax.swing.JMenuItem cannot be cast to javax.swing.JMenu

So is there a way to cast to JMenu, or some other way to determine the name?
Thanks.

A: I would suggest adding a MenuListener to your JMenu and add your code in public void menuSelected(javax.swing.event.MenuEvent evt).
Since this is a MenuEvent, the getSource() method will return the JMenu object
If you want to get it from your ActionEvent, try something like this:
JPopupMenu menu = (JPopupMenu) ((JMenuItem) evt.getSource()).getParent();
JMenu actMenu = menu.getInvoker();

A: Instead of casting to a JMenu just cast to JMenuItem. Then get the JMenu from it.
JMenuItem jmi = (JMenuItem) arg0.getSource();
JPopupMenu jpm = (JPopupMenu) jmi.getParent();
JMenu menu = (JMenu) jpm.getInvoker();

A: Assuming the JMenuItems are the children of JMenu, you may still do it with ActionEvent:
JPopupMenupopup = new JPopupMenu();
popup.setName("popup");

....
@Override
public void actionPerformed(ActionEvent e) {
    JMenuItem source = (JMenuItem)(e.getSource());
    try{
        JMenuItem menuItem = (JMenuItem) e.getSource();
        JPopupMenu popupMenu = (JPopupMenu) menuItem.getParent();
        Component invoker = popupMenu.getInvoker();
        JPopupMenu popup = (JPopupMenu) invoker.getParent();
        System.out.println("NAME OF JMENU: "+popup.getName());

        //If you need the selection of cell(s)
        JTable table = (JTable)popup.getInvoker();
        int row = table.getSelectedRow();
        int col = table.getSelectedColumn();
        System.out.println("Selected cell: "+row+"-"+col);
    }catch(Exception ex){
        ex.printStackTrace();
    }
}


text:
Q: Are there any features on ARM64 iOS device not available if you deploy in armv7? I'd like to deploy some apps in armv7 (all our many closed source dependency libraries only support 32 bit).
I was wondering other than performance improvements, will I lose access to any specific features on arm64 devices if I do this?

A: no. it is just a different arch not a different runtime version or class library
it may change in the future, but right now: no


text:
Q: Añadir valores a un array en python yo estoy codificando para ingresar valores de un vector de la siguiente forma:
array=[]
n=3
for i in range(n):
   x=int(input("Valor: "))
   array.append(x)

Sin embargo, busqué pero no encontre otra forma mas optima de poder ingresar valores al array, vengo de programar mucho en c++ y estoy aprendiendo python, probe de esta forma:
array=[]
    n=3
    for i in range(n):
       A[i]=int(input("Valor: "))

Pero no es valido, ¿Existe una forma mas adecuada de introducir valores por teclado a un array?

A: Yo te recomiendo usar List Comprehensions de la siguiente forma.
numeros = [input("Valor: ") for x in range(3)]

En Python 2 la función input intenta convertir el resultado a una declaración de Python y si quieres obtener todo el resultado como string usa raw_input.
En Python3 raw_input no existe y solo se usa input y te devuelve un string


text:
Q: Edit to Answer Disappeared I edited this question's answer, which was my own question.  The edit I made disappeared and revision history does not show it was edited by me or pending edit.

A: The edit was rejected by Truth and talonmies. You can always view your activity page in your profile to see a list of your suggested edits. It doesn't show which ones were accepted or rejected from that specific page (disappointed face) but you can click them to see the edit and the reasons why it was rejected (if it was).


text:
Q: Difficulty with events I'm having trouble understanding the events. Whenever I see an example of a code with events, I can not find the documentation of them, just being able to understand testing. In this code, for example, I understood the 'SIGINT' by testing, but I did not find the documentation. The 'end' I could not find the documentation and also I can not understand when the 'end' will be fired. What happens to these events? Why so much trouble finding the documentation? Are events contextual? How to know the context and where to search? Thank you and sorry for the stupid question.
const fs = require('fs');

process.stdin.resume();
process.stdin.setEncoding('utf-8');

let inputString = '';
let currentLine = 0;

process.stdin.on('data', inputStdin => { inputString
    inputString += inputStdin;
});

process.stdin.on('end', function() {
    inputString = inputString.replace(/\s*$/, '')
        .split('\n')
        .map(str => str.replace(/\s*$/, ''));

    main();
});

A: This is the documentation of streams: https://millermedeiros.github.io/mdoc/examples/node_api/doc/streams.html
You can see that stdin is a Stream: https://nodejs.org/api/process.html#process_process_stdin
So, whatever applies to Stream, applies to stdin as well.
data event:

The 'data' event emits either a Buffer (by default) or a string if
  setEncoding() was used.

So, data event is loading a chunk of data from the Stream into either a Buffer or a string.
end event:

Emitted when the stream has received an EOF (FIN in TCP terminology).
  Indicates that no more 'data' events will happen. If the stream is
  also writable, it may be possible to continue writing.

So, the end event is triggered, unsurprisingly, when the last data event happened.
To explain this, let's suppose you have a Stream of a file of the size of 2 GB. In this case, chunks of data are loaded from that file, let's suppose that the size of the chunks is S. In this case, you will have around 2 GB / S steps of loading. This means that there will be many data events and the system will always trigger a data event while there is a next packet to load. At the end, when there is nothing more to load, it will trigger the end event. Now that we understand Streams, I think you now understand that the same thing happens for stdin as well. Nothing prevents the possibility that stdin would suddenly receive a very large amount of data.


text:
Q: WCF- redundancy in specifying service name and contract type? Say I have a service contract specified in IEmployService.cs as such:
namespace MyNamespace {
    [ServiceContract]
    public interface IEmployeeService {
      /* ... */
    }
}

and an implementation file in EmployeeService.svc:
namespace MyNamespace {
   public class EmployeeService: IEmployeeService {
       /* implements IEmployeeService fully */
   }
}

now, when I specify my endpoint in my Web.config file, I've seen everybody do this:
<system.serviceModel>
<services>
  <service name="MyNamespace.EmployeeService">
    <endpoint
      address="basic1"
      binding="basicHttpBinding"
      contract="MyNamespace.IEmployeeService"
      ></endpoint>
  </service>
</services>
<!-- other tags -->
<system.serviceModel>

It seems like WCF aught to be able to infer what the contract type is without having to specify contract="MyNamespace.IEmployeeService", since it already has a reference to EmployeeService (who implements the IEmployeeService interface that specifies the service contract). Is this contract attribute in my endpoint strictly necessary?  If so, I'd love to know why.

A: It is at least partially because my class EmployeeService is not restricted to implementing a single service contracted interface.  Say I specify a new contract ISuperContract.cs:
namespace MultipleEndpointSample
{
    [ServiceContract]
    interface ISuperService
    {
        [OperationContract]
        void GetEmployeeName();
    }
}

then the contract-attribute in my Web.config: endpoint definition is very necessary, I now use it to differentiate WHICH sub-service of EmployeeService (which implements two services) this endpoint will cater to.


text:
Q: Uplay Games not Launching I have 2 Ubisoft games on Steam, Assassin's Creed III and Valiant Hearts. I've bought them a while ago, and they seemed to work, I've played them a lot.
But now, when I try to run them, the mouse icon loads for a few seconds and nothing. Nothing happens. I checked my computer processes and there is no "Valiant Hearts" or "Assassin's Creed III" process running.
I can't launch the game from the shortcut, nor steam, nor the Uplay launcher.
What I have tried:

*

*Reinstalling Uplay: This seemed to work in the first place (before I did that, the uplay launcher wouldn't launch as well). After reinstalling, the uplay launcher started to launch, and I was able to play the games once, and then the problem returned. Now, I can open the uplay launcher, but can't launch any games.

*Going Offline: I've read in some internet forums that going offline could help me. I tried. Nothing.

*Update: Tried running all as administrator, didn't work.

I don't have anymore ideas. I don't think that this is an installation problem because I was able to play the games, the problem appeared out of nowhere.
Here are my device's specifications:

*

*Windows 10

*AMD FX Quad-Core Processor

*NVIDIA GForce GT680

*8GB of RAM.

UPDATE
I don't know what happened. I didn't did anything, but today i just tried to start the games and they worked. It seems that uplay is pretty unstable. However, i'll leave the question (and bounty) open, if someone appears with a permanent solution (i don't know how long my games will be working).

A: I have similar problems with Uplay,
there are several posts of user around internet(reddit, Ubisoft forum and so on) complaining about those things.
There are two main and constant problems:

*

*Can't download/update a Uplay Game

*Can't open a Uplay Game

Every single forum, reddit post will tell you to:

*

*Open as administrator

*Reinstal the Game

*Reinstal Uplay

*Reinstal Dx

*Port foward

*Add Uplay+Game on trusted programs in Windows/Anti-Virus

*Close background application.

None of them will work.

If you get luck and receive support they will tell you to do the same again, but for no reason don't follow their advice to disable all windows services from msconfig because that may mess your computer and you will be unable to start windows again.
The only way to find what is really happening is investigating your computer.
You can check the Uplay logs here

Program Files (x86)\Ubisoft\Ubisoft Game Launcher\logs

(
And search google for the exact problem.
You can use the windows Resource Monitor to check the applications. And Windows Event Viewer for some anomaly.
Sadly, most of the time it was a problem with Ubisoft
Can't download/update a Uplay Game:
It was caused, most of the time, for a Ubisoft Server refusing to send a package, just one package (network log)
I found 4 possible solutions:

*

*Wait

*Change your IP, if your ISP allows that.

*Try another ISP if you have two or more at home, you can use your mobile internet to download that last package.

*Download it on a friend, or find a fried with the game downloaded/updated and copy to yours.

Can't open a Uplay Game
It could be caused by needing some third party software, but mostly by Uplay failing to verify it as yours or its dependencies (preventing you to play it), it may vary from game.
In this case I found only two solutions:

*

*Wait (Uplay updates sometimes fix that, but not always)

*Format PC (try in another computer first)

Don't forget to check Uplay logs before trying any drastic measure.

A: To list the things can mess it up

*

*Corrupted installation of uplay, which could also make installing games through uplay corrupted, reinstalling is the only option I can think of.

*Some background process is messing up your uplay (maybe a process you accidentally installed), try to quit every background process which isn't necessary and try to launch uplay/the games then

*Internet connection can make you client go haywire, going offline could fix this (but apparently that's not the problem)

*One other problem is, and this is farfetched, it could be a virus which is blocking you from launching the games. This means that you could potentially solve it by cleaning up your entire pc.

If these problems persist and none of the fixes listed above work. I would suggest that you will contact Ubisoft support. They know more about their own product hopefully and probably can fix your problem.

A: Had a similar problem with uplay games.
What fixed the issue for me was setting everything(steam, uplay, game) to launch on administrator mode. To do so, you need to find the .exe right click it and open properties then go to compatibility tab and mark to launch as admin(you can mark to run in compatibility mode as well since you're using win10).
Also, if it still not working try disabling uplay and steam
EDIT: Sign out of steam BETA participation

A: I had a similar problem some time ago. The Ubisoft support staff listed these options available for me. Maybe you could retry step 1 or make sure you tried 2 and 3.

*

*Re-install Uplay Client - including backupping save games, uninstalling, downloading a current version and installing it "as Administrator"

*Update Drivers for your graphics card - just in case you haven't done it already

*Find the *.exe of the game - Make a shortcut of that file. Right click on that shortcut, select the "Run with graphics processor" menu, and select "High-performance NVIDIA processor."

If none of these work for you, I'd suggest contacting the Ubisoft support.

A: I figured out the problem myself while testing and if anyone else is having the problem here is the solution,

*

*Right click on the uPlay Icon

*Look for a program called 'Ubisoft Game Launcher'

*Right Click and Run as Administrator
This worked for me and if anyone else is having the problem here is a possible solution

A: I had this same problem for the longest time, it seemed to occur after I changed the location of my games to my (E:) hard drive. I tried to reinstall both Uplay and the game but nothing worked. so what I did was move my Uplay app (which had been in my (C:) drive) to my (E:), then I reinstalled my game to my (C:). I am not sure if changing the location of my uplay app was the difference but I am confident that installing my Ubisoft games to my (C:) drive fixed the problems.
In short: INSTALL UBISOFT GAMES TO YOUR (C:) DRIVE.

*

*Other solutions that may have led to this outcome:

*

*moving all steam and Ubisoft folders to E:

*deleting any duplicates on C:.


text:
Q: Our own php Side login but not go to header('Location: home.php'); Our php Side full work in my localserver (Xamp-apach-5.5.6)
but hosting side no work(apach-5.2.17)
Please help me.
public function login($username,$password)
    {
        session_start();
        if($username==!NULL AND $password==!NULL)
        {
            global $pdo;
            $password=md5($password);
            $query = $pdo->prepare("SELECT * FROM employee_list WHERE username='$username' AND userpass='$password'");
            $query->execute();
            $row=$query->rowCount();
            if($row==0)
                {
                $this->massage->loginmass("YOUR USERNAME AND PASSWORD NO MATCH.");
                }
            else
                {
                    $result = $query->fetch();
                    if($result['active_enactive']=="Active")
                    {
                         $_SESSION['mafizusernamerahman'] = $result['username'];
                         $_SESSION['mafizuserpassrahman'] =$result['userpass'];
                         $_SESSION['mafizaccess_permissionrahman'] = $result['access_permission'];
                         $_SESSION['mafizactive_enactiverahman'] = $result['active_enactive'];
                         $_SESSION['mafiznamerahman'] = $result['name'];
                         $_SESSION['mafizemployment_idrahman'] = $result['employment_id'];
                         $_SESSION['mafizfather_namerahman'] = $result['father_name'];
                         $_SESSION['developer'] = "Mafizur";
                        if($_SESSION['mafizaccess_permissionrahman']=="Admin")
                            header("location:all-employee.php");
                        elseif($_SESSION['mafizaccess_permissionrahman']=="User")
                        {
                            if (empty($result['defaltpass'])) {
                                header("location:user-profile.php");
                            }
                            else
                                header("location:defaltchange-password.php");
                        }
                    }
                    else
                        $this->massage->loginmass("YOUR ACCOUNT SUSPEND.");

                }
        }
        else
            $this->massage->loginmass("PLEASE FILL UP YOURUSER NAME AND PASSWORD.");

    }

A: You need to be careful while using relative URLs in Location redirects.
So, it will be better if you print absolute URLs in the headers instead of relative URLs.
https://en.wikipedia.org/wiki/HTTP_location


text:
Q: Connecting a slider to a menu I have a flexslider that i'm trying to connect to my website. In the website i have a menu of several elements. I want to connect the slider to the first element of the menu. There's a fade in/ out function that will allow the slider to fade in once the first element is clicked. Now i tried several times to connect it, however once i click the first element  (aaaaaaa) of my menu, i get nothing. Any help please?
Jsfiddle for the site: https://jsfiddle.net/vL7ojznz/
Jsfiddle for the slider: http://jsfiddle.net/t3sgbq5w/
I have in my site 3 dividers (item11, item22, and item33) :
HTML:

<button>aaaaaaaa</button>

<button>bbbbbbb</button>

<button>ccccccc        </button>

<button>dddddddd         </button>

<button>eeeeeee eee.   </button>

<button>ffffff       </button>

<button>ggggggg       </button>

I want to replace item11 only with the whole slider. Please help, thank you..

A: I think your main problem is you have to initialize .flexslider after your #container fades in.
Look at this Fiddle.


text:
Q: Why is $Tr(AP)=\sum^p_{j=1}\lambda_j(e_je_j^TBB^T)?$ Let $P$ be a $p\times p$ orthogonal projection matrix, $A$ be a $p\times p$ symmetric matrix.
I've been going through a solution to an exercise in my book, and I was confused as to why would $$Tr(AP)=\sum^p_{j=1}\lambda_j(e_je_j^TBB^T)?$$
I know the spectral decomposition of $A$ is $A=E\Lambda E^T$, but I can't seem to see why is $Tr(AP)=Tr(E\Lambda E^TBB^T)=\sum^p_{j=1}\lambda_j(e_je_j^TBB^T)?$
If anyone could help me understand or show how that result is derived, I would be very happy.


text:
Q: Getting time difference for unique values in photo feed using jQuery I am working with a dynamic feed that pulls in recently uploaded photos along with the timestamp of when it was posted. Currently the timestamp is in milliseconds. I have a script that subtracts the posted timestamp value from the integer value of the current time. It then formats the remainding integer value into a time string. Ultimately producing a string of "...posted x minutes ago" (where x is the difference in time). See JS below:
function toSeconds(time_str) {
    // Extract hours, minutes and seconds
    var parts = time_str.split(':');
    return parts[0] * 3600 +
    parts[1] * 60 +
    +
    parts[2]; // seconds
}

//GETS CURRENT EPOCH VALUE & CONVERTS TO TIME STRING
var d = new Date();
var currentEpoch = (d.getTime()-d.getMilliseconds())/1000;
var currentTime = new Date(currentEpoch *1000);
var currentDate = currentTime.toLocaleTimeString({hour12: false});

//GETS EPOCH VALUE OF POST & CONVERTS TO TIME STRING
var postEpoch = $(".timestamp").html();
var postTime = new Date(postEpoch *1000);
var postDate = postTime.toLocaleTimeString({hour12: false});

//GETS THE DIFFERENCE
var difference = Math.abs(toSeconds(currentDate) - toSeconds(postDate));

//FORMAT THE DIFFERENCE
var result = [
Math.floor(difference / 3600)
Math.floor((difference % 3600) / 60)
];

result = result.map(function(v) {
return v < 10 ? '0' + v : v;
}).join(':');

//INJECT DIFFERENCE INTO TIMESTAMP DIV
$(".timestamp").html("posted" + result + " minutes ago");

Each image is contained in its own div along with a nested div for the each timestamp. See sample HTML:

1385537546

1385536903

1385537273

My script seems to be working right, but the problem is that this functionality only works on the very first timestamp div. So the first image will have the correct time value, but the rest of the images inherit the same exact value instead of getting their own unique value. I realize the solution may be throwing in a (this) somewhere, but I am stumped.

A: As I understood from the plugin you can do this:
1. Use

mock (true/false) - Fetch data without inserting images into DOM. Use
  with success callback.

and

success (function) - A callback function called when Instagram returns
  valid data. Takes the JSON data as an object argument.

So basically I overridden the default rendering for each image and inserted a custom item instead.
You can read more about it HERE

Javascript
var feed = new Instafeed({
    pages: 1,
    limit: 5,
    get: 'tagged',
    tagName: 'thetypein',
    clientId: '467ede5a6b9b48ae8e03f4e2582aeeb3',
    mock: true,
    success: function (json) {
        for (var i = 0; i < json.data.length; i++) {
            var cont = $("
")
                .addClass("imgContainer")
                .appendTo($("#instafeed"));
            var img = $("")
                .attr("src", json.data[i].images.thumbnail.url)
                .appendTo(cont);
            var time = $("
")
                .addClass("timestamp")
                .attr("id", "Time_" + (i + 1))
                .text("Added " + CountTime(json.data[i].created_time)+" minutes ago")
                .appendTo(cont);
            }
        }
    });
feed.run();

Also I've modified your function in order to use it properly and fixed your toSeconds function:
Javascript
function CountTime(posttime) {
    function toSeconds(time_str) {
    // Extract hours, minutes and seconds
        time_str= time_str.replace("AM","").replace("PM",""); // added to get rid of "AM" and "PM"
    var parts = time_str.split(':');
    return parts[0] * 3600 +
    parts[1] * 60 +
    +
    parts[2]; // seconds

}
    var d = new Date();
var currentEpoch = (d.getTime()-d.getMilliseconds())/1000;
var currentTime = new Date(currentEpoch *1000);
var currentDate = currentTime.toLocaleTimeString({hour12: false});
    console.log(currentDate);
var postEpoch = posttime;
var postTime = new Date(postEpoch *1000);
var postDate = postTime.toLocaleTimeString({hour12: false});
    console.log(postDate);

    var difference = Math.abs(toSeconds(currentDate) - toSeconds(postDate));
    console.log(toSeconds(postDate));
    var result = [
Math.floor(difference / 3600),
Math.floor((difference % 3600) / 60)
];

    result = result.map(function(v) {
return v < 10 ? '0' + v : v;
}).join(':');
    return result;
};

Here is an example Fiddle
UPDATE 1
After a discussion with Bharath Rallapalli and a small research I've found Out that you should read more about toLocaleTimeString(), because it can wary depending on browser and culture settings on user PC and cause problems.


text:
Q: Delete item permanenly from ListView I pass data from a ListView to another ListView with SharedPreference. I can write items and can remove an item of them.
After I delete item,I restart this page and I see item which I deleted. I cannot remove it permanently.
MainActivity
final DataProvider[] providers = gson.fromJson(jsonurun, DataProvider[].class);
final List<DataProvider> list = new ArrayList<>(Arrays.asList(providers));

listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
    @Override
    public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
        final DataProvider dataProvider = (DataProvider) adapterView.getItemAtPosition(i);
        AlertDialog.Builder builder = new AlertDialog.Builder(Listele1.this);
        builder.setMessage("Silinsin mi ?")
                .setCancelable(false)
                .setPositiveButton("EVET", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        list.remove(dataProvider);
                        prefAdapter.notifyDataSetChanged();
                 }
            })

A: try change
 prefAdapter.notifyDataSetChanged();

for notifyItemRemoved("here, position you has deleted");
    notifyItemRangeChanged("here, position you has deleted" ,"your array".size());

A: When you are passing data form ListView 1 to ListView 2 using SharedPreference.
    using below 2 lines.
final DataProvider[] providers = gson.fromJson(jsonurun, DataProvider[].class);
final List<DataProvider> list = new ArrayList<>(Arrays.asList(providers));

You only remove data from Listview 2 ie: list in your
case : list.remove(dataProvider);

And forgot to delete the data from SharedPreference at same time.That's why when restart the page your deleted item is visible again.

In short try to remove data form SharedPreference as well after performing

 list.remove(dataProvider);
 prefAdapter.notifyDataSetChanged();


text:
Q: New EE Router not working with netgear swtich? I had a setup where my PC (and other items) was connected via a netgear switch which was connected to my sky router. This all worked nicely.
Then I changed to EE just now. It no longer works (cant get to the internet or even ping the EE router).
If I connect my PC directly to the EE router I can get to the internet. After a conversation with EE they just say they don't support netgear stuff.... I don't really understand how it can't work through a switch?
Surely saying that they don't support a switch is like saying saying they don't support ethernet cable?!
I am thinking it must be something to do with their router, right?
I also noticed that the EE router either reboots or resets when I was switch between my switch and direct PC connection (i.e. all the lights go out and then slowly come back on)... something very strange is happening there...
Anyway, any idea how I can fix this - or what to try?
I have a windows PC (win 8).

A: Does the link light come on? If not you might need a crossover cable or a standard 4-pair cable. 2-pair cables just support 100 Mbit/s and don't link at 1 Gbit/s at all unless at least one side supports fallback to 100M. Even today, some ports don't support Auto MDI-X and still require a crossover between a switch and a (router-integrated) switch.


text:
Q: Login and scrape a site that uses CORS(AWS) and JS to populate itself with Google Apps Script I am trying to access the following Japanese site and scrape data from a table, but I am struggling to login using Google Apps Script. I need to use a solution that does not rely on a desktop and can be done completely online. I am not that experienced with web development/web scraping, so I'm basically learning as I go.
I have the username and password, but:

*

*I am unable to figure out what headers I need to send to login. I get 403 errors when using the actual url, https://calllog-dev.123robo.com/#/login, and 502 when using the request url from the browser, https://dbp3xa4g5g.execute-api.us-west-2.amazonaws.com/dev/users/authenticate
2.The login page uses CORS and AWS api to Authenticate, so there are no cookies until I have successfully logged in and send a GET request via browser.
3.There are multple tokens: x-logview-token which is within the response to the POST request for logging in, and a Page Token is generated for each page.
Response to Login Post Request:
    {"username":"user@gmail.com","token":"this-is-the-token-value","enableDigits":true}

I am thinking of using cookies from the browser's GET Request to recreate it and send it through Google Apps Scripts. Is there someway to bypass the login or use the cookies to login?
<!DOCTYPE html>

  <meta charset=utf-8>
  <meta http-equiv=X-UA-Compatible content="IE=edge">
  <meta name=viewport content="width=device-width,initial-scale=1">
  <link rel=icon href=/favicon.ico>
  <link rel=stylesheet href=//cdn.materialdesignicons.com/3.4.93/css/materialdesignicons.min.css>
  <title>123ROBO 通話履歴</title>
  <link href=/css/app.5339eed8.css rel=preload as=style>
  <link href=/css/chunk-vendors.8b9ade74.css rel=preload as=style>
  <link href=/js/app.32f2c21e.js rel=preload as=script>
  <link href=/js/chunk-vendors.cd62bd72.js rel=preload as=script>
  <link href=/css/chunk-vendors.8b9ade74.css rel=stylesheet>
  <link href=/css/app.5339eed8.css rel=stylesheet>

We're sorry but logview doesn't work properly without JavaScript enabled. Please enable it to continue.

Here is the website: https://calllog-dev.123robo.com/#/login
Here is the Code I have been trying to use:
function loginTest(){

//Added Basic Authorization
  var userID = 'user@gmail.com';

  var userPW = 'password'  ;

  var url = 'https://dbp3xa4g5g.execute-api.us-west-2.amazonaws.com/dev/users/authenticate';

  //Added a body as pointed out by Mark. Added Request Headers as suggested by pguardiario
  const requestOptions = {
    method: 'POST',
    headers: { 'Content-Type': 'application/json',
             'authority': 'dbp3xa4g5g.execute-api.us-west-2.amazonaws.com',
              'path': '/dev/users/authenticate',
              'scheme': 'https',
              'accept': '*/*',
              'accept-encoding': 'gzip, deflate, br',
              'accept-language': 'en-US,en;q=0.9,ja;q=0.8',
              'content-type': 'application/json',
              'origin': 'https://calllog-dev.123robo.com',
              'referer': 'https://calllog-dev.123robo.com/',
              'sec-fetch-dest': 'empty',
              'sec-fetch-mode': 'cors',
              'sec-fetch-site': 'cross-site',
              'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/84.0.4147.125 Safari/537.36',
             },

var response = UrlFetchApp.fetch(url, requestOptions);

  Logger.log(response);
  Logger.log(response.getContentText("UTF-8"));

}

A: You can't just send an Authorization header, when it expects a body:
const requestOptions = {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({ username, password })
  }

And this page has one general DOM issue, along with some typos:

[DOM] Password field is not contained in a form: (More info: https://www.chromium.org/developers/design-documents/create-amazing-password-forms)
<input type="password" autocomplete="on" class="input">

A: That's the wrong url, take a look:


text:
Q: HTML Table inside JQuery Dialog not working I'm trying to make my table popup using a JQuery Dialog on clicking a button. However it doesn't seem to work. Below is my code:
HTML for button

<button class="more comment"></button>Some random text here

HTML for Table I want to popup on button click

                Name
                Pseudo

                Tom Cruise
                BOB

JQuery Script

When I click nothing happens. I did import my Jquery library because other Jquery stuff are working except for this one. So I think I may be doing something wrong here.
Any help appreciated.
Thanks.

A: Do you have the jQuery UI library added to your document?
I copied your code and added the jquery ui library and it works.
<!DOCTYPE html>

    <meta charset="UTF-8">
    <title>Document</title>

<button class="more comment"></button>Some random text here

                Name
                Pseudo

                Tom Cruise
                BOB

Here is a jsfiddle: http://jsfiddle.net/L5tumouL/1/

A: It seems you didn't load jQuery UI. It add dialog support.
http://jsfiddle.net/dvxw6okq/ (note: "jQuery UI 1.9.2" is checked)

A: In this piece of code, you set the display attribute of the css to none.

Try setting the display to block.
$(function() {
   $( ".comment").click(function(){
       $( "#dialog-modal" ).dialog({
          height: 140,
          modal: true
        });
       $( "#dialog-modal" ).css("display", "block");
       $( "#dialog-modal" ).show();
    });
 });

I think that should fix it.


text:
Q: R: propensity match within range of continuous variable? I'm working on a retrospective analysis on some oncology data using R. I'm trying to do a lot of the analysis myself.
My colleagues have used SPSS in the past and have asked me to specify limits for matching in continuous variables. For example, specifying match according to age +/- 5 years, tumor size +/- 5 mm, etc.
Is it possible to do this using the MatchIt or a comparable package?

A: It sounds like you want variable-specific calipers.
In the Matching package (not MatchIt), you can specify a vector of values to the caliper argument in Match() or GenMatch(). The values are expected to be in standardized units, so you'll have to compute how many standardized units each of your defined calipers are.
In the designmatch package, you can specify the maximum distance between any pair of units on any given covariates using the near argument in bmatch(). I recommend this option and recommend this package for matching in general.
In MatchIt, you can specify a vector of values to the caliper argument, which is passed directly to Matching::GenMatch() if you are doing genetic matching (i.e., method = "genetic"), but not otherwise. Because it's less clear how MatchIt processes the covariates that are passed to GenMatch(), use this method with caution.

Update:
As of version 4.0.0, you can specify variable-specific calipers using MatchIt. For example, to restrict eligible matches on age and size, you could run
matchit(treat ~ X1 + X2 + age + size, data = data,
        caliper = c(age = 5, size = 5), std.caliper = FALSE)

This would restrict matches so that pairs are within 5 years of age of each other and within 5 mm of size of each other.


text:
Q: Error when making request: The request was aborted: Could not create SSL/TLS secure channel Here is my codes :
try {
    HttpWebRequest req = (HttpWebRequest) WebRequest.Create("https://api.coindesk.com/v1/bpi/currentprice.json");
    req.Method = "GET";
    req.Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,*;q=0.8";
    req.UserAgent = "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2228.0 Safari/537.36";
    req.ContentType = "text/html; charset=utf-8";
    req.Referer = "";
    req.KeepAlive = true;
    req.Timeout = 25000;
    req.AllowAutoRedirect = true;

    CookieContainer cookieJar1 = new CookieContainer();
    req.CookieContainer = cookieJar1;

    HttpWebResponse res = (HttpWebResponse) req.GetResponse();

    foreach(Cookie cookie in res.Cookies) {
        cookieJar1.Add(new Cookie(cookie.Name.Trim(), cookie.Value.Trim(), "/", cookie.Domain));
    }

    Stream Stream = res.GetResponseStream();
    StreamReader reader = new StreamReader(Stream);
    string reader_str = reader.ReadToEnd();

    var obj = JObject.Parse(reader_str);
    string bitcoin_price_str = ((string) obj["bpi"]["USD"]["rate"]).Trim().Replace(",", "");
    bitcoin_price = double.Parse(bitcoin_price_str);

    reader.Close();
    Stream.Close();
    res.Close();
}
catch(Exception ex_1) {
    Send_Email_Gmail();
}

Before today those codes were working ok.
But today i faced an error about Invalid Certificate Date.
When i opened that url in browser (FireFox & Chrome) that error was there.
Some hours ago they fixed the issue on their server.
Now in FireFox & Chrome there is no problem.
But in my codes i face this error :

The request was aborted: Could not create SSL/TLS secure channel.

I tried this solution :
ServicePointManager.Expect100Continue = true;
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12| SecurityProtocolType.Ssl3;

Not help.
What should i do?

A: It seems that api.colindesk.com now only supports TLS 1.2 and 1.3
while blockchain.info still supports the deprecated TLS 1.1.
This immediately (to me at least) suggests that you're using old versions of Windows that don't support TLS1.2 by default - confirmed in the comments on the question.
There are numerous answers on SO that show how to do this.

*

*.Net Framework 4.6.1 not defaulting to TLS 1.2

*WebService using TLS1.1, TLS1.2 unable to connect on development server, works in local development

*TLS 1.2 error Could not create SSL/TLS secure channel


text:
Q: Force Server Side Encryption for S3 Bucket I want to set an S3 bucket policy so that all requests to upload to that bucket will use server side encryption, even if it is not specified in the request header.
I have seen this post (Amazon S3 Server Side Encryption Bucket Policy problems) where someone has managed to set a bucket policy that denies all put requests that don't specify server side encryption, but I don't want to deny, I want the puts to succeed but use server side encryption.
My issue is with streaming the output from EMR to my S3 bucket, I don't control the code that is making the requests, and it seems to me that server side encryption must be specified on a per request basis.

A: Amazon just released new features for enforcing this, making it very easy
Excerpt from the docs on setting this up.
Note that any exiting bucket policies will be evaluated prior to any bucket encryption settings

Amazon S3 evaluates and applies bucket policies before applying bucket
  encryption settings. Even if you enable bucket encryption settings,
  your PUT requests without encryption information will be rejected if
  you have bucket policies to reject such PUT requests . Check your
  bucket policy and modify it if required

A: IMHO There is no way to automatically tell Amazon S3 to turn on SSE for every PUT requests.
So, what I would investigate is the following :

*

*write a script that list your bucket

*for each object, get the meta data

*if SSE is not enabled, use the PUT COPY API (http://docs.aws.amazon.com/AmazonS3/latest/API/RESTObjectCOPY.html) to add SSE
"(...) When copying an object, you can preserve most of the metadata (default) or specify new metadata (...)"

*If the PUT operation succeeded, use the DELETE object API to delete the original object
Then run that script on an hourly or daily basis, depending on your business requirements.
You can use S3 API in Python (http://boto.readthedocs.org/en/latest/ref/s3.html) to make it easier to write the script.
If this "change-after-write" solution is not valid for you business wise, you can work at different level (aligned with Julio's answer above)

*

*use a proxy between your API client and S3 API (like a reverse proxy on your site), and configure it to add the SSE HTTP header for every PUT / POST requests.
Developer must go through the proxy and not be authorised to issue requests against S3 API endpoints

*write a wrapper library to add the SSE meta data automatically and oblige developer to use your library on top of the SDK.
The later today are a matter of discipline in the organisation, as it is not easy to enforce them at a technical level.
Seb

A: S3 will not perform this automatically, you would have to create a workaround. I would suggest passing requests thru a proxy that would "enrich" them adding the proper header. To do that i'd try (in order):
1- Apache Camel Content Enrich
2- NGXINX / HTTPD mod_proxy
3- Custom code
I bet there is also a very smart ruby http lib for that too :)

A: I use this quick bash script to encrypt an entire bucket.

#!/bin/bash

bucket=$1

echo "Encrypting Bucket: ${bucket}"
echo "---------------------------------"

# Bail if no Bucket Name Specified:
if [[ -z $1 ]]
then
  echo "Usage: ./encrypt_bucket.sh <bucket_name>"
  exit 1
fi

# Just so control-c will work and not keep trying to loop through:
trap "echo Stopping Encryption!; exit 1" SIGINT SIGTERM

function get_file_list() {
  file_list=$(aws s3 ls --summarize --recursive s3://${bucket} | awk '{print $NF}' | grep -v Total)
  num_files=$(aws s3 ls --summarize --recursive s3://${bucket} | grep "Total Objects:" |awk '{print $3}')
}

function s3cp() {
  aws s3 cp --sse s3://${bucket}/$1 s3://${bucket}/$1
}

get_file_list

num=0

for i in ${file_list}
 do
   num=$(( $num + 1 ))
   echo "Encrypting File: ${num} of ${num_files}"
   echo "_________________"
   s3cp ${i}
   echo ""
 done

A: You can use AWS Lambda that sets server-side AES256 encryption for each object touched with a PUT operation. Check https://github.com/eleven41/aws-lambda-encrypt-s3-objects. I haven't tried it but looks exactly like the thing you want.


text:
Q: Nginx reverse proxy domain root location redirects back to server IP I have a client with an existing domain name which cannot be pointed to my server just yet.
So in the meanwhile I've added my node app and configuring the reverse proxy. This is what I've done:
1) Added domain entries to my local machine's hosts file:
134.209.53.229 example.com
134.209.53.229 www.example.com

2)on my server hosts file, I did the same:
134.209.53.229 example.com
134.209.53.229 www.example.com

3) My nginx reverse proxy setup. This is my /etc/nginx/sites-available/default file:
server {
    listen 80 default_server;
    listen [::]:80 default_server;

    root /var/www/html;
    index index.php index.js index.html index.htm index.nginx-debian.html;

    server_name example.com www.example.com;

    location / {
    proxy_pass http://localhost:8000;
    proxy_http_version 1.1;
    proxy_set_header Upgrade $http_upgrade;
    proxy_set_header Connection 'upgrade';
    proxy_set_header Host $host;
    proxy_cache_bypass $http_upgrade;
    }
}

Now what happens if I visit any subpath, like http://example.com/products, everything works fine.
But, when I visit root http://example.com - contents are served as expected, but the address in my browser address bar changes to http://134.209.53.229 .
Looking at devtools network tab, I see that initiator is example.com, but in the request headers host is actually 134.209.53.229 (not example.com).
Is any of what I've done above causing this? Or should I be digging up my app? So far I'm not finding any cause inside the app.
EDIT: it appears that this only happens in google chrome. Is this expected behavior from chrome?


text:
Q: Removing duplicates with in an object array using angular 4 I have an array with below list of items as shown in image , I would like to remove the duplicates
[L7-LO, %L7-LO] from that array.

I have tried with the following conditions:
Scenario 1 :
this.formulalist.filter((el, i, a) => i == a.indexOf(el))

Scenario 2:
Observable.merge(this.formulalist).distinct((x) => x.Value)
          .subscribe(y => {
       this.formulalist.push(y)
   });

Scenario 3:
this.formulalist.forEach((item, index) => {
        if (index !== this.formulalist.findIndex(i => i.Value == item.Value))
        {
            this.formulalist.splice(index, 1);
        }

    });

None of the three scenarios above were able to remove the duplicates from that array. Could any one please help on this query?

A: angular is not necessary use vanillajs
filter the elements with only one occurrence and add to the new list the first occurrence
let newFormulalist =  formulalist.filter((v,i) => formulalist.findIndex(item => item.value == v.value) === i);

A: Try populating a new array without duplicates. Assign the new array later to formulalist.
newArr = []
this.formulalist.forEach((item, index) => {
    if (this.newArr.findIndex(i => i.Value == item.Value) === -1)
    {
        this.newArr.push(item)
    }

});
this.formulalist = this.newArr

EDIT
Looking at the answer above, the solution seems so outdated. A better approach would have been to use an Array.filter() than a Array.forEach().
But, having a better solution would be nice, now when I see this question, I feel findIndex() not to be a good approach because of the extra traversal.
I may have a Set and store the values in the Set on which I want to filter, If the Set has those entries, I would skip those elements from the array.
Or a nicer approach is the one that is used by Akitha_MJ, very concise. One loop for the array length, an Object(Map) in the loop with keys being the value on which we want to remove duplicates and the values being the full Object(Array element) itself. On the repetition of the element in the loop, the element would be simply replaced in the Map. Later just take out the values from the Map.

A: const result = Array.from(this.item.reduce((m, t) => m.set(t.name, t), new Map()).values());

Hope this works !!

A: // user reduce method to remove duplicates from object array , very easily

  this.formulalist= this.formulalist.reduce((a, b) => {
      if (!a.find(data => data.name === b.name)) {
        a.push(b);
      }
      return a;
    }, []);

// o/p = in formulalist you will find only unique values

A: Use a reducer returning a new array of the unique objects:

const input = [{
    value: 'L7-LO',
    name: 'L7-LO'
  },
  {
    value: '%L7-LO',
    name: '%L7-LO'
  },
  {
    value: 'L7-LO',
    name: 'L7-LO'
  },
  {
    value: '%L7-LO',
    name: '%L7-LO'
  },
  {
    value: 'L7-L3',
    name: 'L7-L3'
  },
  {
    value: '%L7-L3',
    name: '%L7-L3'
  },
  {
    value: 'LO-L3',
    name: 'LO-L3'
  },
  {
    value: '%LO-L3',
    name: '%LO-L3'
  }
];
console.log(input.reduce((acc, val) => {
  if (!acc.find(el => el.value === val.value)) {
    acc.push(val);
  }
  return acc;
}, []));

A: Filtering for unique values is much faster with assigning values to some object properties - there not will be duplicates.
This approach gets better and better with every +1 member of initial array, because looping will be causing fast algorithm complications

let arr = [
  {value: 'L7-LO', name: 'L7-LO'},
  {value: '%L7-LO', name: '%L7-LO'},
  {value: 'L7-LO', name: 'L7-LO'},
  {value: '%L7-LO', name: '%L7-LO'},
  {value: 'L7-L3', name: 'L7-L3'},
  {value: '%L7-L3', name: '%L7-L3'},
  {value: 'LO-L3', name: 'LO-L3'},
  {value: '%LO-L3', name: '%LO-L3'}
];
let obj = {};

const unique = () => {
  let result = [];

  arr.forEach((item, i) => {
    obj[item['value']] = i;
  });

  for (let key in obj) {
    let index = obj[key];
    result.push(arr[index])
  }

  return result;
}

arr = unique(); // for example;

console.log(arr);

A: if you are working using ES6 and up, basic JS using map and filter functions makes it easy.

var array = [{value:"a"},{value:"b"},{value:"c"},{value:"a"},{value:"c"},{value:"d"}];

console.log(array.filter((obj, pos, arr) => {
    return arr.map(mapObj => mapObj["value"]).indexOf(obj["value"]) === pos;
}));


text:
Q: How to create a big size file in windows with out using any extra tools? I am trying to create a 250 mb of valid file in pdf or any other format. I tried with ms word and created around 3k pages with images in it, but still it was of the size of 10 mb only.
any ideas or suggestions ? I have proper pdf adobe version which can create pdf files.

A: Finally found a way to do this... use adobe acrobat to create the pdf.. add the high end images and create a PDF with the  option to preserve image original quality.


text:
Q: Unexplained password prompt on Windows 8.1 Pro, SharePoint? I'm trying to solve a bit of a mystery that seems connected to SharePoint on my Windows 8.1 Pro (via Pro Pack upgrade) machine. To my knowledge I have never intentionally installed any SharePoint software. I've worked with it before and can't stand it.
If I boot to Windows and my internet connection isn't available I see this prompt:

I never see this when the internet connection is available. I've tried examining the Task Manager when this prompt is shown to see if I can figure it out but this hasn't turned up anything unexpected.
I have Office 365 installed, Avira, and a whole lot more - not having a clue what's causing this I don't have any idea what is relevant to mention.
I haven't tried a password as 1) I don't know if I've ever set up an account for whatever this is and 2) I have no idea what it would do with any passwords I provide (I'm confident my machine is clean but why risk it).
Any thoughts much appreciated.

A: This could be caused by any application trying to make an active network connection.  The Office clients will make active attempts to access O365.  Any of those applications that are running can give you that prompt.  The first place to look is Outlook, Lync, and the OneDrive for business, but be aware that Word, Excel, and PowerPoint can also request this connection depending on what you opening or doing with the applications.


text:
Q: Architecture: Handling large scale photo upload and resizing I have a system where users can upload full resolution sized images of about 16 mega-pixels which result in large files.
The current methodology is:

*

*Receive the upload in a HTTP request.

*Within the request, write the original file to blob store

*Still within the request, make about 10 copies of the file at various resolutions. (These are thumbnails at different sizes, some for Hi-DPI (retina) devices, as well as a dimension for full-sized viewing. I also convert the images to WebP.

*I then transfer all the results to blob stores in different regions for private CDN purposes.

Clearly, the issue is that since this is all done within a HTTP request, it consumes vastly more server resources than any other typical HTTP request, especially when users start uploading images in bulk, several users at a time.  If a user uploads a large image, the memory consumption jumps dramatically (I am using ImageMagick.NET for image processing).
Is this architecture more suitable:

*

*Receive the file upload, write to the blob, add a notification to a processing queue, return success to the user.

*A separate worker server receives the notification of the new file and starts all the re-sizing, processing and replication.

*I just set the client-side JavaScript to not load the image previews for a few seconds, or get it retry if the image is not found (meaning that the image is still being processed, but is likely to show up sometime soon).

At least this new method will scale easier, has more predictable performance.  But it seems like a lot of work just to handle something as 'every day' as photo uploading.  Is there a better way?
I know the new method follows the same principle as using an external re-sizing service where, but wan't to do this in house since I am concerned about privacy of some of these third-party services. It would still mean I would have to adapt the client to deal with missing/unprocessed images.

A: Yes, what you're describing is a better way. It sounds more complicated, but it is how majority of scalable sites handle big load.. offload it to a queue and let workers process it.
I'd add a correction in your case for step #2:
A separate worker server monitors a queue and and starts all the re-sizing, processing and replication when a message appears instructing it to do so.

A: Another option would be to use the new Web Jobs feature. In fact your scenario seems to be so common (in terms of image processing) that it's listed as one of the Typical Scenario on MSDN.

Image processing or other CPU-intensive work. A common feature of web
sites is the ability to upload images or videos. Often you want to
manipulate the content after it's uploaded, but you don't want to make
the user wait while you do that.

Whether its better or not I'll leave it up to you to decide.


text:
Q: Footer Not Staying on Bottom I have a website and I am adding a footer to all the pages. On all the pages except for one with boxes on the right side of the page, the footer stays on the bottom.  On that page, the footer appears floated to the left of the text, not at the bottom where it should be.  Here is the code for that particular page:
HTML

Always a Satisfied Customer

Upfront Pricing

Affordable Rates

Courteous and Respectful

Always On Time

I would recommend EJP to anyone and everyone!  They showed up, looked at my issue, and fixed it promptly.  They are simply the best!
-Tim S.

EJP Electric offers repairs, upgrades, and installations, delivering high customer satisfaction by getting the job done right the first time.

        <address>EJP Electric

                 8603 E M115

                 Cadillac, MI 49601

                 231-775-3799

                 Email
        </address>

CSS
.expert {
    background-color: white;
    display: block;
    border: solid;
    float: right;
    right: 20px;
    padding: 3px;
}

.refer {
    background-color: white;
    border: solid;
    float: right;
    clear: right;
    width: 150px;
    display: block;
    margin-top: 5px;
    padding: 5px;
}

#footer {
    position: absolute;
    width: 600px;
    font-size: 12px;
    float: left;
}

A: You should clear the floating with the clear property:

The clear CSS property specifies whether an element can be next to
  floating elements that precede it or must be moved down (cleared)
  below them.

footer {
  clear: both;
}

.expert {
  background-color: white;
  display: block;
  border: solid;
  float: right;
  right: 20px;
  padding: 3px;
}
.refer {
  background-color: white;
  border: solid;
  float: right;
  clear: right;
  width: 150px;
  display: block;
  margin-top: 5px;
  padding: 5px;
}
#footer {
  position: absolute;
  width: 600px;
  font-size: 12px;
  float: left;
}
footer {
  clear: both;
}

Always a Satisfied Customer

Upfront Pricing

Affordable Rates

Courteous and Respectful

Always On Time

I would recommend EJP to anyone and everyone!  They showed up, looked at my issue, and fixed it promptly.  They are simply the best!
-Tim S.

EJP Electric offers repairs, upgrades, and installations, delivering high customer satisfaction by getting the job done right the first time.

    <address>EJP Electric

      8603 E M115

      Cadillac, MI 49601

      231-775-3799

      Email</address>

A: Your markup is not correct according to HTML5 semantic, of course if its not only the part of it, you can read about this here: html5doctor
Now about your question:
html, body, #wrap { height: 100%; }
body > #wrap {height: auto; min-height: 100%;}

#main {
    padding-bottom: 150px; /*should be the same as footer height*/
}
#footer {
    position: relative;
    margin-top: -150px; /*negative value of footer height*/
    height: 150px;
    clear: both;
}


text:
Q: jClouds + OpenStack: (NoSuchElementException) key [openstack-neutron] not in the list of providers or apis I'm trying to integrate Apache jClouds into a Java project so I can access the OpenStack API. The following code fails:
neutronApi = ContextBuilder.newBuilder("openstack-neutron")
                    .credentials(USERNAME, API_KEY)
                    .endpoint(AUTH_URL)
                    .modules(modules)
                    .buildApi(NeutronApi.class);

With the following error message:
Java.util.NoSuchElementException: key [openstack-neutron] not in the list of providers or apis: {providers=[ultradns-ws], apis=[swift, swift-keystone]}
This is apparently a common problem, however the suggestions offered in jClouds troubleshooting don't resolve it. There's another StackOverflow discussion about this problem but does not have an accepted answer.
A few useful points:

*

*Our Java project uses Ant, whereas jClouds is based on Maven. The jClouds Installation Guide provides directions to install using Ant, but none of them work correctly. Instead, I compiled jClouds from source (https://github.com/jclouds/jclouds) and copied the .jar files into a folder on my classpath. Now I can access the jClouds objects in my code.

*The default jclouds source does not include OpenStack Neutron objects. I eventually found these in the OpenStack Labs source (https://github.com/jclouds/jclouds-labs-openstack). Compiled from source, copied the openstack-neutron-1.9.1.jar file into classpath folder, now I can access Neutron objects.

*All online sources suggest this is a classpath/dependency problem. I've verified the openstack-neutron-1.9.1.jar library is available in both my .classpath and build.xml files. No resolution.

I'd appreciate any ideas or suggestions!

A: When you pass a provider/api id as a string to the ContextBuilder, the java ServiceLoader will be used to load the api classes. It will scan the META-INF/services folder in the classpath and look for implementations of ApiMetadata and ProviderMetadata.
Can you verify that in your environment there are no class loading issues that could prevent the ServiceLoader from operating normally?
As an alternative, you can bypass the ServiceLoader lookup and provide directly the concrete ApiMetadata implementation. In your case it would be something like:
NeutronApi neutron = ContextBuilder.newBuilder(new NeutronApiMetadata())
   .credentials(USERNAME, API_KEY)
   .endpoint(AUTH_URL)
   .modules(modules)
   .buildApi(NeutronApi.class);

If you have the openstack-neutron jar in your classpath this should work. And if it does, it also indicates that there is something in your project that is preventing the ServiceLoader from operating properly. It won't affect jclouds, as it only uses it when creating the context, but it is something you may want to fix.

A: There are some examples here:
https://github.com/jclouds/jclouds-examples/blob/master/rackspace/src/main/java/org/jclouds/examples/rackspace/cloudnetworks/CreateNetwork.java
They use maven, but they are a good starting point to compare code/dependencies.
Also, maybe you can use something like this to manage jclouds dependencies as an alternative? https://maven.apache.org/ant-tasks/
You can also try to download jclouds-neutron from maven, instead of compiling it:
https://search.maven.org/#artifactdetails%7Corg.apache.jclouds.labs%7Copenstack-neutron%7C1.9.1%7Cbundle
What problems are you hitting with the ant instructions?

A: If you're using maven, you should add the following dependency:
<dependency>
    <groupId>org.apache.jclouds.provider</groupId>
    <artifactId>aws-ec2</artifactId>
    <version>${jclouds.version}</version>
</dependency>

and then, package from the command line:
mvn clean package

and add the dependencies:
mvn dependency:copy-dependencies -DoutputDirectory="./lib"

and execute:
java -cp "target/jar-with-dependencies.jar:lib/*" YourClass


text:
Q: Do Azure storage-related APIs participate in System.Transactions? I can't find any information on this anywhere and yet the question is simple.
Can I wrap storage-related actions in a TransactionScope such that e.g. if there is a rollback, the uploaded file is rolled back also?
If the native APIs don't do this already, is there a public implementation anywhere?

A: If you're referring to Table or Blob updates, there's no notion of explicit commit or rollback. When you make an API call (whether direct REST call or via PowerShell / CLI / SDK), it's just an action against storage, and it will either succeed or fail (although some actions take a while and the call may return before completion). There's no transaction scope wrapping this action. You'd need to take care of undoing your Table / Blob updates at an app level.


text:
Q: Workaround for IE's Non-Bubbly Submit Events I'm working on a large web application with a lot of AJAX whose event handling has gotten out of control.  I'm trying to set up an event delegation system to manage all of it, but am wondering if there's a workaround for IE's non-bubbling form submits (there are a lot of forms that get inserted/updated via AJAX).  The best thing I've come up with is executing a bit of javascript to reload submit handlers every time I get a response from an AJAX call, but this seems ugly.  Any ideas?
Also, does anyone have a good reference for which events don't correctly propagate in different versions of IE?  I've had trouble finding good information (though this other question has a bit).

A real example from the site: there is in-place editing of some user content.  Doing event delegation, I would have the body listen for submit events and then see what element triggered the event and handle it accordingly.  Since submits don't bubble in IE, this won't work.  The $5 solution would be to do event delegation for all other events and handle submits using something like this in Prototype:
// call this onload:
$$('form').invoke('observe', 'submit', function(event) { /*delegate*/ });

But this won't work for forms that are created dynamically (I'd have to re-instantiate the handler every time as mentioned above), and the whole thing would just be nicer if I could "make" form submits bubble in IE and just do plain delegation everywhere (no special cases, etc).

A: Can you make the forms return false and just look for the CLICK event on the submit buttons instead of the form submit event? Then submit the forms programatically via your AJAX calls.

A: Rails 3 rails.js has solved this issue by detecting if the browser supports submit event bubbling, if not then bind the onSubmit method to the handler on the first focus event of the form.  Pretty neat.
Check out
http://github.com/rails/rails/commit/f61d923d284062b4e4864d81c603157020198d06

A: One technique you can try is to have only two forms: a "working" form and a hidden "submitting" form and only have these two forms on the page.
The "working" form is what is displayed to the user - it's just a container and can contain elements from various forms. Various buttons on the form don't actually submit, but call a form handler/validation routine in JavaScript.
The handler/validation routine dynamically sets the action of the "submitting" form and adds the required elements to that form dynamically so it can be submitted.
This way you are never adding and removing from tags themselves, you're just changing the appearance and behavior of the two main ones, thus avoiding all the nasty event manipulation.

A: Another option to consider may be reglib.
Latest trunk version has an implementation that allows delegation of submit

A: Matt Kantor,
I strongly suggest you have a look at NWEvents. As you said it actually forces bubbling in IE and make "event delegation" available for any other event in a cross-browser way.
NWEvents source code is on GitHub.

A: Options I've considered thus far:

*

*The crappy solution that I posted in the question itself.

*The Inline Cop-out - Always guaranteed to work, and has relatively low overhead, but is incredibly obtrusive.  I'd have to adapt this idea to work with Prototype (which wouldn't really be hard, I'd probably just write an Event.fix(event) function that stops the event then re-fires it to propagate on its merry way).

*NWEvents - I didn't get a chance to fiddle with this too much, but supposedly this forces all events to bubble.  Looking at the source, I'm not sure that this actually works for dynamically created elements.  I'll have to play with it some more.


text:
Q: Index created under different user I created an index on one table column as sys user, as I did not mention the schema name it got created under the sys schema. When I run the query as different user with read access to table I am not seeing the index being used. Could you please let me know whether the index will be ignore in oracle if index is created under different schema?

A: The is no permissions specific to index objects. So, as of myself, I would have said that the index will be automatically be used -- even if it is in a different schema. But as a comment on the linked answer raised doubt, I made the experiment using oracle 11g:
As user sonia:
SQL> create table t as (select level n from dual connect by level < 100);
Table created.

SQL> explain plan for select * from sonia.t where n < 10;
SQL> @UTLXPLS.SQL

TABLE ACCESS FULL T
SELECT STATEMENT

SQL> grant select on t to sylvain;
Grant succeeded.

As user sylvain:
SQL> explain plan for select * from sonia.t where n < 10;
Explained.

SQL> @UTLXPLS.SQL

TABLE ACCESS FULL T
SELECT STATEMENT

SQL> create index syl_idx on sonia.t(n);
Index created.

SQL> explain plan for select * from sonia.t where n < 10;
Explained.

SQL> @UTLXPLS.SQL

INDEX RANGE SCAN SYL_IDX
SELECT STATEMENT

Back to sonia:
SQL> explain plan for select * from sonia.t where n < 10;
Explained.

SQL> @UTLXPLS.SQL

INDEX RANGE SCAN SYL_IDX
SELECT STATEMENT

As you can see, SYL_IDX (index on sonia.t created in the sylvain schema) is used both when querying the table from sonia and from sylvain. Having the select permission on the table is sufficient.

A: No, it should not be ignored. There can be other reason considered by the optimizer not to use the index.
It's easy to check that you can use an index in a different schema:
-- Connected as power_user
SQL> CREATE TABLE some_user.a_table (a_field INTEGER);
Table created

SQL> INSERT INTO some_user.a_table
  2  SELECT rownum FROM dual CONNECT BY level <= 10000;
10000 rows inserted

SQL> CREATE INDEX power_user.an_index ON some_user.a_table (a_field);
Index created

-- Connected as some_user
SQL> select * from some_user.a_table where a_field = 50;

   A_FIELD
----------
        50

Execution Plan
----------------------------------------------------------
Plan hash value: 573181184

-----------------------------------------------------------------------------
| Id  | Operation        | Name     | Rows  | Bytes | Cost (%CPU)| Time     |
-----------------------------------------------------------------------------
|   0 | SELECT STATEMENT |          |     1 |    13 |     1   (0)| 00:00:01 |
|*  1 |  INDEX RANGE SCAN| AN_INDEX |     1 |    13 |     1   (0)| 00:00:01 |
-----------------------------------------------------------------------------


text:
Q: Salesforce Triggered Send - Secondary Email address I have a secondary email address field (Custom Field) on Leads and I need to send a Triggered Email to this custom Field.
While creating a Triggered Send in Salesforce, the Recepient Lookup field doesn't allow me to select anything other than the Lead ID. Is there a way to send email to a field that is not the primary email field.

A: I was able to resolve this by creating a Triggered Send Definition in Marketing Cloud and using the Marketing Cloud API.
The API will let you specify the From Email address and you can reference any field there. Sample REST API request JSON is mentioned below.

Host: https://www.exacttargetapis.com POST
  /messaging/v1/messageDefinitionSends/key:cust_key/send Content-Type:
  application/json Authorization: Bearer YOUR_ACCESS_TOKEN
{
    "From": {
        "Address": "code@exacttarget.com",
        "Name": "Code@"
    },
    "To": {
        "Address": "example@example.com",
        "SubscriberKey": "example@example.com",
        "ContactAttributes": {
            "SubscriberAttributes": {
                "Region": "West",
                "City": "Indianapolis",
                "State": "IN"
            }
        }
    },
    "OPTIONS": {
        "RequestType": "ASYNC"
    }
}


text:
Q: Extension Method for serializing an IEnumerable object to a string array? My last question was about getting the string representation of an object serialized to XML.   One of the responders wrote an extension method to encapsulate the serialization process.
My question now is how can I use an Extension Method to return an array of strings, when passed an IEnumerable<T> object, where each string in the array would be an individually serialized element of the IEnumerable<T>.
Thanks in advance!

A: To answer your next several questions...
new XElement("people", myPeople.ToXElements());

public static class XmlTools
{
    public static XElement ToXElement<T>(this T input)
    {
        return XElement.Parse(input.ToXmlString());
    }
    public static IEnumerable<XElement> ToXElements<T>(this IEnumerable<T> input)
    {
        foreach (var item in input)
            yield return input.ToXElement();
    }
    public static IEnumerable<string> ToXmlString<T>(this IEnumerable<T> input)
    {
        foreach (var item in input)
            yield return item.ToXmlString();
    }
    public static string ToXmlString<T>(this T input)
    {
        using (var writer = new StringWriter())
        {
            input.ToXml(writer);
            return writer.ToString();
        }
    }
    public static void ToXml<T>(this T objectToSerialize, Stream stream)
    {
        new XmlSerializer(typeof(T)).Serialize(stream, objectToSerialize);
    }

    public static void ToXml<T>(this T objectToSerialize, StringWriter writer)
    {
        new XmlSerializer(typeof(T)).Serialize(writer, objectToSerialize);
    }
}

A: using the code example from your link, you could add another method like this or convert them into array using ToArray() method.
public static class XmlTools
{
  public static IEnumerable<string> ToXmlString<T>(this IEnumerable<T> inputs)
  {
     return inputs.Select(pArg => pArg.ToXmlString());
  }
}

A: I would write my extension method to produce a new IEnumerable rather than an array:
public static IEnumerable<string> XmlSerializeAll<T>(this IEnumerable<T> input)
{
    foreach (T item in input)
    {
        yield return item.ToXmlString();
    }
}

You can get the array you want easily by using
var myArray = myEnumerable.XmlSerializeAll().ToArray();

This way, you add some flexibility. It's possible to produce a List instead, or use infinitely long enumerations if you like :)


text:
Q: Finding how many users have table creation privileges I want to find out how many users have permission to create a table in my Oracle 11g database by using meta data.
What kind of query should I write? (I don't want it to be very complicated).

A: select count(distinct usr)
from (
  select auth, tp, connect_by_root auth usr, connect_by_root tp tp_usr
  from (
    select null grantee, username auth, 'user' tp from dba_users
    union
    select grantee, granted_role, 'role' from dba_role_privs
    union
    select grantee, privilege, 'priv' from dba_sys_privs
  )
  start with grantee is null
  connect by grantee = prior auth
) where tp_usr = 'user' and auth in ('CREATE TABLE', 'CREATE ANY TABLE');

This query also scans granted roles recursively. However, I'm still not sure that it gives all the users who can create a table.

A: It would be good to see what you tried so far. May I let you try first using the following :
dba_users and dba_sys_privs.
The privilege you are looking for is CREATE ANY TABLE.
Please search for them and come up with your try,and I would be happy to help you further.

A: All users and roles who has such privilege:
select *
from dba_sys_privs
where privilege = 'CREATE TABLE' or privilege = 'CREATE ANY TABLE';

Also you need view DBA_ROLE_PRIVS because user can get privilege indirectly, using role.


text:
Q: How to translate this simple C# method that use XPath into a Java method? I am pretty new in the use of XPath in Java and I don't know C#.
In this time I have to convert some C# methods that use XPath into Java methods and I have some doubts about it.
In a C# method I found the following lines of code:
System.Xml.XmlNode element;
System.Xml.XmlNode filter;

filter = _document.CreateElement("filter");
element = _document.CreateElement("name");
element.InnerText = es.Descrizione;
filter.AppendChild(element);

and I am trying to convert it into Java code.
I think that the first 2 lines can be translated as:
Element element;
Element filter;

(it is simple a declaration of a Jdom Element objects)
But I have many doubts about how translate these lines in Java:
filter = _document.CreateElement("filter");
element = _document.CreateElement("name");

filter.AppendChild(element);

Can you help me?
Tnx
Andrea

A: The Java equivalent would be the following:
import javax.xml.parsers.*;
import org.w3c.dom.*;

public class Demo {

    public static void main(String[] args) throws Exception {
        Element element;                            // System.Xml.XmlNode element;
        Element filter;                             // System.Xml.XmlNode filter;

        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        DocumentBuilder db = dbf.newDocumentBuilder();

        Document _document = db.newDocument();
        filter = _document.createElement("filter"); // filter = _document.CreateElement("filter");
        element = _document.createElement("name");  // element = _document.CreateElement("name");
        element.setTextContent(es.Descrizione);     // element.InnerText = es.Descrizione;
        filter.appendChild(element);                // filter.AppendChild(element);
        _document.appendChild(filter);
    }

}

A: Why are you mentioning XPath? I don't see any use of it. If you want to continue to use the DOM API then you could do that even in Java with http://docs.oracle.com/javase/7/docs/api/org/w3c/dom/package-summary.html and your code would be
import org.w3c.dom;

Element element;
Element filter;

filter = _document.createElement("filter");
element = _document.createElement("name");
element.setTextContent(es.Descrizione);
filter.appendChild(element);

If you want to use JDOM then you would need to change the approach and instead of using the DOM based factory methods like document.createElement(..) you would simply use constructor methods like new Element(..).


text:
Q: Are LiveData objects observable in XML? When I bind ObservableField<> objects to a view in XML, changes to the value via set() are immediately reflected in the view. When I bind LiveData<> objects in XML, however, the initial value is rendered but changes via value= have no effect on the view. They are passed to Kotlin observers.
I assumed LiveData would work like Observable* classes in XML bindings. Is that not the case? If I need to observe a value in both XML and Kotlin, do I really need to create two observables?

A: You can make use of data-binding. https://developer.android.com/topic/libraries/data-binding/
With data binding, your xml will be notified when there is a change in your LiveData. You can also attach an observer to the same live data in your java code.
Hopefully this helps!

A: This works for me via data binding, which I assume is what you are using.
You did not provide your code, so I can only guess that perhaps you are not calling setLifecycleOwner() on your binding object (e.g., ActivityMainBinding for an activity_main layout resource). Without that, data binding cannot register an observer.
This sample project shows a layout that uses android:text="@{viewModel.sensorLiveData}" on a TextView. In the activity that uses this layout, I use setLifecycleOwner() to teach the binding about my FragmentActivity:
/***
  Copyright (c) 2013-2017 CommonsWare, LLC
  Licensed under the Apache License, Version 2.0 (the "License"); you may not
  use this file except in compliance with the License. You may obtain a copy
  of the License at http://www.apache.org/licenses/LICENSE-2.0. Unless required
  by applicable law or agreed to in writing, software distributed under the
  License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS
  OF ANY KIND, either express or implied. See the License for the specific
  language governing permissions and limitations under the License.

  Covered in detail in the book _Android's Architecture Components_
    https://commonsware.com/AndroidArch
 */

package com.commonsware.android.livedata;

import android.arch.lifecycle.ViewModelProviders;
import android.databinding.BindingAdapter;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.widget.TextView;
import com.commonsware.android.livedata.databinding.MainBinding;

public class MainActivity extends FragmentActivity {
  @BindingAdapter("android:text")
  public static void setLightReading(TextView tv, SensorLiveData.Event event) {
    if (event==null) {
      tv.setText(null);
    }
    else {
      tv.setText(String.format("%f", event.values[0]));
    }
  }

  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    MainBinding binding=MainBinding.inflate(getLayoutInflater());
    SensorViewModel vm=ViewModelProviders.of(this).get(SensorViewModel.class);

    binding.setViewModel(vm);
    binding.setLifecycleOwner(this);
    setContentView(binding.getRoot());
  }
}

And it works like a champ, assuming your device has an ambient light sensor that works.


text:
Q: Weird MySQL Errors After Distrib Upgrade (SQL 5.0 > 5.1) Just updated Debian from Lenny to Squeeze on one of my servers. It hosts a MySQL server. Upgrade went fine, but afterwords, when MySQL starts up, it checks the databases to make sure they are okay. I am getting errors though for tables that are in the mysql database.
I did an extensive Google search and attempted to do a myiasmchk -r to those tables. Outside of that, I have not found any other possible answers.
Is this just a bug? Is there a way to fix it?

ERROR 1034 (HY000) at line 1: Incorrect key file for table 'columns_priv'; try to repair it
ERROR 1034 (HY000) at line 1: Incorrect key file for table 'db'; try to repair it
ERROR 1034 (HY000) at line 1: Incorrect key file for table 'func'; try to repair it
ERROR 1034 (HY000) at line 1: Incorrect key file for table 'host'; try to repair it
ERROR 1034 (HY000) at line 1: Incorrect key file for table 'tables_priv'; try to repair it

Thanks in advance for your help!

A: Confirmed as bug, patch and details here

A: connect to mysql server and do a commands
repair table func;
repair table db;
repair table host;
etc...


text:
Q: What does "hopefully" mean here? In the following sentence, what does hopefully mean, what part of speech is it, and what does it modify?

Hopefully the rain will end soon.

From http://www.merriam-webster.com/dictionary/hopefully:

1 : in a hopeful manner
  2 : it is hoped : I hope : we hope : hopefully the rain will end soon

It must be #2 according to the example.  If it means "it is hoped" or "I hope" then is the entire main subject and predicate of the sentence subsumed into the word hopefully?
A related question is, if I use a comma, how does that change the sentence grammatically and semantically?

Hopefully, the rain will end soon.

A: Hopefully is an adverb in your excerpt, but it modifies the entire sentence rather than any individual word within it. It is an example of a disjunct, about which Brinton & Brinton (via LinguisticsGirl) say

Disjunct adverbials denote the attitude of the speaker toward or judgment of the proposition such as truthfulness of manner of speaking. …
The grammatical forms that can function as the disjunct adverbial in English grammar are the adverb phrase, prepositional phrase, and adverb clause.

More specifically, it is a sentence adverb, a common if sometimes disliked usage:

Unfortunately, the show ended late.
Thankfully, the kitchen is still open.
Obviously, we will order both desserts.

Oxford reports general suspicion of sentence adverbs in some quarters; some prefer to reword them— it is lucky that in place of luckily— and reject those which refer to the speaker's attitude, which cannot be reworded in this way (one cannot say it is frank that in place of frankly). That seems quite arbitrary, however. Clearly, such usage is widely accepted, and hopefully, you will not get caught up by misguided purists.


text:
Q: Excel in Windows 10 In my target cell I want to subtract the numeric value in one cell from another cell's numeric value - but if one of those two cells contains a zero value, or if it contains the text "ongoing", I do not want any calculation to take place and my target cell to remain empty.
Any help with a formula would be hugely appreciated.

A: (sorry I'd rather have replied to Máté Juhász's comment, but my reputation only allows me to provide answers)
Máté Juhász's suggestion would work just fine, but if you wish the substraction to happen when either of your cells are empty, the formula should rather be =IF(OR(AND(A1=0,A1<>""),AND(A2=0,A2<>""),A1="ongoing",A2="ongoing"),"",A1-A2):
Example


text:
Q: join with latest records only from another table:- Remove replication I have 2 table lets say table1 and table2 table 1 is the master data and table 2 is child. I have to find out records from both table corresponding to the given table1.id. But there are more than 1 record in table2 corresponding to table1.id. So I would like to filter the latest record first from table2 corresponding to table1.id then apply the join on filtered data from table2 and table1.
table1= location_grids
table2= local_ads

Following what I am doing ?
SELECT  * FROM `location_grids`as l
LEFT JOIN `local_ads` la ON `la`.`location_grid_id` = `l`.`id`
Inner join (SELECT id, location_grid_id, max(booked_till) as maxbooked
            from local_ads group by location_grid_id ) as b
            on la. location_grid_id = b.location_grid_id
            and la.booked_till = b.maxbooked
WHERE `l`.`location_id` =  '1'
AND `l`.`flag` =  1

The  query is returning me unfiltered data. How can I filter then apply join on data. Any help will be appreciated.
table1:- location-grid

table2:- local_ad

A: Finally got the solution :- I was searching for following  query.
SELECT location_grid_id, user_id, booked_from, booked_till, purpose, category, duration, price, MAX( created )
FROM local_ads
GROUP BY location_grid_id

Here I wanted to run join with latest record of the particular id as many record must be exist in local_ads


text:
Q: I can download file using Google Chrome but not using cURL in php I have a code here in php,
set_time_limit(0);

$ch = curl_init();

$link  = "https://somelinks-uploads";
$token = "sometoken";

curl_setopt_array($ch, [
    CURLOPT_URL            => "{$link}",
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_MAXREDIRS      => 10,
    CURLOPT_TIMEOUT        => 3600,
    CURLOPT_CUSTOMREQUEST  => "GET",
    CURLOPT_NOPROGRESS     => false,
    CURLOPT_USERAGENT      => "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/101.0.4951.54 Safari/537.36",
    CURLOPT_HTTPHEADER     => [
        "Accept: application/json",
        "Authorization: Bearer {$token}",
        "Content-Type: application/json"
    ]
]);

$response  = curl_exec($ch);
$err       = curl_error($ch);
$http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);

curl_close($ch);

Which, if I run, will not successfully download the file. It will just stop base on the allowed timeout
CURLOPT_TIMEOUT => 3600,

The same with using an application like Insomnia, an alternative to postman. But when I am using Google Chrome and pasted the same link, I can download the file, although I need to wait for around 15-20mins because it's a large file.
What's going on?
What the problem with PHP cURL?


text:
Q: Include textbox within option tag in html I want to include a dropdown in my HTML page where I intend to allow user input also. This question is different from many others on stack overflow asking to add an option altogether.
I have a list of tech indicators in the dropdown. But what I need is when the user selects Simple Moving Average, he/she may also be able to input the desired value for period of SMA. But as far as I have searched, there seems no way to include a textbox within an option tag.
I am ok to use third party plugins like bootstrap/select2. Does anyone have any idea reagarding how this can be achieved?

A: Adding of textbox inside native dropdown box is not possible. but you can add another textbox. when certain value selected you can display that textbox to get data. I just found out a fiddle according to your requirements.

Fiddle link