text:
Q: Location of base class library in .net I see the some of the .net dlls I need are at
C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\v3.5
and the rest in the GAC
C:\Windows\Microsoft.NET\assembly
Why can't they all be in the GAC? Is there a specific reason for some of them to be outside the GAC?

A: From a little bit research that I did, what I gathered is that, the run time uses GAC (C:\Windows\Microsoft.NET\assembly).
The assemblies at C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\v3.5 are for development purposes only (to be used by Visual studio during development).
Please correct me if I am wrong.

A: GAC -Global Assembly cache ,By default the files in assembly were used for intellisense of .Net, Whenever you write a program in .net the intellisense were fetched from the assembly files apart from that all .net frameworks use reference assemblies to filter the intellisense. Additionally you could refer here


text:
Q: Multisite setup on Centos 7 Drupal commerce site I have requirement of Drupal project which is a commerce website. We have used Drupal commerce module for the same purpose before.
I have Centos 7 as my server with EasyApache installed. Everything is installed on the server to run Drupal project and normal Drupal project is working nice.
I have tried to make multisite working for my website. Tried many options:

*

*Added subsite under sites folder (example.com)

*Added site link in sites.php file ($sites['example.co'] = 'example.co';)

*Created virtual host and symlink

*And many more..

There are too many finding for multisite on Google but none of them is working well for me.
Can someone help me to configure multisite on centos 7 server?

A: You can set your domain.com/web/sites/default/settings.php add your host like this :
 $settings['trusted_host_patterns'] = array(
     '^example\.co$',
     '^www.example\.co$',
 );

On linux if you can't due of rights to set it, just change the rights of folder parent and the file.
sudo chmod 777 default
sudo chmod 777 settings.php

After the fix you can reverse to rights by :
sudo chmod 555 default
sudo chmod 444 settings.php

On the admin site you need to set it too and at first time if didn't do it.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to read model attribute from js outside jsp If my javascript/jquery code is written inside a jsp-file, I can refer to Spring's modelAttribute value with "${varName}".
However I would like to move the javascript code into it's own file to keep the jsp-file more readable. When I do that, it won't however be able to find that modelAttribute anymore. How should I solve this problem?
How can I point to model attribute from a .js -file?
Thanks in advance!

A: Alright, I've experimented on my end to try to find and answer for this question.
Actually, it seems there's no direct solution, and here's why:

*

*When you are moving your Javascript code to a separate file, this means that the browser will launch a separate request to fetch that file. As such, data that you store in your request scope (a.k.a. ${varName}) is not part of the request that fetches the .js file; it's only part of the request that fetches your .jsp file instead. As such, the ${varName} value will not be available in your Javascript file.

*Another reason on top of the above: .js files are not processed as server-side code by the web engine (most likely Tomcat in this case), so the ${varName} text is outright ignored. For fun, I tried to do a hack: I renamed my script file from .js to .jsp, and used this within my .jsp page:

<script type="text/javascript" src="js/actually_javascript.jsp"></script>

It fooled the web server to process the file server-side, but this still didn't work, because of reason #1 stated above. It could work if you stored the value in the session instead, but at the end of the day, it would be kind of an ugly hack and you'd lose out on the code highlighting and completion features of your IDE, which would be fooled into thinking you're editing an actual .jsp file. Not recommended.
To conclude, I think the only way to access {$varName} inside your JavaScript is either:

*

*Having the Javascript being a part of your .jsp file, within <script> tags

*Having your Javascript in its own .js file, but still having a <script> tag in your .jsp page which initializes the module you programmed in the .js file and passes the values from the request, like ${varName}

A: You should initialize your javascript file via your jsp file.
Example:
Create a seperate script section for initialization of your variables after loading the .js file in your jsp page:
<script src="js-path/file.js"></script>
<script>
    init(${varFromModel1}, ...);
</script>

And define the init-method in your javascript file:
function init(param1, ...) {
    // initialize variables of .js file here
}

Remember, for this to work, you need to ensure, that the model-attribute output has correct javascript syntax.


text:
Q: selecting specific subelement node trees for output using xslt I have some XML that has an extra element and I want it gone. Input XML:
<top><middle><bottom><!-- other elements --><stuff/></bottom></middle></top>

Output desired:
<top><bottom><!--other elements --><stuff/></bottom></top>

(note "middle" element has been snipped from the node tree)
How do I arbitrarily snip out an element without having to create a template cascade of every possible element in the source? Is there a way to just pass all elments and subelements from a given point? including the XML tagging, attributes and content?
Searches I've done mention using <xsl:copy> but it doesn't work - "node()|@*" only returns the content and attribute value and not the actual subelement XML tree.
How do I do this in XSLT 1 or 2?  The way I am doing it now is to create a template tree for each element but the "stuff"?

A: Use the Identity Transform with an override for the elements you want to remove:
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  <xsl:template match="@*|node()">
    <xsl:copy>
      <xsl:apply-templates select="@*|node()"/>
    </xsl:copy>
  </xsl:template>
  <xsl:template match="middle">
      <xsl:apply-templates/>
  </xsl:template>
</xsl:stylesheet>


text:
Q: Hibernate - 1 Class 2 Tables I have a simple table and I want to store them in another table aswell (create a historic of users). Let's call it Users. I created a table exactly like Users (only different id name) called HISTORY_Users.
So I created the table and now I realize that I have 2 tables for 1 object. So how do I add my object only to the hist table?
I dont want to add them at the same time. I want to add the user to the hist only when he deletes the accounts.
I'm using Hibernate with xml mapping
 //when the user deletes the account I call this function and pass the User
  private static void addToHist(User User) {
      //how do I add only to HIST_Users table??
      Database.addToDatabase(user);

}

 //Save the object to the database
public static void addToDatabase(Object object) {
    SessionFactory factory = HibernateUtil.GetSessionFactory();
    Session session = factory.openSession();
    Transaction tx = null;
    try{
        tx = session.beginTransaction();
        session.save(object);
        tx.commit();
    }catch (HibernateException e) {
        if (tx!=null) tx.rollback();
        e.printStackTrace();
    }finally {
        session.close();
    }
}

A: Maybe better solution will be use the Hibernate Envers: http://hibernate.org/orm/envers/
You can configure when you want to put it into history: on create, update or delete.
Tables are created automatically, you need to add some annotations only like @Audited etc.


text:
Q: Confusion on how cluster and child Process works I have used child process in my electron application. and I forked child process only after the previous child process ends. And also if I fork multiple processes, it won't increase the speed.
so can I able to use the cluster module in electron application to fork multiple child processes at the same time.
let doneFunction = {}
let queue = createQueue(1);
this.state.files.forEach((file, i) => {
    queue.defer(function(details, done) {
        readSizeRecursive(details.path, e); // inside that i forked child
        doneFunction = done;
    }, file);
});

childFinished = () => {
    doneFunction()
}

I previously asked Child process maximum limit but I can't any answer.

*

*if I forked two cluster means, and I fork two child process means, each child runs parallel in two different clusters?

A:
And also if I fork multiple processes, it won't increase the speed.

To increase the speed, you need to speed up the bottleneck which is disk IO in your case(directory size calculation etc...). CPU is much faster than disk IO, therefore multi/single threads/processes just do not matter.

if I forked two cluster means, and I fork two child process means, each child runs parallel in two different clusters?

yes, but it will not speed up your final result as mentioned above

A: You may have a better understanding of cluster mode from this article
Cluster definition in depth
But I personally recommended to use Nginx for such things.
Take a look in NgInx
I hope it helps. happy Coding :)


text:
Q: How to connect from ruby to MS Sql Server I'm trying to connect to the sql server 2005 database from *NIX machine:
I have the following configuration: Linux 64bit

ruby -v
  ruby 1.8.6 (2007-09-24 patchlevel 111) [x86_64-linux]
  important gems:
  dbd-odbc (0.2.4)
  dbi (0.4.1)
  active record sql server adapter - as plugin

ruby-odbc 0.9996 (installed without any options.)
unixODBC is installed
freeTDS is installed

cat /etc/odbcinst.ini

  [FreeTDS]
     Description     = TDS driver (Sybase/MS SQL)
     Driver          = /usr/lib/libtdsodbc.so
     Setup           = /usr/lib/odbc/libtdsS.so
     CPTimeout       =
     CPReuse         =
     FileUsage       = 1

DSN:
DRIVER=FreeTDS;TDS_Version=8.0;SERVER=XXXX;DATABASE=XXX;Port=1433;uid=XXX;pwd=XXXX;"

or
DRIVER=/usr/lib/libtdsodbc.so;TDS_Version=8.0;SERVER=XXXX;DATABASE=XXX;Port=1433;uid=XXX;pwd=XXXX;"

I receive the following error:
>>ActiveRecord::Base.sqlserver_connection({"mode"=>"ODBC", "adapter"=>"sqlserver", "dsn"=>my_dns)
DBI::DatabaseError: IM002 (0) [unixODBC][Driver Manager]Data source name not found, and no default driver specified
    from /usr/lib/ruby/1.8/DBD/ODBC/ODBC.rb:95:in `connect'
    from /usr/lib/ruby/1.8/dbi.rb:424:in `connect'
    from /usr/lib/ruby/1.8/dbi.rb:215:in `connect'
    from /opt/ublip/rails/current/vendor/plugins/activerecord-sqlserver-adapter/lib/active_record/connection_adapters/sqlserver_adapter.rb:47:in `sqlserver_connection'

It looks like ODBC unable to find appropriate ODBC driver, but I have no ideas why.
I had a problem with /usr/lib/libtdsodbc.so which is empty in default debian package free-tds dev, but i solved it with remove broken package and installation from sources.
Will appreciate any thought!
Note:
I'm albe to connect using the same steps on mac 10.5

A: This looks close, and I've gotten the same type of setup to work on Ubuntu 8.04 (with Ruby 1.8.6.) Since this is on Debian, it should be the similar.
These packages should be installed: unixodbc unixodbc-dev freetds-dev libdbd-odbc-ruby tdsodbc
/etc/odbcinst.ini should have something like this:
[FreeTDS]
Description = FreeTDS unixODBC Driver
Driver = /usr/lib/odbc/libtdsodbc.so
Setup = /usr/lib/odbc/libtdsodbc.so
UsageCount = 1

And /etc/freetds/freetds.conf: (where XXX is the database name and NNN... is the IP of the server):
[XXX]
  host = NNN.NNN.NNN.NNN
  tds version = 8.0
  client charset = UTF-8
  text size = 262144
  port = 1433

Then to connect:
ActiveRecord::Base.sqlserver_connection({"mode"=>"ODBC",
  "adapter"=>"sqlserver",
  "dsn"=>"DRIVER=FreeTDS;SERVERNAME=XXX;DATABASE=XXX;uid=XXX;pwd=XXX"
)


text:
Q: Double SQL Query - JOIN I need a double SELECT sql query from 2 different tables with names visits & items
1.: SELECT visitid, visitdate, visitreason FROM visits WHERE personid = 10
    2.: SELECT itemid, itemname, itemtime FROM items WHERE itemvisitid= visitid
I think I need to do a JOIN but don't know exactly how.
Table examples:
Table: visits
visitid | personid | visitdate  | visitreason
1       | 10       | 05/07/2014 | no reason
2       | 10       | 06/07/2014 | some reason
3       | 12       | 06/07/2014 | no reason
4       | 10       | 12/07/2014 | some other reason

Table: items
itemid | personid | itemvisitid | itemname | itemtime
1      |   10     |  2          | box      | 23
2      |   10     |  2          | clock    | 70
3      |   10     | null        | water    | 50
4      |   10     | null        | paper    | 40
5      |   12     | 3           | box      | 26

What I have now is this:
$query = "SELECT visitid, visitdate, visitreason FROM visits WHERE personid = '10' ORDER BY visitdate DESC";

// 2nd select: "SELECT itemid, itemname, itemtime FROM items WHERE itemvisitid= visitid";

    $db->setQuery($query);
    $results = $db->query();
while($row = mysqli_fetch_array($results)){
    echo "

        ".$row['visitid'].", ".$row['visitdate']."
        ".$row['visitreason']."
        ".$row['itemid'].",".$row['itemname'].", ".$row['itemtime']."

";
}

I need results to be something like this:

    1, 05/07/2014	no reason
    2, 06/07/2014	some reason	1, box, 23
2, clock, 70
    4, 12/07/2014	some other reason

A: SELECT `visits`.`visitid`, `visits`.`visitdate`, `visits`.`visitreason`,`items`.`itemname`, `items`.`itemtime` from `visits` INNER JOIN `items` ON `visits`.`personid`=`items`.`personid` WHERE `visits`.`personid` = '10' ORDER BY `visits`.`visitdate` DESC

if there is any error please change the field name personid in 'items' table.and then check.

A: This query:
SELECT v.visitid,
       v.visitdate,
       v.visitreason,
       i.itemid,
       i.itemname,
       i.itemtime
FROM   visits v
       INNER JOIN items i
               ON ( v.visitid = i.itemvisitid )
WHERE  v.person_id = 10
ORDER  BY v.visitdate DESC,
          i.itemid ASC

will link both tables and produce a resultset that you can traverse using a double loop. The outer loop to process changes to the visit, and the inner to add every item visited in a particular visit.

A: I guess your might to use GROUP_CONCAT like this:
DEMO: http://sqlfiddle.com/#!2/9d4e22/15
SELECT visitid, DATE_FORMAT(visitdate,'%m/%d/%Y'), visitreason,
GROUP_CONCAT(itemid,itemname, itemtime)
FROM visits  left join items on visits.visitid = items.itemvisitid
WHERE visits.personid = 10
GROUP BY  visitid, visitdate, visitreason

You might want to read this to know GROUP_CONCAT :
How to use GROUP_CONCAT in a CONCAT in MySQL
The document of GROUP_CONCAT() is here:
http://dev.mysql.com/doc/refman/5.0/en/group-by-functions.html#function_group-concat
hope this helps.


text:
Q: Include precompiled zImage in yocto project I have a custom board with imx6dl chip and peripherals. I have compiled u-boot, zImage and rootfs from examples provided by manufacturer. But when i try to build yocto from git repo with latests releases, it fails to run (some drivers not working, board is loading and display interface, but touchscreen is not working for ex.),
Is there any way to include precompiled binaries zImage, u-boot and device table to bitbake recipes? I'm very new to yocto project, and only need to get bootable image with working drivers and qt5.

A: If you have a working boot chain (e.g. u-boot, kernel and device tree) that you have built out-of-yocto, then you might try building a rootfs only. This requires two main settings, to be made in your local.conf to get started. Please don't firget that this is just a starting point, and it is highly advised to get the kernel/bootloader build sorted out really soon.
PREFERRED_PROVIDER_virtual/kernel = "linux-dummy to have no kernel being built, and something like MACHINE="qemuarm" to set up an armv7 build on poky later than version 3.0. The core-image-minimal target should at least be enough to drop you in a shell for starters, and then you can proceed from there.
Additionally, it might be qorth asking the board vendor or the yocto community (#yocto on the freenode server) if they know about a proper BSP layer. FSL things are quite nicely supported these days, and if your board is closely related to one of the well-known ones, you've got a high chance that meta-freescale just does the trick nicely.
Addition:
@Martin pointed out the mention of Qemu is misleading. This is just the easiest way to make Yocto build a userland for the armv7-architecture which the imx6dl is based on. The resulting root filesystem should be sufficiently compatible to get started, before moving on to more tuned MACHINE configuration.


text:
Q: Is NB-IoT roaming possible? I found a comment on a blog post stating that NB-IoT doesn't support roaming:

nbiot do not support roaming (you must have sim from the operator that have the infrastructure). nbiot also lacks support for handover (you can not maintain connection while moving out of range of cell A and into range of cell B.
in short, NBIoT (LTE NB1) is a mobile standard for stationary objects.
if you want roaming and handover you have to go with LTE Cat m1 (not to be confused with LTE Cat 1) or wait for LTE NB2.

I wasn't able to correlate this informations with other sources. Is this statement true? Is this a technical limitation due to the specification/implementation?

A: If you use your favorite search engine and search for terms like "nb iot roaming" you'll find plenty of other pages backing this.
I'd interpret this (2017) document from the GSMA in a way that it says "NB IoT specifations have been written very quickly, Roaming might be added later"
https://www.gsma.com/iot/wp-content/uploads/2017/08/CLP.28-v1.0.pdf
This source https://1ot.mobi/blog/the-state-of-roaming-narrowband-iot-lte-cat-m1
says

There is a small beam of light indeed. Deutsche Telekom and Vodafone
  completed the first successful NB-IoT Roaming trial this summer.
  (this seems to have been carried out in 2018)

To answer your question:
Yes this seems to be (have been) a technical limitations per specification, but people are working on it.


text:
Q: Quantisation of $z$-angular momentum eigenvalues Consider the eigenvalue equation for the $\hat{l}_z$ angular momentum operator: $$\hat{l}_zY_{lm_l}(\theta,\phi)=m\hbar Y_{lm_l}(\theta,\phi)$$ with separable solution $$Y_{lm_l}(\theta,\phi)=\Theta_{lm_l}(\phi)\exp(im\phi)$$
I am unsure about the following passage from Gasiorowicz's Quantum Physics:

It is sometimes argued that since […] a transformation $\phi\to\phi+2\pi$ leaves the system invariant, it is necessary that $\exp(2\pi im)=1$, so that $m$ is an integer.
This is not quite correct, since the quantities that enter into physical observables are of the type $\int_0^{2\pi}d\phi\Psi_1^*(\phi)A\Psi_2(\phi)$, with wavefunctions $\Psi(\phi)$ of the form $$\Psi(\phi)=\sum_{m=-\infty}^\infty C_m\exp(im\phi).$$
If we require that these arbitrary wavepackets do not change under the transformation $\phi\to\phi+2\pi$, then we are led to the conclusion that the most general allowed values of $m$ are $m=c+$ integer, where $c$ is a constant.

I recognise the integral in the passage as the expectation value of an observable $A$. I understand why the boundary conditions imply $m$ must be an integer; what I don't understand is how/why is $m$ allowed, in principle, to be equal to an integer plus a constant. While it may seem an irrelevant issue, I suspect that when $c=1/2$ then $m$ is half-integer and therefore an eigenvalue of spin, so I would like to understand exactly where this constant factor comes in. If I just plug in $m+$ constant in the equation and then I transform from $\phi$ to $\phi+2\pi$ I seem to break the boundary condition for single-valuedness.

A: Wavefunctions are not observable and and only unique up to a complex phase (i.e. $e^{ic \phi}$), since any complex phase will be equal to one if multiplied with its conjugate. In other words, you can multiply your wavefunction with any $e^{ic \phi}$, and it's still considered the same wavefunction! That said, $c$ can be any numbers, not necessary $1/2$.


text:
Q: Unable to click a particular element in selenium(using python) Below is the tried code
from selenium import webdriver

browser = webdriver.Chrome()

browser.get("https://flipkart.com")

input2_css_locator = "input[name='q']"
cross_button = "//button[@class='_2AkmmA _29YdH8']"
button4_xpath_locator = "//button"
product_button = "//div[@class='_3wU53n']"

# Assign elements
input2_element = browser.find_element_by_css_selector(input2_css_locator)
button4_element = browser.find_element_by_xpath(button4_xpath_locator)
cross_element = browser.find_element_by_xpath(cross_button)
product_element = browser.find_element_by_xpath(product_button)

# browser.switchTo().alert().dismiss()
#Manipulate elements

cross_element.click()

input2_element.send_keys("mobile")
button4_element.click()

product_button.click()
# browser.quit()

It will not work for sure as this will point to 2 classes instead of 1.
I just tried to modify same code in line no 18.
product_element = browser.find_element_by_xpath(product_button).[0].innerText

error in this case:
product_element = browser.find_element_by_xpath(product_button).[0].innerText
^
SyntaxError: invalid syntax
I tried to change the same in line 10 also, but that is also not working.
I just want to click the first link(or any link whichever user wants), Can you help me where I am making mistake and with the solution.
Thanks in advance

A: You have an extra dot(.) before [0]. It should be
product_element = browser.find_element_by_xpath(product_button)[0]

A: Try This
productElement = browser.find_element_by_xpath(BUTTON_NAME)[0]


text:
Q: Specifying an attribute in a generic React component I am trying to build a generic React select component to show a list of options labeled as whatever is passed to the component. My issue is that I want to be able to specify which attribute to use when printing the records which will not always be the same. For instance, if I pass an array of authors, I would use the full_name attribute to populate the list; however, if I wanted to print a list of books, I would want to use title.
I have an options function that I call to populate the select which looks like this:
options = () => {
  return this.props.collection.map(o => {
    return (
      <option key={o.id} value={o.id}>/*DISPLAY METHOD HERE*/</option>
    )
  })
}

Basically I want to be able to pass in a prop to the component specifying the attribute I want to use (full_name, title, etc) and call that on o (o.full_name, o.title, ...) in the return call. Is this possible?

A: Im not sure if I fully understood your question but if you try to access an arbitrary method of an object it is the same in JS as accessing an arbitrary attribute.
So you could like with attributes just access the method by string.
For example for your title:

    const Foo = (o, title) => {
      return o[title]();
    }

    Foo({ Fantastic: () => console.log('Four'), }, 'Fantastic');

"o[title]" would get you the method and "()" invoke it

A:

const SelectPicker = ({ data }) => (
    <select>
      {Object.keys(data).map(key => (
        <option value={key}>{data[key]}</option>
      ))}
    </select>
  );

function App() {
  var obj = {
    userOne: "John Doe",
    userTwo: "John Smith"
  };
  return (

      <SelectPicker data={obj} />

  );
}

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);

You might look for something like this?


text:
Q: Golang equivalent of Python's struct.pack / struct.unpack In Python, using the struct module, I can do something like this to get a packed representation of a value as a string:
import struct
print struct.pack('L', 64)
"@\x00\x00\x00\x00\x00\x00\x00"
struct.unpack('L', '@\x00\x00\x00\x00\x00\x00\x00')
(64,)

I'd like to do something similar in Go, except I'm a little unclear on how to do so. I know I can do something like this:
import (
    "encoding/binary"
    "fmt"
)

bs := make([]byte, 8)
binary.PutUvarint(bs, uint64(64))
fmt.Printf("%s", bs)
"@"

But that's very different and probably not what I want.

A: Yes, "encoding/binary" is what you want, you just don't want the variable length format.
https://play.golang.org/p/e81LuPO_JR
bs := make([]byte, 8)
binary.LittleEndian.PutUint64(bs, uint64(64))
fmt.Printf("%#v\n", bs)

i := binary.LittleEndian.Uint64(bs)
fmt.Println(i)

A: There are a couple interesting solutions.
1st is gist that's simple to follow and its limitations are clear:
https://gist.github.com/cloveryume/9a59e8d77f5836f11720#file-golang_struct_packed-go
2nd is a package that tries to the job of packing:
https://github.com/lunixbochs/struc


text:
Q: adding a variable to array matlab im trying to build a problem that refer to how to travel from Arad to Bucharest.
you can see romania's map here:
romania's map
my code:
clc;clear
goal='bucharest';
list=cell(20,5);
n=cell(20,5);

'city';
n{1,1}='arad';
n{1,2}='zerind';
n{1,3}='sibiu';
n{1,4}='timisoara';

'city';
n{2,1}='zerind';
n{2,2}='arad';
n{2,3}='oradea';

'city';
n{3,1}='sibiu';
n{3,2}='arad';
n{3,3}='oradea';
n{3,4}='fagaras';
n{3,5}='rimnicu vilcea';

'city';
n{4,1}='timisoara';
n{4,2}='arad';
n{4,3}='lugoj';

'city';
n{5,1}='oradea';
n{5,2}='zerind';
n{5,3}='sibiu';

'city';
n{6,1}='fagaras';
n{6,2}='sibiu';
n{6,3}='bucharest';

'city';
n{7,1}='rimnicu vilcea';
n{7,2}='sibiu';
n{7,3}='pitesti';
n{7,4}='craiova';

'city';
n{8,1}='lugoj';
n{8,2}='timisoara';
n{8,3}='mehadia';

'city';
n{9,1}='bucharest';
n{9,2}='fagaras';
n{9,3}='pitesti';
n{9,4}='giurgiu';
n{9,5}='urziceni';

'city';
n{10,1}='pitesti'
n{10,2}='bucharest'
n{10,3}='rimnicu vilcea'
n{10,4}='craiova'

'city'
n{11,1}='craiova';
n{11,2}='pitesti';
n{11,3}='rimnicu vilcea';

'city'
n{12,1}='mehadia';
n{12,2}='lugoj';
n{12,3}='dobreta';

'city'
n{13,1}='giurgiu';
n{13,2}='bucharest';

'city';
n{14,1}='urziceni';
n{14,2}='bucharest';
n{14,3}='hirsova';
n{14,4}='varsui';

'city';
n{15,1}='dobreta'
n{15,2}='mehadia'
n{15,3}='craiova'

'city';
n{16,1}='hirsova';
n{16,2}='urziceni';
n{16,3}='eforie';

'city';
n{17,1}='varsui';
n{17,2}='iasi';
n{17,3}='urziceni';

'city';
n{18,1}='eforie';
n{18,2}='hirsova';

'city';
n{19,1}='iasi';
n{19,2}='neamt';
n{19,3}='vaslui';

'city';
n{20,1}='neamt';
n{20,2}='iasi';

city=n{1,1};
for i=1:20
    for j=1:5
   if strcmp(n{i,j},goal)
       list{i,j}=[goal ' *GOAL*'];
       break;

   else

       list{i,j}=n{i,j};
   end
   end
end
    list{i,j}=n{i,j}

but it doesnt show me previous cities, i want it show me all ways from Arad to Buhcarest, like:
arad-->sibiu-->fagaras-->bucharest
arad-->timisoara-->lugoj-->mehadia-->dobreta-->craiova-->rimnicu vilcea-->sibiu-->fagaras-->bucharest
i dont want the shortest way, i want all ways fromm Arad to Bucharest

A: There are some great network analysis methods that can be used for this sort of thing:
You can achieve this by constructing an adjacency matrix of the network and taking powers of the matrix to find 1 hop, 2 hop, 3 hop journeys etc...
Approximating the matrix exponential will give you the total number of trips from any city on your map to any other city.


text:
Q: What is the purpose for multiple comma-separated expressions in a WHILE condition? I stumbled over the following JavaScript:
Code:
var x="", i=0;
while (i<4, i<7, i<5, i<6)
{
  x=x + "The number is " + i + "<br>";
  i++;
}
document.write(x);

I never know that it is possible to use multiple comma-separated expression in one WHILE statement.
Result:
The number is 0
The number is 1
The number is 2
The number is 3
The number is 4
The number is 5

What is the reason for this and what is the behavior (only the last expression is evaluated for the while-exit)?
Is the behavior standardize in all Javascript/C/Java languages?

A: Only the last result is kept in result of the comma operator, so
while (i<4, i<7, i<5, i<6)

is really equivalent to
while (i<6)

That's the reason why you don't see this more often : it's useless if your comparisons don't have side effects.

A: This is a special operator in JavaScript which is called comma operator;
so when JavaScript comes across this line
(i<4, i<7, i<5, i<6)

it will  evaluate one by one all the operands in the parenthesis and will return the evaluation of the last item i.e. i < 6
It is rarely used; One occasion that I remember to have used it was for indirect call to eval.
(0, eval)(src)

But again in you example the use of it is redundant.


text:
Q: Suppose $n>m$, $A$ is a $m\times n $ matrix with $\operatorname{rank} A =m$, $B$ is a $n\times (n-m)$ matrix, $\operatorname{rank} B= n-m$. Suppose $n>m$, $A$ is a $m\times n $ matrix with $\operatorname{rank} A =m$, $B$ is a $n\times (n-m)$ matrix, $\operatorname{rank} B= n-m$. And we already have $AB=0$. $\alpha$ is a vector satisfy $A\alpha=0$. Prove there exists a vector $\gamma$ such that $\alpha=B\gamma$.
I tried to write $A$ in terms of column vectors.
$$A=\{A_1,A_2,\cdots,A_n\}$$
then $B$ is kind of combination of solutions to $AX=0$.
Now what we want to prove is write a solution in terms of other solution's combination.  Don't know how to continue from this...

A: Hint:
You don't even need to consider elements: $AB=0$ means $\;\operatorname{Im}B\subset \ker A$.
Now the rank-nullity theorem asserts that
$$\dim \ker A= n -\operatorname{rank}A=n-m$$
Can you conclude?


text:
Q: How can I convert a JPEG image to a RAW image with a Linux command? I have a series of JPEG images taken with Canon Powershot to JPEG. How can I convert/transform them to RAW images?
Not with a graphical tool, but from the command line!
NB : Using raw images to stack them in Siril astrophoto application (https://siril.org/fr/)

A: Original RAW images cannot be restored.
Selecting JPEG instead of RAW saves space by sacrificing quality.
This operation is irreversible and lossy.
Simply speaking this means you can't go back.
Sadly you may only select RAW format instead of JPEG next time before you shot.
Note: You could technically find a way to turn the current jpg image into RAW format, but it will not be the same RAW image you might have if you shot and saved directly in RAW format.

Searching in the Canon support you may read

the camera can capture images in JPEG and RAW format.

JPEG
Images  Processed in the camera for optimal image quality and compressed to reduce file size. However, the compression process is irreversible, and images cannot be restored to their original, unprocessed state. Image processing may also cause some loss of image quality.

RAW
"Raw" (unprocessed) data, recorded with essentially no loss of image quality from the camera's image processing. The data cannot be used in this state for viewing on a computer or printing. You must first process images on the camera or use the software (Digital Photo Professional) to convert images to JPEG or TIFF files. Images can be adjusted with minimal loss of image quality.

A: "Raw" is not a well defined format. Examining
Wikipedia Raw image format,
I counted 43 raw formats, each depending on the camera model.
One of the best image packages around is
ImageMagick,
available as a package on Linux or as a download,
which supports a few RAW formats.
Use its commands of magick or convert.
However, the quality of the result would be very poor.
JPEG is processed image data while RAW is not.
Typically, RAW-files have 12-14-bit per pixel which means up to 16384 values.
JPEG can have only 256 luminance values per RGB channel.
This means that JPEG contains much less data than a corresponding RAW-file.
So there is no good way to convert a JPEG to RAW.

A: You can not do that.
You have to save as raw from the camera.
Once it is in JPEG format it would be like removing the cream from your coffee to try to make it a raw file.

A: As others pointed out, there's no way to get the usual RAW format benefits when converting from JPG.
However, with Canon Powershot it's possible to use a custom firmware from  CHDK project that makes it possible to take RAW images. Of course this won't help with existing images.

A: Difficulties and opportunity of trying to convert JPEG into RAW format.
It is not always possible to convert a JPEG file to the original RAW file.
Note: I speak about original or specific RAW format because it is not a standard: RAW formats are service formats, different one from another, used by the manufacturer to quickly save the contents of the CCD into the buffer and in case on the storage device.
Limits. You might be able to turn it into a valid RAW format, but that doesn't mean the individual values stored in the new RAW file are the same as you might have if you saved the shot directly in RAW format.
Opportunity. It is not said that even if you can convert a JPEG image to RAW format and start from it for processing, the final result will be better than if you start directly from the JPEG you already have. In fact you will apply a filter (algorithm) that transforms one format into another and that can introduce further alterations.
Difficulties. Nonetheless, once you know the specific RAW format you may find a way to formally convert the image into your RAW format. This will involve not trivial programming efforts, starting from the modeling of the inverse transformation and ending into coding in the preferred language the algorithm.
Existing Programs. The convert program from the Imagemagick package under Linux (or other OSes) cannot convert any formats directly into the Canon RAW format, it is only capable to read (R) them... So it can do the opposite of what the OP is searching for: to convert RAW to whatever.
convert -list format | grep Canon
      CR2  DNG       r--   Canon Digital Camera Raw Image Format
      CRW  DNG       r--   Canon Digital Camera Raw Image Format

But Imagemagick is even a scripting/programming language. Once that you have access to the single pixel values you may save them as you want... programming it. But you need to know the specifications of the desired format.
Moreover, since it is an open source program, you can see in the code the routines used to convert from RAW into whatever and see if you are able to invert them.
On the irreversibility of RAW to JPEG conversion.
This happens for many reasons. Among them:

*

*Some formats are lossy, JPEG is usually one of them. You save space at the cost of artifacts and a general modification of the original values for individual pixels.

*In the classic JPEG format there are only 8 bits for color (it means 256 shades). In a CCD sensor usually the couters are of 12 or 14 bits (that means 4096 and 16384 shades).
If you think of your image as a histogram, you are going to average in a single bin (column) of the JPEG image, the values that are contained in 16 and 64 bins in the 12 and 14 bits counters respectively. How can you restore individual bin values from the average?

*Even if your JPEG is in the recent 12-14-16 bit format (JPEG_XT), you are not aware of the algorithm used for this transformation inside the camera.
(In simple terms, the sensor can have a non-linear efficiency curve. The manufacturer can take this into account by transforming the number from RAW format to a linear shade level in the JPEG, TIFF, ..., format.)

*The geometry of the CCD is different from the geometry of an image.
Roughly speaking, in the images we have a pixel with 3 or 4 values relative to the exact same geometric square. All squares are adjacent.
In the CCD instead we have geometrically separated sensors sensitive to different wavelengths, again speaking roughly for the R, G, B values. These sensors may or may not have the same surface, and certainly have a different efficiency which, among other things, changes according to the number of counts per second.
How these RGB sensor sequences are aligned and spaced from each other depends on the design of the CCD. You can see some examples of Color filter array on internet.

Image from Wikipedia

Image from Ephotozine
How the values of the counts of the red sensors translate, for example, into an image value of a pixel R, depends on their geometric position and on the algorithm chosen which may or may not also take into account the values of nearby sensors, either of those sensitive to the same as to other wavelengths.
All of these things are hardly reversible.


text:
Q: How to select 6 top records of each individual records at the database when selecting from all rows Assume that i have the following table
CREATE TABLE #tblUsersPokemons (
    RecordId int NOT NULL,
    PokemonId int NOT NULL,
    PokemonExp int NOT NULL,
    PokemonLevel int NOT NULL,
    UserId int NOT NULL
)

Now the below query works awesome as expected
select
  SUM(cast(PokemonExp as bigint)) as TotalExp,
  MAX(PokemonLevel) as MaxPokeLevel,
  Count(PokemonId) as TotalPoke,
  UserId
from #tblUsersPokemons
group by UserId

Here example result of such query
ToplamExp   MaxPokeLevel    TotalPoke   UserId
----------- --------------- ----------- --------
29372294    101             4           1
1134696     98              1           2
1400        98              1           101
24534365    98              4           102
1400        98              1           1102
1400        98              1           1103
1400        98              1           2102
1400        98              1           2103
789220      98              7           2105
1468        98              1           3104

Now here my question comes
I want to limit counted PokemonIds. What i mean is i want to select maximum 6 of each same PokemonId records. And from these records top 6 ordered desc by PokemonExp should be counted in.
For example a user has the below records

From this table the query should take record id : 1,2,3,4,5,6,9 and not take 7,8 since top 6 records for PokemonId 1 taken

A: If I understand correctly, you want the aggregations on the top 6 rows for each user.  You can do this easily using row_number():
select SUM(cast(PokemonExp as bigint)) as ToplamExp,
       MAX(PokemonLevel) as MaxPokeLevel,
       Count(PokemonId) as TotalPoke,UserId
from (select p.*,
             row_number() over (partition by userid order by pokemanexp desc) as seqnum
      from tblUsersPokemons p
     ) p
where seqnum <= 6
group by UserId;

EDIT:
I think you want to include PokemonId in the partition by clause:
select SUM(cast(PokemonExp as bigint)) as ToplamExp,
       MAX(PokemonLevel) as MaxPokeLevel,
       Count(PokemonId) as TotalPoke,UserId
from (select p.*,
             row_number() over (partition by userid, PokemonId
                                order by pokemanexp desc) as seqnum
      from tblUsersPokemons p
     ) p
where seqnum <= 6
group by UserId;


text:
Q: Build Qt 5.0 with mingw Ther's some way to build Qt 5.0 with mingw64 or Visual Studio 2012, or have I wait the next release?
I've tried the instruction to build qt 5.0 with mingw64 in the following link: http://qt-project.org/wiki/MinGW-64-bit but seems I non way for me...
Does someone compiled Qt 5.0 with mingw64 (or Visual C++ 2012)?

A: check these prebuilt binaries for Qt for 4.8.4, 5.0.0, 5.0.1, 32 and 64 bit, compiled with mingw-w64 (gcc 4.7.x I guess)
http://sourceforge.net/projects/mingwbuilds/files/external-binary-packages/Qt-Builds/


text:
Q: memory leak issues using schematron 5.* libraries I have a memory leak problem while using schematron libraries.  here is the method
public int validateSchematron(File schemaFile1, File inputFile1, StringBuilder serviceReturnStatus) {

    File schemaFile = schemaFile1;
    File inputFile = inputFile1;

    try {

        IReadableResource schFile = new FileSystemResource(schemaFile);
        ISchematronResource aResSCH = new SchematronResourceSCH(schFile);

        if (!aResSCH.isValidSchematron ()) {
            serviceReturnStatus.append("\nInvalid Schematron file:" + schemaFile.getName());
            return STEP_STATUS_FAILRE_INT;
        }

        int count = 0;
        Source xmlFile = new StreamSource(inputFile);
        SchematronOutputType schematronOutputType = aResSCH.applySchematronValidationToSVRL (xmlFile);
        List<Object> failedAsserts = schematronOutputType.getActivePatternAndFiredRuleAndFailedAssert();
        if(failedAsserts != null) {
            for (Object object : failedAsserts) {
                if (object instanceof FailedAssert) {
                    if (!(count > 0)) {
                        serviceReturnStatus.append("\n\nSchematron (" + schemaFile.getName() + ") validation errors encountered:");
                    }
                    final FailedAssert failedAssert = (FailedAssert) object;
                    if ((failedAssert.getFlag().equalsIgnoreCase("warning"))) {
                        if (treatWarningAsError)
                            validationFailure = true;
                        serviceReturnStatus.append("\n" + failedAssert.getFlag().toUpperCase() + " : ");
                        serviceReturnStatus.append(failedAssert.getText());
                        serviceReturnStatus.append("\n\t" + "Location : " + failedAssert.getLocation());
                    }
                    if ((failedAssert.getFlag().equalsIgnoreCase("error"))) {
                        validationFailure = true;
                        serviceReturnStatus.append("\n" + failedAssert.getFlag().toUpperCase() + " : ");
                        serviceReturnStatus.append(failedAssert.getText());
                        serviceReturnStatus.append("\n\t" + "Location : " + failedAssert.getLocation());
                    }
                    if ((failedAssert.getFlag().equalsIgnoreCase("fatal"))) {
                        validationFailure = true;
                        serviceReturnStatus.append("\n" + failedAssert.getFlag().toUpperCase() + " : ");
                        serviceReturnStatus.append(failedAssert.getText());
                        serviceReturnStatus.append("\n\t" + "Location : " + failedAssert.getLocation());
                    }
                    count++;
                }
            }
        }
                }
    catch(IllegalArgumentException ia) {
        serviceReturnStatus.append("\n\nInvalid or malformed input file.\nPlease retry or correct the input file.\n\n" + ia.getLocalizedMessage());
        validationFailure = true;
    }
    catch(Exception e){
        serviceReturnStatus.append("\n\n" + e.getLocalizedMessage());
        validationFailure = true;
        return STEP_STATUS_FAILRE_INT;
    }

    return STEP_STATUS_SUCCESS_INT;
}

The problem appears to be when the schematron file is validated DOM objects are created that persist after the method returns.  Any ideas or suggestions on why that would be?


text:
Q: Microsoft SQL 2005: I just created a trigger but it won't show me the code under "Database triggers"? Once you create a trigger with the create trigger code, how do you get it to show up in the "Database Triggers" folder?  I refresh and nothing shows.  I know it's there because I can see two database counts when I update the table.

A: You will be able to find the trigger undeer the table structure itself.
Expand the table, you will see something like Columns, Keys, Constraints, Triggers, Indexes, Statistics. It will be under the Triggers section.


text:
Q: Prove that level set is measurable It's probably straightforward to most of you, but I was trying to solve the following exercise during self study on "measure integral and probability".
Prove that if f is a Lebesgue measurable function, then the level set $\{x:f(x)=a\}$ is measurable for every $a\in\mathbb{R}$.
Using Cantor intersection theorem (I think...), we can rewrite
$$\{x:f(x)=a\} \equiv \bigcap_n \{x:a-\frac{1}{n}\leq f(x)\leq a+\frac{1}{n}\}$$
Since f is measurable any set on the R.H.S is measurable, and so is the intersection.
Is that correct, are there any parts that need more justifications ?

A: Let $\phi_n$ be a continuous function such that $\phi_n(a) = 1$ and $\phi_n(y) = 0$ if $|y-a| \ge 2^{-n}$. Now $\phi_n(f(x))$ will be meausurable and therefore also $\psi(x)=\lim_{n\to\infty}\phi_n(f(x))$. Now we have that $\psi(x)=1$ on the level set and zero otherwise that is it's the characteristic function for the level set. As it's a measurable characteristic function then the set itself is measurable.


text:
Q: CSS how to make special div shape Any idea how to make the div shape like this ?

A: Just create a rectangle and skew the Y axis using the CSS3 transform property.
In this case, transform: skewY(-20deg) will work.

.shape {
    border: 2px solid;
    height: 200px;
    width: 100px;
    transform: skewY(-20deg);
    margin: 2em 0;
}

A: This will work in all modern browsers and will fall back to a rectangle in older browsers.

.skewed {
  border: solid 5px black;
  height: 200px;
  margin-top: 50px;
  width: 100px;
  transform: skewY(-30deg);
}


text:
Q: Optimal MySQL index for search query within date ranges I have a MySQL table of the form
CREATE TABLE `myTable` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `timestamp` datetime NOT NULL,
  `fieldA` int(11) NOT NULL,
  `fieldB` int(11) NOT NULL,
....
)

The table will have around 500,000,000 rows, with the remaining fields being floats.
The queries I will be using will be of the form:
SELECT * FROM myTable
WHERE fieldA= AND fieldB= AND timestamp>'' and timestamp<=''
ORDER BY timestamp;

At the moment I have two indices: a primary key on id, and a unique key on timestamp,fieldA,fieldB (hashed). At the moment, a select query like the above takes around 6 minutes on a reasonably powerful desktop PC.
What would the optimal index to apply? Does the ordering of the 3 fields in the key matter, and should I be using a binary tree instead of hashed? Is there a conflict between my primary key and the second index? Or do I have the best performance I can expect for such a large db without more serious hardware?
Thanks!

A: For that particular query adding an index to fieldA and fieldB probably would be optimal. Order of the columns in the index do matter.
Index Order
In order for Mysql to even consider using a particular index on the query the first column must be in the query, so for example:
alter table mytable add index a_b_index(a, b);

select * from mytable where a = 1 and b = 2;

The above query should use the index a_b_index. Now take this next example:
alter table mytable add index a_b_index(a, b);

select * from mytable where b = 2;

This will not use the index because the index starts with a, but a is never used in the query so mysql will not use it.
Comparison
Mysql will only use an index if you use equality comparison. So < and > won't use an index for that column, same with between
LIKE
Mysql does use indexes on the LIKE statement, but only when the % is at the end of the statement like this:
select * from mytable where cola like 'hello%';

Whereas these will not use a index:
select * from mytable where cola like '%hello';
select * from mytable where cola like '%hello%';

A: Hashed indexes are not used for ranges. They are used for equality comparisons only. Therefore, a hashed index cannot be used for the range portion of your query.
Since you have a range in your query, you should use a standard b-tree index. Ensure that fielda and fieldb are the first columns in the index, then timestamp. MySQL cannot utilize the index for searches beyond the first range.
Consider a multi-column index on (fielda, fieldb, timestamp).
The index should also be able to satisfy the ORDER BY.
To improve the query further, select only those three columns or consider a larger "covering" index.


text:
Q: Foreach combine output - specific vectors I am just getting started with foreach & parallel and encountered some challenges with combining my outputs from each iteration.
Currently, in each iteration, I am outputting a set of variables that I would like to combine into a vector, so that I can obtain some summary stats for across all iterations.
An example:
foreach (s = 1:num) %dopar%{
var1 = ...
var2 = ...
var3 = ...}

Ultimately I'd like 3 vectors containing each iteration's produced output, so:
var1 = c(var1 from s=1, var1 from s=2, var1 from s=3, ...)
I looked into the .combine option and attempted to create a function that would append, but found no success.

A: The {} after foreach...%dopar% behaves like a function, that is, it will return a value whether you explicitly specify it or not. It is generally not specified but by specifying you can return whatever value you like
foreach(I=1:3) %dopar% { <complicated stuff>
                         return(1) }

# [[1]]
# [1] 1

# [[2]]
# [1] 1

# [[3]]
# [1] 1

In your case, you want to return 3 vectors, unfortunately this is not possible
library(foreach)
library(doParallel)
cl <- makeCluster(detectCores())
registerDoParallel(cl)

foreach(I=1:8) %dopar% { v1 <- "ant"
                 v2 <- "pant"
                 return(v1, v2) }

Which results in the following error
Error in { : task 1 failed - "multi-argument returns are not permitted"

But you can make a list of your vectors, and return the value
foreach(I=1:8, .combine=rbind) %dopar% {  v1 <- "ant"
                                          v2 <- "pant"
                                          return(list(v1, v2)) }

         # [,1]  [,2]
# result.1 "ant" "pant"
# result.2 "ant" "pant"
# result.3 "ant" "pant"
# result.4 "ant" "pant"
# result.5 "ant" "pant"
# result.6 "ant" "pant"
# result.7 "ant" "pant"
# result.8 "ant" "pant"

stopCluster(cl)

A: Solution using future:
doFuture is future's wrapper for foreach which I prefer instead of parallel.
Here we create data.frame res and you can access vector using res$vector1
library(doFuture)
registerDoFuture()
plan(multiprocess)

Nlength <- 1000
Nvector <- 3

res <- foreach(i = 1:Nvector, .combine = cbind) %dopar% {
    1:Nlength / pi * rnorm(1)
}
res <- data.frame(res)
colnames(res) <- paste0("vector", 1:Nvector)

dim(res)
[1] 1000    3


text:
Q: Virtual keyboard can't interact with webpage via control event I am using UWP JS to make a system application.
I have made one virtual keyboard, which works fine with the whole application.
I have also made one page that is used to open any website.
I can use my virtual keyboard with my application's textbox because I know the textbox's id.
However, I can't get the virtual keyboard to work with the website page because I don't know what the textbox id is.

A: You could use tag selector to get all input element in your html page via jQuery. And call your visual keyboard in the focus event handle method.
$(document).ready(function () {
     $("input").focus(function () {
         //Do some stuff
         $(this).addClass("bor");

     });
});


text:
Q: AppId or GUID of a Running Service My instructions are to
The default port used by a Performance Center host service is 8731.
To configure SSL on a host for port 8731, refer to the Microsoft Web Site: How To Configure a Port with an SSL Certificate, using the following URL: http://msdn.microsoft.com/en-us/library/ms733791.aspx.
I am at a step where i need to run

netsh http add sslcert ipport=0.0.0.0:8000
  certhash=0000000000003ed9cd0c315bbb6dc1c08da5e6
  appid={00112233-4455-6677-8899-AABBCCDDEEFF}

I was able to find everything except appid
if i just give any random value then i get error

"SSL Certificate add failed, Error: 1312 A specified logon session
  does not exist. It may already have been terminated."

This Link https://help.screenconnect.com/index.php?title=Installing_and_binding_an_SSL_certificate_on_Windows
says use empty GUID {00000000-0000-0000-0000-000000000000}
But that also fails for me

A: You may use any valid GUID. It is only used to identify the binding later.

A: The following method worked for me. It will generate a valid GUID & will get placed on {%NewGUID%}.
For /F %%a In ('Powershell -Command "$([guid]::NewGuid().ToString())"') DO (Set NewGUID=%%a)

Netsh.exe Http Add SSLCert IPPort="0.0.0.0:8731" Certhash="0000000000003ed9cd0c315bbb6dc1c08da5e6" CertStoreName="My" AppID="{%NewGUID%}"


text:
Q: VBA Move files via LAN network doesn't work Im struggling with moving files via Local Network using VB script.
The problem is that at my local directory it works, but when I try use it on another computer on LAN it doesn't. Using very simple code:
Set fso = CreateObject("Scripting.FileSystemObject")
folderPath = "C:\Test\test.txt"
outFilePath = "C:\Test2\test.txt"
fso.MoveFile folderPath, outFilePath

And on my local computer it works. Then changing paths for another computer in LAN connection:
Set fso = CreateObject("Scripting.FileSystemObject")
folderPath = "\\computerName\Test\test.txt"
outFilePath = "\\computerName\Test2\test.txt"
fso.MoveFile folderPath, outFilePath

And it doesn't. I've shared this folders on network, switched off Windows defender, tested lots of path combination(IP address instead of name, added C location before computer name and so on). LAN works. Destination computer has Windows Enterprise LTSC.


text:
Q: How to avoid sending null headers in gatling http request? I'm trying to setup a HTTP request using feeders in Gatling, but I'm struggling not to send headers if the value of a property is null.
For example, given I have the following CSV file where the second record for prop_2 is null:
prop_1,prop_2
val_1,val_1
val_2,
val_3,val_3

And the given Gatling test config (part of it at least):
val feeder = csv("values.csv").random

val req1 =
  feed(feeder)
  .exec(
    http("Request 1")
      .get("/endpoint")
      .headers(Map(
        "prop_1", "#{prop_1}",
        "prop_2", "#{prop_2}" // Header not to send when value is null
      ))
  )

When there are null values I don't want to send the headers with empty values as part of the request, because the Back-end only expects headers with values. For while I have to create two CSV files with different properties (not mixing records with null values) and two requests, this is cumbersome and complex do handle.
Is there a better way to handle this use case?

A: It's currently not possible to define a dynamic set of headers, only dynamic header values.
Please explain your actual use case. Why do you have optional headers?

because the Back-end only expects headers with values

Note: HTTP headers with an empty value (that's what you have, not a null value) are perfectly valid according to the HTTP spec. Your back-end not being able to handle them is a bug on its side.


text:
Q: Unable to compile a functor template I'm trying to define a function
template<typename Functor> static void start(DataSize size, ThreadNum threadNum, Functor f)
{
    ....

    std::for_each<int>(allocated, size, f);

    ....
}

allocated and size are just int.
The caller calls the function
start(image.width() * image.height(), _threads, RGBHistogramFun<T>(image, hist));

and
template<typename T> class RGBHistogramFun
{
    ...

    void operator()(std::size_t i)
    {
        ....
    }
}

I set T to int for the template. I'm trying to define std::for_each so that it calls RGBHistogramFun::operator(std::size_t i) for each integer from allocated to size. The operator() will use the index to manipulate its internal array data.
However, I'm getting compiler error something about xutility.

A: n3337 25.2.4
template<class InputIterator, class Function>
Function for_each(InputIterator first, InputIterator last, Function f);

Effects: Applies f to the result of dereferencing every iterator in the range [first,last), starting
 from first and proceeding to last - 1.
int cannot be dereferenced.


text:
Q: How to run C++ program in CodeBlocks i have 3 files.

*

*header(x.h)

*functions with file handling using OOP(y.cpp)

*main.cpp

In Fedora it ran perfectly with no warning or error
>>c++ x.h y.cpp main.cpp

or
>>g++ ++ x.h y.cpp main.cpp

>>./a.out*

I'm new to CodeBlocks, I installed codeblocks-13.12mingw-setup.exe
Opened three files, then Build and run (F9) it didn't run, but gave 12 error, related to:

undefined reference to 'pqr::abc' ...

please help
Is there any other alternative to easily run these type of cpp program in windows?

A: Create a project, go to Project->Add files... an add x.h, y.cpp and main.cpp (add at least the .cpp files).

undefined reference to 'pqr::abc' ...

is a linking error because Codeblocks can't guess that you want to link those files unless you add them into a project.


text:
Q: Cannot read property on of undefined. Electron BrowserWindow object I am trying to learn Electron, but am running into an issue with the Pluralsight tutorial I am using. I installed the 'electron-prebuilt' module. I get an error everytime I run "npm start". The window opens as expected, but the error message that pops up in a dialog box kind of ruins the whole thing. Here is the error:
Uncaught Exception:
TypeError: Cannot read property 'on' of undefined at Object.
There's more to the long error message but it won't let me copy and paste, and the rest of the error just refers to the location of the supposed problem on line 14 of my main.js code. Here is my main.js file:
const electron = require('electron')
const app = electron.app
const BrowserWindow = electron.BrowserWindow

let mainWindow

app.on('ready', _ => {
  mainWindow = new BrowserWindow({
      height: 400,
      width: 400
  })
})

mainWindow.on('closed', _ => {
    console.log('closed')
    mainWindow = null
})

It's indicating that the BrowserWindow object I created doesn't have an "on" method, but I know this to be false per the Electron documentation:
https://electronjs.org/docs/api/browser-window
So I'm thinking that the value of mainWindow just isn't being set. I could try instantiating mainWindow with a new BrowserWindow object at the time I declare it, but I get an error message if I try that indicating that I can only instantiate BrowserWindow objects in ready functions.

A: you have to understand how callbacks work in node.js, callbacks are executed asynchronously, before app.onready fires, mainWindow is still undefined hence the declaration of let mainWindow assigns undefined to mainWindow, take mainWindow.on("closed", ....) into the app.on("ready") event handler. Do this
const electron = require('electron')
const app = electron.app
const BrowserWindow = electron.BrowserWindow

let mainWindow

app.on('ready', _ => {
  mainWindow = new BrowserWindow({
      height: 400,
      width: 400
  })
  mainWindow.on('closed', _ => {
    console.log('closed')
    mainWindow = null
  })
})

A: This error also occurs if you are just calling node on your electron script instead of electron. Your npm start script should be calling npx electron . instead, so try running npx electron . or npx electron main.js first. See this relevant issue here:
https://github.com/electron/electron/issues/7475


text:
Q: Big O, Big Omega, Big Theta functions This is the question
I am taking a data structures class, i am kind of confused on how to go with this type of problem. Any leads will be helpful, thanks in advance.

A: Let me explain one of these and see if you can make an attempt at the rest.
f(n) is O( g(n) )   "function f of n" is ("big O") **Order** g(n)

if for some n (maybe not f(0) or f(1)  or... but eventually for some n)
and for some **constant** (1, 2, 50, 80 million, something)

f(n) <= c * g(n)

So if we say some function f is "O(log n)" than means that starting at
some  n  that we pass into f(), and some number  c   then

    f(n) <= c * log(n)

Lets take a really simple example:
function f ( n ) {

     answer = 0;
     for (i = 0; i < n; ++i) {        // loops n times
         answer += n+3;                // 2 ops: add, add
         answer /= (7*n);              // 2 ops: mult, div
         answer ^= 2;                  // 1 op:  xor
     }                                 // 2 + 2 + 1 = 5
     return answer;
}

So, we might say 'c' is 5, and g(n) is n (we clearly loop n times).
f (n)   <=   5 * g(n)
f (n)   <=   5 * n

f () is O(n)

basically what this is saying is the constant factors don't matter at all when n gets big enough. It makes almost no difference if f(n) is (5n) or (7n) or (27n) when we might compare it to other functions which could be (87log(n))   or (0.01n²).
     \ n   10     1000      100000
 f(n) \-----------------------------
    7n |   70     7000      700000       O(n) grows linearly with prob size
87logn | ~200     ~600       ~1000       O(log n) grows slowly [good!]
 .01n² |   10    10000   100000000       O(n²) grows fast [bad!]


text:
Q: If $f(x+1) = x^2 + 3x +5$, then find $f(x)$ A challenge problem from precalc class. I don't know what to do with the one from $f(x+1)$, it doesn't factor well, I could do completing the square but then how do I find $f(x)$? Just stuck on this.

A: Hint:
$$f(x+1)=x^2+3x+5=(x+1)^2+(x+1)+3$$

A: With the substitution $x = u - 1$ the given identity translates to:
$$f((u-1) + 1) = (u-1)^2 + 3 (u-1) + 5$$
$$f(u) = u^2 -2 u + 1 + 3 u - 3 + 5 = u^2 + u + 3$$
Since the name of the variable is inconsequential in the definition of a function, this is the same as:
$$f(x) = x^2 + x + 3$$

A: Just to be different.
$$f(x+1) = x^2 + 3x + 5$$
\begin{align}
   f(x) - f(x+1)
   &= f((x-1)+1) - f(x) \\
   &= (x-1)^2 + 3(x-1) + 5) - (x^2 + 3x + 5) \\
   &= ((x-1)^2 - x^2) + (3(x-1) - 3x) + (5-5) \\
   &= (x-1-x)(x-1+x) - 3\\
   &= (-1)(2x-1) - 3 \\
   &= -2x - 2
\end{align}
So $f(x) = f(x+1) - 2x - 2 = x^2 + x + 3$
proof by induction
It is not unreasonable to suppose that $f(x) = x^2 + ax + b$ for some real numbers $a$ and $b$. We can use inductive reasoning to prove that this is the case and to find the values of $a$ and $b$ at the same time.
Our hypothesis will be $f(x) = x^2 + ax + b$ for some real numbers $a$ and $b$.
$f(0) = f(-1+1) = (-1)^2 + 3(-1) + 5 = 3$
By our hypothesis, $f(0) = b$. Hence $b = 3$
So our hypothesis is now $f(x) = x^2 + ax + 3$
Again, by our hypothesis, $f(x+1) = (x+1)^2 + a(x+1) + 3$
Hence
\begin{align}
   x^2 + 3x + 5 &= (x+1)^2 + a(x+1) + 3 \\
   x^2 + 3x + 5 &= (x^2+2x+1) + (ax + a) + 3 \\
   x^2 + 3x + 5 &= x^2 + (2 + a)x + (a + 4) \\
\end{align}
And we see that this is true when $a = 1$.
Hence, by mathematical induction,  $f(x) = x^2 + x + 3$.
Now that I look at this, I realize that I have only shown that $f(n) = n^2 + n + 3$ for $n = 0, 1, 2, \dots$. It is true however that three points uniquely determine a parabola. And we have agreement at an infinite number of points. So this is still a proof.

A: $x^2+3x+5=x^2+2x+1+x+4=(x+1)^2+x+4=(x+1)^2+(x+1)+3$
So $f(x)=x^2+x+3$

A: Just ask yourself "What are the operations that I need to perform on $x+1$ to get $x^2+3x+5$?".
$$\begin{align}
f(x+1) &= x^2 + 3x +5\\
&= ((x+1) - 1)^2 + 3((x+1)-1) +5\\
\end{align}$$
Now, suppose that $u = x+1$, then
$$f(u) = (u-1)^2 +3(u-1)+5 = u^2+u+3$$
Evaluating $f$, instead, at $x$, we have
$$f(x) = x^2+x+3$$


text:
Q: Data returned from fetch request is not what is expected I am calling some data from my API to the front end.
The call from my front end looks something like:
if(sessionStorage.getItem('Mix') == null){
        const myApi = await fetch('thisSite.io/deetz', { credentials: 'same-origin' })
                .catch(err => console.log(err));
        const my = await myApi.json;
        console.log(myApi.json, 'kjasdlaj');
}

The response in the console is
function json() kjasdlaj
Although when I send a request on my browser to thisSite.io/deetz I get a JSON response giving me something like
0
  Name        Jake
  Occupation  Engineer
1
  Name        Mike
  Occupation  Kite Fyler

Can someone tell me what is going wrong. I have been using this format of fetch for my other code and that seems to work fine.
I can post a minimum reproducible sample also, but since it is a bit lengthy and I guess something is wrong in my code here because it my fetching works correctly elsewhere I am just posting the code I feel there is an issue.
If someone still wants a minimum please tell me.

A: You need to execute json. So replace const my = await myApi.json with const my = await myApi.json().
Next you need to console.log my, not myApi.json. So do this:
const my = await myApi.json();
console.log(my, 'kjasdlaj');

A: A fetch response's .json property is an asyncronous function which returns the response's body as a JavaScript object, assuming the response was a JSON string. It is not an object or property to be accessed.
Instead, you probably want this:
if (sessionStorage.getItem('Mix') == null) {
  const responseObject =
    await fetch('thisSite.io/deetz', { credentials: 'same-origin' })
      .then(res => res.json());
      .catch(err => console.log(err));

  console.log(responseObject, 'kjasdlaj');
}

This will log the response as an object, allowing you to access properties.

A: You aren't executing the function.  You're passing it the reference to the function itself.  You need to call await myApi.json(), not await myApi.json.  You should also log the variable my, and not myApi.json.


text:
Q: Python run script on copy to cliboard How can I make Python run a script upon the user copying something to the clipboard and then store what they copied in a variable? Should this be in some sort of a loop?
I used pyperclip for the storage of what is copied:
import pyperclip
s = pyperclip.paste()
pyperclip.copy(s)
print(s)


text:
Q: How To Make Search Box Close If User Clicks Somewhere? My search box closes on clicking the font awesome "fa-times" icon. But I want the search box close when the user clicks anywhere on the site.
Any help appreciated :)Any help appreciated :)Any help appreciated :)

button.search-open {
    position: absolute;
    z-index: 999;
    background-color: transparent;
    border: none;
    padding: 8px 20px;
    font-size: 20px;
    color: #fff;
    top: 10px;
    margin-left: 1225px;
    border-radius: 4px;
    cursor: pointer;
}
     <button class="search-open">

     </button>

       <form action="<?php echo home_url( '/' ); ?>">

Type Here To Search

            <input type="text" name="s" placeholder="Search...">
            <button type="submit" class="submit-btn"></button>

          </form>


text: Q: Get different result when using R CMD check with Valgrind I did a package which has a Rcpp function computing the intersection of two 3d meshes, and there is an example included in the package. This function firstly checks whether the input meshes self-intersect, and throws an error if one of them does. The example runs without issue. But when I check the package using R CMD check with Valgrind, this example throws the error: the code detects that the first mesh self-intersects (it doesn't). Why is there a different behavior using Valgrind? As far as I understand, this point has nothing to do with Valgrind; if the two R versions are the same then one should get the same behavior, no?


text:
Q: Compilation Error OmniThreadLibrary-3.03b in Delphi 2009 I got errors while compiling OmniThreadLibrary-3.03b in Delphi 2009 ...
Errors are:
[DCC Error] GpStuff.pas(332): E2003 Undeclared identifier: 'GetAsAnsiString'
[DCC Error] GpStuff.pas(332): E2003 Undeclared identifier: 'GetSize'
[DCC Error] GpStuff.pas(332): E2003 Undeclared identifier: 'SetAsAnsiString'
[DCC Error] GpStuff.pas(332): E2003 Undeclared identifier: 'GetValue'
[DCC Fatal Error] OmniThreadLibraryRuntime2009.dpk(54): F2063 Could not compile used unit '..\src\GpStuff.pas'
Anyone know why its prompting all above errors in Delphi 2009???

A: It looks to me like a compiler bug in Delphi 2009. The undeclared identifiers in TGpBuffer that trigger the compiler warnings have strict protected visibility. The code looks like this:
type
  TGpBuffer = class(TInterfacedObject, IGpBuffer)
  strict private
    FData: TMemoryStream;
  strict protected
    function  GetAsAnsiString: AnsiString; inline;
    function  GetSize: integer; inline;
    function  GetValue: pointer; inline;
    procedure SetAsAnsiString(const value: AnsiString);
  public
    constructor Create; overload;
    constructor Create(data: pointer; size: integer); overload;
    destructor  Destroy; override;
    procedure Add(b: byte); overload; inline;
    procedure Add(ch: AnsiChar); overload; inline;
    procedure Allocate(size: integer); inline;
    procedure Assign(data: pointer; size: integer); inline;
    procedure Clear; inline;
    function  IsEmpty: boolean; inline;
    property AsAnsiString: AnsiString read GetAsAnsiString write SetAsAnsiString;
    property Size: integer read GetSize;
    property Value: pointer read GetValue;
  end; { TGpBuffer }

The errors occur on the property declarations, which all refer to strict protected getters and setters. This must be a compiler error. How can a class declare an identifier and not be able to see it? The code compiles in Delphi 2010 so I can only believe that this is a compiler bug in Delphi 2009, and possibly earlier (strict private and strict protected were added in Delphi 2005).
I suggest that you change strict protected to protected and see if the code compiles. You'll have the same problem with the GpLists unit. If that is indeed the problem then please do submit a bug report at the OTL Google Code site.
Finally, I recommend that you take the latest version from revision control rather than a canned ZIP file download.
Update: Primož has committed a change to the repo that works around the bug.


text:
Q: How can I make my Mac Mini 1,1 display 1080p? I have an early intel Mac Mini (1,1 Late 2006) that I'm resurrecting for the purposes of a media centre (intend to replace with a modern device when finances allow). This model is furnished with a DVI output, I'm going direct to VGA via DVI-VGA cable. It is giving me a headache because it will not connect at 1080p. Running 10.6.8, fully updated.
I'm getting a huge list of possible resolutions in Display Prefs, each with different freq's, here are the some:

*

*1280 x 1024 (displays correctly)

*1344 x 1008 (no display)

*1400 x 1050 (displays correctly)

*1600 x 1200 (displays correctly horizontally, must be scaling vertically)

*1920 x 1440 (no display)

*2048 x 1536 (no display)

I've tried using ScreenResX, but when I add a custom resolution of 1080p and restart, the custom resolution is not available "not activated - invalid?". According to tech specs the mini is capable of outputting to 1080p. How can I get this machine to output correctly?
I can successfully output to this LCD TV at 1080p (native res) from:

*

*Powermac G5 2GHz (directly via DVI->VGA cable)

*Macbook Pro (miniDisplayPort->DVI adaptor, DVI->VGA cable)

Many thanks for any suggestions!

A: As answered in the comment by bispymusic, this was resolved by using a DVI->HDMI adaptor or cable. The Mac mini was able to output a whole new set of resolutions, and jumped straight to 1080p as the most suitable. Thanks.


text:
Q: Javascript file stops rest of javascript from working Im new to Javascript and jquery and I almost have my problem solved.  I built an accordion menu that in some versions of IE is bad, I mean, Im sure its bad overall, but it stops all Javascript on the page from working if its called first. Im guessing its some syntax thing I dont know and therefore cant find.
// JavaScript Document

function initiateMenu() {
var pathname = window.location;
console.log( window.location.pathname );

$('.sub').hide();
$("#menu a[href='"+pathname+"']").next().show();
$("#menu a[href='"+pathname+"']").parents('.sub').show();
$("ul.sub").parent().prepend("");

$('#menu li span').click(
  function() {
    var checkElement = $(this).parent().find("ul.sub");

    if((checkElement.is('ul')) && (checkElement.is(':visible'))) {
      return false;
      }

    if((checkElement.is('ul')) && (!checkElement.is(':visible'))) {
      $('#menu ul:visible').slideUp('normal');
      checkElement.slideDown('normal');
      return false;
      }
    }
  );
}

$(document).ready(function() {initiateMenu();});

I cant see what is wrong with the script but its stopping all other Javascript from working.
If i call it after other scripts on the page the other scripts work.  Please help
If you need to look at the page its http://www.jardencustom.com/2012/
The home page has the accordion script moved below the other scripts, the rest do not.

A: get rid of this:
console.log( window.location.pathname );

IE doesn't support console and will break if you use it.
check out this SO question and answer:
What happened to console.log in IE8?


text:
Q: How to setup SpEL contextProvider for @Query How can I setup the context provider to make my SpEL extension available in a @Query("...")?
We use r2dbc with postgres.
From what I understand I would need to register my extension with a ReactiveExtensionAwareQueryMethodEvaluationContextProvider but I cannot find any documentation on how to do this. Is there a specific bean or @Configuration to use for it?
I found this unit test. It is monogo instead of r2dbc, but I think it's the same principle - however because it is a unit test it does not show how to setup the context in my normal code.
Trying to implement it like this does not provide the my() method in the SpEL
@Configuration
class MySpELExtensionConf {

  @Bean
  fun mySpELExtension() : ReactiveEvaluationContextExtension {
    return ReactiveSpelExtension()
  }

  class ReactiveSpelExtension : ReactiveEvaluationContextExtension {

    override fun getExtension(): Mono<out EvaluationContextExtension> {
      return Mono.just(SpelExtension.INSTANCE)
    }

    override fun getExtensionId(): String {
      ReactiveQueryMethodEvaluationContextProvider.DEFAULT
      return "mySpELExtension"
    }
  }

  enum class SpelExtension : EvaluationContextExtension {
    INSTANCE;

    override fun getRootObject(): Any? {
      return this
    }

    override fun getExtensionId(): String {
      return "mySpELExtension"
    }

    fun my(): String {
      return "x"
    }
  }
}

I now see the mySpELExtension in the application context, but using the my() method in a @Query is not possible:
interface MyRepository : ReactiveCrudRepository<MyEntity, Long> {
  @Query("""
    ...
    :#{my()}
    ...
  """)
  fun findByMyQuery() : Flux<MyEntity>
}

results in
EL1004E: Method call: Method my() cannot be found on type java.lang.Object[]

A: I figured out a solution using PostBeanProcessor.
@Configuration
class MySpELExtensionConf {

  companion object {
    // list of provided extensions
    val contextProviderWithExtensions =
      ReactiveExtensionAwareQueryMethodEvaluationContextProvider(listOf(ReactiveSpelExtension()))
  }

  /**
   * Registers the customizer to the context to make spring aware of the bean post processor.
   */
  @Bean
  fun spELContextInRepositoriesCustomizer(): AddExtensionsToRepositoryBeanPostProcessor {
    return AddExtensionsToRepositoryBeanPostProcessor()
  }

  /**
   * Sets the [contextProviderWithExtensions] for SpEL in the [R2dbcRepositoryFactoryBean]s which makes the extensions
   * usable in `@Query(...)` methods.
   */
  class AddExtensionsToRepositoryBeanPostProcessor : BeanPostProcessor {
    override fun postProcessBeforeInitialization(bean: Any, beanName: String): Any {
      if (bean is R2dbcRepositoryFactoryBean<*, *, *>) {
        bean.addRepositoryFactoryCustomizer { it.setEvaluationContextProvider(contextProviderWithExtensions) }
      }
      return bean
    }
  }

 // ... extension implementation as in question ...
}

Note that customizing R2dbcRepositoryFactoryBean works for CoroutineCrudRepository and you might need to customize a different factory bean depending on the repositories you use.


text:
Q: HDIO_GETGEO and HDIO_GET_IDENTITY in Linux using C++ Can anyone explain the core difference between HDIO_GETGEO and HDIO_GET_IDENTITY. From Linux documentation I know that the former is for getting device geometry and the latter for getting IDE identification info.
Which HDIO_ ioctl call should I use to get the no. of sectors and bytes per sector of my hard disk in Linux??


text:
Q: Sharp architecture, how and where do I implement queries? I need help with implementing validation logic for users. I need to check whether the password entered by the user matches the passwordhash inside a SQL Server user table.
The big question for me is, where do I implement this validation logic?
You can see my user implementation below:
public class User : BaseEntity
{
    public virtual string Username { get; set; }
    public virtual string Hash { get; set; }
    public virtual string Salt { get; set; }
}

public interface IUserTasks
{
    List<User> GetAll();
    User Get(int id);
    User CreateOrUpdate(User user);
    void Delete(int id);
    bool Validate(string username, string password);
}

public class UserTasks : IUserTasks
{
    private readonly IRepository<User> _userRepository;
    private readonly IValidateHashQuery _validateHashQuery;

    public UserTasks(IRepository<User> userRepository, IValidateHashQuery validateHashQuery)
    {
        _userRepository = userRepository;
        _validateHashQuery = validateHashQuery;
    }

    public List<User> GetAll()
    {
        return _userRepository.GetAll().ToList();
    }

    public User Get(int id)
    {
        return _userRepository.Get(id);
    }

    public User CreateOrUpdate(User user)
    {
        return _userRepository.SaveOrUpdate(user);
    }

    public void Delete(int id)
    {
        var entity = _userRepository.Get(id);

        if(entity != null)
        {
            _userRepository.Delete(entity);
        }
    }

    public bool Validate(string username, string password)
    {
        return _userRepository.PerformQuery(_validateHashQuery) != null ? true : false;
    }
}

Do need to implement the validation logic inside the Task implementation or do I need to create a new query object inside my domain and use it in my Task implementation?
I really need help with this, looking forward to your replies!
Rob

A: Its an age old argument and one I've fought with myself before.
Take Sharp arch's lead. They solve these problems with attributes check out their DomainSignatureAttrribute, for solving an object's persistence uniquness.
For me, this is domain logic. Tasks are for orchestrating one or more events in a request.
I'd inject a repository interface into your core object and do the checking there:
public User(IUserRepsoitory userRepository)
{
 this.userRepsoitory = userRepository;
}

public void IsValid()
{
 return userRepository.IsPsswordValid(this);
}

I dont see how this breaks any rules. This generally isnt recommended.

A: AFAIK the IRepository.PerformQuery(IQuery query) has been removed from latest build of SA, in favor of using Enhanced query object.
public class ValidateHashQuery : IValidateHashQuery
{
    public bool Validate(string  username, string password)
    {
        ISession nhSession = NHibernateSession.Current;
        // you now have your session and run your query however you like
    }
}

public class UserTasks : IUserTasks
{
    private readonly IRepository<User> _userRepository;
    private readonly IValidateHashQuery _validateHashQuery;

    public UserTasks(IRepository<User> userRepository, IValidateHashQuery         validateHashQuery)
    {
        _userRepository = userRepository;
        _validateHashQuery = validateHashQuery;
    }

    public List<User> GetAll()
    {
        return _userRepository.GetAll().ToList();
    }

    public User Get(int id)
    {
        return _userRepository.Get(id);
    }

    public User CreateOrUpdate(User user)
    {
        return _userRepository.SaveOrUpdate(user);
    }

    public void Delete(int id)
    {
        var entity = _userRepository.Get(id);

        if(entity != null)
        {
            _userRepository.Delete(entity);
        }
    }

    public bool Validate(string username, string password)
    {
        return _validateHashQuery.Validate(username, password);
    }
}

But looking at your user tasks, it doesn't seem to be doing anything other than calling the repository, not sure what value that brings why not just use the repository directly?
Same goes for the validate query, you could add that dependency to your controller and call the user validation query directly from there, and set cookie/session according to result.
Then before performing a task that requires a user to be logged in, you check for that cookie (Ideally some attribute on the action [Autherise]). Depending on your scenario you might want to have that authorisation in the task itself.


text:
Q: Why does systemd boot so much slower than upstart Recently upgraded from 14.04 to 15.04 and immediately noticed my boot times went from 10-20 seconds all the way up to 120 seconds.
Can confirm that systemd is at least part of the problem, because if I manually select to boot using upstart (from the GRUB menu), the machine boots in 10-20 seconds.
Here is my systemd-analyze blame output: http://pastebin.com/iE3nrwRS
Here is my systemd-analyze critical-chain output: http://snag.gy/dX9q3.jpg
I will be happy to provide more information as requested.
Edit 1
I know this doesn't answer the question, but I think I am just going to permanently move back to upstart (something that works): https://wiki.ubuntu.com/SystemdForUpstartUsers#Permanent_switch_back_to_upstart

A: Had the same problem. Boot time was approx. 100s. Also tried "systemd-analyze blame" and "systemd-analyze critical-chain", but that didn't really help. Switching to upstart dramatically decreased boot time.
Finally, I found out that the swap configured in /etc/fstab was invalid. The configured swap partition didn't exist any more. After I deleted the entry in /etc/fstab, the boot time with systemd went back to normal.
So, I recommend you to check all entries in /etc/fstab if they are valid.


text:
Q: How to install GDAL extension for GeoServer on Windows I am in search of guidance to set up the GDAL extension for GeoServer.
I used GeoServer 2.11.0 with the geoserver-2.11.0-gdal-plugin.zip files, folowing the guide from http://docs.geoserver.org/stable/en/user/data/raster/gdal.html but gets errors running it.
Welcome to GeoServer!

JAVA_HOME: C:\Program Files (x86)\Java\jre1.8.0_121

Please wait while loading GeoServer...

WARNING: Module not found [ssl]
2017-04-27 09:24:30.623:INFO::main: Logging initialized @565ms
2017-04-27 09:24:30.770:INFO:oejs.Server:main: jetty-9.2.13.v20150730
2017-04-27 09:24:30.793:INFO:oejdp.ScanningAppProvider:main: Deployment monitor [file:/C:/Data/geoserver-2.11.0/webapps/] at interval 1
2017-04-27 09:24:31.885:INFO:oejw.StandardDescriptorProcessor:main: NO JSP Support for /geoserver, did not find org.eclipse.jetty.jsp.JettyJspServlet
2017-04-27 09:24:32.755:WARN:oejuc.AbstractLifeCycle:main: FAILED o.e.j.w.WebAppContext@1be98f5{/geoserver,file:/C:/Data/geoserver-2.11.0/webapps/geoserver/,STARTING}{C:\Data\geoserver-2.11.0\webapps\geoserver}: java.util.ServiceConfigurationError: javax.imageio.spi.ImageReaderSpi: Provider it.geosolutions.imageio.plugins.arcbinarygrid.ArcBinaryGridImageReaderSpi could not be instantiated
java.util.ServiceConfigurationError: javax.imageio.spi.ImageReaderSpi: Provider it.geosolutions.imageio.plugins.arcbinarygrid.ArcBinaryGridImageReaderSpi could not be instantiated
        at java.util.ServiceLoader.fail(Unknown Source)
        at java.util.ServiceLoader.access$100(Unknown Source)
        at java.util.ServiceLoader$LazyIterator.nextService(Unknown Source)
        at java.util.ServiceLoader$LazyIterator.next(Unknown Source)
        at java.util.ServiceLoader$1.next(Unknown Source)
        at javax.imageio.spi.IIORegistry.registerApplicationClasspathSpis(Unknown Source)
        at javax.imageio.spi.IIORegistry.<init>(Unknown Source)
        at javax.imageio.spi.IIORegistry.getDefaultInstance(Unknown Source)
        at javax.imageio.ImageIO.<clinit>(Unknown Source)

The system is:
Win 7 64bit

MSVC 2005, 2008, 2010, 2012, 2013 2015 is installed in both 64 and 32 bit

Java(TM) SE Runtime Environment (build 1.8.0_121-b13)
Java HotSpot(TM) Client VM (build 25.121-b13, mixed mode)

I installed the 32bit dlls and ECW driver:
gdal-1.9.2-MSVC2010.zip
gdal-19-1600-ecw.msi
For full error log see https://pastebin.com/ret8qZhi

A: I could make GDAL-ImageI/O-Ext extension work in GeoServer 2.14.1 on Windows just in ONE way: using Apache Tomcat 8.5 and installing GeoServer as a WAR.
Using the Windows installer adds one more layer to the stack: the wrapper.
This has proved to be a source of further troubles that can mix with all other ones making the deployment very triky.
My recipe is the following:
Make sure you have MSVC 2010 64bit installed. Is a a requirement of the GDAL native libraries.
Install Tomcat 8.5 64bit ona a 64bit JDK (I tested with 1.8.202). DO NOT GO WITH A 32bit JDK/JRE!
Use "Configure Tomcat" link in Start Menu to increase assigned RAM to 2048Mb
Copy Geoserver 2.14.1 WAR in [TomcatInstallDir]\webapps : this will make Tomcat self-deploy (unpack) the WAR into a /geoserver sub-dir and serve it on URL http://localhost:8080/geoserver (..or whatever port you choose during installation)
Uzip gdal-data.zip in C:/gdal/gdal-data
Unzip native libs GDAL from gdal-1.9.2-MSVC2010-x64.zip in C:/gdal/
Unzip GDAL Extension plugin for your Geoserver version (mine was 2.14.1) from
http://geoserver.org/release/2.14.1/ into [TomcatInstallDir]\webapps\geoserver\WEB-INF\lib
Optional for JP2 / ECW support
Unzip "driver" native libs forer JP2/ECW from gdal-19-1600-x64-ecw.msi (ECW lib) in C:/gdal/
Add to PATH env var:
C:/gdal
Configure in Windows the following Environment variables:
GDAL_DRIVER_PATH = C:\gdal
GDAL_DATA = C:\gdal\gdal-data
GEOSERVER_DATA_DIR = [TomcatInstallDir]\webapps\geoserver\data
The latter \data dir can be moved from the default out-of-the box location to a more sensible one. The GEOSERVER_DATA_DIR will have to reflect thischange.
* * * NOTE: As of Feb 2019 I still do not know a way to use any other, more recent version of GDAL other than v. 1.9.2 in Geoserver on Windows * * *


text:
Q: Edit button does not have any functionality, no red circle with a minus appears on the left side of cells I have looked at another question that was asking the exact same question as mine, but the answer told them to call the setEditing function (which I tried, and say later in the question). But I don't see how you could call this function only when the edit button is clicked. I suppose I could create my own BarButtonItem and run this method when my bar button item is clicked, but I figured this would be far easier since I need the basic functionality of the edit button.
I have a UIViewController that has a table on it named peersTable. When I click the edit button it switches to done, but nothing happens on the table. I have also added my own UITableViewRowActions and when I swipe to the left on the cells, my custom actions do show up.
Here is some of my code:
class PeerViewController: UIViewController, UITableViewDelegate, UITableViewDataSource, ConnectionManagerDelegate {

@IBOutlet weak var peersTable: UITableView!
...

override func viewDidLoad() {
    ...
    peersTable.delegate = self
    peersTable.dataSource = self

    self.navigationItem.rightBarButtonItem = self.editButtonItem
    ...
}

I have also tried calling the peersTable.setEditing(true, animated: true) method myself, and in this case, the red minus does appear. I've never seen this issue before, so I don't understand why it's happening. Am I somehow setting the delegate wrong? Or possibly I'm doing something wrong since this is a regular View and not a TableView (even though I've done this before in a previous project).
Thanks in advance! If you need any more information let me know!

A: Since this is a not a TableViewController it won't automatically set your tableView to editing mode when you press the edit button.
You need to override setEditing method so you can set the tableView to editing mode.
Add this to your ViewController class:
override func setEditing(_ editing: Bool, animated: Bool) {
    super.setEditing(editing, animated: animated)
    peersTable.setEditing(editing, animated: animated)
}


text:
Q: Is there a function that will allow me to prepend a string to the beginning of a set of lines within a text file? I am trying to prepend the IP addresses (in screenshot below) to the beginning of every line for their relative results.
Text File showing current format of results
Current file format:
Host: 192.168.1.4 ()
21  open    tcp     ftp     vsftpd 2.3.4
23  open    tcp     telnet      Linux telnetd
25  open    tcp     smtp        Postfix smtpd
53  open    tcp     domain      ISC BIND 9.4.2
Host: 192.168.1.6 ()
21  open    tcp     ftp     Microsoft ftpd
25  open    tcp     smtp        Microsoft ESMTP 6.0.2600.2180
80  open    tcp     http        Microsoft IIS httpd 5.1
135 open    tcp     msrpc       Microsoft Windows RPC
139 open    tcp     netbios-ssn     Microsoft Windows netbios-ssn

I have managed to append the first IP address to the beginning of every line using the following:
awk 'NR==1{IP="IP" FS $2 FS}NR!=1{$0=IP $0;print}' IPadd.txt > new.txt

Is there any way to modify this function so that I can have the different IP's at the beginning of each line and generate a file like this:
I want the new text file to read:
192.168.1.4 21  open    tcp     ftp     vsftpd 2.3.4
192.168.1.4 23  open    tcp     telnet      Linux telnetd
192.168.1.4 25  open    tcp     smtp        Postfix smtpd
192.168.1.4 53  open    tcp     domain      ISC BIND 9.4.2
192.168.1.6 21  open    tcp     ftp     Microsoft ftpd
192.168.1.6 25  open    tcp     smtp        Microsoft ESMTP 6.0.2600.2180
192.168.1.6 80  open    tcp     http        Microsoft IIS httpd 5.1
192.168.1.6 135 open    tcp     msrpc       Microsoft Windows RPC
192.168.1.6 139 open    tcp     netbios-ssn     Microsoft Windows netbios-ssn

A: Could you please try following.
awk '/^Host:/{ip=$2;next} NF{print ip,$0}'  Input_file

Output will be as follows.
192.168.1.4 21  open    tcp     ftp     vsftpd 2.3.4
192.168.1.4 23  open    tcp     telnet      Linux telnetd
192.168.1.4 25  open    tcp     smtp        Postfix smtpd
192.168.1.4 53  open    tcp     domain      ISC BIND 9.4.2
192.168.1.6 21  open    tcp     ftp     Microsoft ftpd
192.168.1.6 25  open    tcp     smtp        Microsoft ESMTP 6.0.2600.2180
192.168.1.6 80  open    tcp     http        Microsoft IIS httpd 5.1
192.168.1.6 135 open    tcp     msrpc       Microsoft Windows RPC
192.168.1.6 139 open    tcp     netbios-ssn     Microsoft Windows netbios-ssn

A: This might work for you (GNU sed):
sed '/^Host/h;//d;G;s/\(.*\)\nHost: \(.*\) ()/\2 \1/' file

Make a copy of the current Host line and append it to non-host lines, manipulating the host line to just present the ip address.


text:
Q: HTTP Error 405 when uploading an image using uploadify I'm trying to create an uploading control in MVC3.
At first i've tried with javascript and HTML5 to create upload control, but that doesn't work with any of the IE versions. So,i've move to this flash version of uploadify.
I'm getting HTTP Error: 405 when uploading
Here is my code in javascript for uploadify
$(function () {
        $('#file_upload').uploadify({
            debug:true,
            'swf': '/Content/uploadify/uploadify.swf',
            'uploader': '/Content/uploadify/uploadify.php',
            'cancelImg': '/Images/uploadify-cancel.png',
            'script': '/Home/Uploadify',
            'folder': '/Content/uploads',
            auto: true

        });
    });

I've even tried with debug: true to see what was gone wrong, but i couldn't get what is wrong.
Here is my output with debug:
---SWFUpload Instance Info---
Version: 2.2.0 2009-03-25
Movie Name: SWFUpload_0
Settings:
    upload_url:               /Content/uploadify/uploadify.php
    flash_url:                /Content/uploadify/uploadify.swf?preventswfcaching=1355289873808
    use_query_string:         false
    requeue_on_error:         false
    http_success:
    assume_success_timeout:   30
    file_post_name:           Filedata
    post_params:              [object Object]
    file_types:               *.*
    file_types_description:   All Files
    file_size_limit:          0
    file_upload_limit:        0
    file_queue_limit:         999
    debug:                    true
    prevent_swf_caching:      true
    button_placeholder_id:    file_upload
    button_placeholder:       Not Set
    button_image_url:         /
    button_width:             120
    button_height:            30
    button_text:
    button_text_style:        color: #000000; font-size: 16pt;
    button_text_top_padding:  0
    button_text_left_padding: 0
    button_action:            -110
    button_disabled:          false
    custom_settings:          [object Object]
Event Handlers:
    swfupload_loaded_handler assigned:  false
    file_dialog_start_handler assigned: true
    file_queued_handler assigned:       true
    file_queue_error_handler assigned:  true
    upload_start_handler assigned:      true
    upload_progress_handler assigned:   true
    upload_error_handler assigned:      true
    upload_success_handler assigned:    true
    upload_complete_handler assigned:   true
    debug_handler assigned:             true

SWF DEBUG: SWFUpload Init Complete
SWF DEBUG:
SWF DEBUG: ----- SWF DEBUG OUTPUT ----
SWF DEBUG: Build Number:           SWFUPLOAD 2.2.0
SWF DEBUG: movieName:              SWFUpload_0
SWF DEBUG: Upload URL:             /Content/uploadify/uploadify.php
SWF DEBUG: File Types String:      *.*
SWF DEBUG: Parsed File Types:
SWF DEBUG: HTTP Success:           0
SWF DEBUG: File Types Description: All Files (*.*)
SWF DEBUG: File Size Limit:        0 bytes
SWF DEBUG: File Upload Limit:      0
SWF DEBUG: File Queue Limit:       999
SWF DEBUG: Post Params:
SWF DEBUG: ----- END SWF DEBUG OUTPUT ----
SWF DEBUG:
SWF DEBUG: Event: fileDialogStart : Browsing files. Multi Select. Allowed file types: *.*
SWF DEBUG: Select Handler: Received the files selected from the dialog. Processing the file list...
SWF DEBUG: Event: fileQueued : File ID: SWFUpload_0_0
SWF DEBUG: Event: fileDialogComplete : Finished processing selected files. Files selected: 1. Files Queued: 1
SWF DEBUG: StartUpload: First file in queue
SWF DEBUG: Event: uploadStart : File ID: SWFUpload_0_0
SWF DEBUG: ReturnUploadStart(): File accepted by startUpload event and readied for upload.  Starting upload to /Content/uploadify/uploadify.php for File ID: SWFUpload_0_0
SWF DEBUG: Event: uploadProgress (OPEN): File ID: SWFUpload_0_0
SWF DEBUG: Event: uploadProgress: File ID: SWFUpload_0_0. Bytes: 846359. Total: 846359
SWF DEBUG: Event: uploadError: HTTP ERROR : File ID: SWFUpload_0_0. HTTP Status: 405.
SWF DEBUG: Event: uploadComplete : Upload cycle complete.

Can anyone tell me, where am i wrong ?
EDIT:
This is the request responce tracked from Fiddler:
POST /Content/uploadify/uploadify.php HTTP/1.1
Host: localhost:6930
Connection: keep-alive
Content-Length: 561702
Origin: http://localhost:6930
User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.11 (KHTML, like Gecko) Chrome/23.0.1271.64 Safari/537.11
Content-Type: multipart/form-data; boundary=----------Ef1Ij5Ef1cH2GI3GI3ei4Ij5ae0gL6
Accept: */*
Referer: http://localhost:6930/
Accept-Encoding: gzip,deflate,sdch
Accept-Language: en-US,en;q=0.8
Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.3

HTTP/1.1 405 Method Not Allowed
Cache-Control: private
Allow: GET, HEAD, OPTIONS, TRACE
Content-Type: text/html; charset=utf-8
Server: Microsoft-IIS/8.0
X-SourceFiles: =?UTF-8?B?YzpcdXNlcnNcYWRtaW5pc3RyYXRvclxkb2N1bWVudHNcdmlzdWFsIHN0dWRpbyAyMDEyXFByb2plY3RzXERhdGVBbmRUaW1lQ29udHJvbFxEYXRlQW5kVGltZUNvbnRyb2xcQ29udGVudFx1cGxvYWRpZnlcdXBsb2FkaWZ5LnBocA==?=
X-Powered-By: ASP.NET
Date: Wed, 12 Dec 2012 10:03:44 GMT
Content-Length: 5506

A: I've solve my problem finally. Its the uploader that troubled me.
the uploader should be the action of the controller in mvc.
Here is the solution:
$(function () {
        $('#file_upload').uploadify({
            debug:true,
            'swf': '/Content/uploadify/uploadify.swf',
            'uploader': '/Home/Uploadify',
            auto: true

        });
    });


text:
Q: Generate list of mismatched data element Combinations between two sources We receive data on a weekly and monthly basis with information regarding customers. We also sometimes have the same information stored from another source. The two sources sometimes provide contradictory information regarding customers.
How would I write a query which tells me the mismatched CustomerId and corresponding Vehicle? For example, CustomerId 947623 is associated with Kia in the vendor extract [Table 1] whereas we have the same customer stored as related to Hyundai [Table 2].
Table 1: Data received from the vendor.

CustomerId
FirstName
LastName
Vehicle
MiscColumns

027548
Jane
Doe
Honda
MiscData

947623
John
Smith
Kia
MiscData

549816
Erin
Woods
Chevy
MiscData

739232
Henry
Jackson
Ford
MiscData

Table 2: Internal data records

CustomerId
FirstName
LastName
Vehicle
MiscColumns

027548
Jane
Doe
Honda
MiscData

947623
John
Smith
Hyundai
MiscData

549816
Erin
Woods
Chevy
MiscData

739232
Henry
Jackson
Ford
MiscData

A: Please try the following solution.
It will work starting from SQL Server 2016 onwards.
SQL
-- DDL and sample data population, start
DECLARE @TableA TABLE (CustomerId CHAR(6) PRIMARY KEY, FirstName VARCHAR(100), LastName VARCHAR(100), Vehicle VARCHAR(100));
DECLARE @TableB table (CustomerId CHAR(6) PRIMARY KEY, FirstName VARCHAR(100), LastName VARCHAR(100), Vehicle VARCHAR(100));

INSERT INTO @TableA (CustomerId, FirstName, LastName, Vehicle) VALUES
('027548', 'Jane', 'Doe', 'Honda'),
('947623', 'John', 'Smith', 'Kia'),
('549816', 'Erin', 'Woods', 'Chevy'),
('739232', 'Henry', 'Jackson', 'Ford');

INSERT INTO @TableB (CustomerId, FirstName, LastName, Vehicle) VALUES
('027548', 'Jane', 'Doe', 'Honda'),
('947623', 'John', 'Smith', 'Hyundai'),
('549816', 'Erin', 'Woods', 'Chevy'),
('739232', 'Henry', 'Jackson', 'Ford');
-- DDL and sample data population, end

SELECT CustomerId
      ,[key] AS [column]
      ,Org_Value = MAX( CASE WHEN Src=1 THEN Value END)
      ,New_Value = MAX( CASE WHEN Src=2 THEN Value END)
FROM (
        SELECT Src=1
              ,CustomerId
              ,B.*
         FROM @TableA A
         CROSS APPLY ( SELECT [Key]
                             ,COALESCE(Value, '') AS Value
                       FROM OpenJson( (SELECT A.* For JSON Path,Without_Array_Wrapper,INCLUDE_NULL_VALUES))
                     ) AS B
        UNION ALL
        SELECT Src=2
              ,CustomerId
              ,B.*
         FROM @TableB A
         CROSS APPLY ( SELECT [Key]
                             ,COALESCE(Value, '') AS Value
                       FROM OpenJson( (SELECT A.* For JSON Path,Without_Array_Wrapper,INCLUDE_NULL_VALUES))
                     ) AS B
      ) AS A
GROUP BY CustomerId,[key]
HAVING MAX(CASE WHEN Src=1 THEN Value END)
     <> MAX(CASE WHEN Src=2 THEN Value END)
ORDER BY CustomerId,[key];

Output

CustomerId
column
Org_Value
New_Value

947623
Vehicle
Kia
Hyundai