text:
Q: Java. Cannot open connection I'm using

oracle.ucp.jdbc.PoolDataSource

for getting connections. Each connection wrapped to custom class (historic solution). Generally connection is getting by entityManager. My system require hight performance processing. There is ThreadPool using for it. Thread pool can provide 15 threads at the same time, like connection pool.
Every thing works fine, but sometimes i get exception (in this moment were used only 4 connections):
2012-09-26 17:51:45.835 | ERROR | ThreadExecutor-7 | org.hibernate.ejb.AbstractEntityManagerImpl | Exception in thread "ThreadExecutor-7"
javax.persistence.PersistenceException: org.hibernate.exception.GenericJDBCException: Cannot open connection
    at org.hibernate.ejb.AbstractEntityManagerImpl.convert(AbstractEntityManagerImpl.java:1235)
    at org.hibernate.ejb.AbstractEntityManagerImpl.convert(AbstractEntityManagerImpl.java:1168)
    at org.hibernate.ejb.AbstractEntityManagerImpl.throwPersistenceException(AbstractEntityManagerImpl.java:1245)
    at org.hibernate.ejb.TransactionImpl.begin(TransactionImpl.java:63)
    ...
    at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:886)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:908)
    at java.lang.Thread.run(Thread.java:619)
Caused by: org.hibernate.exception.GenericJDBCException: Cannot open connection
    at org.hibernate.exception.SQLStateConverter.handledNonSpecificException(SQLStateConverter.java:140)
    at org.hibernate.exception.SQLStateConverter.convert(SQLStateConverter.java:128)
    at org.hibernate.exception.JDBCExceptionHelper.convert(JDBCExceptionHelper.java:66)
    at org.hibernate.exception.JDBCExceptionHelper.convert(JDBCExceptionHelper.java:52)
    at org.hibernate.jdbc.ConnectionManager.openConnection(ConnectionManager.java:449)
    at org.hibernate.jdbc.ConnectionManager.getConnection(ConnectionManager.java:167)
    at org.hibernate.jdbc.JDBCContext.connection(JDBCContext.java:142)
    at org.hibernate.transaction.JDBCTransaction.begin(JDBCTransaction.java:85)
    at org.hibernate.impl.SessionImpl.beginTransaction(SessionImpl.java:1463)
    at org.hibernate.ejb.TransactionImpl.begin(TransactionImpl.java:60)
    ...
    at org.hibernate.jdbc.ConnectionManager.openConnection(ConnectionManager.java:446)

If i synchronize specified getConnection performance of the system going down 8-12 times.
Is any ideas for fix?

A: Please check you are setting appropriate values for
 <property name="minPoolSize" value="5"/>
 <property name="maxPoolSize" value="100"/>//Change if you want
 <property name="initialPoolSize" value="5"/>
 <property name="validateConnectionOnBorrow" value="true"/>
 <property name="maxStatements" value="10"/>

You can check configuration here
You should change connection pooling in hibernate.
http://docs.jboss.org/hibernate/orm/3.3/reference/en/html/session-configuration.html

Hibernate's own connection pooling algorithm is, however, quite rudimentary. It is intended to help you get started and is not intended for use in a production system, or even for performance testing. You should use a third party pool for best performance and stability. Just replace the hibernate.connection.pool_size property with connection pool specific settings. This will turn off Hibernate's internal pool. For example, you might like to use c3p0.

hibernate.c3p0.min_size=5
hibernate.c3p0.max_size=20
hibernate.c3p0.timeout=1800
hibernate.c3p0.max_statements=50


text:
Q: F# FAKE will not execute powershell script file Update: The actual cause of the issue was the '\' being round the wrong way, should have been './GenerateNuspecFile.ps1' - weird thing with F# parsing.

I am unable to run a ps1 script file from F# FAKE.
Question here which works well for running a chocolatey cpack
#r "packages/FAKE.3.12.2/tools/FakeLib.dll"
#r "System.Management.Automation"
#r "System.Core.dll"

open Fake
open System.Management.Automation
...

Target "GenerateNuspecFile" <| fun _ ->
    PowerShell.Create()
        .AddScript("Invoke-Command -ScriptBlock { cd './chocolatey' | iex .\GenerateNuspecFile.ps1 }")
        .Invoke()
        |> Seq.iter (printfn "%O")
...

This is not actually running the script file that I am trying to run.
Set-ExecutionPolicy is "unrestricted"

A: Your powershell script has some issues, and would not work even if run from the command line.
In particular, cd .\somedir | iex .\SomeScript.ps1 is nonsensical - you are piping the result of a cd (which is $null, since cd doesn't return anything) to Invoke-Expression, which is basically saying "run this $null as a script.". Invoke-Command should not be needed at all.
If your goal is simply to run GenerateNuSpecFile.ps1, your script should just be:
.AddScript("cd '<somepath>'; .\GenerateNuspecFile.ps1")

Or
.AddScript("& '<somepath>\GenerateNuspecFile.ps1'")

redpajama_set_name: RedPajamaStackExchange


text:
Q: The 2-sphere and $\mathbb{CP}^1$ As is very well known, the algebraic variety $S^2$ is isomorphic to projective variety $\mathbb{CP}^1$ as a complex manifold. As is also well known, the coordinate ring of $S^2$ is given by $< x,y,z > / < x^2 + y^2 +z^2 - 1 >$ and the function field of $\mathbb{CP}^1$ is $\mathbb{C}(\mathbb{CP}^1)$ (its coordinate ring being $\mathbb{C}$). My question is how the coordinate ring of $S^2$ and the function field of $\mathbb{CP}^1$ are related? Presumably this relation is a special case of a general variety-complex manifold relationship.

A: Any projective variety is also a real affine variety, by using the real and imaginary parts of the coordinates $x_{jk} = z_j\overline{z_k}$.  You should first normalize the projective coordinates to have Hermitian-Euclidean length 1.  Ordinarily the projective coordinates are sections of a line bundle that is only defined up to a scalar.  But with the length normalization, the only ambiguity is the phase.  The phase cancels out in the definition of $x_{jk}$, so it is a well-defined function rather than just a section.
This realification of $\mathbb{CP}^n$ is a map to $(n+1) \times (n+1)$ Hermitian matrices.  It is important in quantum probability:  The image of the map is the set of pure states of a quantum system; its convex hull is the set of all states.  This convex region is the quantum analogue of the simplex of states (= measures = distributions) for classical probability on a finite set.  The matrices have unit trace, so the image lies in an $(n^2+2n)$-dimensional real subspace.  You can check that it is a sphere when $n=1$.
Another viewpoint that is important is that of toric varieties.  The phase part of the toric action on $\mathbb{CP}^1$ is rotation about the $z$ axis, and the moment map is the projection onto the $z$ coordinate.  This too generalizes to any projective toric variety.


text:
Q: Not getting desired result back from SQL I am trying to retrieve specific set of data from mysql database using slim framework. My sql query is not giving me exacting what i want. any help would be much appreciated!
Query :
    function getModules($matric)
  {
  $sql = "SELECT DISTINCT students.module1,time_tables.days, time_tables.time  FROM `students`,`time_tables`
   WHERE students.matricNos = '$matric' AND students.module1 = time_tables.module_tag

   UNION

   SELECT DISTINCT students.module2,time_tables.days, time_tables.time  FROM `students`,`time_tables`
   WHERE students.matricNos = '$matric' AND students.module2 = time_tables.module_tag

   UNION

   SELECT DISTINCT students.module3,time_tables.days, time_tables.time  FROM `students`,`time_tables`
   WHERE students.matricNos = '$matric' AND students.module3 = time_tables.module_tag";

  try
  {
        $db = getConnection();
        $stmt = $db-> query($sql);
        $result = $stmt-> fetchAll(PDO::FETCH_OBJ);
        $db=null;
        echo json_encode($result);
    }
    catch(PDOException $e) {
        echo '{"error":{"text":'. $e->getMessage() .'}}';
    }

}

what I am getting back from the query
[{"module1":"ACC07103","days":"Thursday","time":"09:00-10:00"},{"module1":"CLP07112","days":"Tuesday","time":"14:00-15:00"},{"module1":"BMS08100","days":"Thursday","time":"10:00-11:00"}]

whats happening here is its giving me the correct values but its giving me the same tags like module1 and when it shows another module it should be module2 but it shows module 1 as well and same for module 3
my desired result;
[{"module1":"ACC07103","days":"Thursday","time":"09:00-10:00"},{"module2":"CLP07112","days":"Tuesday","time":"14:00-15:00"},{"module3":"BMS08100","days":"Thursday","time":"10:00-11:00"}]

in my database the columns are labeled like module1, module2, module3 but i don't understand why it is giving me the correct values but same names for different columns..
Thanks..

A: I suspect this is to do with the UNION taking the column names from the first SELECT query.
Does this still happen if you change SELECT DISTINCT students.module1 to SELECT DISTINCT students.module1 as module?

A: try that:
 $sql = "SELECT students.module1,null as module2,null as module3, time_tables.days, time_tables.time  FROM `students`,`time_tables`
   WHERE students.matricNos = '$matric' AND students.module1 = time_tables.module_tag
   GROUP BY students.module1

   UNION

   SELECT null as module1,students.module2,null as module3, time_tables.days, time_tables.time  FROM `students`,`time_tables`
   WHERE students.matricNos = '$matric' AND students.module2 = time_tables.module_tag
   GROUP BY students.module2
   UNION

   SELECT null as module1, null as module2,students.module3,time_tables.days, time_tables.time  FROM `students`,`time_tables`
   WHERE students.matricNos = '$matric' AND students.module3 = time_tables.module_tag
   GROUP BY students.module3";

in this aproach , you will select module1 , module2, module3 with null value if it doesnt match.

A: Unless you want to run 3 queries, there is no way to do exactly what you want.
Your column name can't change mid-query.
You could run 3 queries rather than use UNION in the SQL.
Then join your results together, something like:
 $result1 = $stmt1-> fetchAll(PDO::FETCH_OBJ);
 $result2 = $stmt2-> fetchAll(PDO::FETCH_OBJ);
 $result3 = $stmt3-> fetchAll(PDO::FETCH_OBJ);

 $result = array_merge($result1,$result2,$result3);

Alternatively, you can add an extra column in your query to indicate the module:
$sql = "
 SELECT DISTINCT 'module1' as module, students.module1,time_tables.days, time_tables.time
   FROM `students`,`time_tables`
  WHERE students.matricNos = '$matric' AND students.module1 = time_tables.module_tag

UNION

  SELECT DISTINCT 'module2',students.module2,time_tables.days, time_tables.time
     FROM   `students`,`time_tables`
  WHERE students.matricNos = '$matric' AND students.module2 = time_tables.module_tag

UNION

  SELECT DISTINCT 'module3', students.module3,time_tables.days, time_tables.time
    FROM `students`,`time_tables`
  WHERE students.matricNos = '$matric' AND students.module3 = time_tables.module_tag";

Then you will have to construct your display or saving routine to pull the module name from a different column, rather than using the column name itself.


text:
Q: Android application I want to know basically the hint of the softkeybaord which is displayed while editing or typing something in textbox is actually where it is stored.I want to know the location and way to handle it through programming.

A: Usually the "hint" that is displayed in an EditText input area is from a
<string name="hint_string">Hint text</string>

entry in the values/strings.xmlresource.
Then to populate the "hint" in the EditText box you simply add this attribute to the layout .xml file:
<EditText>
    android:hint="@string/hint_string"
</EditText>

Further info found here.


text:
Q: PHP Read files inside of the server root In my current PHP script I am attempting to read files which are not inside of /var/www/html (which the script seems to be limited too) but files inside of /root/ or anywhere behind /var/www/html.
Just to explain why, I need to read critical data from files which I do not want downloadable or accessible under any circumstances (no matter how much verification).
I have messed around with getcwd() and chdir($_SERVER['DOCUMENT_ROOT']) but with no success.
My question: Is this even possible, and if so, how can I do this?
P.S. My method of reading is just standard fopen($filename, "rb") and fread;

A: It depends if php has the permissions to access the required files. You'll need to allow permissions for the user "www-data" (if you're using apache on linux) to be able to read the files.


text:
Q: Using Azure Service Bus in local I am working with Azure Service Bus Topics and Subscriptions. It's being used to send control messages across the application. The message listeners (subscribers) are running in a worker role and they are picking up the messages and processing the request. Each message in the bus can be picked up by only once, even if there are multiple listeners running simultaneously.
There is no issue in using the Service Bus; however we are facing some issues while debugging/testing the application in local. We have 2 service bus, one for the cloud and one for local debugging. Now if multiple people are debugging the application simultaneously, the message is being picked by only one of the system (at random). This is the intended behavior, but it's causing a nuisance while debugging.
Is there any way how I can use a local emulator for the Service Bus? I did some research but I couldn't find any reliable solution for this. Is there any way how we debug the application in isolation?

A: Azure Service Bus is a broker with competing consumers. Having multiple developers debugging using the same namespace will be be tough (message lock duration expired and another developer that happened to be debugging got that message).
I would suggest to look into a namespace per developer. With MSDN license you're given enough Azure credit to have each developer work in a "sandboxed" namespace. As to how to get it working, you can read from a configuration file, environment variable, etc.
On the ASB for Windows Server - currently it's on version 1.1 where Azure SB is on 3+. Hosted version will be always ahead of the on-premises. Something to consider.

A: The problem should probably be solved by abstracting the service bus implementation so that it can be swapped for something that you actually can run locally (or in memory). I would suggest not to re-invent that wheel though and choose a library like Masstransit https://masstransit-project.com.

A: We ended up using a different topic name for each developer while debugging which is working pretty good.

A: Unfortunately, there is no Azure SB local emulator. That was asked before, and you can try to use Service Bus for Windows Server but it is slightly behind the cloud service in terms of features support/functionality, etc. Still, it supports Azure SDK, for example. MSDN link for SB for WS.

A: We use the devlopers machine name in the path for alot of dev things. for example a queueName like "TheEventMessageQueue" can be "TheEventMessageQueue-Machine123" and we use a dev subscription so we dont make a mess :)
By using the machine name its easy to se who the que belongs to if its going out of control


text:
Q: Параграф в JSX файле Как решить проблему с переносом строки в JSX файле в ReactJS? Тег pre не работает, а br выглядит ужасно и неэффективно.

{props.title}

    {props.poem}
    Գիշերն ամբողջ հիվանդ, խելագար,

    Ես երազեցի արեւի մասին:

    Շուրջս ո՛չ մի ձայն ու շշուկ չկար –

    Գունատ էր շուրջս՝ գիշեր ու լուսին:

    Ես երազեցի արեւի ոսկին,

    Տենչացի նրա հրաշքը խնդուն՝

    Ուզեցի սիրել շշուկն իմաստուն՝

    Արեւանման, արնավառ խոսքի, –

    Բայց շուրջս այնպես գունատ էր, տկար –

    Խոսքեր չկային, ու արեւ չկար …

A: Шаблонные литералы позволяют использовать многострочные строки, которые сохраняют начальные/конечные пробелы и новые строки. Шаблонные литералы должны быть заключены в обратные кавычки. Плюс ко всему в JSX нужно этот шаблонный литерал заключить в фигурные скобки. Для наглядности приведет пример ниже:
class SomeComponent extends React.Component {
   render() {
        return (

{`
            Hello,
            World.
          `}

        )
    }
}

Пример, согласно прикрепленному блоку кода из вопроса:

class SomeComponent extends React.Component {
   render() {
        return (

{`
                    Գիշերն ամբողջ հիվանդ, խելագար,
                    Ես երազեցի արեւի մասին:
                    Շուրջս ո՛չ մի ձայն ու շշուկ չկար –
                    Գունատ էր շուրջս՝ գիշեր ու լուսին:
                    Ես երազեցի արեւի ոսկին,
                    Տենչացի նրա հրաշքը խնդուն՝
                    Ուզեցի սիրել շշուկն իմաստուն՝
                    Արեւանման, արնավառ խոսքի, –
                    Բայց շուրջս այնպես գունատ էր, տկար –
                    Խոսքեր չկային, ու արեւ չկար …
          `}

        )
    }
}

ReactDOM.render(
  <SomeComponent />,
  document.getElementById('pre')
)

Ссылка на источник: Formatting code with  tag in React and JSX


text:
Q: How does the $I$-$V$ curve for bulk metal look like? For semiconductors, the current (I) vs. voltage (V) relationship is as shown in the picture below.

As we increase the applied voltage, the electron-hole pairs generate increases too, so we see an almost linear increase in current.
Now if we consider metals, how will current behave if we increase voltage? Metals are full of electrons, so on increasing V, will it have any effect on I at all? I feel, the curve might be like this:

Is it correct?

A: Ohm's law applies to metals.
In fact, Ohm developed the law through investigation of metals, not semiconductors, insulators, or other types of materials.

how will the I-V curve look like?

The I-V curve for a metallic conductor, or any other Ohmic conductor, is a straight line through the origin.
(In practical measurements, you might find the line is not perfectly straight, due to Joule heating and the material resistivity varying with temperature)


text:
Q: Knockout-Validation not triggering I'm using knockout.js with CakePHP and I cannot seem to get knockout-validation to work. I'm using chrome and knockout-validation is loaded in the scripts and also shows in the network tab. Also, when I remove the "include script" I get all sorts of errors, so I know it's being included.
I have a view model called ReserveViewModel. Here's an example of an input I'm trying to validate. I don't get any errors, it just doesn't flag anything.
ko.validation.configure({
    registerExtenders: true,
    messagesOnModified: true,
    insertMessages: true,
    parseInputAttributes: true,
    messageTemplate: null
});

function ReserveViewModel(){

    var self = this;

    self.firstName = ko.observable("").extend({ required: true })
                .extend({ minLength: 3 })
                .extend({ pattern: {
                    message: 'Please enter your first name',
                    params: '^[a-zA-Z]'
                }});

    //button to continue to another div with more options
    self.continue = function(){
        self.errors = ko.validation.group(self);
        if (self.errors().length == 0) {
            alert('Error found');
        }
    }

}

ko.validation.registerExtenders();

ko.applyBindings(new ReserveViewModel());

When I click the "continue" button and the firstName input is blank it still continues. I tried putting an alert on self.errors().length and it results in the following error
function m(){if(0<arguments.length){if("function"===typeof r)r.apply(c,arguments);else throw Error("Cannot write a value to a ko.computed unless you specify a 'write' option. If you wish to read the current value, don't pass any parameters.");return this}l||e();a.q.bb(m);return k}

If it makes a difference, I'm loading this content via an AJAX call through CakePHP. Would that affect it anything? Could it be some kind of closure?
Edit I got it to work
I ended up using jQuery to retrieve all the scripts necessary. Then I would use AJAX to populate the div. On the page I was retrieving via AJAX I included the ViewModel file.
It was a strange mixup due to files loading at different times, so I just had to make them load sequentially with jquery.


text:
Q: Is there a way to make Selenium Grid 2 DesiredCapabilities browser-agnostic? I'm wondering if there's a (preferably built-in) way for Selenium hubs to ask for nodes that have any browser available. Basically, I want my hub to specify something like "BrowserName = 'any'", match on a node that is running less instances than its maxInstances, then let the node decide which browser to run on.
The motivation behind this is that I want to maximize the number of tests running in parallel on any given node without having multiple instances of any one browser. I don't care which browser is running for any given test.
As a reference, I'm currently using selenium server 2.17.

A: Here you go:
java -jar selenium-server-standalone-2.14.0.jar -role node  -hub http://localhost:4444/grid/register -maxSession 3 -browser browserName=firefox,maxInstances=1 -browser browserName=chrome,maxInstances=1 ...

A: Ack, this is annoying.
I'm fairly sure there's a command line parameter that let's you override the specified browserName, but now I can't find it.
If my memory is not way off, the parameter let you do more or less what you are asking for - regardless of what browsers the node says it has, and regardless of what the hub asks for, one particular browser is always started.
Note to self: start a proper list of all command line options for selenium, and possibly submit it to the team for inclusion in the wiki.
One way to achieve this in any case would be to write a your own "CapabilityMatcher" class - but that may not be an option unless you want to create a custom JAR, and you want teh hub to do the change of browser, rather than the individual nodes.


text:
Q: int() argument must be a string, a bytes-like object or a number, not 'tuple' will using sql formating in python I am making a code to add an item to a database, however, I get the error
int() argument must be a string, a bytes-like object or a number, not 'tuple'

as I am trying to turn the information you get from a tuple when using the fetchall() function in python (i.e. (1,),(2,),(3,) into an int, however I do not know how to do this. Here is the code I am working on.
try:
    adding_item_name = input("What would you like to name the item to be? >>> ")
    adding_item_value = input("What would you like the value of the item to be? >>> ")
    adding_item_quantity = int(input("What would you like the quantity to be? >>> "))
    cursor.execute('SELECT item_ID FROM Items_in_stock ORDER BY item_ID')
    adding_item_ID = int(cursor.fetchall()[-1])
    adding_item_ID += 1
    print(adding_item_ID)
    print(adding_item_ID2)
    cursor.execute('INSERT INTO Items_in_stock (item_ID, item_name, item_value, item_quantity) VALUES (?,?,?,?)',
    (adding_item_ID_int, adding_item_name, adding_item_value, adding_item_quantity,))
    print("Added item successfully")
except Exception as e:
    print(str(e))
    print("Unable to add item")

I have tried to do this:
x = [0, 1, 2]
y = ''.join(map(str, x))
z = int(y)

but to no avail.

A: you can try this:
adding_item_ID = cursor.fetchall()[-1][0]  # get the first element of the tuple
adding_item_ID = int(adding_item_ID)  # convert to int

you can also use a for loop to iterate over the tuple and convert each element to an integer:
for item_id in cursor.fetchall():
    item_id = int(item_id[0])

A: Each query always produces a tuple of results, no matter how many fields the SELECT statement requests, so that the API is not dependent on the particular argument to execute.
Likewise, fetchall returns a list of results, so that the API doesn't change depending on whether the query produces 0, 1, or more results.
So you need to index cursor.fetchall() twice: once to get the last (and only?) element of the result, and once to get the only value in tuple.
adding_item_ID = int(cursor.fetchall()[-1][0])

It's possible you could refine the query to avoid needing fetchall. Use something like
cursor.execute('SELECT max(item_ID) FROM Items_in_stock ORDER BY item_ID')

and then you can use
adding_item_ID = int(cursor.fetchone()[0])

This will be more efficient as well, as the work of selecting the largest item id is done in the database, not in Python, and only one result has to be retrieved.


text:
Q: Tag synonym request - [tfpt] -> [tfs-power-tools] The tags tfpt and tfs-power-tools appear to refer to the same thing.
I'm mostly suggesting the synonym as a recent tag wiki edit seems to confuse this with TFTP.
The more verbose tag is likely clearer and won't be as confusing.

A: Synonymized and merged the small amount of questions.
tfs-power-tools ← tfpt


text:
Q: Visual Studio Form Design Error This has happened to me twice now, the first time it happened I created a new project and copied all of my data to and it worked for a while.  Then the error came back unexpectedly.
I have a simple VB.net project that consists of a single dialog box.  I am getting an error on the Design tab of that dialog box that says

Could not find type 'System.Windows.Forms.Form'

In the list of references the path for "System" says

The system cannot find the reference specified

I have tried removing the System reference and re-adding it.  Even closing and opening VS in between.  Every time it gives the same error message.  If I create a new project it has a valid path.
I am using Visual Studio 2013, VB.net

A: I found the issue.  I had included a folder with an executable in it.  Whenever I excluded the folder all of the issues went away.


text:
Q: How to sum two rows within CASE in SQL Server Management Studio I'm currently trying to build a SQL Server Agent which should a fix a price issue we do have with our database. This should be a quick fix, hopefully or provider does come up with a more convenient solution. I have the following statement:
SELECT
    CASE
        WHEN KHKVKBelegePositionen.StuecklistenTyp = '0'
            THEN (SELECT KHKVKBelegePositionen.Gesamtpreis)
        WHEN KHKVKBelegeStuecklisten.Gesamtpreis != '0,00'
             AND KHKVKBelege.A0Land != 'DE'
             AND (KHKVKBelegePositionen.Artikelgruppe != '181' OR
                  KHKVKBelegePositionen.Artikelgruppe != '182' OR
                  KHKVKBelegePositionen.Artikelgruppe != '183')
             AND KHKVKBelegePositionen.StuecklistenTyp != '0'
            THEN (SELECT KHKVKBelegeStuecklisten.Gesamtpreis)
        WHEN (KHKVKBelegePositionen.Artikelgruppe = '181' OR
              KHKVKBelegePositionen.Artikelgruppe = '182' OR
              KHKVKBelegePositionen.Artikelgruppe = '183')
             AND KHKVKBelegePositionen.StuecklistenTyp != '0'
            THEN (SELECT KHKVKBelegeStuecklisten.Gesamtpreis)
        ELSE
            CAST(KHKVKBelegeStuecklisten.GesamtpreisInternEW as varchar)
    END AS Gesamtpreis
FROM
    KHKVKBelegeStuecklisten (READUNCOMMITTED)
INNER JOIN
    KHKVKBelege ON KHKVKBelegeStuecklisten.Belid = KHKVKBelege.BElid
INNER JOIN
    KHKVKBelegePositionen ON KHKVKBelegeStuecklisten.BelID = KHKVKBelegePositionen.BelID
WHERE
    KHKVKBelegePositionen.BelID = '3519582'

Some items do consists from two parts and each one has a value. So the output are 2 lines with 2 values. I want to sum these values to one value, to update a table.
This part I do struggle the most with
WHEN (KHKVKBelegePositionen.Artikelgruppe = '181' OR
      KHKVKBelegePositionen.Artikelgruppe = '182' OR
      KHKVKBelegePositionen.Artikelgruppe = '183')
     AND KHKVKBelegePositionen.StuecklistenTyp != '0'
    THEN (SELECT KHKVKBelegeStuecklisten.Gesamtpreis) `

On my example, data would be like this:
Overall Price
1. 13.75
2. 2.57

I need this value merged summed up to be able to update


text:
Q: Using python in windows to run a remote perl script on linux I need to connect from a Windows machine to a remote Linux server and execute a Perl script.
I've tried using
command = "perl /usr/local/xfer/file.pl -ssh root@"+hostname+" -pw password -batch"
pid = subprocess.Popen(command, shell=True)

but it tells me Can't open perl script "usr/local/xfer/file.pl'": No such file or directory.
What am I doing wrong here, and how can I get it to work?

A: The command above uses the Perl installation on Windows but you said the script is located on a Linux server.
So you need to wrap the invocation in a call to ssh:
child = subprocess.Popen(['plink', '-ssh', 'user@server', 'perl', '/usr/local/xfer/file.pl',
            '-ssh', 'root@'+hostname, '-pw', 'password', '-batch'], shell=True)

Note: Never ever use the "string command" version of subprocess.Popen(), always pass command and arguments as a list.
Back to your problem: This will start plink (command line version of Putty since Windows doesn't have ssh(1)) with all the other list elements as arguments.
Note that the Putty Agent must run for this to work, otherwise plink will ask for a password. See the manual for details.


text:
Q: How can I cast a float numpy array value to an int inside of a numba jitted function in nopython mode Inside a numba jitted nopython function, I need to index an array with the values inside of an another array. Both arrays are numpy arrays floats.
For example
@numba.jit("void(f8[:], f8[:], f8[:])", nopython=True)
def need_a_cast(sources, indices, destinations):
    for i in range(indices.size):
        destinations[i] = sources[indices[i]]

My code is different, but let's assume the problem is reproducible by this stupid example (i.e., I cannot have indices of type int). AFAIK, i cannot use int(indices[i]) nor indices[i].astype("int") inside of nopython jit function.
How do I do this?

A: Using numba 0.24 at least, you can do a simple cast:
import numpy as np
import numba as nb

@nb.jit(nopython=True)
def need_a_cast(sources, indices, destinations):
    for i in range(indices.size):
        destinations[i] = sources[int(indices[i])]

sources = np.arange(10, dtype=np.float64)
indices = np.arange(10, dtype=np.float64)
np.random.shuffle(indices)
destinations = np.empty_like(sources)

print indices
need_a_cast(sources, indices, destinations)
print destinations

# Result
# [ 3.  2.  8.  1.  5.  6.  9.  4.  0.  7.]
# [ 3.  2.  8.  1.  5.  6.  9.  4.  0.  7.]

A: If you really cannot use int(indices[i]) (it works for JoshAdel and also for me) you should be able to work around it with math.trunc or math.floor:
import math

...

destinations[i] = sources[math.trunc(indices[i])] # truncate (py2 and py3)
destinations[i] = sources[math.floor(indices[i])] # round down (only py3)

math.floor works only for Python3 as far as I know because it returns a float in Python2. But math.trunc on the other hand rounds up for negative values.


text:
Q: Exporting user input to txt file I can enter data in the form of "DATA > 11,12,54,34,67,23" and it saves to the txt file in this format;

(DATA > 11,12,54,34,67,23)

However if i try and add another after running this again, this first one is deleted and replaced.
How can i make it so that there are no brackets being saved as my read function does not work with the brackets, and the next one saved goes on the next line instead of replacing the original?
Here is my code
  val mapdata3 = readFile("newDataFile.txt")
  var mapdata2 = Map()
  println ("Data in file " + mapdata3)

  // *******************************************************************************************************************
  // UTILITY FUNCTIONS
  //GETS THE DATA FROM THE DATA.TXT
  def readFile(filename: String): Map[String, List[Int]] = {
    processInput(Source.fromFile(filename).getLines)
  }
  def processInput(lines: Iterator[String]): Map[String, List[Int]] = {
    Try {
      lines.foldLeft(Map[String, List[Int]]()) { (acc, line) =>

        val splitline = line.split(",").map(_.trim).toList
        acc.updated(splitline.head, splitline.tail.map(_.toInt))
      }
    }.getOrElse {
      println("Sorry, an exception happened.")
      Map()
    }
  }
  // *****************************************************************************************

  print("Enter Data key > ")
  val key = readLine()

  var result = key.split(";").map(_ split ">") collect { case Array(k, v) => (k, v) } toMap

  println ("Data entered into file" + result)

  // Writes the newly created stock list to the txt file
  val data = result
  val file = "newDataFile.txt"
  val writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file)))
  for (x <- data) {
    writer.write(x + "\n")  // however you want to format it
  }
  writer.close()

A: You need to open the file in append mode. Use this constructor instead:
public FileOutputStream(File file,
                boolean append)
                 throws FileNotFoundException

append - if true, then bytes will be written to the end of the file
  rather than the beginning

The rest seems fine, you already have a new line at the end of your write.


text:
Q: User ID or Username I have a CakePHP app that uses the default "Created By" behaviour to store user IDs of authors of articles (for example - amongst other things).
Is it better to store the User ID or the Username in the Created By field?
My instinct is the User ID, but what if somehow something got out of sync and the authors got mixed up during database version migrations etc.
Probably a stupid question, but what do you do?

A: Store user ID, not user name. Highly likely in your SQL schema, you'll have this as a foreign key, ie being a primary autoincrement key in another table.
This is more efficient in terms of indexing and takes less space than the name.


text:
Q: SSH Key Auth failed ... sometimes with SSSD I have an issue with one of my server
I use keys to authenticate on my server with AD account, it works most of the time.
SSSD module is used to authenticate AD user.
Sometimes i can't authenticate with my AD users, it seems that the server tries with local user
Here it's working authentication
Sep 17 15:06:02 x3v6prod sshd[6762]: debug1: userauth-request for user sagex3 service ssh-connection method gssapi-with-mic
Sep 17 15:06:02 x3v6prod sshd[6762]: debug1: attempt 1 failures 0
Sep 17 15:06:02 x3v6prod sshd[6759]: debug1: PAM: setting PAM_RHOST to "blueway-prod.XXXXXXXXXX.fr"
Sep 17 15:06:02 x3v6prod sshd[6759]: debug1: PAM: setting PAM_TTY to "ssh"
Sep 17 15:06:02 x3v6prod sshd[6762]: Postponed gssapi-with-mic for sagex3 from 192.168.60.184 port 49310 ssh2
Sep 17 15:06:02 x3v6prod sshd[6762]: debug1: userauth-request for user sagex3 service ssh-connection method publickey
Sep 17 15:06:02 x3v6prod sshd[6762]: debug1: attempt 2 failures 0
Sep 17 15:06:02 x3v6prod sshd[6762]: debug1: test whether pkalg/pkblob are acceptable
Sep 17 15:06:02 x3v6prod sshd[6759]: debug1: temporarily_use_uid: 285005224/285000513 (e=0/0)
Sep 17 15:06:02 x3v6prod sshd[6759]: debug1: trying public key file /home/XXXXXXXXXX.FR/sagex3/.ssh/authorized_keys
Sep 17 15:06:02 x3v6prod sshd[6759]: debug1: fd 8 clearing O_NONBLOCK
Sep 17 15:06:02 x3v6prod sshd[6759]: debug1: matching key found: file /home/XXXXXXXXXX/sagex3/.ssh/authorized_keys, line 1
Sep 17 15:06:02 x3v6prod sshd[6759]: Found matching RSA key: ca:38:16:a0:d0:ca:60:6b:28:63:09:5b:01:b2:90:d1
Sep 17 15:06:02 x3v6prod sshd[6759]: debug1: restore_uid: 0/0
Sep 17 15:06:02 x3v6prod sshd[6762]: Postponed publickey for sagex3 from 192.168.60.184 port 49310 ssh2
Sep 17 15:06:02 x3v6prod sshd[6762]: debug1: userauth-request for user sagex3 service ssh-connection method publickey
Sep 17 15:06:02 x3v6prod sshd[6762]: debug1: attempt 3 failures 0
Sep 17 15:06:02 x3v6prod sshd[6759]: debug1: temporarily_use_uid: 285005224/285000513 (e=0/0)
Sep 17 15:06:02 x3v6prod sshd[6759]: debug1: trying public key file /home/XXXXXXXXXX/sagex3/.ssh/authorized_keys
Sep 17 15:06:02 x3v6prod sshd[6759]: debug1: fd 8 clearing O_NONBLOCK
Sep 17 15:06:02 x3v6prod sshd[6759]: debug1: matching key found: file /home/XXXXXXXXXX/sagex3/.ssh/authorized_keys, line 1
Sep 17 15:06:02 x3v6prod sshd[6759]: Found matching RSA key: ca:38:16:a0:d0:ca:60:6b:28:63:09:5b:01:b2:90:d1
Sep 17 15:06:02 x3v6prod sshd[6759]: debug1: restore_uid: 0/0
Sep 17 15:06:02 x3v6prod sshd[6759]: debug1: ssh_rsa_verify: signature correct

And here not working authentication
Sep 17 15:06:06 x3v6prod sshd[6795]: debug1:userauth-request for user sagex3 service ssh-connection method none
Sep 17 15:06:06 x3v6prod sshd[6795]: debug1: attempt 0 failures 0
Sep 17 15:06:06 x3v6prod sshd[6799]: debug1: SSH2_MSG_KEXINIT received
Sep 17 15:06:06 x3v6prod sshd[6799]: debug1: kex: client->server aes128-ctr hmac-md5 none
Sep 17 15:06:06 x3v6prod sshd[6799]: debug1: kex: server->client aes128-ctr hmac-md5 none
Sep 17 15:06:06 x3v6prod sshd[6799]: debug1: expecting SSH2_MSG_KEXDH_INIT
Sep 17 15:06:06 x3v6prod sshd[6792]: debug1: PAM: initializing for "sagex3"
Sep 17 15:06:06 x3v6prod sshd[6795]: debug1: userauth-request for user sagex3 service ssh-connection method gssapi-with-mic
Sep 17 15:06:06 x3v6prod sshd[6795]: debug1: attempt 1 failures 0
Sep 17 15:06:06 x3v6prod sshd[6792]: debug1: PAM: setting PAM_RHOST to "blueway-prod.XXXXXXXXXX.fr"
Sep 17 15:06:06 x3v6prod sshd[6792]: debug1: PAM: setting PAM_TTY to "ssh"
Sep 17 15:06:06 x3v6prod sshd[6795]: Postponed gssapi-with-mic for sagex3 from 192.168.60.184 port 49314 ssh2
Sep 17 15:06:06 x3v6prod sshd[6795]: debug1: userauth-request for user sagex3 service ssh-connection method publickey
Sep 17 15:06:06 x3v6prod sshd[6795]: debug1: attempt 2 failures 0
Sep 17 15:06:06 x3v6prod sshd[6795]: debug1: test whether pkalg/pkblob are acceptable
Sep 17 15:06:06 x3v6prod sshd[6792]: debug1: temporarily_use_uid: 285005224/285000513 (e=0/0)
Sep 17 15:06:06 x3v6prod sshd[6799]: debug1: SSH2_MSG_NEWKEYS sent
Sep 17 15:06:06 x3v6prod sshd[6799]: debug1: expecting SSH2_MSG_NEWKEYS
Sep 17 15:06:06 x3v6prod sshd[6792]: debug1: trying public key file /home/SAGEX3/.ssh/authorized_keys
Sep 17 15:06:06 x3v6prod sshd[6799]: debug1: SSH2_MSG_NEWKEYS received
Sep 17 15:06:06 x3v6prod sshd[6799]: debug1: KEX done
Sep 17 15:06:06 x3v6prod sshd[6792]: debug1: Could not open authorized keys '/home/SAGEX3/.ssh/authorized_keys': No such file or directory
Sep 17 15:06:06 x3v6prod sshd[6792]: debug1: restore_uid: 0/0
Sep 17 15:06:06 x3v6prod sshd[6792]: debug1: temporarily_use_uid: 285005224/285000513 (e=0/0)
Sep 17 15:06:06 x3v6prod sshd[6792]: debug1: trying public key file /home/SAGEX3/.ssh/authorized_keys2
Sep 17 15:06:06 x3v6prod sshd[6792]: debug1: Could not open authorized keys '/home/SAGEX3/.ssh/authorized_keys2': No such file or directory
Sep 17 15:06:06 x3v6prod sshd[6792]: debug1: restore_uid: 0/0
Sep 17 15:06:06 x3v6prod sshd[6792]: Failed publickey for sagex3 from 192.168.60.184 port 49314 ssh2
Sep 17 15:06:06 x3v6prod sshd[6799]: debug1: userauth-request for user sagex3 service ssh-connection method none
Sep 17 15:06:06 x3v6prod sshd[6799]: debug1: attempt 0 failures 0
Sep 17 15:06:06 x3v6prod sshd[6795]: debug1: userauth-request for user sagex3 service ssh-connection method password
Sep 17 15:06:06 x3v6prod sshd[6795]: debug1: attempt 3 failures 1
Sep 17 15:06:06 x3v6prod sshd[6792]: Failed none for sagex3 from 192.168.60.184 port 49314 ssh2
Sep 17 15:06:06 x3v6prod sshd[6795]: debug1: userauth-request for user sagex3 service ssh-connection method password
Sep 17 15:06:06 x3v6prod sshd[6795]: debug1: attempt 4 failures 2
Sep 17 15:06:06 x3v6prod sshd[6792]: Failed password for sagex3 from 192.168.60.184 port 49314 ssh2
Sep 17 15:06:06 x3v6prod sshd[6795]: debug1: userauth-request for user sagex3 service ssh-connection method password
Sep 17 15:06:06 x3v6prod sshd[6795]: debug1: attempt 5

And SSSD logs
Tue Sep 17 15:06:01 2019) [sssd[be[XXXXXXXX]]] [ad_gpo_access_done] (0x0040): GPO-based access control failed.
(Tue Sep 17 15:06:01 2019) [sssd[be[XXXXXXXX]]] [ad_gpo_access_done] (0x0040): Ignoring error: [22](Invalid argument); GPO-based access control failed, but GPO is not in enforcing mode.
(Tue Sep 17 15:06:01 2019) [sssd[be[XXXXXXXX]]] [child_sig_handler] (0x0020): waitpid did not found a child with changed status.
(Tue Sep 17 15:06:01 2019) [sssd[be[XXXXXXXX]]] [child_sig_handler] (0x0020): child [6688] failed with status [1].
(Tue Sep 17 15:06:01 2019) [sssd[be[XXXXXXXX]]] [gpo_cse_done] (0x0020): ad_gpo_parse_gpo_child_response failed: [22][Invalid argument]
(Tue Sep 17 15:06:01 2019) [sssd[be[XXXXXXXX]]] [ad_gpo_cse_done] (0x0040): Unable to retrieve policy data: [22](Invalid argument}
(Tue Sep 17 15:06:01 2019) [sssd[be[XXXXXXXX]]] [ad_gpo_access_done] (0x0040): GPO-based access control failed.
(Tue Sep 17 15:06:01 2019) [sssd[be[XXXXXXXX]]] [ad_gpo_access_done] (0x0040): Ignoring error: [22](Invalid argument); GPO-based access control failed, but GPO is not in enforcing mode.
(Tue Sep 17 15:06:01 2019) [sssd[be[XXXXXXXX]]] [child_sig_handler] (0x0020): child [6700] failed with status [1].
(Tue Sep 17 15:06:01 2019) [sssd[be[XXXXXXXX]]] [ad_gpo_get_som_attrs_done] (0x0040): no attrs found for SOM; try next SOM
(Tue Sep 17 15:06:02 2019) [sssd[be[XXXXXXXX]]] [gpo_cse_done] (0x0020): ad_gpo_parse_gpo_child_response failed: [22][Invalid argument]
(Tue Sep 17 15:06:02 2019) [sssd[be[XXXXXXXX]]] [ad_gpo_cse_done] (0x0040): Unable to retrieve policy data: [22](Invalid argument}
(Tue Sep 17 15:06:02 2019) [sssd[be[XXXXXXXX]]] [ad_gpo_access_done] (0x0040): GPO-based access control failed.
(Tue Sep 17 15:06:02 2019) [sssd[be[XXXXXXXX]]] [ad_gpo_access_done] (0x0040): Ignoring error: [22](Invalid argument); GPO-based access control failed, but GPO is not in enforcing mode.
(Tue Sep 17 15:06:02 2019) [sssd[be[XXXXXXXX]]] [child_sig_handler] (0x0020): child [6743] failed with status [1].
(Tue Sep 17 15:06:02 2019) [sssd[be[XXXXXXXX]]] [ad_gpo_get_som_attrs_done] (0x0040): no attrs found for SOM; try next SOM
(Tue Sep 17 15:06:02 2019) [sssd[be[XXXXXXXX]]] [gpo_cse_done] (0x0020): ad_gpo_parse_gpo_child_response failed: [22][Invalid argument]
(Tue Sep 17 15:06:02 2019) [sssd[be[XXXXXXXX]]] [ad_gpo_cse_done] (0x0040): Unable to retrieve policy data: [22](Invalid argument}
(Tue Sep 17 15:06:02 2019) [sssd[be[XXXXXXXX]]] [ad_gpo_access_done] (0x0040): GPO-based access control failed.
(Tue Sep 17 15:06:02 2019) [sssd[be[XXXXXXXX]]] [ad_gpo_access_done] (0x0040): Ignoring error: [22](Invalid argument); GPO-based access control failed, but GPO is not in enforcing mode.
(Tue Sep 17 15:06:02 2019) [sssd[be[XXXXXXXX]]] [child_sig_handler] (0x0020): child [6763] failed with status [1].
(Tue Sep 17 15:16:18 2019) [sssd[be[XXXXXXXX]]] [sdap_ad_tokengroups_initgr_mapping_done] (0x0080): Domain not found for SID S-1-5-21-374409226-1497903906-623647154-2705
(Tue Sep 17 15:16:18 2019) [sssd[be[XXXXXXXX]]] [sdap_ad_tokengroups_initgr_mapping_done] (0x0080): Domain not found for SID S-1-5-21-374409226-1497903906-623647154-2663
(Tue Sep 17 15:16:18 2019) [sssd[be[XXXXXXXX]]] [sdap_ad_tokengroups_initgr_mapping_done] (0x0080): Domain not found for SID S-1-5-21-374409226-1497903906-623647154-1560
(Tue Sep 17 15:18:45 2019) [sssd[be[XXXXXXXX]]] [sdap_id_conn_data_expire_handler] (0x0080): connection is about to expire, releasing it
(Tue Sep 17 15:20:45 2019) [sssd[be[XXXXXXXX]]] [sdap_id_conn_data_expire_handler] (0x0080): connection is about to expire, releasing it
(Tue Sep 17 15:32:28 2019) [sssd[be[XXXXXXXX]]] [sdap_get_server_opts_from_rootdse] (0x0080): Received invalid value for AD compatibility level. Using the lowest-common compatibility level
(Tue Sep 17 15:47:22 2019) [sssd[be[XXXXXXXX]]] [sdap_id_conn_data_expire_handler] (0x0080): connection is about to expire, releasing it
(Tue Sep 17 15:48:28 2019) [sssd[be[XXXXXXXX]]] [sdap_get_server_opts_from_rootdse] (0x0080): Received invalid value for AD compatibility level. Using the lowest-common compatibility level
(Tue Sep 17 16:00:01 2019) [sssd[be[XXXXXXXX]]] [sdap_get_server_opts_from_rootdse] (0x0080): Received invalid value for AD compatibility level. Using the lowest-common compatibility level
(Tue Sep 17 16:00:01 2019) [sssd[be[XXXXXXXX]]] [sysdb_get_real_name] (0x0040): Cannot find user [postfix] in cache
(Tue Sep 17 16:00:01 2019) [sssd[be[XXXXXXXX]]] [sysdb_get_real_name] (0x0040): Cannot find user [postfix] in cache
(Tue Sep 17 16:03:22 2019) [sssd[be[XXXXXXXX]]] [sdap_id_conn_data_expire_handler] (0x0080): connection is about to expire, releasing it
(Tue Sep 17 16:03:30 2019) [sssd[be[XXXXXXXX]]] [sdap_get_server_opts_from_rootdse] (0x0080): Received invalid value for AD compatibility level. Using the lowest-common compatibility level
(Tue Sep 17 16:03:33 2019) [sssd[be[XXXXXXXX]]] [sbus_dispatch] (0x0080): Connection is not open for dispatching.
(Tue Sep 17 16:03:33 2019) [sssd[be[XXXXXXXX]]] [sbus_dispatch] (0x0080): Connection is not open for dispatching.
(Tue Sep 17 16:03:33 2019) [sssd[be[XXXXXXXX]]] [sbus_dispatch] (0x0080): Connection is not open for dispatching.
(Tue Sep 17 16:03:34 2019) [sssd[be[XXXXXXXX]]] [be_process_init] (0x0080): No SUDO module provided for [XXXXXXXX] !!
(Tue Sep 17 16:03:34 2019) [sssd[be[XXXXXXXX]]] [be_process_init] (0x0020): No selinux module provided for [XXXXXXXX] !!
(Tue Sep 17 16:03:34 2019) [sssd[be[XXXXXXXX]]] [be_process_init] (0x0020): No host info module provided for [XXXXXXXX] !!
(Tue Sep 17 16:03:34 2019) [sssd[be[XXXXXXXX]]] [sdap_get_server_opts_from_rootdse] (0x0080): Received invalid value for AD compatibility level. Using the lowest-common compatibility level
(Tue Sep 17 16:03:34 2019) [sssd[be[XXXXXXXX]]] [be_run_online_cb] (0x0080): Going online. Running callbacks.
(Tue Sep 17 16:03:34 2019) [sssd[be[XXXXXXXX]]] [be_ptask_enable] (0x0080): Task [AD machine account password renewal]: already enabled
(Tue Sep 17 16:03:34 2019) [sssd[be[XXXXXXXX]]] [resolv_gethostbyname_done] (0x0040): querying hosts database failed [5]: Input/output error
(Tue Sep 17 16:03:34 2019) [sssd[be[XXXXXXXX]]] [nsupdate_get_addrs_done] (0x0040): Could not resolve address for this machine, error [5]: Input/output error, resolver returned: [11]: Could not contact DNS servers
(Tue Sep 17 16:03:34 2019) [sssd[be[XXXXXXXX]]] [nsupdate_get_addrs_done] (0x0040): nsupdate_get_addrs_done failed: [5]: [Input/output error]
(Tue Sep 17 16:03:34 2019) [sssd[be[XXXXXXXX]]] [sdap_dyndns_dns_addrs_done] (0x0040): Could not receive list of current addresses [5]: Input/output error
(Tue Sep 17 16:03:34 2019) [sssd[be[XXXXXXXX]]] [ad_dyndns_sdap_update_done] (0x0040): Dynamic DNS update failed [5]: Input/output error
(Tue Sep 17 16:03:34 2019) [sssd[be[XXXXXXXX]]] [ad_dyndns_nsupdate_done] (0x0040): Updating DNS entry failed [5]: Input/output error
(Tue Sep 17 16:06:22 2019) [sssd[be[XXXXXXXX]]] [sbus_dispatch] (0x0080): Connection is not open for dispatching.
(Tue Sep 17 16:06:22 2019) [sssd[be[XXXXXXXX]]] [sbus_dispatch] (0x0080): Connection is not open for dispatching.
(Tue Sep 17 16:06:22 2019) [sssd[be[XXXXXXXX]]] [sbus_dispatch] (0x0080): Connection is not open for dispatching.
(Tue Sep 17 16:06:22 2019) [sssd[be[XXXXXXXX]]] [be_process_init] (0x0080): No SUDO module provided for [XXXXXXXX] !!
(Tue Sep 17 16:06:22 2019) [sssd[be[XXXXXXXX]]] [be_process_init] (0x0020): No selinux module provided for [XXXXXXXX] !!
(Tue Sep 17 16:06:22 2019) [sssd[be[XXXXXXXX]]] [be_process_init] (0x0020): No host info module provided for [XXXXXXXX] !!
(Tue Sep 17 16:06:22 2019) [sssd[be[XXXXXXXX]]] [sdap_get_server_opts_from_rootdse] (0x0080): Received invalid value for AD compatibility level. Using the lowest-common compatibility level
(Tue Sep 17 16:06:22 2019) [sssd[be[XXXXXXXX]]] [be_run_online_cb] (0x0080): Going online. Running callbacks.
(Tue Sep 17 16:06:23 2019) [sssd[be[XXXXXXXX]]] [be_ptask_enable] (0x0080): Task [AD machine account password renewal]: already enabled
(Tue Sep 17 16:06:23 2019) [sssd[be[XXXXXXXX]]] [resolv_gethostbyname_done] (0x0040): querying hosts database failed [5]: Input/output error
(Tue Sep 17 16:06:23 2019) [sssd[be[XXXXXXXX]]] [nsupdate_get_addrs_done] (0x0040): Could not resolve address for this machine, error [5]: Input/output error, resolver returned: [11]: Could not contact DNS servers
(Tue Sep 17 16:06:23 2019) [sssd[be[XXXXXXXX]]] [nsupdate_get_addrs_done] (0x0040): nsupdate_get_addrs_done failed: [5


text:
Q: Prestashop localization fail to Import a localization pack Prestashop (1.6.1.10) localization fail to Import a localization pack (Israel)
I get
[PrestaShopException]

Property Currency->decimals is not valid
at line 909 in file classes/ObjectModel.php

904.             }
905.
906.             $message = $this->validateField($field, $this->$field);
907.             if ($message !== true) {
908.                 if ($die) {
909.                     throw new PrestaShopException($message);
910.                 }
911.                 return $error_return ? $message : false;
912.             }
913.         }
914.
ObjectModelCore->validateFields - [line 299 - classes/LocalizationPack.php]
LocalizationPackCore->_installCurrencies - [line 97 - classes/LocalizationPack.php] - [1 Arguments]
LocalizationPackCore->loadLocalisationPack - [line 203 - controllers/admin/AdminLocalizationController.php] - [4 Arguments]
AdminLocalizationControllerCore->postProcess - [line 178 - classes/controller/Controller.php]
ControllerCore->run - [line 367 - classes/Dispatcher.php]
DispatcherCore->dispatch - [line 58 - admin/index.p

This is used to work in the passed, I think something is broken in the language page

A: Here is how I by-pass the issue:
In the  IMPORT A LOCALIZATION PACK form, uncheck Currency.
Import the pack, and create the currency manually.


text: Q: C# sample codes on how to received email from Office 365 using OAUTH or OAUTH2 I am looking for a simple C# codes on how to retrieve email, email attachment from Office365 using OAUTH or OAUTH2. Thank you in advanced!


text:
Q: angular js templateUrl with absolute path On the video watch page with the url

/watch/video_id

, I had a ng app. The directive is shown as below.
app.directive('myApp', function() {
    return {
      restrict: 'E',
      templateUrl: 'ng-templates/myTemplate.html',
      link: function(scope, elem, attrs) {
      },
      controller: 'Controller'
    };
  });

Since the templateUrl is the relative path, it will try to find the template in

'/watch/ng-templates/myTemplate.html'

which is an error.
I want to put all the templates in the ng-templates folder. But it won't work if the ng app always looks for the relative path. Is there a way to configure the app making it to look for '/ng-template/myTemplate.html'?

A: Did you try to add leading slash to templateUrl, like
templateUrl: '/ng-templates/myTemplate.html',


text:
Q: Missing fonts folder on jekyll deploying to netlify When deploying jekyll project to netlify I am missing my fonts folder.
It works perfectly find when in development mode but when I tell it to run in production it seems to skip over adding my fonts folder to the _site/assets directory.
I believe it has to be something in the config but I am fairly new to jekyll and YAML. And in the code its seems to be saying to add all the assets underneath it to the build process.
Below is my _config.yml file.
copy:
  # Paths to static assets that aren't (S)CSS or JavaScript
  # because these are completely handled by the sass and javascript tasks
  assets:
    # all files below the assets dir
    - "assets/**/*"
    # exclusions:
    - "!assets/{js,scss,css}/**/*"   # js, scss and css files
    - "!assets/css{,/**}"            # css dir
    - "!assets/js{,/**}"             # js dir
    - "!assets/scss{,/**}"           # scss dir
    - "!assets/vendor{,/**}"         # vendor di
  dist: "_site/assets/"
  notification: "Running Copy"

A: Note:  I work for Netlify
While I'm not sure of the fail mode here, I can tell you a couple things that would help you debug:

*

*the easiest way to debug a build is described in this article:  https://www.netlify.com/blog/2016/10/18/how-our-build-bots-build-sites/  .  This lets you duplicate our build environment in a way that you can access during/after the build so you can see what is happening or has happened in more depth than our build logs

*If you write into support we can set a verbose flag on your builds that does the equivalent of 'set -x' on the building shell script to show you what's being run in production, though filtering this output is quite a task for a human, it may be more useful than nothing!


text:
Q: Why is Javascript object reference not updated? I'm creating a bunch of objects and I want to use some of the objects in others, so I'm passing them in so I can update them later. I'd expect to hold a reference to each object, but if I pass an object before it's created, it stays undefined even after I create it. Here's the code:
this.screen = new BatchScreen(screenList);
this.fieldData = new FieldData(this.screen, this.nutrientData);
this.nutrientData = new NutrientData(this.screen, this.fieldData);

function FieldData(screen, nutrientData)
{
    this.nutrientData = nutrientData;
}

this.fieldData.nutrientData is "undefined", which I don't understand as I thought this.fieldData holds a reference to this.nutrientData, which I create after it's assigned in this.fieldData.

A: Short: you are not passing references.
Long: the evaluation strategy in JS is something called Call by sharing. It also is explained as "references passed by values".
What it means in details is that - in your
this.fieldData = new FieldData(this.screen, this.nutrientData);

statement the this.screen holds a reference, so it's passed by value. And the this.nutrientData holds nothing - so undefined is passed.
Then when you run
this.nutrientData = new NutrientData(this.screen, this.fieldData);

statement the this.nutrientData is being defined as a reference to a new object. But it's too late - we have already passed the undefined in the FieldData constructor.
So the best way to understand it - is to always think that the data is always passed by values, but sometimes those values keep references.
For your code to work as you expect the self.nutrientData and others must be pointers, which JS does not support in any way.
The solution:
if you have 2 mutially dependent objects then you cannot have both in their own constructors. One of them just have to expose additional setter and accept the dependency through it.

A: Not an answer but a possible solution. You really need a getter but support isn't sufficiently widespread. If you have interdependent properties, you can implement a getter for one (or perhaps both for consistency) so you have:
this.screen = new BatchScreen(screenList);

// Don't bother passing this.nutrientData since you know it's not defined yet,
// pass in the object that you want the nutrientData property of
this.fieldData = new FieldData(this.screen, this);
this.nutrientData = new NutrientData(this.screen, this.fieldData);

// In here, use a function to return the property so its read when called,
// not when defined
function FieldData(screen, obj) {
    this.getNutrientData = function () {return obj.nutrientData};
}

Then instead of:
var foo = someInstance.fieldData.nutrientData;

use:
var foo = someInstance.fieldData.getNutrientData();

But there seems to be a circular relationship between fieldData and nutrientData.

A: In this case, this.nutrientData in the second line, is not being passed as a reference, since no reference to an object exists (at that point there is no this.nutrientData, so you are literally passing undefined).
I'd guess you are also having scope issues with this;
Try this (no pun intended):
var self = this;
this.screen = new BatchScreen(screenList);
this.fieldData = new FieldData(self.screen, new NutrientData(self.screen, self.fieldData));
// assumes that the nutrientData property exists from the object passed into FieldData
this.nutrientData = this.fieldData.nutrientData;
function FieldData(screen, nutrientData)
{
    this.nutrientData = nutrientData;
}


text:
Q: How to get nesting level of executed function? F.e code snippet
function func_1() {
   echo get_nesting_level();
   func_2();
}

function func_2() {
   // how to detect current nesting level?
   echo get_nesting_level();
   func_1();
}

function get_nesting_level() {
   // how to implement this function?
}

func_1();

Expected result
1
2
3
4
...
and so on.
Then I could hit conditional breakpoint if nesting level > 255.
But for the breakpoint I need to know how to detect current nesting level?
This function needs to hit conditionally breakpoint with XDebug to understand the issue.
When nesting level > 255.
How can I get nesting level of current function on execution flow?


text:
Q: Chrome Extension API - Trigger File Upload Dialog I am trying to trigger a file upload dialog from my content script.
When I type the following in the page console directly, it works and shows the input dialog box.
document.getElementById("upload").click();

But if I do the same in my content.js script, it doesn't.
I also tried to inject a script in the page and then trigger it;
injectScript('events.js');

function injectScript(filename) {
  var script = document.createElement('script');
  // TODO: add "script.js" to web_accessible_resources in manifest.json
  script.src = chrome.extension.getURL(filename);
  script.onload = function() {
      this.remove();
  };
  (document.head || document.documentElement).appendChild(script);
}

//in document ready
var event = document.createEvent('customEvent');
event.initCustomEvent('triggerUpload', true, true, {});
document.dispatchEvent(event);

And then in events.js:
document.addEventListener('triggerUpload', function (e) {
    console.log("inside"); //yes, my event triggered successfully

    var el = document.getElementById("upload");

    el.click();

    //other things tried..
    var evt = document.createEvent("HTMLEvents");
    evt.initEvent("click", false, true);
    el.dispatchEvent(evt);

    var event = new Event('click');
    el.dispatchEvent(event);
});

However, nothing works.
Is this not possible?


text:
Q: boost python vector of map .. (of structs) .. no luck Trying to expose a vector of maps (key being strings and value being struct objects) with following types:
// boost includes ..

struct MyStruct {
  double a;
  vector<double> vec;
  bool operator==(const MyStruct& other) {return false;}
  bool operator!=(const MyStruct& other) {return true;}
};

typedef map<string, MyStruct>      MyMap;

typedef vector<MyStruct>           MyVec;
typedef vector<MyMap>              MyVec2;

BOOST_PYTHON_MODULE(_axstatistics)
{

    py::class_<MyStruct>("MyStruct")
        .def_readwrite("a", &MyStruct::a)
        .def_readwrite("vec", &MyStruct::vec)
        ;

    py::class_<MyMap>("MyMap")
        .def(map_indexing_suite<MyMap>());

    py::class_<MyVec>("MyVec")
        .def(vector_indexing_suite<MyVec>());

// uncomment and boum
//    py::class_<MyVec2>("MyVec2")
//        .def(vector_indexing_suite<MyVec2>());

}

This works for MyVec but not for MyVec2, I get an almost unreadable compilation error to me..
Anyone have an idea or has experience with such a pattern ?
Thx in advance..

A: got it running by also defining == operators on the MyMap and MyVec2 classes.


text:
Q: eclipse does not recognize android constants I know this may be a simple question but eclipse does not recognize android constants like VISIBLE :
ImageView bin = (ImageView)findViewById(R.id.delete_icon);
bin.setVisibility(VISIBLE);

is there a reason for that ?

A: Try
bin.setVisibility(View.VISIBLE);

It needs to know what class that constant belongs to


text:
Q: Android grid view loads in reverse order Whenever I change the orientation of the phone, I see the order of items in grid view reverses i.e. what was at the first position now comes at the end and so on.
How can I get rid of this issue?  Based on the position clicked, I am invoking different activities. But because the order changes, wrong activities are being called when the screen orientation is changed.
I have added android:configChanges="orientation|keyboardHidden" in my manifest file.
Any help is appreciated.
Adapter Class:
class ImageAdapter extends BaseAdapter {

    Context mContext;

    private String[] mHome_icon_text = { "A", "B",
            "C", "D", "E","F" };

    private Integer[] mHome_icon_image = { R.drawable.icon,
            R.drawable.icon, R.drawable.icon, R.drawable.icon,
            R.drawable.icon, R.drawable.icon, };

    public ImageAdapter(Context c) {
        mContext = c;
    }

    @Override
    public int getCount() {
        // TODO Auto-generated method stub
        return mHome_icon_text.length;
    }

    @Override
    public Object getItem(int position) {
        return null;
    }

    public long getItemId(int position) {
        return 0;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        // TODO Auto-generated method stub
        View v;
        if (convertView == null) {
            LayoutInflater li = getLayoutInflater();
            v = li.inflate(R.layout.home_grid_view_item, null);
            TextView tv = (TextView) v.findViewById(R.id.home_icon_text);
            tv.setText(mHome_icon_text[position]);
            ImageView iv = (ImageView) v.findViewById(R.id.home_icon_image);

            iv.setImageResource(mHome_icon_image[position]);

        } else {
            v = convertView;
        }
        return v;
    }
}

In the main class:
grid_main.setOnItemClickListener(new OnItemClickListener() {
    public void onItemClick(AdapterView<?> parent, View v,
            int position, long id) {
        Intent i;
        switch (position) {
        case 0:
            // start A
            i = new Intent(Home.this,
                    com.da.A.class);
            startActivity(i);
            break;

        case 3: //Cactivity
            i = new Intent(Home.this,
                    com.da.C.class);
            startActivity(i);
            break;
        default:
            Toast
                    .makeText(Home.this, "" + position,
                            Toast.LENGTH_SHORT).show();
        }

    }
});

A: That v = convertView looks suspicious. I think you need to update the view with the required image and text for that position. (Otherwise you're simply re-using a cached view which may well be fed to you in the wrong order when the grid is rebuilt.)
1) As a test, try taking the if (convertView == null) { branch even if it is not null and see if that fixes it. (This will unnecessarily inflate new views when scrolling or rotating, so don't leave it like this.)
2) If that does fix it, you can correctly recycle a previously inflated convertView by finding your R.id.home_icon_text etc within it, and updating it for the current position in the convertView != null branch.


text:
Q: How do I create a database with EF and begin using it? I have a small app I am writing as an exercise to learn how to work with SQL databases in C# .NET.  My app tries to open a connection to a database, and if it fails, it assumes that the database was not there and creates it.  This database is used only by my app, and is always local, so it's a lot simpler than many other database situations.  Here is the code, based on things I've read on SO and also in "Pro C# 7: With .NET and .NET Core", by Andrew Troelsen:
private static DbConnection connection = null;
private static MyAppModels context = null;
public static void SetupDatabase()
{
    string dataProvider = "System.Data.SqlClient";
    DbProviderFactory factory = DbProviderFactories.GetFactory(dataProvider);

    // get connection object (closes automatically at end of using scope)
    connection = factory.CreateConnection();
    if (connection == null) { /* throw Exception */ }

    string connectionString = @"Data Source=(localdb)\mssqllocaldb;Initial Catalog=MyAppDB;Integrated Security=True";
    connection.ConnectionString = connectionString;
    try { connection.Open(); }
    catch (Exception)
    {
        // database could not be found; try to create it...
        connection.ConnectionString = @"Data Source=(localdb)\mssqllocaldb;Integrated Security=True;database=master";
        connection.Open();
        string str = "CREATE DATABASE MyAppDB ON PRIMARY " +
                     "(NAME = MyApp_Data, FILENAME = 'C:\\Users\\Me\\Documents\\MyApp\\MyAppData.mdf', " +
                     "SIZE = 2MB, MAXSIZE = 50MB, FILEGROWTH = 10%) " +
                     "LOG ON (NAME = MyApp_Log, FILENAME = 'C:\\Users\\Me\\Documents\\MyApp\\MyAppLog.ldf', " +
                     "SIZE = 1MB, MAXSIZE = 10MB, FILEGROWTH = 10%)";
        DbCommand myCommand = connection.CreateCommand();
        myCommand.CommandText = str;
        try { myCommand.ExecuteNonQuery(); }
        catch (System.Exception ex) { /* throw Exception */ }
    }

    context = new MyAppModels(connection);
    return;
}

This code seems to execute without a problem until I try to add data to a table, at which point I get the following error:
"The model backing the 'MyAppModels' context has changed since the database was created. Consider using Code First Migrations to update the database (http://go.microsoft.com/fwlink/?LinkId=238269)."
If I exit my app and re-open it, it's able to connect to the now-existing database and add records without a problem.  But I don't want users of my app to be required to exit and re-open the app after first installing it, just to get around this problem!
I looked as several other posts here, including:
The model backing the 'POSContext' context has changed since the database was created
The model backing the  context has changed since the database was created
These both seemed to point to the same solution.  Also, the second one had the following quote from a member of the Microsoft EF team:

When a model is first created, we run a DatabaseInitializer to do things like create the database if it's not there or add seed data. The default DatabaseInitializer tries to compare the database schema needed to use the model with a hash of the schema stored in an EdmMetadata table that is created with a database (when Code First is the one creating the database). Existing databases won't have the EdmMetadata table and so won't have the hash…and the implementation today will throw if that table is missing. We'll work on changing this behavior before we ship the fial version since it is the default. Until then, existing databases do not generally need any database initializer so it can be turned off for your context type by calling:

Database.SetInitializer<YourDbContext>(null);

I don't really understand all this.  But I tried adding that code to my DbContext class anyway:
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
    Database.SetInitializer<MyAppModels>(null);
    base.OnModelCreating(modelBuilder);
}

Now I get the following error when I try to add the first record to a table:
"An error occurred while updating the entries. See the inner exception for details."
Inner exception:
"String or binary data would be truncated. The statement has been terminated."
And now, if I close and re-open the app, the same error occurs every time.  So things are now worse.  From looking at other SO posts, I see that this error is pointing to a problem where the data being entered into the database exceeds the field size.  But I get the error on the first record I try to add and it definitely does NOT exceed any field size in that table.
I suspect that I should not be passing null to SetInitializer().  I noted the comment, "... we run a DatabaseInitializer to do things like create the database if it's not there or add seed data."  My code is already trying to handle the database creation.  Should my app not be doing that?  How would SetInitializer() know the location to put the database or the MAXSIZE?  And I don't think I need it to "add seed data", either.
I also noted this comment, "We'll work on changing this behavior before we ship the fial (sic) version since it is the default."  That makes it sound like a bug.  The comment was written ~9 years ago, so I would have hoped that it was already fixed.
In the meantime, does anyone have any tips for how to get this working right?
--Update--
I was able to get this working with a small addition to the creation code shown above:
myCommand.ExecuteNonQuery();
// close & try again to open the database
connection.Close();
connection.ConnectionString = @"Data Source=(localdb)\mssqllocaldb;Integrated Security=True;Initial Catalog=MyAppDB";
connection.Open();

Seems like it should be unnecessary, but it works...
Then I tried something else.  I replaced all the code in SetupDatabase() with one line, as I had seen in several example tutorials:
context = new MyAppModels();

This allows/relies on EF to open the database, creating it, if necessary (in some undefined/default location).  This worked when the database already existed, but when the database needed to be created, it failed:

System.Data.SqlClient.SqlException   HResult=0x80131904
  Message=CREATE FILE encountered operating system error 5(Access is denied.)
  while attempting to open or create the physical file
  'C:\Users\MyAppDB.mdf'. CREATE DATABASE failed. Some file
  names listed could not be created. Check related errors.   Source=.Net
  SqlClient Data Provider

Note the lack of a backslash between  and MyAppDB.mdf.  I don't know why this happens or how to fix it.  I don't see anything obvious in App.config that would control this...
<connectionStrings>
  <add name="MyAppConnection" connectionString="data source=(localdb)\mssqllocaldb;initial catalog=MyAppDB;integrated security=True;MultipleActiveResultSets=True;App=EntityFramework" providerName="System.Data.SqlClient" />
</connectionStrings>

Can someone help me work this out, so I can use "pure" EF, or do I need to go back to my hack that works...?

A: Well

is the code, based on things I've read on SO and also in "Pro C# 7: With .NET and .NET Core"

it seems that you have tried mixing both manual DB creation and code first migrations.
And it ended badly.
Can we solve this problem?
Yes...with some additional details/code and it may even require reworking a lot of things from the scratch, so I am not sure it would be worth the time, as you seem to be studying technologies, rather than trying to solve some technological mishmash in some business critical internal program suite.
So, I recommend you to decide what you are trying to learn and do it step by step using standard tutorials:

*

*You want to learn how to work with EF context and Code-First migrations? - https://learn.microsoft.com/en-us/ef/ef6/modeling/code-first/migrations/

*Want to learn how to do it with already existing DB? - https://learn.microsoft.com/en-us/ef/ef6/modeling/code-first/workflows/existing-database

*Want to learn how to work with basic ADO.NET classes (DbConnection, DbDataReader) - https://learn.microsoft.com/en-us/dotnet/framework/data/adonet/ado-net-code-examples

*Want to do something in between? - just be sure that you have used each thing separately before mixing them and that you really want to try it (academic interest/desire to experiment is all good, but applying non-standard approaches to real problems is usually a bad idea).

P.S.: You seem to be using EF6 (as you used DatabaseInitializer), but I'd actually advise you to start learning EF Core as it is the latest iteration of Entity Framework.

A: The code you've posted is how you would "manually" create a database using "dynamic" SQL. You don't need to use that approach at all when using Entity Framework.
One of the easiest ways to start with Entity Framework is to use Model-First:

*

*Add a new "ADO.NET Entity Data Model" to your project.

*Choose "Empty EF Designer Model".

*Edit the model to design your database.

*Upon saving (or in VS2019 you have to "Run Custom Tool" on the .tt files) you will have all of your entity classes created.

*In the model choose "Generate Database from Model" to generate an SQL file containing all of the SQL statements needed to create the new database with that model. This step also creates all of the necessary bindings between the database and the C# code. (All of which exists behind the scenes.)

Entities that you add to the model become tables in the database and classes in the C# code.
Attributes that you add become fields in the database and properties in the C# code.
Associations that you add become foreign key relationships in the database and collections ("navigation properties") in the C# code.
You can then start building queries in C# code using LINQ and IQueryable.
You can make changes to the model, and go through the "Generate Database from Model" process again to get a new SQL file that creates the database, but note that it will first nuke any existing database when you execute the script. This can be ok when testing, but it can also help to use a version control system so that you can see the changes to the SQL and then make manual changes to the database structure to make sure the database matches the model without having to delete it first.


text:
Q: Get rid of annoying EditText focus I have a pretty big ScrollView that consists of EditTexts and Spinners.
I have a huge problem with EditText focus that has been driving me nuts for the last 2 days. The issue is:
After editing an EditText, press 'back' to close the keyboard (the EditText) still remains focused, so when I scroll down to a Spinner and pick an item, the ScrollView jumps back to the last focused EditText, which is very annoying.
I've looked all over StackOverflow and tried everything. I've tried clearFocus() on the EditText after editing, but the focus just jumps to another EditText. I put     android:focusableInTouchMode="true"  and android:focusable="true"on the parent LinearLayout, hoping that it would steal the focus. Still doesn't work.
I have tried setting click listeners on spinners, and calling requestFocus() when clicking them. Nothing works.
Please help.


text:
Q: Qual o propósito do moment.js? Comprei um template bootstrap novo para o meu sistema, e ele veio com um negócio incluido que me devolve vários alertas, o moment.js.
Pelo que consegui entender ele é como uma biblioteca de validação client-side com suporte a idiomas e conversão de alguns formatos de data e não entendi mais nada além disso.
Exemplo:
Possuo um daterange pra gerar relatorios, e quando ativo esse daterange, o moment notifica ao meu console:

Deprecation warning: moment().subtract(period, number) is deprecated.
  Please use moment().subtract(number, period).

Mas o codigo funciona, e se eu corrijo isso informado warning, o daterange para de funcionar como deveria.
A dúvida é:

Pra que realmente serve o moment.js ?
O que eu posso fazer com ele ?

Obs: Pergunto isso porque eu realmente não vi utilidade nenhuma nele, e vários templates vem com ele acoplado, mas acredito que eu esteja errado acerca disso e que provavelment ele deve ser util.

A: Esta mensagem indica que quem criou o template usou comandos descontinuados do moment.js:

Deprecation warning: moment().subtract(period, number) is deprecated. Please use moment().subtract(number, period).

O moment.js é uma lib usada para trabalhar com data e hora, a API deles permite fazer calculos e formatações de maneira mais fácil.
Se esta emitindo esses warnings então é preciso solicitar ao desenvolvedor do template que faça os ajustes necessários, ele provavelmente escreveu as primeiras versões do template usando o código conforme uma versão mais antiga do moment.js, quando ele foi fazer o upgrade do moment.js ele não notou os warnings.
Essa mensagem especifica que você citou é mencionada em https://momentjs.com/docs/#/manipulating/subtract/

Before version 2.8.0, the moment#subtract(String, Number) syntax was also supported. It has been deprecated in favor of moment#subtract(Number, String).

Então mude o códigos semelhantes a este:
 moment().subtract('seconds', 1); // Deprecated in 2.8.0

Para algo semelhante a isto:
 moment().subtract(1, 'seconds');


text:
Q: Help me for create a xml, based on Room Count of hotel Help me for create a xml, based on Room Count of hotel
For example:
I have 5 Rooms: Room1, Room2, Room3, Room4 and Room5.
In Room1: 2 Adults, 1 Child, Age 6
In Room2: 1 Adult, 0 Child
In Room3: 2 Adults, 2 Child, Age 6, Age 7
In Room4: 1 Adult, 0 Child
In Room5: 2 Adult, 1 Child, Age 6

*

*If Child is 0 and Adult count comes same ( here the example adult count is 1), we take that rooms in one ( as 2 rooms). Other rooms in different .

<%
XMLLIST ="<Hotel>"&_
      "<RoomList>"&_
      "<Room>"&_
"<RoomCount>2</RoomCount>"&_
"<Adults>1</Adults>"&_
"<Child>0</Child>"&_
      "</Room>"&_

"<Room>"&_
"<RoomCount>1</RoomCount>"&_
"<Adults>2</Adults>"&_
"<Child>1</Child>"&_
"<Age>6</Age>"&_
      "</Room>"&_
"<Room>"&_
"<RoomCount>1</RoomCount>"&_
"<Adults>2</Adults>"&_
"<Child>2</Child>"&_
"<Age>6</Age>"&_
"<Age>7</Age>"&_
      "</Room>"&_
"<Room>"&_
"<RoomCount>1</RoomCount>"&_
"<Adults>2</Adults>"&_
"<Child>1</Child>"&_
"<Age>6</Age>"&_
      "</Room>"&_
      "</RoomList>"&_
      "</Hotel>"
%>

Plz help me to create a loop in asp code for create .

A: Check out Gelatin for converting text files to XML. (Note that what you posted isn't XML though.)


text:
Q: Annotations in Java I was wondering what exactly anotations are used for in Java, I have a basic understanding of it. However my true question is, what does annotions mean when their in a comment? For example: /** @param **/. Does it have any effect in the code itself?
Thank you.

A:
I was wondering what exactly anotations are used for in Java

They are used for all sorts of things.  It is not possible to give an "exact" answer, because the use-cases for annotations are (literally) infinite.  And besides, you have probably seen a few use-cases already.  (Google for examples, if you want to find more ...)

However my true question is, what does annotions mean when their in a comment?

When they are in comments, they are not annotations.  In this case, they are javadoc tags ... which are used when generating the javadoc documentation for the code,

For example: /** @param **/. Does it have any effect in the code itself?

It has no effect on the code itself.  A Java compiler ignores anything in Java comments.  (Of course, it is possible to write a compiler for a Java-derived language that pays attention stuff in comments.  But that ain't Java.)

A: It is used when the JavaDoc is created for a specific class, because its in a comment block the compiler doesn't look at it, and it isn't used.


text:
Q: function onClick() - cart not adding - what's wrong? I have a product page on Shopify with an Add to Cart button.
On click, the product gets added to cart and page redirects to another upsell product.
After they add upsell product to cart, it goes to checkout page BUT it's only displaying the upsell product and not the first product user wanted to buy. What's wrong with the code below?
How do I make both products appear in checkout?
<script>
function redirectToUpsellPageHandler(wrapper) {
  var upsellPageUrl = '/clientproducts/cryogenic-storage';
  var addToCartButton = wrapper.querySelector('.sqs-add-to-cart-button');
  var productVariants = wrapper.querySelector('.product-variants');

  if (addToCartButton) {
    addToCartButton.addEventListener('click', onClick);
  }

  function isVariantInStock() {
    return productVariants.getAttribute('data-variant-in-stock');
  }

  function onClick() {
    if (productVariants && isVariantInStock() || !productVariants) {
      setTimeout(function() {
        document.location.href = upsellPageUrl;
      }, 1000);
    }
  }
}

function redirectToUpsellPage() {
  // Product Page
  var productPage = document.querySelector('.collection-type-products.view-item');
  if (productPage) {
    redirectToUpsellPageHandler(productPage);
  }

  // Product Blocks
  var productBlocks = [].slice.call(document.querySelectorAll('.sqs-block-product'));
  productBlocks.forEach(redirectToUpsellPageHandler);
}

document.addEventListener('DOMContentLoaded', redirectToUpsellPage);
window.addEventListener('mercury:load', redirectToUpsellPage);
</script>

A: Add some console.logs and make sure you're getting into your onClick function. If you're not there may be some type of issue with using a function named onClick since that is a reserved function in jQuery or JS.


text:
Q: Comma in a C# statament I'm reviewing this code (written in C#):
string root = match.Groups[1].Value,
                secon = match.Groups[2].Success ? match.Groups[2].Value.Substring(1) : string.Empty,
                third = match.Groups[3].Success ? match.Groups[3].Value.Substring(1) : string.Empty;

Can someone explain the purpose of the commas?

A: It declares 3 variables of the type string named root, secon and third respectively. Like this:
int a, b, c;

A: It's a syntactic shortcut. Your example above is syntactic sugar for and is exactly the same as:
string root  = match.Groups[1].Value   ;
string secon = match.Groups[2].Success ? match.Groups[2].Value.Substring(1) : string.Empty ;
string third = match.Groups[3].Success ? match.Groups[3].Value.Substring(1) : string.Empty ;

So it saves you a little typing.
That is all.

A: They are used as a shortcut to create variables, and, in your example, all of which are of type string.


text:
Q: Hibernate: получить только часть колонок таблицы. День добрый, господа!
Есть таблица с большим количеством колонок. На эту таблицу аннотациями замаплена некая сущность. Этот маппинг очень не хотелось бы менять.
Задача: надо получить из таблицы данные, которые касаются лишь малой части колонок. Как это лучше сделать?
Я вижу такие варианты:
1) Замапить на таблицу новую сущность.
2) Загрузить ненужные свойства как lazy. Не совсем понимаю как это сделать, не меняя основного маппинга. И кроме того, насколько я понимаю, в таком случае в ДАО мне придется использовать Session, а вспомогательные классы более высокого уровня типа EntityManager и ли спринговые HibernateTemplate пролетают т.к. они закрывают сессию после загрузки.
3) Использовать criteria.multiselect, который вернет массив нужных мне полей моей сущности. Я нашел такой пример в Hibernate Reference:
CriteriaQuery<Object[]> criteria = builder.createQuery( Object[].class );
Root<Person> personRoot = criteria.from( Person.class );
Path<Long> idPath = personRoot.get( Person_.id );
Path<Integer> agePath = personRoot.get( Person_.age );
criteria.multiselect( idPath, agePath );
criteria.where( builder.equal( personRoot.get( Person_.eyeColor ), "brown" ) );
List<Object[]> valueArray = em.createQuery( criteria ).getResultList();
for ( Object[] values : valueArray ) {
    final Long id = (Long) values[0];
    final Integer age = (Integer) values[1];
    ...
}

(Примерно то же можно сделать через Tuple. Нужно ли? Что дает использование Tuple?)
В приведенном коде не пойму одну вещь: что такое здесь Person_ ? Это же не сама сущность Person, а что тогда?
Ну а глобально - какой способ лучше?


text:
Q: Python, is there a easier way to add values to a default key? The program I am working does the following:

*

*Grabs stdout from a .perl program

*Builds a nested dict from the output

I'm using the AutoVivification approach found here to build a default nested dictionary. I'm using this method of defaultdict because it's easier for me to follow as a new programmer.
I'd like to add one key value to a declared key per pass of the for line in the below code. Is there a easier way to add values to a key beyond making a [list]  of values then adding said values as a group?
import pprint

class Vividict(dict):
    def __missing__(self, key):
        value = self[key] = type(self)()
        return value

reg = 'NtUser'
od = Vividict()
od[reg]

def run_rip():
    os.chdir('/Users/ME/PycharmProjects/RegRipper2.8')  # Path to regripper dir
    for k in ntDict:
        run_command = "".join(["./rip.pl", " -r
                              /Users/ME/Desktop/Reg/NTUSER.DAT -p ", str(k)])
        process = subprocess.Popen(run_command,
                               shell=True,
                               stdout=subprocess.PIPE,
                               stderr=subprocess.PIPE)
        out, err = process.communicate()  # wait for the process to terminate
        parse(out)
        # errcode = process.returncode // used in future for errorcode checking
        ntDict.popitem(last=False)

def parse(data):
    pattern = re.compile('lastwrite|(\d{2}:\d{2}:\d{2})|alert|trust|Value')
    grouping = re.compile('(?P<first>.+?)(\n)(?P<second>.+?)
                         ([\n]{2})(?P<rest>.+[\n])', re.MULTILINE | re.DOTALL)
    if pattern.findall(data):
        match = re.search(grouping, data)
        global first
        first = re.sub("\s\s+", " ", match.group('first'))
        od[reg][first]
        second = re.sub("\s\s+", " ", match.group('second'))
        parse_sec(second)

def parse_sec(data):
    pattern = re.compile(r'^(\(.*?\)) (.*)$')
    date = re.compile(r'(.*?\s)(.*\d{2}:\d{2}:\d{2}.*)$')
    try:
        if pattern.match(data):
            result = pattern.match(data)
            hive = result.group(1)
            od[reg][first]['Hive'] = hive
            desc = result.group(2)
            od[reg][first]['Description'] = desc

        elif date.match(data):
            result = date.match(data)
            hive = result.group(1)
            od[reg][first]['Hive'] = hive
            time = result.group(2)
            od[reg][first]['Timestamp'] = time

        else:
            od[reg][first]['Finding'] = data

    except IndexError:
         print('error w/pattern match')

run_rip()
pprint.pprint(od)

Sample Input:
bitbucket_user v.20091020
(NTUSER.DAT) TEST - Get user BitBucket values

Software\Microsoft\Windows\CurrentVersion\Explorer\BitBucket
LastWrite Time Sat Nov 28 03:06:35 2015 (UTC)

Software\Microsoft\Windows\CurrentVersion\Explorer\BitBucket\Volume
LastWrite Time = Sat Nov 28 16:00:16 2015 (UTC)

A: If I understand your question correctly, you want to change the lines where you're actually adding values to your dictionary (e.g. the od[reg][first]['Hive'] = hive line and the similar one for desc and time) to create a list for each reg and first value and then extend that list with each item being added. Your dictionary subclass takes care of creating the nested dictionaries for you, but it won't build a list at the end.
I think the best way to do this is to use the setdefault method on the inner dictionary:
od[reg][first].setdefault("Hive", []).append(hive)

The setdefault will add the second value (the "default", here an empty list) to the dictionary if the first argument doesn't exist as a key. It preempts the dictionary's __missing__ method creating the item, which is good, since we want a the value to be list rather than another layer of dictionary. The method returns the value for the key in all cases (whether it added a new value or if there was one already), so we can chain it with append to add our new hive value to the list.


text:
Q: Как синхронизировать progressbar и WebClient.DownloadFileAsync? Есть вот такой код:
using System.ComponentModel;
using System.Net;
using System.Net.Mime;
using ShellProgressBar;

class Program
{
    static void Main()
    {
        Download();
    }

    static void Download()
    {
        const int totalTicks = 100;

        var options = new ProgressBarOptions
        {
            ProgressCharacter = '─',
            ProgressBarOnBottom = true
        };

        using (WebClient wc = new WebClient())
        {
            var pbar = new ProgressBar(totalTicks, "Initial message", options);
            wc.DownloadProgressChanged += (s, e) => { pbar.Tick(e.ProgressPercentage,"Download XML Plugin..."); };
            wc.DownloadFileAsync(new Uri("http://dev.osel.pp.ua/Consulo/Plugins/com.intellij.xml_2961.zip"),"/home/ketronix/xml.tar.gz");
            Console.ReadKey();
        };
    }
}

Он то работает, но я хочу чтобы по окончанию загрузки программа прекращала работу. Если другими словами - сейчас программа после загрузки ждет нажатия enter чтобы закрытся, как дальше нет никакого кода, можно сделать так чтобы она не ждала энтер, и если дальше кода нет, она вырубалась? А если код есть - продолжала работать? Всем спасибо.

A: Если в лоб решать, то как-то так. Всегда решение подобных задач начинайте с чтения документации.
class Program
{
    static async Task Main()
    {
        await DownloadAsync();
    }

    static async Task DownloadAsync()
    {
        var options = new ProgressBarOptions
        {
            ProgressCharacter = '─',
            ProgressBarOnBottom = true
        };

        using (WebClient wc = new WebClient())
        {
            var pbar = new ProgressBar(totalTicks, "Initial message", options);
            wc.DownloadProgressChanged += (s, e) => { pbar.Tick(e.ProgressPercentage,"Download XML Plugin..."); };
            await wc.DownloadFileTaskAsync(new Uri("http://dev.osel.pp.ua/Consulo/Plugins/com.intellij.xml_2961.zip"),"/home/ketronix/xml.tar.gz");
        };
    }
}

Имейте в виду, WebClient устарел и будет убран из .NET в будущем. Если интересует более современное решиение, то вот так.


text:
Q: 'Bizarre' ordering of sets in python When I convert a Python 3.8.0 list to a set, the resulting set ordering* is highly structured in a non-trivial way. How is this structure being extracted from the pseudo-random list?

As part of an experiment I am running, I am generating a random set. I was surprised to see that plotting the set suddenly showed unexpected linear structure in the set. So there are two things puzzling me - why does converting to a set result have an ordering* which ends up highlighting this structure; and, to a lesser extent why does the pseudo-random set have this "hidden" structure at all?
The code:
X = [randrange(250) for i in range(30)]
print(X)
print(set(X))

which outputs, for example
[238, 202, 245, 94, 111, 106, 148, 164, 154, 113, 128, 10, 196, 141, 69, 38, 106, 8, 40, 53, 160, 87, 85, 13, 38, 147, 204, 50, 162, 91]

{128, 8, 10, 141, 13, 147, 148, 154, 160, 162, 164, 38, 40, 50, 53, 196, 69, 202, 204, 85, 87, 91, 94, 106, 238, 111, 113, 245}

A plot** of the above list looks fairly random, as expected:

whereas plotting the set (as it is ordered in the output) exhibits the structure present in the set:

This behaviour 100% consistent on my machine (more examples below) with the values 250 and 30 used in the above code (the example I used is not cherry picked - it is just the last one I ran). Tuning these values sometimes results in slightly different structure (e.g. a subset of three arithmetic progressions*** instead of two).
Is this reproducible on other people's machines? Of course, that such structure exists seems indicative of a not-so-great pseudo-random number generation, but this does not explain how converting to a set would in some sense 'extract' this structure.
As far as I am aware, the there is no formal guarantee that the ordering of a set (when converted from a list) is deterministic (and even if it is, there is no sophisticated ordering being done in the background). So how is this happening?!

(*): I know, sets are unordered collections, but I mean "ordered" in the sense that, when calling the print statement, the set is output in some order which consistently highlights the underlying set structure.
(**): These plots are from Wolfram Alpha. Two more examples are below:

(***): Two plots when changing the range of the random numbers from 250 to 500:

A: Basically, this is because of two things:

*

*A set in Python is implemented using a hashtable,

*The hash of an integer is the integer itself.

Therefore, the index that an integer appears in the underlying array will be determined by the integer's value, modulo the length of the underlying array. So, integers will tend to stay in ascending order when you put a contiguous range of them into a set:
>>> list(set(range(10000))) == list(range(10000))
True # this can't be an accident!

If you don't have all of the numbers from a contiguous range, then the "modulo the length of the underlying array" part comes into play:
>>> r = range(0, 50, 4)
>>> set(r)
{0, 32, 4, 36, 8, 40, 12, 44, 16, 48, 20, 24, 28}
>>> sorted(r, key=lambda x: x % 32)
[0, 32, 4, 36, 8, 40, 12, 44, 16, 48, 20, 24, 28]

The sequence is predictable if you know the length of the underlying array, and the (deterministic) algorithm for adding elements. In this case the array's length is 32, because it's initially 8 and is quadrupled while elements are added.
Except for a blip near the end (because the numbers 52 and 56 aren't in the set), the range is divided into two sequences 0, 4, 8, ... and 32, 36, 40, ... which alternate because the hashes, which are the numbers' values themselves, are taken modulo 32 to choose indices in the array. There are collisions; for example, 4 and 36 are equal modulo 32, but 4 was added to the set first so 36 ends up at a different index.
Here's a chart for this sequence. The structure in your charts is just a noisier version, because you generated your numbers randomly rather than from a range with a step.

The number of interleaved sequences will depend on the size of the set in proportion to the length of the range the numbers are sampled from, since that determines how many times the range's length "wraps around" modulo the length of the hashtable's underlying array. Here's an example with three interleaved sequences 0, 6, 12, ..., 66, 72, 78, ... and 36, 42, 48, ...:
>>> set(range(0, 90, 6))
{0, 66, 36, 6, 72, 42, 12, 78, 48, 18, 84, 54, 24, 60, 30}


text:
Q: PRNG based on statistical data (Python) I want to generate random numbers based on statistics. I have statistics on Internet traffic for people of different age categories (12-24, 25-34, 35-44, 45-54, 55+, total number and percentage).
Table and Histogram.
Can I use Python to generate random numbers (age) based on these statistics?


text:
Q: Сумма элементов массива с заданным значением Прошу помочь решить данную задачку с помощью обычного for.
Моя версия:
#include <iostream>
using namespace std;
int main() {
   int i;
   int sum;
   int mas[i] = {1,1,1,1};
   for (i=0; i<4; i++) { sum+=i; }
   cout << sum;
}

A: Тут крайне не любят вопросы, где автор даже не попытался написать свой код на эту тему, не приложив свои попытки и четко не описав, что именно он не понимает. Но все же поможем вам:)
for (int i = 0; i<N; i++){
    if (mas[i] == tmp) sum += mas[i];
}

N - длинна массива.
tmp - заданное значение.
sum - переменная, куда мы записываем сумму элементов.
p.s. постарайтесь больше не задавать так вопросы.

A: Готовый код:
#include <iostream>
using namespace std;
int main()
{
int i, sum, mas[4] = {1,1,1,1};
sum=0;
for (i=0; i<4; i++) sum+=i;
cout << sum;
return 0;
}

Такс, а теперь объяснение:
Массив 4 потому что есть данные числа и определённое их количество;
Можно переменные задавать в одну строку;
sum=0; -должно быть начальное значение (если умножение тогда равно 1);
Цикл фор всегда после себя исполняет одну операцию (а вы ради этого использовали ещё одну под программу так сказать);
return 0;

так сказать корректный выход из программы int main(){... return 0;}
ещё иногда его не хватает и есть операторsystem("pause"); он ставится перед return 0;.