text:
Q: Why this error is occurred on checked working program on my system? about Tensorflow/Keras memory management problem I'm sure this code doesn't have any problem.
I got this code from my professor, and I checked its work.
But because of some reason, it doesn't work on my system(Anaconda).
history = model.fit(train_data, train_labels, epochs=500, validation_split=0.2, callbacks=[early_stop])

Train on 323 samples, validate on 81 samples
Epoch 1/500
 32/323 [=>............................] - ETA: 5sWARNING:tensorflow:Early stopping conditioned on metric `val_loss` which is not available. Available metrics are:
---------------------------------------------------------------------------
InternalError                             Traceback (most recent call last)
<ipython-input-15-b496e4002de6> in <module>
----> 1 history = model.fit(train_data, train_labels, epochs=500, validation_split=0.2, callbacks=[early_stop])

~\anaconda3\envs\AINN\lib\site-packages\tensorflow_core\python\keras\engine\training.py in fit(self, x, y, batch_size, epochs, verbose, callbacks, validation_split, validation_data, shuffle, class_weight, sample_weight, initial_epoch, steps_per_epoch, validation_steps, validation_freq, max_queue_size, workers, use_multiprocessing, **kwargs)
    817         max_queue_size=max_queue_size,
    818         workers=workers,
--> 819         use_multiprocessing=use_multiprocessing)
    820
    821   def evaluate(self,

~\anaconda3\envs\AINN\lib\site-packages\tensorflow_core\python\keras\engine\training_v2.py in fit(self, model, x, y, batch_size, epochs, verbose, callbacks, validation_split, validation_data, shuffle, class_weight, sample_weight, initial_epoch, steps_per_epoch, validation_steps, validation_freq, max_queue_size, workers, use_multiprocessing, **kwargs)
    340                 mode=ModeKeys.TRAIN,
    341                 training_context=training_context,
--> 342                 total_epochs=epochs)
    343             cbks.make_logs(model, epoch_logs, training_result, ModeKeys.TRAIN)
    344

~\anaconda3\envs\AINN\lib\site-packages\tensorflow_core\python\keras\engine\training_v2.py in run_one_epoch(model, iterator, execution_function, dataset_size, batch_size, strategy, steps_per_epoch, num_samples, mode, training_context, total_epochs)
    126         step=step, mode=mode, size=current_batch_size) as batch_logs:
    127       try:
--> 128         batch_outs = execution_function(iterator)
    129       except (StopIteration, errors.OutOfRangeError):
    130         # TODO(kaftan): File bug about tf function and errors.OutOfRangeError?

~\anaconda3\envs\AINN\lib\site-packages\tensorflow_core\python\keras\engine\training_v2_utils.py in execution_function(input_fn)
     96     # `numpy` translates Tensors to values in Eager mode.
     97     return nest.map_structure(_non_none_constant_value,
---> 98                               distributed_function(input_fn))
     99
    100   return execution_function

~\anaconda3\envs\AINN\lib\site-packages\tensorflow_core\python\eager\def_function.py in __call__(self, *args, **kwds)
    566         xla_context.Exit()
    567     else:
--> 568       result = self._call(*args, **kwds)
    569
    570     if tracing_count == self._get_tracing_count():

~\anaconda3\envs\AINN\lib\site-packages\tensorflow_core\python\eager\def_function.py in _call(self, *args, **kwds)
    630         # Lifting succeeded, so variables are initialized and we can run the
    631         # stateless function.
--> 632         return self._stateless_fn(*args, **kwds)
    633     else:
    634       canon_args, canon_kwds = \

~\anaconda3\envs\AINN\lib\site-packages\tensorflow_core\python\eager\function.py in __call__(self, *args, **kwargs)
   2361     with self._lock:
   2362       graph_function, args, kwargs = self._maybe_define_function(args, kwargs)
-> 2363     return graph_function._filtered_call(args, kwargs)  # pylint: disable=protected-access
   2364
   2365   @property

~\anaconda3\envs\AINN\lib\site-packages\tensorflow_core\python\eager\function.py in _filtered_call(self, args, kwargs)
   1609          if isinstance(t, (ops.Tensor,
   1610                            resource_variable_ops.BaseResourceVariable))),
-> 1611         self.captured_inputs)
   1612
   1613   def _call_flat(self, args, captured_inputs, cancellation_manager=None):

~\anaconda3\envs\AINN\lib\site-packages\tensorflow_core\python\eager\function.py in _call_flat(self, args, captured_inputs, cancellation_manager)
   1690       # No tape is watching; skip to running the function.
   1691       return self._build_call_outputs(self._inference_function.call(
-> 1692           ctx, args, cancellation_manager=cancellation_manager))
   1693     forward_backward = self._select_forward_and_backward_functions(
   1694         args,

~\anaconda3\envs\AINN\lib\site-packages\tensorflow_core\python\eager\function.py in call(self, ctx, args, cancellation_manager)
    543               inputs=args,
    544               attrs=("executor_type", executor_type, "config_proto", config),
--> 545               ctx=ctx)
    546         else:
    547           outputs = execute.execute_with_cancellation(

~\anaconda3\envs\AINN\lib\site-packages\tensorflow_core\python\eager\execute.py in quick_execute(op_name, num_outputs, inputs, attrs, ctx, name)
     65     else:
     66       message = e.message
---> 67     six.raise_from(core._status_to_exception(e.code, message), None)
     68   except TypeError as e:
     69     keras_symbolic_tensors = [

~\anaconda3\envs\AINN\lib\site-packages\six.py in raise_from(value, from_value)

InternalError:  Blas GEMM launch failed : a.shape=(32, 13), b.shape=(13, 64), m=32, n=64, k=13
     [[node sequential/dense/MatMul (defined at <ipython-input-15-b496e4002de6>:1) ]] [Op:__inference_distributed_function_747]

Function call stack:
distributed_function

Any idea about solving this problem?
Thank you.

A: That error often ocurs (atleast on my machine), when there are some kind of memory issues during training with gpu. That happens, as jakub already mentioned in the comments. You might want to restart your kernel and try again. If that does not help, try to decrease the batch size. Also check your gpu memory usage to see if the gpu has memory left (which would prove this).
The machine of your professor might have more gpu memory than yours, unfortunately tensorflow not also shows a proper out of memory exception.


text:
Q: System.OutOfMemoryException while MDX Query using Invoke-ASCmd i want to import a MDX result set into Powershell using Invoke-ASCmd.
Import-Module SQLPS -DisableNameChecking
Import-Module SQLASCMDLETS

Push-Location SQLSERVER:\SQLAS\$ServerInstance\Default\Databases\$Database\Cubes\

$result = Invoke-ASCmd -Database $Database -Query $Query

Pop-Location

It fails with a System.OutOfMemoryException

*

*The same MDX query works fine in SQL Server Management Studio.

*There is still a lot of RAM free.

*The Powershell runs in 64bit mode.

*MaxMemoryPerShellMB is increased.

*I am using SQL Server 2016 and Powershell 4

What's to do, to import large datasets from SQL Server Analysis Services using Powershell?

A: I found an workaround for this:
If you add a linked server to a SQL Server to the SSAS Cube you can execute it wrapped in SQL.
Invoke-Sqlcmd `
    -ServerInstance $ServerInstance `
    -Query "SELECT * FROM OpenQuery([SSAS_LinkedServer],'$( $query.Replace("'", "''" ) )')"

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to close opened transaction in rx-java and rxjava-jdbc to avoid TransactionAlreadyOpenException DbUtils.java
public final class DbUtils {

    private final static Database DATABASE = Database.from("jdbc:h2:mem:" + App.DB_NAME + ";INIT=runscript from '~/create.sql';MODE=ORACLE");

    public static Database database() {
        synchronized (Lock.class) {
            return DATABASE;
        }
    }

}

PersonService.java
public class PersonService {

    private final Database db;

    public PersonService(Database db) {
        this.db = db;
    }

    public Observable<Integer> insert(Person person) {
        Observable<Boolean> beginTransaction = db.beginTransaction();
        Observable<Integer> count = db.update("insert into person values (?, ?, ?, ?)")
                .dependsOn(beginTransaction)
                .parameters(person.getId(), person.getName(), person.getAddress(), person.getContact())
                .count();
        db.commit(count);
        return count;
    }

    //.......

}

PersonServiceTest.java
public class PersonServiceTest {

    final PersonService personService = new PersonService(DbUtils.database());

    public PersonServiceTest() {
    }

    @Test
    @DisplayName("@Person#insert()")
    public void testInsert() {
        Observable<Integer> insert1 = personService.insert(new PersonBuilder()
                .setId(1).setName("Bhuwan")
                .setAddress("KTM")
                .setContactNo("22222").createPerson()
        );
        insert1.subscribe((Integer count) -> {
            Person person = personService.find(1);
            System.out.println(person.toString());
            assertNotNull(person);
            assertEquals("Bhuwan", person.getName());
        });

        Observable<Integer> insert2 = personService.insert(new PersonBuilder()
                .setId(1).setName("BhuwanUpadhyay")
                .setAddress("Dhangadhi")
                .setContactNo("111111").createPerson()
        );

        insert2.subscribe((Integer count) -> {
            Person person = personService.find(1);
            System.out.println(person.toString());
            assertNotNull(person);
            assertEquals("BhuwanUpadhyay", person.getName());
        });
    }

}

I got following exception but i don't understand how to close opened transaction in rxjava-jdbc library. Please, anybody know how to close opened transaction on this library.
Caused by: com.github.davidmoten.rx.jdbc.exceptions.TransactionAlreadyOpenException
    at com.github.davidmoten.rx.jdbc.Database.beginTransactionObserve(Database.java:647)
    at com.github.davidmoten.rx.jdbc.QueryContext.beginTransactionObserve(QueryContext.java:45)
    at com.github.davidmoten.rx.jdbc.QueryUpdateOnSubscribe.performBeginTransaction(QueryUpdateOnSubscribe.java:115)
    at com.github.davidmoten.rx.jdbc.QueryUpdateOnSubscribe.call(QueryUpdateOnSubscribe.java:78)


text:
Q: Successive states with only one change without repetition of previous state I would like to build a piece of code that generates successive lists of ints which can take only two states: 0 or 1.
The contraint are the following:

*

*the state t+1 cannot be the same as state t

*the duo (t, t+1) cannot be retrieved

*bonus: all combinations of two successive changes are generated

Here is an example:
Let assume that I have at T0 a list with four ints: [0, 1, 1, 0]
The next state T1 CANNOT be [0, 1, 1, 0].
The next state T1 can be either:

*

*[1, 1, 1, 0]

*[0, 0, 1, 0]

*[0, 1, 0, 0]

*[0, 1, 1, 1]

The state T2 can be equals to whatever.
If T2 was equal to T0, the state T3 CANNOT be equals to what was in T1 in order to have a sequence different between (T0, T1) and (T2, T3).
I try to solve this problem from days, but cannot figure out how to. Any ideas?


text:
Q: Trying to prove that if two matrices with the same Eigenvectors are summed, the result has the same eigenvectors This is a proof I am tyring to work out:  A and B are square matrices, of same size.  I am trying to show that if the eigenvector V of both and A and B, then v is also an eigenvector of $ M = c_1 A + c_2 B $ and $c_1 , c_2$ are constants.  What is the eigenvalue of $M$?
My logic is as follows:  because it is a square matrix $n$ then the collection of eigenvectors $m = n$  then the matrices are diagonalisable.
$ D = P^{-1} AP$ and $D = P^{-1} BP$ and $D = P^{-1} MP$  therefore the equation shows that   $PDP^{-1} = c_1PDP^{-1} + c_2PDP^{-1}$  and that the eigenvalues of M corresponding to the eigenvector v is the diagonal $D = P^{-1}MP = diag(\lambda_1,...\lambda_n)$
Please let me know your thoughts.

A: That is way overkill. Matrix multiplication is a linear operation. If we let $M = c_1A + c_2B$ as you did above, what is $Mv$?
Look at this and try to apply the definition of eigenvectors. (A vector $v$ such that $Av = \lambda v$.)


text:
Q: Copy dialogue box issue in Ubuntu 17.04 I am relatively new to ubuntu and using Ubuntu 17.04 with Gnome DE. While I am copying the files, it's showing a small window (I don't know what we call that stuff) as in any other OS.

My problem is that every time I open a
new window by pressing Ctrl + N the same dialogue box will be there. Can I disable that feature/bug?


text:
Q: Priority Queue has no member named top()? Here is my comparator class:
template <class T>
class EdgeComparator{
    public:
        bool operator()(std::pair<Edge<T>, int>& lhs, std::pair<Edge<T>, int>& rhs) const{
            return lhs.second <= rhs.second;
        }
};

Here is my priority queue init:
//Initialize the priority queue
std::priority_queue<
    std::pair<Edge<T>,int>,
    std::vector<std::pair<Edge<T>,int>,
    EdgeComparator<T>>
> pQueue;

Here is where the error occurs--after a stream of weird error messages about the precompiler:
std::pair<Edge<T>, int> topEdge = pQueue.top();
./Prim.cpp:60:54: error: 'class std::priority_queue<std::pair<Edge<int>, int>, std::vector<std::pair<Edge<int>, int>, EdgeComparator<int> >, std::less<std::pair<Edge<int>, int> > >' has no member named 'top'
         std::pair<Edge<T>, int> topEdge = pQueue.top();

ATTEMPT 1(Added const to Comparator params):
template <class T>
class EdgeComparator{
    public:
        bool operator()(const std::pair<Edge<T>, int>& lhs, const std::pair<Edge<T>, int>& rhs) const{
            return lhs.second <= rhs.second;
        }
};

A: I think I've found one subtle mistake here:
std::priority_queue<
    std::pair<Edge<T>, int>,
    std::vector<std::pair<Edge<T>, int>,
                                     ^^
    EdgeComparator<T> > > pQueue;
                      ^^^

Looks like it should go this way:
std::priority_queue<
    std::pair<Edge<T>, int>,
    std::vector<std::pair<Edge<T>, int> >,
                                      ^^^^
    EdgeComparator<T> > pQueue;
                     ^^^

The first declaration doesn't build for me. Also, the error message speaks in favor of my suggestion. Look closely:
./Prim.cpp:60:54: error: 'class std::priority_queue<std::pair<Edge<int>, int>,
std::vector<std::pair<Edge<int>, int>, EdgeComparator<int> >,
std::less<std::pair<Edge<int>, int> > >' has no member named 'top'
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

It's using the standard comparator std::less<> instead of your own class EdgeComparator<>. Hence, I conclude that the comparator template parameter is missing from your declaration, and that is because it's standing in the wrong position due to the missing angular brace.


text:
Q: Home-Brew Server Farm and Remote Debugging I want to create a home-brew server farm, hosted on my own Windows 7 x64 box.  There would be three guest 2k8 Servers, one each to run IIS, a domain controller, and SQL Server 2k8 R2.  All guest machines would belong to a domain.  The host machine is in a workgroup (not in a domain), and has Visual Studio 2010 Ultimate installed.
I want to know:

*

*Can I remote debug (from the host machine in a workgroup) managed code on the guest OS (which is in a domain)?

*

*Any complications if I'm using VirtualBox?  I see a similar topic elsewhere, but it does not address the domain issue.

*Can I use the VMWare Workstation "integrated virtual debugger" to do the same (debug managed code on guest OS)?  Has VMWare started supporting this in VS 2010 yet?

Either way I need to take into account the workgroup-accessing-domain story I'd be dealing with.

A: You should be able to remote debug the guest OS's.  Take a look at this article on MSDN for information on cross-domain remote debugging, which I believe still applies with the host not actually being on a domain.  You simply ignore the fact either machine is on a domain and create like for like local accounts on the machines - all described in the aforementioned MSDN article.
If that creates problems for you, you can also disable authentication which seems to be a popular choice, despite being insecure:
http://communities.vmware.com/message/1617741
The article you linked in your post solves any networking issues so between that and the above you should be able to get the remote debugger up and running.
Is this question and answer any use regarding question 2?  I can't find anywhere a mention that the integrated VM remote debugger is actually available for 2010, but then I can't find any posts complaining that it isn't.  Perhaps it's just a closely guarded secret!?
EDI #19 or so:
Unfortunately I've found this article complaining that VS2010 isn't support by VSID. =(
Good luck!


text:
Q: AES encryption in Perl 6? I'm trying to convert a module writing in Python to Perl 6, I find there is no AES method in Perl 6:
from Cryptodome.Cipher import AES
import base64

def aes(text, key):
    pad = 16 - len(text) % 16
    text = text + bytearray([pad] * pad)
    encryptor = AES.new(key, 2, b"0102030405060708")
    ciphertext = encryptor.encrypt(text)
    return base64.b64encode(ciphertext)

Is there any module writing in Perl 6 that implemented AES method?

A: It seems that the OpenSSL module provides access to various AES ciphers. It depends on the openssl library being available (although on Windows I believe it downloads the DLL as part of the module installation process).
With that installed (zef install OpenSSL), one can:
use OpenSSL::CryptTools;

And then use encrypt/decrypt:
# Fake IV and key
my $iv = ('0' x 16).encode;
my $key = ('xy' x 16).encode;

# Encrypt.
my $ciphertext = encrypt("asdf".encode, :aes256, :$iv, :$key);
say $ciphertext;

# Decrypt.
say decrypt($ciphertext, :aes256, :$iv, :$key).decode;

See these tests for more examples.


text:
Q: resume a paused mp3 file in c# winforms using WMPLib.WindowsMediaPlayer with WMPLib.WindowsMediaPlayer i am able to play and pause mp3 files but i am not able to resume from the paused point.
Can anybody tell me how to resume the song
thanks

A: Actually I think that it's quiet easy I use the "Pause" method to pause the song and "Play" method to continue it ::: here is the code that I've used
WMPLib.WindowsMediaPlayer wmp = new WMPLib.WindowsMediaPlayer();
wmp.url="the mp3 path that you want to play";
//NOTE::: after the above command the mp3 file or other multimedia file will automatically play.

//And for PAUSING use this code:
wmp.controls.pause();

//AND for continue PLAYING use below code:
wmp.controls.play();

this code works for me and I hope that works for you.

A: The solution is change media players. Add a reference to this player:AxWMPLib.AxWindowsMediaPlayer. I found a reference in  This project.
I simply changed the player reference. Tweaked the properties: This "moPlayer.Controls.pause()" became "moPlayer.Ctlcontrols.pause()" and I was in business. I hope this helps. I did this and my player can pause and resume.


text:
Q: Javascript Shortcode Parse I need to parse following shortcode, for example my shortcode is :
[shortcode one=this two=is three=myshortcode]

I want to get this, is and myshortcode and add to array so it will :
['this', 'is', 'myshortcode']

NOTE : I know generally shortcode parameter marked with " and " ( ie [shortcode one="this" two="is" three="myshortcode"] ), but I need to parse shortcode above without ""
Any help really appreciated

A: I'm assuming you want to parse the first string with Regex and output the three elements  in order to add them to an array later. That seems rather simple, or am I misunderstanding what you need? I'm assuming the word shortcodeis as it will be in your string. You'd probably need two regex operations if you haven't located and isolated the shortcode string yet that you posted above:
/\[shortcode((?: \S+=\S+)+)\]/

Replacement: "$1"
If you already have the code exactly as you posted it, then you can skip the regex above. At any rate, you'll have end with the following regex:
  / \S+=(\S+)(?:$| )/g

You can then add all the matches to your array.
If this is is not what you're looking for, then perhaps a more real example of your code would help.

A: var str="[shortcode one=this two=is three=myshortcode]";
eval('var obj=' + str.replace(/shortcode /,"").replace(/=/g,"':'").replace(/\[/g,"{'").replace(/\]/g,"'}").replace(/ /g,"','"));
var a=[];
for(x in obj) a.push(obj[x]);
console.log(a);

You can try the above code.

A: Here's my solution: https://jsfiddle.net/t6rLv74u/
Firstly, remove the [shortcode and trailing ]
Next, split the result by space " "
After that, run through the array and remove anything that's on and before =, .*?=.
And now you have your result.

A: Here you go I have built a perfectly scalable solution for you. The solution works for any number of parameters.

function myFunction() {
    var str = "[shortcode one=this two=is three=myshortcode hello=sdfksj]";
var output = new Array();
    var res = str.split("=");
for (i = 1; i < res.length; i++) {
var temp = res[i].split(" ");
if(i == res.length-1){
temp[0] = temp[0].substring(0,temp[0].length-1);
}
output.push(temp[0]);
}
    document.getElementById("demo").innerHTML = output;
}
<button onclick="myFunction()">Try it</button>


text:
Q: Change spacing between legend border and legend title I am attempting to save a plot as a metafile (*.emf) using RStudio.  The formatting of the plot looks okay in the *.emf file except that there is no gap between the top border of the legend and the legend title.  How can I add such a gap?  I am using base R.
Here is the code.  I cannot upload an *.emf file to Stack Overflow.
cov       <- 1:20

B0.1      <-  0.2
B1.1      <-  0.2
B0.2      <- -0.2
B1.2      <-  0.1
B0.3      <- -0.6
B1.3      <- -0.02

y.1 <- exp(B0.1 + B1.1 * cov) / (1 + exp(B0.1 + B1.1 * cov))
y.2 <- exp(B0.2 + B1.2 * cov) / (1 + exp(B0.2 + B1.2 * cov))
y.3 <- exp(B0.3 + B1.3 * cov) / (1 + exp(B0.3 + B1.3 * cov))

par(mfrow=c(1,1), pty="s")

plot(cov, y.1, bty = "l", type = 'l', col = 'black', lwd = 2, lty = 1,
     xlab = 'Cov', ylab = 'Probability', ylim=c(0,1))

     lines(cov, y.2, type = 'l', col = 'black', lwd = 2, lty = 2)
     lines(cov, y.3, type = 'l', col = 'black', lwd = 2, lty = 3)

     abline(v = 10, lwd = 2, lty = 6)

     title('My Plot')

     op <- par(cex = .67)

     legend("bottomright",          c('Prob 1', 'Prob 2', 'Prob 3'),
                              col = c("black", "black", "black"),
                              lty = c(1, 2, 3),
                              lwd = c(2, 2, 2),

                              y.intersp = c(1.5, 1.5, 1.5),

                              title = "Legend", cex = 1.00, text.width = 2.50)

A: Print the border of the legend afterwards with your own positions:
First a legend without a border (set bty to "n" ), save the positions in "a":
a <- legend("bottomright",c('Prob 1', 'Prob 2', 'Prob 3'),
       col = c("black", "black", "black"),
       lty = c(1, 2, 3),bty="n",
       lwd = c(2, 2, 2),
       y.intersp = c(1.5, 1.5, 1.5),
       title = "Legend", cex = 1.00, text.width = 2.50)

Define your own positions of the rectangle:
rect(a$rect$left, a$rect$top-a$rect$h[1], a$rect$left+a$rect$w, a$rect$h[1])


text:
Q: Python script freezes randomly I'm using python 3.7 (64 Bit) on windows 10. My script works well, it just freezes sometimes during writing to the database. Sometimes it writes over 100k rows, sometimes it freezes at 5000 or something like that. It is just randomly and i don't know why.
Here is my code:
import mysql.connector
import datetime
from math import log2
import time

corporaDb = mysql.connector.connect(
    host="localhost",
    user="root",
    passwd="root"
)
dictionaryDb = mysql.connector.connect(
    host="localhost",
    user="root",
    passwd="root",
    database="dictionaries"
)
dictionaryDatabaseName = "dictionaries"
corpus = "deu_news_2015"

corporaCursor = corporaDb.cursor()
dictionaryCursor = dictionaryDb.cursor()

lang = corpus[:3]
print(lang)
print(datetime.datetime.now().time())
query = "SELECT freq FROM "+corpus+".words order by freq desc LIMIT 1"
corporaCursor.execute(query)
freqMax= corporaCursor.fetchone()
freqMax = freqMax[0]

query = "SELECT w.freq, t.translation_id FROM "+dictionaryDatabaseName+".word_translations t INNER JOIN "+corpus+".words w ON t.translation = w.word where target_language = '"+lang+"' LIMIT 2700000, 2000000"
corporaCursor.execute(query)
result = corporaCursor.fetchall();
i= 0
for row in result:
    if(i % 1000 == 0):
        print(i)
    if(row[0] != "None"):
        try:
            frequencyClass = round(log2(freqMax/row[0]))
            query = "UPDATE word_translations SET freq = "+str(row[0])+", available = 1, freq_class = "+str(frequencyClass)+" WHERE translation_id = '"+str(row[1])+"'"
            dictionaryCursor.execute(query)
            if(i % 100 == 0):
                dictionaryDb.commit()
        except:
            dictionaryCursor.close()
            print ("fehler")
            time.sleep(30)
            dictionaryCursor = dictionaryDb.cursor()
            pass
    i+=1

corporaDb.close()


text:
Q: Simulating the feedback network in constant-current step-down converter I'm analysing a (real) step-down converter which gives a constant-current output and want help in how to simulate the feedback circuit, in the abstract.
The real circuit has an ST L5973AD (datasheet), with feedback circuit from ST Application Note 2823 Figure 5 with R1=2.8 kΩ, R6=1.4 kΩ, and Rsense of 0.68 Ω.  Per application note equation 4, it should give 298 mA with these values (measured values within tolerence.)  The internal error amplifier has a voltage ref of 1.235 V.
How do we simulate this? (In Circuit Lab or anythign else.)  Surely a voltage-controlled voltage source is required.  But I don't see how how to choose the multiplier.  A crazy value of 109 seems to give plausible answers, but what is the correct way to do this?

simulate this circuit – Schematic created using CircuitLab

Edit Take 2 to add circuit in response to Andy Aka's answer: do you mean something like this, with comp left of LC?

simulate this circuit
Andy's comment said this was wrong

A:
A crazy value of \$10^9\$ seems to give plausible answers, but what is
the correct way to do this?

\$10^9\$ is high but \$10^3\$ wouldn't be a million miles off. If you look at the data sheet they say the error amplifier has a DC open-loop gain of 57 dB and that is a real-number gain of 708: -

So, you can use the VCVS with that gain but you would also need to add the inductor and output capacitor so that the stability of the circuit can be checked. And, of course, if the L and C are added it may become unstable hence you should add the compensation components shown in figure 5: -

Then, to implement the compensation circuit you'd need to model the error amplifier as a voltage to current converter as per this: -

The E/A in the diagram implies an error voltage to current converter and the output voltage develops across the compensation components shown earlier.
But, on the plus side, you don't need to model the switching parts if you just want to prove the dynamics of the control system. In other words it can be modelled as a linear regulator to get a decent fix on performance.
It all depends on how far you want to go.
All images in this answer are taken from links in the question.


text:
Q: Почему результат сравнения строк неправильный? Сравниваю так:
String s = "-123";
Boolean y = false;
if ("-".equals(s.charAt(0))){
    y = true;
}

Результат: y=false
Почему?

A: Потому что Вы сравниваете разные типы.
Метод charAt(...) возвращает значение типа char, которое автоупаковывается в объектный Character и Вы этот объект сравниваете со объектом типа String, в результате несовпадения типов Вы и получаете такой результат.
Посмотрите исходный код метода String.equals(...):
public boolean equals(Object anObject) {
    if (this == anObject) {
        return true;
    }
    if (anObject instanceof String) {
        String anotherString = (String)anObject;
        int n = value.length;
        if (n == anotherString.value.length) {
            char v1[] = value;
            char v2[] = anotherString.value;
            int i = 0;
            while (n-- != 0) {
                if (v1[i] != v2[i])
                    return false;
                i++;
            }
            return true;
        }
    }
    return false;
}

Первое условие ложно, второе – тоже ложно, в результате метод возвращает false.
Добиться желаемого поведения, можно, например, так:
if ("-".equals(String.valueOf(s.charAt(0)))){
    y = true;
}

UPD:

Мне нужно узнать, есть ли в строке определенный символ?

String s = "123";
char c = '2';
boolean contains = s.contains(String.valueOf(c));

или так:
String s = "123";
String c = "2";
boolean contains = s.contains(c);

A: Метод .charAt() ожидаемо возвращает не String, а char, который упаковывается (boxing) в класс Character. Character сам по себе не равен строке, даже если строка состоит из одного этого символа - это было бы неверно даже семантически, потому что строка, например, реализует интерфейс CharSequence.


text:
Q: JSONObjectWithData wrong decimal places while parsing In one of my api I am getting below response form server (If convert data into string)
{"success":true,"order_id":102232,"Total":68.6,"delivery_time":"7:30PM-10:00PM","delivery_date":"2016-03-25"}

But when I used the same with
[NSJSONSerialization JSONObjectWithData:data options:self.readingOptions error:&serializationError];

Its return
{
Total = "68.59999999999999";
"delivery_date" = "2016-03-25";
"delivery_time" = "7:30PM-10:00PM";
"order_id" = 102232;
success = 1;

}
Due to multiple places after decimal in total field its creating problem in calculation.
I think the JSON serialization method converting it internally but don't know how to resolve this

A: @gnasher hinted at the issue, but didn't explain it in detail.
Computers use binary floating point to represent floating point numbers internally.
A floating point number is usually stored as either a float or a double. On most 64 bit platforms a float is stored in 4 bytes and a double is stored in 8 bytes.
Binary floating point can't represent many decimal values exactly. Internally, 68.6 is represented in binary as a value that works out to 68.59999999999999 in decimal. That is the closest that a computer can get to 68.6 when saving your value as a float.
Binary floating point values like floats and doubles do not have a "number of decimal places." The value gets converted to decimal for display, or for conversion to a string, and there is always the potential for rounding errors in that conversion.
Take this code for example:
float aFloat = 68.6;
NSLog(@"aFloat = %f", aFloat);

That displays:
aFloat = 68.599998

However, this code:
NSLog(@"aFloat (1 decimal place)= %.1f", aFloat);

Displays:
aFloat (1 decimal place)= 68.6

The JSON string you are parsing has numbers in it that are not in quotes. When you convert your JSON string to a Cocoa object, the value of "Total" gets saved as an NSNumber object, probably using a double type internally.
If you need to do math on your "Total" value then you need it to be a number.
If you want to avoid decimal conversion errors, change your server code to send the value "Total" as a string, (in quotes) not a numeric value. Then the JSONObjectWithData function will keep it as a string, "68.6"
In that case your JSON string would look like this:
{"success":true,"order_id":102232,"Total":"68.6","delivery_time":"7:30PM-10:00PM","delivery_date":"2016-03-25"}

You said "Due to multiple places after decimal in total field its creating problem in calculation." What problem? On the iOS side, or the server side?

A: This resolved my problem
NSNumberFormatter *fmt = [[NSNumberFormatter alloc] init];
[fmt setPositiveFormat:@"0.##"];
NSLog(@"%@", [fmt stringFromNumber:dataDict[@"Total"]]);

Output of this log is 68.6

A: Swift Got the same issue while parsing, backend team was sending decimal. Just covert it to Float.
let value = Float(48.9999999999)
print(value) // 49.0

let value = Float(48.9799999999)
print(value) // 48.98

A: You are using floating point arithmetic. What you are seeing is absolutely normal. You would have the exact same thing happening if you just assigned 68.6.
How do you resolve this? By learning about floating point arithmetic. But what problems do you actually see? Are you just panicking because you see loads of nines, or is there an actual problem?
What makes you actually think that converting the data back to JSON will produce something that the server misunderstands? Have you tried it? Are you worrying about a theoretical possibility, or do you have actual evidence of a problem? Clearly the server stored something rounded to one decimal.
I mean seriously do you get that what you are worrying about is the output of an NSLog statement?


text:
Q: Opinions: Viewbox I don't want to deal with varying screen resolutions in a WPF windows app. So, I came upon an approach which I believe deals with all of the various issues of the display - within reason.
The design of the window goes like this:
<Window x:Class="MyWindow.Window3"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        mc:Ignorable="d" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" d:DesignHeight="872" Title="My Window" SizeToContent="Manual" WindowState="Maximized" d:DesignWidth="1242"
        Height="768" Width="1024" VerticalAlignment="Stretch" Closing="Window_Closing" Icon="Icon.ico" WindowStyle="ThreeDBorderWindow">

    <Grid>
        <Viewbox HorizontalAlignment="Left" VerticalAlignment="Top" StretchDirection="Both">
<!-- your controls go here -->

        </Viewbox>
    </Grid>
</Window>

With this approach, the window is scaled to align to the display, regardless of the resolution. There are corner cases, which should be mentioned;

*

*If the window is minimized to a very small resolution, it will be unusable, as the controls are dramatically scaled down.

*If the window is designed in a different aspect ratio than the target, then there is likely to be a large amount of whitespace displayed
Apart from the potential negative constraints called out, I am very happy with the results at this point. I don't need to worry about scrollbars, or various scaling options - it just works!
I can't be the first person to discover this, but I have not seen this approach mentioned anywhere before. I am still a newbie in the world of C#, and this is a recent discovery.
I would like to hear about negatives to the approach which I have not considered here, and hope that this will help others in their design efforts.
Thanks to all......

A: It should be the user's choice how big the elements are. He can change the DPI or the resolution (although this may not be such a good idea with LCDs, it worked well with CRTs). If he wants to be able to see lots of information in smaller font, let him do it.
If he has tiny display, you should display scrollbars, not illegibly small font.


text:
Q: PHP feedback form not sending email I have created a feedback form for a website, the below code executes when i try to send the form and comes back as been completed successfully but when I check my emails no email has been received. Any help would be greatly appreciated.
HTML form:
<form action="send_form_email.php" method="post" name="contactform">

                First Name *

                <input maxlength="50" name="first_name" size="30" type="text">

                Last Name *

                <input maxlength="50" name="last_name" size="30" type="text">

                Email Address *

                <input maxlength="80" name="email" size="30" type="text">

                Telephone Number

                <input maxlength="30" name="telephone" size="30" type="text">

                Comments *

                <textarea cols="25" maxlength="1000" name="comments" rows="6"></textarea>

                <input type="submit" value="Submit">

    </form>

PHP:
<?php
if(isset($_POST['email'])) {

    // EDIT THE 2 LINES BELOW AS REQUIRED
    $email_to = "email";
    $email_subject = "Your email subject line";

    function died($error) {
        // your error code can go here
        echo "We are very sorry, but there were error(s) found with the form you submitted. ";
        echo "These errors appear below.

";
        echo $error."

";
        echo "Please go back and fix these errors.

";
        die();
    }

    // validation expected data exists
    if(!isset($_POST['first_name']) ||
        !isset($_POST['last_name']) ||
        !isset($_POST['email']) ||
        !isset($_POST['telephone']) ||
        !isset($_POST['comments'])) {
        died('We are sorry, but there appears to be a problem with the form you submitted.');
    }

    $first_name = $_POST['first_name']; // required
    $last_name = $_POST['last_name']; // required
    $email_from = $_POST['email']; // required
    $telephone = $_POST['telephone']; // not required
    $comments = $_POST['comments']; // required

    $error_message = "";
    $email_exp = '/^[A-Za-z0-9._%-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4}$/';
  if(!preg_match($email_exp,$email_from)) {
    $error_message .= 'The Email Address you entered does not appear to be valid.
';
  }
    $string_exp = "/^[A-Za-z .'-]+$/";
  if(!preg_match($string_exp,$first_name)) {
    $error_message .= 'The First Name you entered does not appear to be valid.
';
  }
  if(!preg_match($string_exp,$last_name)) {
    $error_message .= 'The Last Name you entered does not appear to be valid.
';
  }
  if(strlen($comments) < 2) {
    $error_message .= 'The Comments you entered do not appear to be valid.
';
  }
  if(strlen($error_message) > 0) {
    died($error_message);
  }
    $email_message = "Form details below.\n\n";

    function clean_string($string) {
      $bad = array("content-type","bcc:","to:","cc:","href");
      return str_replace($bad,"",$string);
    }

    $email_message .= "First Name: ".clean_string($first_name)."\n";
    $email_message .= "Last Name: ".clean_string($last_name)."\n";
    $email_message .= "Email: ".clean_string($email_from)."\n";
    $email_message .= "Telephone: ".clean_string($telephone)."\n";
    $email_message .= "Comments: ".clean_string($comments)."\n";

// create email headers
$headers = 'From: '.$email_from."\r\n".
'Reply-To: '.$email_from."\r\n" .
'X-Mailer: PHP/' . phpversion();
@mail($email_to, $email_subject, $email_message, $headers);
?>

Thank you for contacting us. We will be in touch with you very soon.

<?php
}
?>

A: check this code may be this will help you.
 // create email headers
$headers = 'From: '.$email_from."\r\n".
'Reply-To: '.$email_from."\r\n" .
'X-Mailer: PHP/' . phpversion();

          if(mail($email_to,  $email_subject, $email_message))
                  {

                        echo "";
                       }


text:
Q: Node looks up at a different path I have installed nodejs on my linux terminal. On typing nodejs -v I can see the version of node, but on typing node -v the terminal returns:
bash: /usr/local/bin/node: No such file or directory

When I search the following:
which node

I get the following result:
/usr/bin/node

The command 'node' looks up in a different directory from where it actually is and this also is causing a problem while installing npm.
Please help me out.


text:
Q: pylint W0622 (Redefining built-in) when overriding "standard" methods in subclasses In Python, many methods define argument variables with "standardized" names, like:
def __exit__(self, type, value, traceback):

In the line above, variable type causes pylint to warn (W0622) that a built-in is being redefined: Redefining built-in 'type' (redefined-builtin).
There are many ways to fix this and make pylint happy (rename the variable, add a pylint directive (# pylint: disable=W0622) to ignore the problem, etc.).
What is the best/preferred/suggested/conventionally-used way (if any) to maintain a good code quality and make pylint happy in these cases?

A: It could be considered as a bad practise to disable pylint warning.
Quoting quantifiedcode.com :

In order for __exit__ to work properly it must have exactly three arguments: exception_type, exception_value, and traceback. The formal argument names in the method definition do not need to correspond directly to these names, but they must appear in this order.

As such a good option could be to use tuple packing def __exit__(self, *exc)
This what is suggested in this official documentation:
https://docs.python.org/3/library/contextlib.html


text:
Q: Comparing number of identical column elements between two rows in Python I am trying to write a basic script that will help me to find how many similar columns there are between rows. The information is very simple, something like:
array = np.array([0 1 0 0 1 0 0], [0 0 1 0 1 1 0])

I would have to execute this script between all permutations of the list, so row 1 compared to row 2, row 1 compared to row 3, etc.
Any help would be greatly appreciated.

A: Your headline question can be addressed with basic numpy techniques. Let's assume you have a two-d numpy array a and you want to compare rows m and n:
row_m = a[m, :] # this selects row index m and all column indices, thus: row m
row_n = a[n, :]
shared = row_m == row_n # this compares row_m and row_n element-by-element storing each individual result (True or False) in a separate cell, the result thus has the same shape as row_m and row_n
overlap = shared.sum() # this sums over all elements in shared, since False is encoded as 0 and True as 1 this returns the number of shared elements.

The easiest way of applying this recipe to all pairs of rows is broadcasting:
 first = a[:, None, :] # None creates a new dimension to make space for a second row axis
 second = a[None, :, :] # Same but new dim in first axis
 # observe that axes 0 and 1 in these two array are arranged as for a distance map
 # a binary operation between arrays so layed out will trigger broadcasting, i.e. numpy will compute all possible pairs in the appropriate positions
 full_overlap_map = first == second # has shape nrow x nrow x ncol
 similarity_table = full_overlap_map.sum(axis=-1) # shape nrow x nrow

A: If you can rely on all rows being binary valued the "similar columns" count is simply
def count_sim_cols(row0, row1):
    return np.sum(row0*row1)

If there's the possibility of a wider range of values, you would just replace the product with a comparison
def count_sim_cols(row0, row1):
     return np.sum(row0 == row1)

If you would like a tolerance on "similarity", say tol, some small value, this is just
def count_sim_cols(row0, row1):
    return np.sum(np.abs(row0 - row1) < tol)

Then you can double-nested loop to get the counts. Assuming X is a numpy array with n rows
sim_counts = {}
for i in xrange(n):
    for j in xrange(i + 1, n):
        sim_counts[(i, j)] = count_sim_cols(X[i], X[j])


text:
Q: Yii and Git Repos I'm learning both Yii and Git at the same time, and am finding issues with my commits. I'm using BitBucket if that matters any.
Basically, if I create a project and commit to the repo, when I then try to pull that repo onto another machine, I start with a whole bunch of Yii runtime configuration errors.
I've found a way around it, but it seems messy. If I load an older commit of the repo from just after the project was added and delete the project manually then re-add it through the yii tools (yiic) I can overwrite it then with the updates from the most recent commit to get everything back.
This seems messy and like it's asking for trouble. Is there something I'm doing wrong here with Yii?
Edit
Below is the exact error message as it appears:
CException

Application runtime path "/Applications/MAMP/htdocs/yii-sandbox/projects/trackstar/protected/runtime" is not valid. Please make sure it is a directory writable by the Web server process.

/Applications/MAMP/htdocs/yii-sandbox/framework/base/CApplication.php(289)

277             return $this->_runtimePath;
278         }
279     }
280
281     /**
282      * Sets the directory that stores runtime files.
283      * @param string $path the directory that stores runtime files.
284      * @throws CException if the directory does not exist or is not writable
285      */
286     public function setRuntimePath($path)
287     {
288         if(($runtimePath=realpath($path))===false || !is_dir($runtimePath) || !is_writable($runtimePath))
289             throw new CException(Yii::t('yii','Application runtime path "{path}" is not valid. Please make sure it is a directory writable by the Web server process.',
290                 array('{path}'=>$path)));
291         $this->_runtimePath=$runtimePath;
292     }
293
294     /**
295      * Returns the root directory that holds all third-party extensions.
296      * @return string the directory that contains all extensions. Defaults to the 'extensions' directory under 'protected'.
297      */
298     public function getExtensionPath()
299     {
300         return Yii::getPathOfAlias('ext');
301     }

A: You have added your main.php configuration file to the git repository. That file contains per-host configuration settings that will likely not be valid if the file is transferred to another machine, as you are finding out.
The solution is to not include the live configuration file in the repository. Instead, include a reference configuration file (that won't be loaded by Yii) and copy its contents to a new main.php when you deploy. Here's what you need to do as the first step:
git mv main.php main.reference.php
git commit -m "renamed configuration file"

After this you also need to add the name /protected/config/main.php to the list of the files that git ignores, so that it won't bother you about unversioned files in your deployment directory. To do this, create a file named .gitignore in the root directory of your checkout and add the line
protected/config/main.php

A: try to use gitignore to put the user dependent files there so that these files will not be overridden while pulling and pushing


text:
Q: Mysql SQL Query Across 2 Tables - Not Sure How to Do It Properly I have 2 tables set up like this (irrelevant rows omitted):
> product
  - id
  - user_id

> thread
  - id
  - prod_id
  - user_id
  - due_date

now I want to create a query that picks all rows from thread table that either:

*

*have a thread.user_id of (for example) "5"

*have a prod_id where the product.user_id is "5"

I am assuming there is a way to do this, something like ...
SELECT
    thread.due_date
FROM
    product, thread
WHERE
    thread.user_id='5'
OR
    // not sure how to finish it

Up to this point, I would just use PHP to do this, but would really like to kick up my SQL knowledge a notch and get this working via SQL if possible.
Thanks -

A: You should be able to use an outer join to do this:
SELECT thread.* FROM thread
LEFT OUTER JOIN product
ON thread.prod_id = product.id
WHERE thread.user_id = 5 OR product.user_id = 5

A problem you might find is that you could get duplicate threads if a thread has a user id 5 but also a product with user id 5. Not sure if that will be an issue in your case though. You may be able to use SELECT DISTINCT to remove these (thanks  Alex Martelli)

A: I would do something like:
SELECT t.due_date
FROM thread t
INNER JOIN product p ON p.id = t.prod_id
WHERE t.user_id = 5 OR p.user_id = 5

Edit:
My example is using the SQL 92 standard.  If you'd like to stick with the SQL-89 style join from your original post you can do something like:
SELECT thread.due_date
FROM product, thread
WHERE product.id = thread.prod_id
AND (thread.user_id = 5 OR product.user_id = 5)

However, check out Beginning MySQL - it has some good information about the two standards.

A: SELECT thread.* LEFT OUTER JOIN product ON thread.prod_id=product.id WHERE thread.user_id=5 OR product.user_id=5;

I'm not sure about the SELECT thread.* but it makes sense since that table.* stuff works when GRANTing privileges.


text:
Q: displaying all table data mysql I have 6 tables which all contain student information.
table names: student details, doctor details, admission details, previous_school, fathers details, mothers details.
each of these tables contain an unique ID.
To bring all these tables into one i have a student_info table which contains all the id's from the above 6 tables. these are linked to the unique id's in the corresponding table.
I need to display all student information, i know i would use left join and right join, I just am not sure how mysql reads the id in student_info table and grabs all the information from the corresponding table allowing the user to see all the student information in one form.
thankyou in advance.

A: EDIT: http://sqlfiddle.com/#!2/c5489/2  (working example)
You don't need to put all of the ids in each table, rather each table would have its own primary key ID - guaranteed to be unique, and you would most likely join each table using an inner join
Table A(user_id int, user_name varchar(255))
Table B(student_id int, student_email varchar(255))

And then select the data you want, by using the relating ID's to join:
Select user_name from TableA
INNER JOIN TableB ON
TableA.user_id = TableB.student_id

A: You have to specify the joins to make this work:
select * from student, student_info where student_info.student_id = student.id

This tells the server to return all information from both tables, where the student id is matched by the student info's stored student id.
Here, I'm assuming that the student is a 1:many with student_info (where there is at least one, but can be multiple student info rows per student info).


text:
Q: Testing multiple hypotheses simultaneously Let $X_{ij}$ be data modeled by$X_{ij} \stackrel{\text{iid}}{\sim}N(\theta_j,\sigma_j^2), i=1,2,...,50, j=1,2,...,10$. We test $H_{0j}:\theta_j=0 $ against $H_{1j} : \theta_j\neq0$ for $j=1,2,...,10$ at a
level of $\alpha=0.05$. Generate $X_{ij}$ and test the hypothesis, replicate $1000$ times to get the familywise error rate.
I am trying to use R to implement my solution.
From my understanding our sample size will be $50$. So we can get the values like so:
r.norm <- rnorm(50)

We want to find the Type-I error (where $H_0$ is true but we reject the null hypothesis). I wrote the below to count how many time we have a false rejection. But that seems incorrect, because our mean will not be equal to $0$, although that is out null hypothesis. Is my logic to calculate FWER correct?
FWER.count <- 0

for(i in 1:1000) {
    for(j in 1:10) {
        r.norm <- rnorm(50)
        if(mean(r.norm) != 0) {
            if(t.test(r.norm)$p.value <= 0.05) {
                FWER.count <- FWER.count + 1;
                break
            }
        }
    }
}

FWER <- FWER.count/1000

Edit: Update FWER to have seperate variable for count and the probability. Also added a break to the loop, since we only need to know when one nulls in a group is falsely classified.

A: This my translation of your code snippet.
If the mean of the sample has a mean of zero (it matches the family mean). A t-test is performed. If the p value is less than or equal to $ \alpha $, increment FWER. However, sample mean would only get tested if it matched the mean from the family exactly. The p-values would be 1. The null hypothesis would never get rejected.
Note
FWER would need to be divided by n, to make it a probability. The FWER is the probability of making even one type I error.
To make your code check sample means against the family where the sample mean does not equal zero, then this line.
if(mean(r.norm) == 0)

Should be this.
if(mean(r.norm) != 0)

Why because with a small sample size, I highly doubt the mean would ever be zero. I ran a small test to check.
sapply(rep(50,10), function(x) mean(rnorm(x)))
[1] -0.007272193  0.101159429  0.001891395 -0.138410041 -0.083892761  0.124589734 -0.057765727  0.240548953 -0.072762234 -0.193889501

It gets close, but never zero exactly.
You probably don't even need that first if statement, the mean would rarely be zero and the t-test if statement would ignore any mean that was close to zero.


text:
Q: Can I use same name and IP in server 2016 migration? I'm going to upgrade some servers from 2008 to 2016 clean install, the servers are domain controllers and file server, is it possible to use the same name and ip when I turn off the old server, what's recommended in this case since many services will be pointing to the old name and IP?

A: Domain Controllers:  It is possible, but not recommended.  The clean build would need to be built from a backup / restore of the AD environment, and you would need to do all of your AD services / servers at the same time without the old servers online.  I won't describe the details here, Technet does that much more thoroughly than I could in a quick note.  A critical consideration is that the AD environment and service configuration includes SIDs, names and IP's across a whole host of settings, and the relationship between all of those is critical for AD services to continue to replicate and work correctly.
A more common practice (and easier, frankly) is to build a new clean machine (new name, new IP), add the AD service(s), promote the server (which adds the server to the AD environment and updates the AD database in a coordinated way) and then demote and remove the old server.  See Technet for the instructions on promotion/demotion.
If you have services that are hard configured to Name/IPs, I would recommend you update those to use DNS, DHCP or similar dynamic source records.  Once you do that, you make your life easier in so many ways.
File Servers: Are you using any DFS services?  If not, it is possible, and relatively straight forward.  Build the new server with a temporary name and IP, add services, replicate your data on the new server, rename the old server to a temporary name and IP, rename the new server to the original name and update IP to the original IP.
If you are using DFS, I would recommend you use the DFS service configuration to add a new  file server (new name and IP) to the DFS-N scheme, then use DFS-R to replicate the shared files.  Once you have replicated all data, then you can remove the old server from the DFS-N scheme and DFS-R replica.  Once removed you can delete the server.
Since you are asking these question, I recommend you look into use of DFS for file shares, and eliminate dependencies on fixed names/IPs.


text:
Q: UART 3 Will Not Accept 5th Byte The chip in question is PIC24FJ256GB210
It is a 100-Pin TQFP form factor
We have an embedded system with two microprocessors.
The two microprocessors use a UART to communicate Which is (according to me) mapped to UART #3 on the PIC24.
I place 4 bytes into UART #3. All goes well.  The 5th byte will not go in.
I say FIFO backup.
My local hardware expert says that if I turn off flow control that the bytes will go out no matter what.
Is this true ? I've never heard that one before. I thought it was a hardware signal on the other side; i.e., a read signal has to occur on the other side before the FIFO buffer would allow room on this side.
His definition of "turn off flow control" is for me to not use PPS (Peripheral Pin Select) to map either the RTS (Request to Send) or CTS (Clear To Send) pins to their corresponding physical pin on the board.
I did that. Result: no change; the FIFO buffer still fills up. The "#UTXBF" bit never clears after the fourth byte goes in.
I have the schematic diagram with physical pins numbered and labeled.
I have the source code and MpLab showing the executable down at the register level, right at the assembly language instructions themselves.
I am mapping the pins of UART #3 exactly and identically to the manner that I am mapping UART #2 and UART #1, and both of those other two work perfectly.
While the numbers are different, the instruction sequences are identical. The numbers match the pins.
I am debugging this for the third time, watching each bit in each register and comparing them against the manual to make sure that I have the correct corresponding numbers in the correct bit positions in the correct special function registers.
This is from MpLab's disassembler window where the opcodes show exactly which bits are set and cleared.
 206CC1     mov.w #0x6cc,0x0002            Mov     #Uart_3_Tx_PPS_Output_Register, W1              ;This is the register we want
 21C002     mov.w #0x1c00,0x0004           Mov     #Uart_3_Tx_Or_In_Bit_Pattern, W2                ;These are the bits we want on
 2C0FF3     mov.w #0xc0ff,0x0006           Mov     #Uart_3_Tx_And_Off_Bit_Pattern, W3              ;These are the bits we want off

 780211     mov.w [0x0002],0x0008          Mov     [W1], W4                                        ;The existing pattern
 618204     and.w 0x0006,0x0008,0x0008     And     W3, W4, W4                                      ;Turn existing bits off
 710204     ior.w 0x0004,0x0008,0x0008     Ior     W2, W4, W4                                      ;Turn Desired bits on
 780884     mov.w 0x0008,[0x0002]          Mov     W4, [W1]                                        ;And that's all there is to it

After execution, RPOR6 (which is the Uart_3_Tx_PPS_Output_Register) contains 0x1C06
This is from the inc file that is used to create the masks and patterns. (I try to avoid hard coding numbers in the source files which have the actual instructions.)
 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
 ;;                                                                                ;;
 ;;                                                                                ;;
 ;;    Map UART # 3 Tx Pin                                                                  ;;
 ;;                                                                                ;;
 ;;    Docs for this are: Manual DS39975A                                                   ;;
 ;;                                                                                ;;
 ;;    Find "TABLE 2: COMPLETE PIN FUNCTION DESCRIPTIONS FOR 100-PIN DEVICES"               ;;
 ;;    in Manual DS39975A, Page 8, where We find the secret PIC Pin Names for               ;;
 ;;    the actual physical pin numbers                                                      ;;
 ;;                                                                                ;;
 ;;    TABLE 10-4: SELECTABLE OUTPUT SOURCES (MAPS FUNCTION TO OUTPUT)                      ;;
 ;;    Page 160, We find the output function numbers                                        ;;
 ;;                                                                                ;;
 ;;                                                                                ;;
 ;;                                                                                ;;
 ;;                                   PIC     Associated             Output                 ;;
 ;;    Circuit           Physical     PIN     Control       Actual   Func.                  ;;
 ;;    Function          Pin          NAME    Reg           Bits     Number                 ;;
 ;;    ------------      ------       -----   -------       ----     -----                  ;;
 ;;                                                                                ;;
 ;;    UART #3, TX       Pin 23       RP13    RPOR6         3F00     28         Output      ;;
 ;;                                                                                ;;
 ;;                                                                                ;;
 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;

I combined that knowledge with these notes from the family data sheet to create the constants with meaningful names.
    .Equiv  Uart_3_Tx_PPS_Output_Register,  RPOR6           ;Register 10-35, Page 177
    .Equiv  Uart_3_Tx_Reg_Control_Bits,     0x3F00          ;Look for "RP13R" in the big include file               ;;;DEBUG DEBUG Date: 2013-02-05  Time: 20:47:02
    .Equiv  Uart_3_Tx_Output_Func_Number,   28              ;From Table 10-4, P. 160

    .Equiv  Uart_3_Tx_And_Off_Bit_Pattern,                  ~(Uart_3_Tx_Reg_Control_Bits)
    .Equiv  Uart_3_Tx_Or_In_Bit_Pattern,                    ( Uart_3_Tx_Output_Func_Number << RP13R0 )

From the File: "p24FJ256GB210.inc" (no quotes)
 ;----- RPOR6 Bits -----------------------------------------------------
         .equiv RP12R0,  0x0000
         .equiv RP12R1,  0x0001
         .equiv RP12R2,  0x0002
         .equiv RP12R3,  0x0003
         .equiv RP12R4,  0x0004
         .equiv RP12R5,  0x0005
         .equiv RP13R0,  0x0008    ;;; <<<<<----- RP13 is in the right place
         .equiv RP13R1,  0x0009
         .equiv RP13R2,  0x000A
         .equiv RP13R3,  0x000B
         .equiv RP13R4,  0x000C
         .equiv RP13R5,  0x000D

After all is said and done, with or without RTS or CTS enabled, the PIC on the other side of the UART apparently never sees the first byte that I put in on this side.
Does anyone see anything where I put the wrong bit in the wrong place ?
At this moment, I cannot confidently answer yes or no to this question: Is the UART #3 TX function correctly connected to physical Pin 23 on a 100-Pin TQFP configured PIC24FJ256GB210 ?
Thanks a ton if you can identify what's going on here.

A: Here is where I found the error and the answer to the problem
Look at special function register U3STA
Look for the bit UTXEN
It must be set.
If not, you will fill the FIFO and clog it up after the 4th byte.
The UTXEN is bit #10. The assembler and compiler will probably change it to #2 in the next higher numbered byte.

A: There is a errata issued from MicroChip about this behaviour on PIC24 microcontroller.
refer: http://ww1.microchip.com/downloads/en/DeviceDoc/80522c.pdf.
Page 4 of the document indicates that:
Module: UART (TX Buffer)
If the transmit buffer is filled sequentially with
four characters, the characters may not be
transmitted in the correct order.
Work around
Do not completely fill the buffer before transmit-
ting data; send three characters or less at a
time.

Another work arround is suggested by a developer to use the TRMT flag instead, refer to: http://www.microchip.com/forums/m622420-print.aspx
Hope it helps.

A:
My local hardware expert says that if I turn off flow control that the bytes will go out no matter what.

Yes, that's true.  But that takes time, serial ports are very slow.  Getting one byte transmitted from the fifo takes an eternity, about a millisecond at 9600 baud.  Which is why UARTs are normally fed from a larger buffer by an interrupt handler.


text:
Q: Query Too Complex, despite it only containing 5 linked queries and one table I've looked into this issue and have not found a solution for my issue. I've analyzied the SQL code and cannot find any issues (I'm not good at SQL) and have spent about 2 hours trying to solve the issue but I cannot figure it out.
The table is used for a video game, it is a database for keeping track of shooting range scores in Ravenfield. I'll go ahead and post the SQL for someone to anaylize.
The table is set up by joining multiple queries together, however, they're not complex queries, and the data is fairly simple. The main table is the weapon information table, and the rest are the range tables.
Here is the sql for those who want to look at it to tell me if something is wrong with my SQL:
SELECT [Weapon Information].[Weapon Name], [Weapon Information].[Weapon ID], [Weapon Information].[Sub ID], [Weapon Information].[Based On], [Weapon Information].[Country of Origin], [Weapon Information].Type, [Weapon Information].Caliber, [Weapon Information].Capacity, [Weapon Information].Manufacture, [Pistol-1 Final]![Final Score]+[Rifle-1 Final]![Final Score]+[Indoor Range Final]![Final Score]+[Testing Field Final]![Final Score]+[CQB-2 Final]![Final Score] AS [Final Score], [Pistol-1 Final]![Final hits]+[Rifle-1 Final]![Final hits]+[Indoor Range Final]![Final hits]+[Testing Field Final]![Final hits]+[CQB-2 Final]![Final hits] AS [Final Hits], [Pistol-1 Final]![Final Misses]+[Rifle-1 Final]![Final Misses]+[Indoor Range Final]![Final Misses]+[Testing Field Final]![Final Misses]+[CQB-2 Final]![Final Misses] AS [Final Misses], [Final Hits]/[Final Misses] AS [Final Accuracy]
FROM (((([Weapon Information] INNER JOIN [Pistol-1 Final] ON ([Weapon Information].[Sub ID] = [Pistol-1 Final].[Sub ID]) AND ([Weapon Information].[Weapon ID] = [Pistol-1 Final].[Weapon ID]) AND ([Weapon Information].[Weapon Name] = [Pistol-1 Final].[Weapon Name])) INNER JOIN [Rifle-1 Final] ON ([Weapon Information].[Sub ID] = [Rifle-1 Final].[Sub ID]) AND ([Weapon Information].[Weapon ID] = [Rifle-1 Final].[Weapon ID]) AND ([Weapon Information].[Weapon Name] = [Rifle-1 Final].[Weapon Name])) INNER JOIN [Indoor Range Final] ON ([Weapon Information].[Sub ID] = [Indoor Range Final].[Sub ID]) AND ([Weapon Information].[Weapon ID] = [Indoor Range Final].[Weapon ID]) AND ([Weapon Information].[Weapon Name] = [Indoor Range Final].[Weapon Name])) INNER JOIN [Testing Field Final] ON ([Weapon Information].[Sub ID] = [Testing Field Final].[Sub ID]) AND ([Weapon Information].[Weapon ID] = [Testing Field Final].[Weapon ID]) AND ([Weapon Information].[Weapon Name] = [Testing Field Final].[Weapon Name])) INNER JOIN [CQB-2 Final] ON ([Weapon Information].[Sub ID] = [CQB-2 Final].[Sub ID]) AND ([Weapon Information].[Weapon ID] = [CQB-2 Final].[Weapon ID]) AND ([Weapon Information].[Weapon Name] = [CQB-2 Final].[Weapon Name]);

A: You've got NULL data somewhere. The query analyzer hits the NULL data, can't complete the query plan, and crashes out. Fix it by wrapping with ISNULL where required -- or restructure using a table so that the query analyzer doesn't try to move up the selection criteria to a place where it's not valid. (Also, replace all those ! with . )


text:
Q: Lonely Integer Specific Solution The Lonely Integer assumes an array with an odd number of elements. With every element occurring twice except for one element. The task is to find this 'lonely' element.
Within the Discussion section on HackerRank for this challenge, a working solution was suggested
int lonelyinteger(vector<int> a) {
    int r = 0;
    for (auto v : a) {
        r ^= v;
    }
    return r;
}

I am trying to understand this solution and added console output during each step to try to see what is going on, but I can't quite wrap my head around it.
^ is the XOR operator but I do not understand how ^= would work.
In addition to this, the condition within the for loop is hard for me to understand as well. Is there a more beginner way to write this? I assume that it is simply iterating through the array?

A: First, understand that XOR carries several properties you're probably familiar with. But in case your not

*

*Identity: N ^ 0 == N

*Self-inverse: N ^ N == 0

*Associative: A ^ (B ^ C) == (A ^ B) ^ C

*Commutative: A ^ B == B ^ A

Now, consider we have a sequence of, say five elements:
a b c a b

XOR'ing these in sequence yields (obviously):
a ^ b ^ c ^ a ^ b

Now, per the properties previously described this can be rewritten as:
a ^ a ^ b ^ b ^ c

However, we already know that a ^ a is zero (0), and likewise for b ^ b.  Therefore, this becomes.
0 ^ 0 ^ c

which becomes
0 ^ c

which finally becomes
c

The odd-man out.
Regarding what operator ^= does. It is nothing more than shorthand for modify-and-store. E.g.
r ^= v

is equivalent to:
r = r ^ v


text:
Q: dynamic textbox and save to database in c#.net i have a backend where an administrator will store a value suppose 10. i want to populate 10 dropdown dynamically and save it to the database.
here is the codes but i've hardcoded it.
    <%@ Page Title="" Language="C#" MasterPageFile="~/Site1.Master" AutoEventWireup="true"
    CodeBehind="student_project_choice.aspx.cs" Inherits="Final_Year_Project_Allocation_System.student_project_choice" %>

<asp:Content ID="Content3" ContentPlaceHolderID="BodyContent" runat="server">

                                Choice number

                                Project titles

                                Demand

                                1

                                <asp:DropDownList ID="DropDownList1" runat="server"
                                    DataSourceID="SqlDataSource1" DataTextField="projectTitle"
                                    DataValueField="lecturerProjectId"
                                    onselectedindexchanged="DropDownList1_SelectedIndexChanged"
                                    AutoPostBack="True">
                                </asp:DropDownList>
                                <asp:SqlDataSource ID="SqlDataSource1" runat="server"
                                    ConnectionString="<%$ ConnectionStrings:UomDBConnectionString1 %>"
                                    SelectCommand="SELECT * FROM [tbl_lecturer_project]"></asp:SqlDataSource>

                            <asp:ScriptManager ID="ScriptManager1" runat="server">
                             </asp:ScriptManager>
                                <asp:UpdatePanel ID="UpdatePanel1" runat="server">
                                <ContentTemplate>
                                    <asp:Label ID="lblDemand" runat="server" Text=""></asp:Label>
                                </ContentTemplate>
                                    <Triggers><asp:AsyncPostBackTrigger ControlID="DropDownList1" EventName="SelectedIndexChanged"/></Triggers>
                                </asp:UpdatePanel>

                                2

                                <asp:DropDownList ID="DropDownList2" runat="server"
                                    DataSourceID="SqlDataSource1" DataTextField="projectTitle"
                                    DataValueField="lecturerProjectId">
                                </asp:DropDownList>

                                3

                                <asp:DropDownList ID="DropDownList3" runat="server"
                                    DataSourceID="SqlDataSource1" DataTextField="projectTitle"
                                    DataValueField="lecturerProjectId">
                                </asp:DropDownList>

                                4

                                <asp:DropDownList ID="DropDownList4" runat="server"
                                    DataSourceID="SqlDataSource1" DataTextField="projectTitle"
                                    DataValueField="lecturerProjectId">
                                </asp:DropDownList>

                                5

                                <asp:DropDownList ID="DropDownList5" runat="server"
                                    DataSourceID="SqlDataSource1" DataTextField="projectTitle"
                                    DataValueField="lecturerProjectId">
                                </asp:DropDownList>

                                6

                                <asp:DropDownList ID="DropDownList6" runat="server"
                                    DataSourceID="SqlDataSource1" DataTextField="projectTitle"
                                    DataValueField="lecturerProjectId">
                                </asp:DropDownList>

                                7

                                <asp:DropDownList ID="DropDownList7" runat="server"
                                    DataSourceID="SqlDataSource1" DataTextField="projectTitle"
                                    DataValueField="lecturerProjectId">
                                </asp:DropDownList>

                                8

                                <asp:DropDownList ID="DropDownList8" runat="server"
                                    DataSourceID="SqlDataSource1" DataTextField="projectTitle"
                                    DataValueField="lecturerProjectId">
                                </asp:DropDownList>

                                9

                                <asp:DropDownList ID="DropDownList9" runat="server"
                                    DataSourceID="SqlDataSource1" DataTextField="projectTitle"
                                    DataValueField="lecturerProjectId">
                                </asp:DropDownList>

                                10

                                <asp:DropDownList ID="DropDownList10" runat="server"
                                    DataSourceID="SqlDataSource1" DataTextField="projectTitle"
                                    DataValueField="lecturerProjectId">
                                </asp:DropDownList>

                <asp:Button ID="btnSubmit" runat="server" Text="Submit" CssClass="btn btn-primary" />
                <input id="Reset1" type="reset" value="reset" class="btn btn-primary" />

    </fieldset>
</asp:Content>

please give me some ideas how can i achieve this.
    using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Web.Configuration;

namespace Final_Year_Project_Allocation_System
{
    public partial class student_project_choice : System.Web.UI.Page
    {
        private string connectionString = WebConfigurationManager.ConnectionStrings["UomDBConnectionString1"].ConnectionString;
        protected void Page_Load(object sender, EventArgs e)
        {

        }

        protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
        {
            try
            {
                string selected = DropDownList1.SelectedItem.Value;
                string selectSQL = "select Count(choiceNumber) from tbl_student_project_choice where choiceProjectId = '" + selected + "' and choiceNumber='"+1+"'";
                // Define the ADO.NET objects.
                SqlConnection con = new SqlConnection(connectionString);
                con.Open();
                SqlCommand cmd = new SqlCommand(selectSQL, con);
                int result = (int)cmd.ExecuteScalar();
                lblDemand.Text = result.ToString();

            }
            catch (Exception exce)
            {
                lblMessage.Text = exce.Message;
            }

        }

    }

}


text:
Q: How to exit a macro where the current sheet grand total = 0 (no values picked up in the pivot table) I've recorder a VBA Macro which works well and does what I want, however the issue is when there isn't any values the Macro Breaks and doesn't work, is there anyway to check the current sheet's pivot table for when it = 0 e.g. Count of Number field, the Macro ends the sub?
Thanks in advance.


text:
Q: How to get http header status code in webview on android? I want to get header status code in webview. For example if status code is 200, do it or status code is 404, do other thing. But I didn't get header status code. Is webview allow it? If it allows , how?

A: I posted an answer here that used a simple HTTP request to check the status.  If status = 200 GOOD! Load remote URL to webview, else load local HTML page from assets.


text:
Q: List elements are null just after adding them I have an unusual problem with my List. The code looks like this:
tanks = new List<Tank>();

tanks.Add(new Tank("Player", position1, false));
tanks.Add(new Tank("Enemy", position2, true));

if (tanks[0] == null) Debug.LogError("tanks[0] == null");

For some reason the error appears. Why does it happen? If I call List.Count, it returns 2... Can someone help me?

A: As we can see on this example your code works perfectly. This means that the code you provided does not have the error you talk about.
What is most definitely happening is what @Everts talked about in the comments, your Debug.LogError("tanks[0] == null"); line is probably not within the if block in your code. Try adding brackets {}around it.
here is your updated code
tanks = new List<Tank>();

tanks.Add(new Tank("Player", position1, false));
tanks.Add(new Tank("Enemy", position2, true));

if (tanks[0] == null)
{
    Debug.LogError("tanks[0] == null");
}

A: For people who might have the same issue: creating Monobehaviours using ,,new" keyword is not allowed and it will cause an error. Just enable your warnings ;)


text:
Q: Логика работы функции srand () Пытаюсь разобраться в генерации псевдослучайных чисел в СИ.
Верно ли я понимаю, что функция srand (seed) устанавливает начальную точку для генерации
множества псевдослучайных целых чисел, а генерирует в свою очередь непосредственно функция rand () и в качестве аргумента seed для
переустановки генератора используется любое число?
Вопрос образовался когда я увидел, что при одинаковом значении аргумента seed, числа, получаемое из функции rand () будут равны.
Пример, в котором первые три числа всегда будут равны:
int main(void) {
  srand(4);
  printf("%d\n", 80 + rand()%21);
  srand(4);
  printf("%d\n", 80 + rand()%21);
  srand(4);
  printf("%d\n", 80 + rand()%21);
  srand(1);
  printf("%d\n", 80 + rand()%21);
  srand(0);
  printf("%d\n", 80 + rand()%21);
}

A:
Верно ли я понимаю, что функция srand (seed) устанавливает начальную точку для генерации множества псевдослучайных целых чисел, а генерирует в свою очередь непосредственно функция rand () и в качестве аргумента seed для переустановки генератора используется любое число?

Да, верно.
При этом спецификация языка гарантирует, что до первого вызова srand функция rand ведет себя как после srand(1). То есть вот в таком случае
int main(void) {
  printf("%d\n", 80 + rand()%21);
  srand(1);
  printf("%d\n", 80 + rand()%21);
}

числа тоже будут равны.


text:
Q: Notifications on iOS for new questions in selected tags Is there a way to get notified on an iOS device for new questions in selected tags ?
There are some tags where a new question comes in every couple of hours. For them, I would like to be notified as soon as a new question arrives.  (This would not be useful for a high traffic tag like java etc)
Fast notifications have been discussed before in q1, q2 or q3. Mobile notifications are not discussed there. The suggested stacksguru app is not for mobile as far as I see.

A: What probably works (I haven't tested it) is to combine an RSS feed like this one:
https://stackoverflow.com/feeds/tag?tagnames=html&sort=newest
with an iOS app from the App Store which sends push notifications based on changes in an RSS feed, like Newsify or another one listed here.


text:
Q: Jquery code working fine until I included strict mode A piece of Jquery Code was working just fine until "superiors" told me I must include strict mode on all my Javascript code. Everything is working fine on my main.js file except this piece of code. I can't reccon the error but my console error triggers every time i activate the script, it is a Boostrap 4 toggler button, it does open a menu, but the menu opens from up to bottom and really laggy. The button is supossed to collapse from right to left.
$(function(){
    // mobile menu slide from the left
    $('[data-toggle="collapse"]').on('click', function() {
        $navMenuCont = $($(this).data('target'));
        $navMenuCont.animate({'width':'toggle'}, 280);
    });
})

Console error goes as follow:
Uncaught ReferenceError: $navMenuCont is not defined
    at HTMLButtonElement.<anonymous> (main.js:61)
    at HTMLButtonElement.dispatch (jquery-3.3.1.js:5183)
    at HTMLButtonElement.elemData.handle (jquery-3.3.1.js:4991)

A: From the MDN reference:

First, strict mode makes it impossible to accidentally create global
  variables. In normal JavaScript mistyping a variable in an assignment
  creates a new property on the global object and continues to "work"
  (although future failure is possible: likely, in modern JavaScript).
  Assignments, which would accidentally create global variables, instead
  throw an error in strict mode.

You need to declare your $navMenuCont variable.
For example:
var $navMenuCont = $($(this).data('target'));

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Strict_mode


text:
Q: How to do OpenCL programming in the newest Xilinx Vivado (2014.2)? I used a simple "Hello, world." OpenCL program in the version 2014.2 Xilinx Vivado IDE, which declared its OpenCL support. One of the code snippets is as follows:
#include <CL/opencl.h>

...

// Connect to a compute device

//

int gpu = 1;

err = clGetDeviceIDs(NULL, gpu ? CL_DEVICE_TYPE_GPU : CL_DEVICE_TYPE_CPU, 1, &device_id, NULL);

if (err != CL_SUCCESS)

{

    printf("Error: Failed to create a device group!\n");

    return EXIT_FAILURE;

}

However, it seems that this Vivado couldn't recognize the header "CL/opencl.h" and the cl related functions. I resolved the header problem by manually put a external CL directory (derived from CUDA SDK) in my current Vivado HLS project, but it still reported errors like "function 'clGetDeviceIDs' has no function body".

A: #include <CL/opencl.h> is how it's done on Mac OS X, but on Windows it is usually #include <CL/cl.h>. Have you located your CL include folder? Have you told the IDE where it is? It sounds like your second problem (after you worked around the first) is that you're not linking against OpenCL.lib (or whatever the library extension is on your platform). You need to locate that too and link to it. On an ICD-supporting platform, the Khronos lib can be used and it dynamically locates the installed drivers, but on your platform it is probably be different, so consult the Xilinx instructions.

A: It seems that including clc.h in my Vivado 2015.2 did the trick.


text:
Q: Assign unique id to columns pandas data frame Hello I have the following dataframe
df =
A      B
John   Tom
Homer  Bart
Tom    Maggie
Lisa   John

I would like to assign to each name a unique ID and returns
df =
A      B         C    D

John   Tom       0    1
Homer  Bart      2    3
Tom    Maggie    1    4
Lisa   John      5    0

What I have done is the following:
LL1 = pd.concat([df.a,df.b],ignore_index=True)
LL1 = pd.DataFrame(LL1)
LL1.columns=['a']
nameun = pd.unique(LL1.a.ravel())
LLout['c'] = 0
LLout['d'] = 0
NN = list(nameun)
for i in range(1,len(LLout)):
   LLout.c[i] = NN.index(LLout.a[i])
   LLout.d[i] = NN.index(LLout.b[i])

But since I have a very large dataset this process is very slow.

A: Here's one way. First get the array of unique names:
In [11]: df.values.ravel()
Out[11]: array(['John', 'Tom', 'Homer', 'Bart', 'Tom', 'Maggie', 'Lisa', 'John'], dtype=object)

In [12]: pd.unique(df.values.ravel())
Out[12]: array(['John', 'Tom', 'Homer', 'Bart', 'Maggie', 'Lisa'], dtype=object)

and make this a Series, mapping names to their respective numbers:
In [13]: names = pd.unique(df.values.ravel())

In [14]: names = pd.Series(np.arange(len(names)), names)

In [15]: names
Out[15]:
John      0
Tom       1
Homer     2
Bart      3
Maggie    4
Lisa      5
dtype: int64

Now use applymap and names.get to lookup these numbers:
In [16]: df.applymap(names.get)
Out[16]:
   A  B
0  0  1
1  2  3
2  1  4
3  5  0

and assign it to the correct columns:
In [17]: df[["C", "D"]] = df.applymap(names.get)

In [18]: df
Out[18]:
       A       B  C  D
0   John     Tom  0  1
1  Homer    Bart  2  3
2    Tom  Maggie  1  4
3   Lisa    John  5  0

Note: This assumes that all the values are names to begin with, you may want to restrict this to some columns only:
df[['A', 'B']].values.ravel()
...
df[['A', 'B']].applymap(names.get)

A: (Note: I'm assuming you don't care about the precise details of the mapping -- which number John becomes, for example -- but only that there is one.)
Method #1: you could use a Categorical object as an intermediary:
>>> ranked = pd.Categorical(df.stack()).codes.reshape(df.shape)
>>> df.join(pd.DataFrame(ranked, columns=["C", "D"]))
       A       B  C  D
0   John     Tom  2  5
1  Homer    Bart  1  0
2    Tom  Maggie  5  4
3   Lisa    John  3  2

It feels like you should be able to treat a Categorical as providing an encoding dictionary somehow (whether directly or by generating a Series) but I can't see a convenient way to do it.
Method #2: you could use rank("dense"), which generates an increasing number for each value in order:
>>> ranked = df.stack().rank("dense").reshape(df.shape).astype(int)-1
>>> df.join(pd.DataFrame(ranked, columns=["C", "D"]))
       A       B  C  D
0   John     Tom  2  5
1  Homer    Bart  1  0
2    Tom  Maggie  5  4
3   Lisa    John  3  2


text:
Q: What is the protocol for loading test suites for both nose and unittest? I used the unittest load_tests() protocol, because I want my automated tests to include a doctest but only for one module. This works fine when discovered and run by unittest, but fails when instead run by nose.
import doctest
import unittest

import my.module

suite = doctest.DocTestSuite(my.module)

def load_tests(loader, std, pat): # invoked by unittest discovery process
    return suite

The error is:
Traceback (most recent call last):
  File "/g/data/w85/brl654/conda/envs/haz/lib/python2.7/site-packages/nose/case.py", line 197, in runTest
    self.test(*self.arg)
TypeError: load_tests() takes exactly 3 arguments (0 given)

If I make those arguments optional, will nose run the tests? Is there a better way to integrate this test suite, so that it can be run by either unittest or by nose?

A: The difficulty is that nosetests normally searches for a combination of both unittest.TestCase subclasses and functions with test-like names. A unittest.TestSuite is neither a TestCase subclass nor a function, so it cannot naturally be picked up by nose. (Furthermore, nose erroneously does pick up load_tests and try to run it as a test function, contrary to unittest's test-loading protocol.)
A crude solution is:
load_tests.__test__ = False # instruct nose to skip load_tests()
def test_with_nose():
    assert suite.run(unittest.TestResult()).wasSuccessful()


text:
Q: Что делает оператор "-->"? После прочтения Hidden Features and Dark Corners of С++/STL на comp.lang.c++.moderated, я был удивлен  тому что следующий фрагмент, скомпилировался и работает в Visual Studio 2008, так и в g++ 4.4.
Код:
#include <stdio.h>
int main()
{
    int x = 10;
    while (x --> 0) // x goes to 0
    {
        printf("%d ", x);
    }
}

Я предположил, что это C, так как он работает Visual Studio 2008 и в GCC. Где это определено в стандарте и откуда взялся такое оператор?
свободный перевод вопроса What is the "-->" operator in C++

A: --> не является оператором. Это фактически два отдельных оператора, -- и >
С начало происходит операция -- (минус единица от x) после сравнивание x с 0
Чтобы лучше понять, выражение можно записать следующим образом:
while( (x--) > 0 )

x может уменьшаться ещё быстрее:
int x = 10;

while( 0 <---- x )
{
   printf("%d ", x);
}

результат:
8 6 4 2

Вы можете контролировать скорость с помощью стрелок!
int x = 100;

while( 0 <-------------------- x )
{
   printf("%d ", x);
}

результат:
90 80 70 60 50 40 30 20 10

;)


text:
Q: Working with nodejs api I'm new to nodejs and this is my first app. I am trying to use a nodejs API called event registry to get some data. Implementation below:
app.get('/eventregistry', function(req,res){
    console.log("dfsdfdf");
    var er = new erBase.EventRegistry({apiKey: "API Key"});
    er.getConceptUri("syria").then((conceptUri) => {
        var q = new erBase.QueryArticlesIter(er, {conceptUri: conceptUri, sortBy: "date"});
        q.execQuery((items) => {
            for(var item of items) {
                console.info(item);
            }
        })
    });
});

My problem is when I run the server and go to the route nothing happens. My event package is installed and required as well. What am I doing wrong?

A: you must send a response back to client using that res object in your callback function:
app.get('/eventregistry', function(req,res){
    console.log("dfsdfdf");
    var er = new erBase.EventRegistry({apiKey: "API Key"});
    er.getConceptUri("syria").then((conceptUri) => {
        var q = new erBase.QueryArticlesIter(er, {conceptUri: conceptUri, sortBy: "date"});
        q.execQuery((items) => {
            for(var item of items) {
                console.info(item);
            }
            res.status(200).json(items); // as example
        })
    });
});

I highly recommend you reading express documentation, exceptionally their Response Object part.


text:
Q: Vue.js: how do you set a data variable in a vue method inside a .vue template file I am learning vue.js for the first time tonight and I can't wrap my head around why when I set a "list" array in the data function, i cannot change it in a method below. I have the following code and my template still spits out my original {name: 'daniel'}, {name: 'lorie'} variable.
My http call is definitely being made as i can see an array of like 100 users in the network tab, but "this.list = data" is not resetting my data variable
<template>
  <pre>{{list}}</pre>
</template>

<script>
export default {
  data () {
    return {
      list: [{name: 'daniel'}, {name: 'lorie'}]
    }
  },
  created () {
    this.fetchContactList()
  },
  methods: {
    fetchContactList () {
      this.$http.get('https://jsonplaceholder.typicode.com/users', (data) => {
        this.list = data
      })
    }
  }
}
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style lang="scss">
  ul.user-list {
    background: #fafafa;
    border:1px solid #ebebeb;
    padding:40px;
    li {
      list-style: none;
      display: block;
      margin-bottom:10px;
      padding-bottom:10px;
      border-bottom:1px solid #ebebeb;
    }
  }
</style>

A: You are attempting to pass your success callback in the options argument. The $http service uses promises with the following format:
this.$http.get('/someUrl', [options]).then(successCallback, errorCallback);

Change your get request to this:
this.$http.get('https://jsonplaceholder.typicode.com/users').then( (response) => {
    this.list = response.body; // The data you want is in the body
  });


text:
Q: C++: Manipulating String using pointer through a function I have written following program which will delete all the common characters from string1, present in string2.
 #include<iostream>
 #include<string>
 #include<iterator>

 using namespace std;

 void DelCommonChar(char *input, string s2)
  {
          string s1(input);
          string::iterator it1;
          string::iterator it2;

          for(it1=s1.begin();it1<s1.end();it1++)
          {
                  for(it2=s2.begin();it2<s2.end();it2++)
                  {
                          if(*it1==*it2){it1=s1.erase(it1);it1--;}
                  }
          }
          cout<<s1<<endl;              // Line Number 20
  }

  int main()
  {
          char c[32];
          strncpy(c,"Life of Pie",32);
          DelCommonChar(c,"def");
          cout<<c<<endl;              //Line Number 29
  }

Output:Li o pi  ......... printed through line number 20.

But now I want to chagne the variable c[32] itself which is in main function and I want line number 29 to print the output.
Could you help me out, how to change the variable c[32] only inside the function DelCommonChar ?
Note: I dont want to change the function return data type void.

A: If you are unable to modify function signature. You could use "c_str()" to return C String. This is not recommended.
#include<iostream>
#include<string>
#include<iterator>

using namespace std;

void DelCommonChar(char *input, string s2)
{
        string s1(input);
        string::iterator it1;
        string::iterator it2;

        for(it1=s1.begin();it1<s1.end();it1++)
        {
                for(it2=s2.begin();it2<s2.end();it2++)
                {
                        if(*it1==*it2){it1=s1.erase(it1);it1--;}
                }
        }
        std::strcpy (input, s1.c_str());
}

int main()
{
        char *c = (char *)malloc(32);
        strncpy(c,"Life of Pie",32);
        DelCommonChar(c,"def");
        cout<<c<<endl;
}

A: When you initialize s1:
string s1(input);

It copies contents of input into its internal buffer. Modfying s1 won't change original buffer. If you want to store contents within input either copy them back (strcpy, strncpy, memcpy - they're all "unsafe", though) or operate on input directly.
A better idea would be to avoid using C strings (char*) and use std::strings with references.
void DelCommonChar(std::string &input, string s2)
{
      std::string &s1 = input;//you don't need that, you can use input directly.
      ...

 }

A: You can maintain two pointers, one which checks, one which writes. Something like:
int check=0,write=0;
while (input[check])
{
    if (input[check] is not to be deleted)
    {
        input[write++]=input[check];
    }
    ++check;
}
input[write]=0;


text:
Q: How to insert decimal point and round using SQL Data set is from https://sqlzoo.net/wiki/SELECT_from_WORLD_Tutorial, number 9
I am using
SELECT name, ROUND(population, 3,0), ROUND(GDP, 3,0)
FROM world
WHERE continent = 'South America'

Answer should be
name
Argentina   42.67   477.03
Bolivia 10.03   27.04
Brazil  202.79  2254.11

I am getting
name
Argentina   42669500    477028000000
Bolivia 10027254    27035000000
Brazil  202794000   2254109000000

...

A: You want the population in millions and GDP in billions, both rounded to two decimals. Consider:
SELECT name, ROUND(population/1000000, 2), ROUND(GDP/1000000000, 2)
FROM world
WHERE continent = 'South America'


text:
Q: Simple field extension Let $L/K$ be a finite field extension of degree $n$ and $\vartheta\in L$. Further let there exist $\sigma_1,\ldots,\sigma_n\in\text{Aut}_K(L)$ with $\sigma_i(\vartheta)\neq \sigma_j(\vartheta)$ for $i\neq j$. Then I want to show that $\vartheta$ is primitive for $L/K$, e.g. that $L=K(\vartheta)$.
Do you have any hints? I know that zeros are send to zeros by any automorphism, but I dont know that there exist an element $\lambda$ with $L=K(\lambda)$, or do I? Thanks in advance.

A: Let $f$ be the minimal polynomial of $\vartheta$ over $K$.
As you say, an automorphism fixing $K$ preserves the property of being a zero of a polynomial over $K$, so each $\sigma_i(\vartheta)$ is a root of $f$.
Hence, degree of $\,\vartheta\ =\,$ degree of $f\ \ge n$.


text:
Q: How can give installation permission to domain user? How can I give installation permission to a particular domain user on a domain client machine?
Thanks for the great help!

A: Do you mean you want a domain user to be able to install software on one particular machine? If so all you need to do is add that domain user to the administrators group on the specific machine. If I've misunderstood your question please come back.


text:
Q: how to enable Mono.Simd I'd like to use Simd in Mono, but the following code is highlighted as error in MonDevop
using Mono.Simd
I already installed the "Mono 2.8 for Windows", what else I need to install to enable Mono.Simd?
In this link
http://tirania.org/blog/archive/2008/Nov-03.html
It talk about the tarbal, but after download it an uncompress it (mono-Mono.Simd.Math-942e804), there are many cs file and no dll file.

A: Did you add the Mono.Simd.dll to the build? MonoDevelop correctly highlights the error because in the assemblies you're using there isn't any Mono.Simd namespace.
Mono.Simd.dll is included in recent Mono releases.
As for the other answer, Mono.Simd works on any operating system on x86 and amd64, not only on Linux.

A: Mono.Simd only works when you run your programs on Mono runtime, on a supported operating system. If I'm not mistaken, it's currenly restricted to 32 & 64 bit Linux. Even if you manage to compile it on Windows, you won't get any speed benefit from it.

A: MonoDevelop for Windows runs on the .Net runtime, while the Mono.Simd.dll that comes with Mono 2.8 is installed in Mono's GAC.
You will need to Add Reference in your project to the Mono.Simd.dll that came with Mono 2.8.
It should be roughly in:
C:\Program Files (x86)\Mono-2.8\lib\mono\2.0\Mono.Simd.dll.


text:
Q: minimize button is gray and non responsive, how do regain that function I have a MacBook Pro and am running OS X Yosemite. The minimize button goes gray if the window is opened fully. This happened before and I found an answer online but am unable to find a solution now.
I am not at all familiar with code or much in the computer world. How can I fix this?

A: Fullscreen windows cannot be minimised, as they take their own Space & there is nothing 'behind' them.
If you want to be able to minimise, then use Maximise rather than Fullscreen - Opt-click the green Fullscreen button; note the double arrow <> changes to the old (pre-Yosemite) + sign for maximise.