text:
Q: Converting latin1 to utf8 A month ago, we migrated our database from DB2 to MySQL. The original data was in utf8, but when it got imported into MySQL, the default encoding was latin1. We only realized this after discovering funny characters in the data, and some research. We would like to change the encoding for MySQL to utf8, and have some helpful instructions on this, but my concern is that in the past month, if there were any changes to the data it would have saved in latin1.
The data is entered via web pages set in utf8, but since the database is currently in latin1, would the changes be saved in latin1? If so, how could we figure out which data is really in latin1 and not in the original utf8?
Secondly, if there were some data in latin1 and some in the original utf8 on the same table column, how would we handle the conversion since some data require conversion and some don't?
Thanks for your help!


text:
Q: Align bar horizontally on xAxis on recharts I have a Recharts Bar chart with a single bar, code below:
<ResponsiveContainer width="100%" height={300}>
    <BarChart data={exampleDataset}
     margin={{
      top: 20,
      right: 10,
      left: 20,
      bottom: 0,
    }}>

    <CartesianGrid vertical={false} strokeDasharray="5" />
    <XAxis dataKey="name">
    </XAxis>
    <YAxis tickSize={10} tickCount={8}
      minTickGap={2}
    >

    </YAxis>
    <Tooltip formatter={(value: any) => `${value} €`}/>

    <Bar dataKey="value" barSize={45} fill='#b7b8d4'>

    </Bar>

    </BarChart>
</ResponsiveContainer>

By default the single bar is aligned to the center horizontally, I want it instead to be aligned to the left(the start of the chart).
The only way possible that I found to somewhat achieve this by setting the padding={{left: some negative number}} prop to XAxis component, but it requires hardcoding values, which makes it unusable for my purposes.
Is there any other way that would be dynamic?

redpajama_set_name: RedPajamaStackExchange


text:
Q: LM22673 diode selection
I'm fairly new to electronics, and in my project I'm using LM22673 as Buck Converter in this Diode selection parts this is given which is confusing for me.
as

*

*Ultra-fast diodes can switch very fast, so what's the issue with that? How it will damage the IC?

*Also, why choose a diode with reverse breakdown rating of max Vin. It's on Output side right, so why does it matter?

A: Reverse recovery
There are several good posts on this forum that describe this phenomenon.
What is the reverse recovery time in a diode?. What they are stating in the datasheet is that the Schottky diode has even better reverse recovery characterstics than an ultra fast one.
Reverse breakdown voltage
The output voltage of an ideal buck converter is between 0V and Vin. Therefore the highest possible voltage the diode can experience is Vin. However, considering tolerances, voltage ripple/spikes etc it is a good idea to add some safety margin.


text:
Q: BackgroundWorker OnWorkCompleted throws cross-thread exception I have a simple UserControl for database paging, that uses a controller to perform the actual DAL calls. I use a BackgroundWorker to perform the heavy lifting, and on the OnWorkCompleted event I re-enable some buttons, change a TextBox.Text property and raise an event for the parent form.
Form A holds my UserControl. When I click on some button that opens form B, even if I don't do anything "there" and just close it, and try to bring in the next page from my database, the OnWorkCompleted gets called on the worker thread (and not my Main thread), and throws a cross-thread exception.
At the moment I added a check for InvokeRequired at the handler there, but isn't the whole point of OnWorkCompleted is to be called on the Main thread? Why wouldn't it work as expected?
EDIT:
I have managed to narrow down the problem to arcgis and BackgroundWorker. I have the following solution wich adds a Command to arcmap, that opens a simple Form1 with two buttons.
The first button runs a BackgroundWorker that sleeps for 500ms and updates a counter.
In the RunWorkerCompleted method it checks for InvokeRequired, and updates the title to show whethever the method was originaly running inside the main thread or the worker thread.
The second button just opens Form2, which contains nothing.
At first, all the calls to RunWorkerCompletedare are made inside the main thread (As expected - thats the whold point of the RunWorkerComplete method, At least by what I understand from the MSDN on BackgroundWorker)
After opening and closing Form2, the RunWorkerCompleted is always being called on the worker thread. I want to add that I can just leave this solution to the problem as is (check for InvokeRequired in the RunWorkerCompleted method), but I want to understand why it is happening against my expectations. In my "real" code I'd like to always know that the RunWorkerCompleted method is being called on the main thread.
I managed to pin point the problem at the form.Show(); command in my BackgroundTesterBtn - if I use ShowDialog() instead, I get no problem (RunWorkerCompleted always runs on the main thread). I do need to use Show() in my ArcMap project, so that the user will not be bound to the form.
I also tried to reproduce the bug on a normal WinForms project. I added a simple project that just opens the first form without ArcMap, but in that case I couldn't reproduce the bug - the RunWorkerCompleted ran on the main thread, whether I used Show() or ShowDialog(), before and after opening Form2. I tried adding a third form to act as a main form before my Form1, but it didn't change the outcome.
Here is my simple sln (VS2005sp1) - it requires
ESRI.ArcGIS.ADF(9.2.4.1420)
ESRI.ArcGIS.ArcMapUI(9.2.3.1380)
ESRI.ArcGIS.SystemUI (9.2.3.1380)

A:
Isn't the whole point of OnWorkCompleted is to be called on the Main thread? Why wouldn't it work as expected?

No, it's not.
You can't just go running any old thing on any old thread. Threads are not polite objects that you can simply say "run this, please".
A better mental model of a thread is a freight train. Once it's going, it's off on it's own track. You can't change it's course or stop it. If you want to influence it, you either have to wait til it gets to the next train station (eg: have it manually check for some events), or derail it (Thread.Abort and CrossThread exceptions have much the same consequences as derailing a train... beware!).
Winforms controls sort of support this behaviour (They have Control.BeginInvoke which lets you run any function on the UI thread), but that only works because they have a special hook into the windows UI message pump and write some special handlers. To go with the above analogy, their train checks in at the station and looks for new directions periodically, and you can use that facility to post it your own directions.
The BackgroundWorker is designed to be general purpose (it can't be tied to the windows GUI) so it can't use the windows Control.BeginInvoke features. It has to assume that your main thread is an unstoppable 'train' doing it's own thing, so the completed event has to run in the worker thread or not at all.
However, as you're using winforms, in your OnWorkCompleted handler, you can get the Window to execute another callback using the BeginInvoke functionality I mentioned above. Like this:
// Assume we're running in a windows forms button click so we have access to the
// form object in the "this" variable.
void OnButton_Click(object sender, EventArgs e )
    var b = new BackgroundWorker();
    b.DoWork += ... blah blah

    // attach an anonymous function to the completed event.
    // when this function fires in the worker thread, it will ask the form (this)
    // to execute the WorkCompleteCallback on the UI thread.
    // when the form has some spare time, it will run your function, and
    // you can do all the stuff that you want
    b.RunWorkerCompleted += (s, e) { this.BeginInvoke(WorkCompleteCallback); }
    b.RunWorkerAsync(); // GO!
}

void WorkCompleteCallback()
{
    Button.Enabled = false;
    //other stuff that only works in the UI thread
}

Also, don't forget this:

Your RunWorkerCompleted event handler should always check the Error and Cancelled properties before accessing the Result property. If an exception was raised or if the operation was canceled, accessing the Result property raises an exception.

A: The BackgroundWorker checks whether the delegate instance, points to a class which supports the interface ISynchronizeInvoke. Your DAL layer probably does not implement that interface. Normally, you would use the BackgroundWorker on a Form, which does support that interface.
In case you want to use the BackgroundWorker from the DAL layer and want to update the UI from there, you have three options:

*

*you'd stay calling the Invoke method

*implement the interface ISynchronizeInvoke on the DAL class, and redirect the calls manually (it's only three methods and a property)

*before invoking the BackgroundWorker (so, on the UI thread), to call SynchronizationContext.Current and to save the content instance in an instance variable. The SynchronizationContext will then give you the Send method, which will exactly do what Invoke does.

A: It looks like a bug:
http://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=116930
http://thedatafarm.com/devlifeblog/archive/2005/12/21/39532.aspx
So I suggest using the bullet-proof (pseudocode):
if(control.InvokeRequired)
  control.Invoke(Action);
else
  Action()

A: The best approach to avoid issues with cross-threading in GUI is to use SynchronizationContext.


text:
Q: Updating 200,000+ rows containing UNC paths to a new host name in SQL Server table We are replacing a file server in the business that has failed on us and in some tables in a SQL Server database there are approx. 200k records that have a column which stores an UNC file path to a file hosted on the old file server.
I am currently using the below code to achieve the update, unfortunately it fails complaining that the transaction logs are full and I end up having to restore the database.
DECLARE @currentServerName as nvarchar(50)
DECLARE @newServerName as nvarchar(50)
DECLARE @likeMatch as nvarchar(50)
SET @currentServerName = N'\\dom-fls-p01.localdom\';
SET @newServerName =     N'\\dom-filesrv.localdom\';
SET @likeMatch =     @currentServerName + '%';

UPDATE [DownloadQueue]
SET [LocalPath] = @newServerName + SUBSTRING([LocalPath], LEN(@currentServerName)+1, LEN([LocalPath])-LEN(@currentServerName))
WHERE [LocalPath] LIKE @likeMatch

UPDATE [DetectionFile]
SET [OriginalFileLocation] = @newServerName + SUBSTRING([OriginalFileLocation], LEN(@currentServerName)+1, LEN([OriginalFileLocation])-LEN(@currentServerName))
WHERE [OriginalFileLocation] LIKE @likeMatch

UPDATE [FileTransferOperation]
SET [TargetPath] = @newServerName + SUBSTRING([TargetPath], LEN(@currentServerName)+1, LEN([TargetPath])-LEN(@currentServerName))
WHERE [TargetPath] LIKE @likeMatch

UPDATE [WorkQueue]
SET [Location] = @newServerName + SUBSTRING([Location], LEN(@currentServerName)+1, LEN([Location])-LEN(@currentServerName))
WHERE [Location] LIKE @likeMatch

Can anyone suggest a better method to achieve my goal?
Thanks,
Xavier.
Ps. yes we are changing it to a new CName that way future replacements doesn't need database updates :)

A: You can try one of the following solutions

*

*Take a Log backup of the database before starting the UPDATE. Take a log backup after all UPDATES are complete. you could since there is no transaction boundary (BEGIN TRAN, COMMIT) run these independently, you can take a log backup after each of the UPDATE statement. Something like this.
UPDATE [DownloadQueue] SET [LocalPath] = @newServerName + SUBSTRING([LocalPath], LEN(@currentServerName)+1, LEN([LocalPath])-LEN(@currentServerName)) WHERE [LocalPath] LIKE @likeMatch

Run Log backup
BACKUP LOG <DatbaseName>

Next Update Statement
UPDATE [DetectionFile] SET [OriginalFileLocation] = @newServerName + SUBSTRING([OriginalFileLocation], LEN(@currentServerName)+1, LEN([OriginalFileLocation])-LEN(@currentServerName)) WHERE [OriginalFileLocation] LIKE @likeMatch

Run Log backup
BACKUP LOG <DatbaseName>

and so on...

*Change to Simple recovery model and run the UPDATE. Switch back to a full recovery model and take a full backup.

*If Update still fails due to transaction log space after switching to Simple recovery model. You can alternatively try to Run the Update in a batch. take a batch size, say 10k records and run the UPDATE for the specific batch, issue a CHECKPOINT then and then continue to the next batch.

*If all else fails, Increase the Log File Space

A: Sounds like you just need to backup & truncate the tlogs before running this.  It would also help to increase the max log size if possible.
If it's still unable to complete, run it in batches (Update top (10000)) until the logs fill up, backup the logs again, repeat until complete.


text:
Q: "MKL ERROR: Parameter 12..." for large matrices with scipy.linalg.eigvalsh in Anaconda 2019.10-py37 (updated) First of all, note that the problem seems to exist for a long time now (e.g. GitHub Scipy Issue 8205).
It happens that I get an MKL error (see below) when trying to get the eigenvalues of complex matrices with size 2000x2000 or larger using eigvalsh.
Apparently, the problem should have been fixed on the MKL side with release 2019.0 as far as I understand, so I upgraded Anaconda to 2018.12-py37 since Scipy is linked against MKL 2019.1 in this version. Unfortunately, this does not work for me and I still get the error. Did I miss something or is there a fix in sight for this? There seems to be no MKL conda-forge version of Scipy so it might be the most recent version available (in Anaconda with MKL).
Anaconda Release 2018.12-py37
an extract from conda list:
# Name                    Version                   Build  Channel
blas                      1.0                         mkl
mkl                       2019.1                      144
numpy                     1.15.4           py37h7e9f1db_0
numpy-base                1.15.4           py37hde5b4d6_0
scipy                     1.1.0            py37h7c811a0_2

I have already built a virtual conda environment with only the necessary modules. It raises the same errors.
import numpy as np
from scipy.linalg import eigvalsh
mat = np.random.rand(2000,2000) + 1j * np.random.rand(2000,2000)
mat += mat.conjugate().T
eigvalsh(mat)

I get the following error:
Intel MKL ERROR: Parameter 12 was incorrect on entry to ZHBRDB.

It just raises the error and returns an array with only zeros, except for the last entry.
Edit:
Now with Anaconda Release 2019.10-py37, i invested some more time and was able to trace the problem down to the point where LAPACK functions are wrapped:
eigvalsh calls eigh with eigvals_only=True.
By investigating the eigh routine, I found out that the main difference is in setting the flag jobz for the LAPACK function to 'N' (only eigenvalues) instead of 'V' (eigenvalues and eigenvectors). By reconstructing the code I was able to test the wrapped heevr routine for different cases - application to complex64 and complex 128 hermitian matrices give the error as explained above, application to float32 and float64 symmetric matrices give no error and reasonable results for at least up to 20kx20k randomly generated matrices.
A new minimal example:
    from numpy.random import rand
    from scipy.linalg.lapack import get_lapack_funcs
    mat = rand(2000,2000) + 1j * rand(2000,2000)
    mat += mat.conjugate().T
    (heevr,) = get_lapack_funcs(('heevr',), (mat,))
    (syevr,) = get_lapack_funcs(('syevr',), (mat.real,))
    w, v, info = heevr(mat, jobz='N') # produces error as described
    #w, v, info = heevr(mat, jobz='V') # no error
    #w, v, info = syevr(mat.real, jobz='N') # no error
    #w, v, info = syevr(mat.real, jobz='V') # no error
    print(w, v, info)

The variable info is 0 in every case.


text:
Q: Show that for sufficiently small $\delta A$, we get $||\delta x||\leq ||A^{-1}||(||\delta A||\cdot||\hat{x}||+||\delta b|| )$ is strictly an equality Proof attempt:
Given $\delta x=\hat{x}-x,\,Ax=b$. Assume $||A^{-1}\delta A||<1$
Now, $\hat{x}-x=(A+\delta A)^{-1}(b+\delta b)-A^{-1}b=((A+\delta A)^{-1}-A^{-1})b+(A+\delta A)^{-1}\delta b$
So $||\hat{x}-x||\leq ||(A+\delta A)^{-1}-A^{-1}||\cdot||b||+||(A+\delta A)^{-1}||\cdot||\delta b||$
but $||(A+\delta A)^{-1}||=||(A+\delta A)^{-1}-A^{-1}+A^{-1}||\leq||(A+\delta A)^{-1}-A^{-1}||+||A^{-1}||$
but $||(A+\delta A)^{-1}-A^{-1}||\leq||A^{-1}||\cdot||(I+A^{-1}\delta A)^{-1}(I+A^{-1}\delta A-I)||=||A^{-1}||\cdot||(I+A^{-1}\delta A)^{-1}A^{-1}\delta A||\leq\frac{||A^{-1}||\cdot||A^{-1}\delta A ||}{1-||A^{-1}\delta A||}$
Now, going back $||\hat{x}-x||\leq\frac{||A^{-1}||}{1-||A^{-1}\delta A||}(||A^{-1}\delta A||\cdot||b||+||\delta b||)\leq\frac{||A^{-1}||}{1-||A^{-1}\delta A||}(||x||\cdot||\delta A||+||\delta b||)$
$\implies ||\hat{x}-x||\leq||A^{-1}||(||\delta A||\cdot||x||+||\delta b||)$
Am I going in the right direction? Any adjustments need to be done?

A: I would start with
$$
A·(\hat x-x)=(-δA·\hat x+b+δb)-b=-δA\,\hat x+δb,
$$
the claimed identity follows directly.


text:
Q: What does 'limbs' mean in this context?
'As to our second new appointment,' Dumbledore continued, as the lukewarm applause for Professor Lupin died away, 'well, I am sorry to tell you that Professor Kettleburn, our Care of Magical Creatures teacher, retired at the end of last year in order to enjoy more time with his remaining limbs. However, I am delighted to say that his place will be filled by none other than Rubeus Hagrid, ...

I'm wondering if 'limbs' is used to mean its literal meaning or a special meaning. What does it mean exactly? (arms & legs, large branches of a tree, or something else)
-- From Harry Potter - and the Prisoner of Azkaban, Chapter 5.

A: It's the literal meaning.
The joke is that Professor Kettleburn's job was Care of Magical Creatures, but presumably wasn't very good at it as he has lost at least one of his arms or legs, and he's retired before he can lose any more.


text:
Q: Maximum recommended socket sending capacity I'm creating a program (it's a game) which will have multiplayer. It will need both client-to-server and server-to-client, with the server being run on one of the player's machines, not on a separate machine. I'll be using C# sockets, and I need to know the maximum amount of data that they can handle. For instance, my data will be between 256b and 128kb, I can assume. Am I going to have any trouble sending that through the sockets? (There will never be more than 7 clients connected to the server-handler machine).
EDIT
After reading some other posts, I don't think it will be a problem. Others have said that sending data upwards of 1MB doesn't cause a problem, so I don't think I'll have an issue.
P.S.
If this is not the case, please let me know. Thanks!


text:
Q: I mistakenly deleted the .app file from products and .dsym I mistakenly deleted the .app file from products and .dsym file..I want to change the product name,i changed it in Bundle name and Build settings.I thought if i delete the app file it will create again with new name..but it is not creating it even..how should i create it.It is showing red ?Any help

A: Close Xcode and start again. This should fix. It fixed mine.


text:
Q: Debian 9 не видит 32 гиговую флешку Вставил флешку (32 гиговую ) в формате FAT32, в разьём microSD.   И вот что мне выдал linux ;_;
root@R2CPU:/dev# mmc0: host does not support reading read-only switch, assuming write-enable
sdhci: Tuning procedure failed, falling back to fixed sampling clock
mmc0: tuning execution failed: -5
mmc0: error -5 whilst initialising SD card
mmc0: host does not support reading read-only switch, assuming write-enable
sdhci: Tuning procedure failed, falling back to fixed sampling clock
mmc0: tuning execution failed: -5
mmc0: error -5 whilst initialising SD card
mmc0: host does not support reading read-only switch, assuming write-enable
sdhci: Tuning procedure failed, falling back to fixed sampling clock
mmc0: tuning execution failed: -5
mmc0: error -5 whilst initialising SD card
mmc0: host does not support reading read-only switch, assuming write-enable
sdhci: Tuning procedure failed, falling back to fixed sampling clock
mmc0: tuning execution failed: -5
mmc0: error -5 whilst initialising SD card

После воспользовался командой fdisk -l
root@R2CPU:/dev# fdisk -l
Disk /dev/ram0: 64 MiB, 67108864 bytes, 131072 sectors
Units: sectors of 1 * 512 = 512 bytes
Sector size (logical/physical): 512 bytes / 4096 bytes
I/O size (minimum/optimal): 4096 bytes / 4096 bytes

Disk /dev/ram1: 64 MiB, 67108864 bytes, 131072 sectors
Units: sectors of 1 * 512 = 512 bytes
Sector size (logical/physical): 512 bytes / 4096 bytes
I/O size (minimum/optimal): 4096 bytes / 4096 bytes

Disk /dev/ram2: 64 MiB, 67108864 bytes, 131072 sectors
Units: sectors of 1 * 512 = 512 bytes
Sector size (logical/physical): 512 bytes / 4096 bytes
I/O size (minimum/optimal): 4096 bytes / 4096 bytes

Disk /dev/ram3: 64 MiB, 67108864 bytes, 131072 sectors
Units: sectors of 1 * 512 = 512 bytes
Sector size (logical/physical): 512 bytes / 4096 bytes
I/O size (minimum/optimal): 4096 bytes / 4096 bytes

Disk /dev/ram4: 64 MiB, 67108864 bytes, 131072 sectors
Units: sectors of 1 * 512 = 512 bytes
Sector size (logical/physical): 512 bytes / 4096 bytes
I/O size (minimum/optimal): 4096 bytes / 4096 bytes

Disk /dev/ram5: 64 MiB, 67108864 bytes, 131072 sectors
Units: sectors of 1 * 512 = 512 bytes
Sector size (logical/physical): 512 bytes / 4096 bytes
I/O size (minimum/optimal): 4096 bytes / 4096 bytes

Disk /dev/ram6: 64 MiB, 67108864 bytes, 131072 sectors
Units: sectors of 1 * 512 = 512 bytes
Sector size (logical/physical): 512 bytes / 4096 bytes
I/O size (minimum/optimal): 4096 bytes / 4096 bytes

Disk /dev/ram7: 64 MiB, 67108864 bytes, 131072 sectors
Units: sectors of 1 * 512 = 512 bytes
Sector size (logical/physical): 512 bytes / 4096 bytes
I/O size (minimum/optimal): 4096 bytes / 4096 bytes

Disk /dev/ram8: 64 MiB, 67108864 bytes, 131072 sectors
Units: sectors of 1 * 512 = 512 bytes
Sector size (logical/physical): 512 bytes / 4096 bytes
I/O size (minimum/optimal): 4096 bytes / 4096 bytes

Disk /dev/ram9: 64 MiB, 67108864 bytes, 131072 sectors
Units: sectors of 1 * 512 = 512 bytes
Sector size (logical/physical): 512 bytes / 4096 bytes
I/O size (minimum/optimal): 4096 bytes / 4096 bytes

Disk /dev/ram10: 64 MiB, 67108864 bytes, 131072 sectors
Units: sectors of 1 * 512 = 512 bytes
Sector size (logical/physical): 512 bytes / 4096 bytes
I/O size (minimum/optimal): 4096 bytes / 4096 bytes

Disk /dev/ram11: 64 MiB, 67108864 bytes, 131072 sectors
Units: sectors of 1 * 512 = 512 bytes
Sector size (logical/physical): 512 bytes / 4096 bytes
I/O size (minimum/optimal): 4096 bytes / 4096 bytes

Disk /dev/ram12: 64 MiB, 67108864 bytes, 131072 sectors
Units: sectors of 1 * 512 = 512 bytes
Sector size (logical/physical): 512 bytes / 4096 bytes
I/O size (minimum/optimal): 4096 bytes / 4096 bytes

Disk /dev/ram13: 64 MiB, 67108864 bytes, 131072 sectors
Units: sectors of 1 * 512 = 512 bytes
Sector size (logical/physical): 512 bytes / 4096 bytes
I/O size (minimum/optimal): 4096 bytes / 4096 bytes

Disk /dev/ram14: 64 MiB, 67108864 bytes, 131072 sectors
Units: sectors of 1 * 512 = 512 bytes
Sector size (logical/physical): 512 bytes / 4096 bytes
I/O size (minimum/optimal): 4096 bytes / 4096 bytes

Disk /dev/ram15: 64 MiB, 67108864 bytes, 131072 sectors
Units: sectors of 1 * 512 = 512 bytes
Sector size (logical/physical): 512 bytes / 4096 bytes
I/O size (minimum/optimal): 4096 bytes / 4096 bytes

Disk /dev/mmcblk1: 3.5 GiB, 3783262208 bytes, 7389184 sectors
Units: sectors of 1 * 512 = 512 bytes
Sector size (logical/physical): 512 bytes / 512 bytes
I/O size (minimum/optimal): 512 bytes / 512 bytes
Disklabel type: dos
Disk identifier: 0x694737e4

Device         Boot  Start     End Sectors  Size Id Type
/dev/mmcblk1p1        2048  264191  262144  128M 83 Linux
/dev/mmcblk1p2      264192 6555647 6291456    3G 83 Linux

Disk /dev/mmcblk1boot1: 16 MiB, 16777216 bytes, 32768 sectors
Units: sectors of 1 * 512 = 512 bytes
Sector size (logical/physical): 512 bytes / 512 bytes
I/O size (minimum/optimal): 512 bytes / 512 bytes

Disk /dev/mmcblk1boot0: 16 MiB, 16777216 bytes, 32768 sectors
Units: sectors of 1 * 512 = 512 bytes
Sector size (logical/physical): 512 bytes / 512 bytes
I/O size (minimum/optimal): 512 bytes / 512 bytes

Такое чуство что он (линукс) чуствует флешку и пытаеться её примонтировать но всё четно

A: Разобрался, (плохо прочитал инструкции ) аппарат Marathon IOremote R2CPU читает флешки как на второй картинке. А до этого у меня были флешки только как на третьей картинке.
первая картинка

вторая картинка

третья картинка


text:
Q: Memory exhausted using php://input When using fopen("php://input") to upload a 120MB file we get a "memory exhausted" warning from php. The php memory_limit is set to 256MB and we have enough memory available.
We removed all the code except for fopen("php://input") and it is still failing, so the error must be in there.
We tried different memory limits and at about 500MB the error disappears. Still, we really shouldn't use 500MB so the question remains: Why do we get a memory exhausted error using fopen on a file that's 115-120MB in size.
Our php test-file:
<?php
    $inputHandler = fopen('php://input', "r");
?>

And the error:
262144000 bytes exhausted (tried to allocate 120829495 bytes)

I hope someone can help us out. This is driving us mad!
Thanks in advance!

A: Try to configure to unlimited memory usage:
ini_set('memory_limit', '-1');

A: It can be because php is trying to automatically parse POST data.
To disable this, in php version 5.4+ you can set enable_post_data_reading to 0. (I used .htaccess for this purpose)
But, actually, in php 5.4+ it is better to use $_FILES for uploads...


text:
Q: Which is more efficient way in Java to read csv file CSVReader or RandomAccessFile? I want to read a huge data file (csv format) containing rows and columns. I want to read and process individual columns in order. Which method is more efficient in terms of speed and memory utilization?
Shall I use CSVReader or Random Access File feature of Java?
Please help.
Thanks

A: If performance and efficiency are your utmost concern, use memory mapped files and NIO and write your own CSV parser.
But most often, this is just a waste of your time. So I suggest that you first try CSVReader and only if you find out that this doesn't work for you, you write your own CSV parser.
Also note that a BufferedReader will usually be faster than RandomAccessFile.


text:
Q: Reflection - Can't create a new object instance C# I am trying to create a plug-in type archetecure for my project. I would like the ability to load an assembly, get a type that is derived from an abstract base class in my project, instantiate it and load that derived type into the main processing object.
My problem right now is that when I instantiate the object from the reflected assembly, it is always null. I feel that the problem may lie in the fact that the referenced assembly has 3rd party dlls that it is using. Here is the code: the only exception that gets hit is the final one.
static void Main(string[] args)
{
    string engineFilePath = ConfigurationManager.AppSettings["EngineFilesDirectory"]
        + "\\" + ConfigurationManager.AppSettings["EngineDllFileName"];
    Assembly asm = Assembly.LoadFile(engineFilePath);

    Type engineType = asm.GetType(ConfigurationManager.AppSettings["EngineType"]);

    if (!engineType.IsSubclassOf(typeof(EngineConcrete)))
    {
        throw new ArgumentException("Engine is not derived from base implimentation.");
    }

    object engineInstance = asm.CreateInstance(engineType.Namespace + "." + engineType);

    if (engineInstance == null)
    {
       //always thrown at this point
        throw new Exception(string.Format("Engine object is null."));
    }

    return;
}

If I change the instantiation line to Activator.CreateInstance(engineType), I receive an error saying that one of the 3rd party dll's being referenced by the reflected assembly can't be found, though they are in the same directory as the .dll being reflected.
There is a public constructor for the type that is being reflected as well. It has no parameters and inherits from the EngineConcrete class.

A: This is the bug: engineType.Namespace + "." + engineType — this expression evaluates into "The.Namespace.The.Namespace.Type" instead of "The.Namespace.Type". Either use engineType.FullName or the Activator.CreateInstance class and use the engineType directly.
Update: Note that MSDN says "… or null if typeName is not found." about Assembly.CreateInstance's return value.

A: I think null is what you get when the type can't be found; the namespace name plus the type name may not be sufficient (strong naming issues). What happens if you put the 3rd-party dlls in the directory of the executing application, not the directory of the plugin?

A: The issue is that the CLR is not finding the third-party assemblies because they are not in a folder that is being probed.
You could add an event handler for the AppDomain.CurrentDomain.AssemblyResolve event to handle those cases.  Below is an example implementation that worked for me where assemblies are being dynamically loaded from a "Plugins" folder that is contained within the bin folder:
class Program
{
    static string _PluginDirectory;
    static string PluginDirectory
    {
        get
        {
            if (_PluginDirectory == null)
            {
                _PluginDirectory = System.IO.Path.Combine(System.IO.Path.GetDirectoryName(Assembly.GetEntryAssembly().Location), @"Plugins");
            }
            return _PluginDirectory;
        }
    }

    static Assembly CurrentDomain_AssemblyResolve(object sender, ResolveEventArgs args)
    {
        AssemblyName assemblyName = new AssemblyName(args.Name);
        return Assembly.LoadFile(System.IO.Path.Combine(PluginDirectory, assemblyName.Name + ".dll"));
    }

    static void Main(string[] args)
    {
        AppDomain.CurrentDomain.AssemblyResolve += new ResolveEventHandler(CurrentDomain_AssemblyResolve);

        var asm = Assembly.LoadFile(System.IO.Path.Combine(PluginDirectory, @"Plugin.dll"));

        var transmogrifier = asm.CreateInstance("Plugin.ConcreteTransmogrifier") as Common.Transmogrifier;

        if (transmogrifier != null)
        {
            Console.WriteLine(transmogrifier.Transmogrify("Wowzers!"));
        }
    }
}


text:
Q: ImagePicker results do not show up in a PhotoView I am new to Flutter and have progressed quite well in the last week or so. I am trying to use imagePicker to choose an image from my gallery. Reading and testing code from the web, I am able to bring in an image with no problems. However, I want to be able to zoom and pan using the functionality of the PhotoView Widget. I have tried to connect the code of imagePicker results into a PhotoView...but with no luck. Any help would be greatly appreciated. Thank you!
Please find my code below:
import 'package:flutter/material.dart';
import 'package:photo_view/photo_view.dart';
import 'dart:io';
import 'package:image_picker/image_picker.dart';

void main() { runApp(MaterialApp (
  title: 'FaceJam Trial',

initialRoute: '/',

    routes: {

    '/': (context)=> StartScreen(),

      '/second': (context) => Horizontal(),

      '/third': (context) => Vertical(),
    },

)

);

}

class StartScreen extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      //appBar: AppBar (),
        bottomNavigationBar: BottomAppBar(

          child: Row(
            mainAxisAlignment: MainAxisAlignment.spaceEvenly,
            children: <Widget>[
              IconButton(icon: Icon(Icons.border_horizontal,color: Colors.blue, size: 40,),
                onPressed: () {
                  Navigator.pushNamed(context, '/second');
                }
              ),
          IconButton(icon: Icon(Icons.border_vertical, color: Colors.blue,size: 40,),
            onPressed: () {
              Navigator.pushNamed(context, '/third');
            },

              )
            ],
          ),

        ) ,

      body: Container(
        decoration: BoxDecoration(
          image: DecorationImage(
            image: AssetImage("assets/Splash.jpg"),
            fit: BoxFit.cover,
          )
    ),
      ),

        );

  }

}

class Horizontal extends StatefulWidget {
@override
_HorizontalState createState() => _HorizontalState();
}

class _HorizontalState extends State<Horizontal> {

  File imageA;
  File imageB;

  Future getImageA() async{
    var image = await ImagePicker.pickImage(source: ImageSource.gallery);

     setState(() {
      imageA = image;
    });

  }

  Future getImageB() async {
    var images = await ImagePicker.pickImage(source: ImageSource.gallery);

    setState(() {
      imageB = images;
    });
  }

      @override
  Widget build(BuildContext context) {
    return Scaffold(
          body: Column(
              children: <Widget>[
                Expanded(
                    child: Stack (
                            children: <Widget>[
                              Center(
                                  child: PhotoView(
                                    enableRotation: true,
                                      imageProvider: AssetImage('imageA'),
                                  )
                                  ),

                              IconButton(
                                  icon:Icon(Icons.image,color: Colors.green, size: 40,),
                                  onPressed: getImageA
                              )
                            ],
                          )
                    ),
                    Expanded(
                        //child: Container(
                          child: ClipRect(
                                child: Stack (
                                  children: <Widget>[
                                    Center(

                                          child: PhotoView(
                                          enableRotation: true,
                                          imageProvider: AssetImage('imageB'),
                                          ),
                                           ),

                                    IconButton(
                                        icon:Icon(Icons.image,color: Colors.red, size: 40,),
                                        onPressed: getImageB
                                    )

                                  ],

                                )
                         ),
                         )
                       //  )
                        ]
                         ),
      floatingActionButton: FloatingActionButton(
          child: Icon(Icons.arrow_forward_ios),
      onPressed: () {
        Navigator.pop(context);

      },

    ),
    );

   }
}

class Vertical extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return Scaffold(
        body: Row(
            children: <Widget>[
              Expanded(
                child: Container(
                  child: PhotoView(
                    enableRotation: true,
                    imageProvider: NetworkImage('https://flutter.github.io/assets-for-api-docs/assets/widgets/owl.jpg'),
                  ),
                ),
              ),
              Expanded(
                  child: Container(
                    child: ClipRect(
                      child: PhotoView(
                        enableRotation: true,
                        imageProvider: NetworkImage('https://flutter.github.io/assets-for-api-docs/assets/widgets/owl.jpg'),
                      ),
                    ),
                  )
              )
            ]
        ),
      floatingActionButton: FloatingActionButton(
        child: Icon(Icons.arrow_forward_ios),
        onPressed: () {
          Navigator.pop(context);
        },
      ),
    );

  }
}

A: Remember that a File instance is an object that holds a path on which operations can be performed. So in this case, you only need to get the path of your Image File to use it in the AssetImage widget, try the next code:
Center(
    child: imageA != null
              ? PhotoView(
                  enableRotation: true,
                  imageProvider: AssetImage(imageA.path),
                )
              : Container()
 )


text:
Q: Search in select tag (without jquery and datalist) I need to search on select tag options.
I tried datalist it works but in input when I choose option goes value of option and I don't need that, with select there is no such problems.
Also tried jquery chosen and select2 didn't work for me, maybe because I use angular and it overwrites something.
Tried angular material with its mat-form-field does not work.
Hope someone could help.
Here's my code
<select class="form-control form-control-sm"
              [(ngModel)]="filters.userId">
        <option value=""></option>
        <option *ngFor="let user of users"
                [value]="user.id">

          <!--{{ user._profile?.lastName }}-->
          <!--{{ user._profile?.firstName }}-->
          <!--{{ user._profile?.fatherName }}-->

          {{ user.fullName }}

        </option>
</select>

A: The select field does not offer the option, to do a filter search trough it's items. Since you use angular, you can write your own component for this.


text:
Q: Reset counter on window functions I have a dataset like the below and I want to create a new column C that acts like a counter/row number which should get reset every time column B has 0 partitioned by column value of A
Using SparkSQL / SQL only (I can do it using Pyspark)
>>> rdd = sc.parallelize([
...     [1, 0], [1, 1],[1, 1], [1, 0], [1, 1],
...     [1, 1], [2, 1], [2, 1], [3, 0], [3, 1], [3, 1], [3, 1]])
>>> df = rdd.toDF(['A', 'B'])
>>>
>>> df.show()
+---+---+
|  A|  B|
+---+---+
|  1|  0|
|  1|  1|
|  1|  1|
|  1|  0|
|  1|  1|
|  1|  1|
|  2|  1|
|  2|  1|
|  3|  0|
|  3|  1|
|  3|  1|
|  3|  1|
+---+---+

What I would like to achieve
+---+---+---+
|  A|  B|  C|
+---+---+---+
|  1|  0|  1|
|  1|  1|  2|
|  1|  1|  3|
|  1|  0|  1|
|  1|  1|  2|
|  1|  1|  3|
|  2|  1|  1|
|  2|  1|  2|
|  3|  0|  1|
|  3|  1|  2|
|  3|  1|  3|
|  3|  1|  4|
+---+---+---+

What I have so far
>>> spark.sql('''
...    select *, row_number() over(partition by A order by A) as C from df
...    ''').show()

    +---+---+---+
    |  A|  B|  C|
    +---+---+---+
    |  1|  0|  1|
    |  1|  1|  2|
    |  1|  1|  3|
    |  1|  0|  4|
    |  1|  1|  5|
    |  1|  1|  6|
    |  3|  0|  1|
    |  3|  1|  2|
    |  3|  1|  3|
    |  3|  1|  4|
    |  2|  1|  1|
    |  2|  1|  2|
    +---+---+---+

A: SQL tables represent unordered sets.  You need a column that specifies the ordering of the data.
With such a column you can accumulate the 0 values because they appear to be breaks.  So:
select df.*, row_number() over (partition by A, grp order by A) as C
from (select df.*,
             sum(case when b = 0 then 1 else 0 end) over (partition by A order by <ordering column>) as grp
      from df
      ) df


text:
Q: $X$ is Hausdorff, $G$ is a finite group prove that $X/G$ is Hausdorff. I want to start this off by saying I've seen the other questions that are identical to this one, but I didn't really understand the suggestions given in those.
So the question states: Let $G$ act continuously on $X$ i.e the map $G\times X\to X$ sending $(g,x)\mapsto gx$ is continuous. Then define an equivalence relation $x\sim y$ if and only if there exists a $g\in G$ such that $gx=y$. Then give $X/\sim :=X/G$ the quotient topology. Show that if $X$ is Hausdorff and $G$ is finite then $X/G$ is Hausdorff.
I have my attempt bellow, however I am stuck on the last part where I want to show $U$ and $V$ are disjoint. I'm not really sure how to come to a conclusion.

Choose two orbits, $Gx\neq Gy$, then we have
$x\neq y$. Define $U_g$ and $V_g$ to be open neighbourhoods of $gx$
and $gy$ respectively, such that $U_g\cap V_h=\emptyset$ for all
$h,g\in G$, which we can do as $X$ is Hausdorff and $gx\neq hy$ as
they are in different orbits. Now consider all the sets $p(U_g)$ and
$p(V_g)$, I claim that $U=~\bigcap_{g\in G}p(U_g)$ and
$V=\bigcap_{g\in G}p(V_g)$ are disjoint neighbourhoods of
$\overline{x}$ and $\overline{y}$ (The equivalence classes of $x$ and $y$ respectively).
Since each $p(U_g)$ and $p(V_g)$ are open by Lemma 2 (Lemma 2 just
says $p$ is an open map), furthermore $U$ and $V$ are finite
intersections of these open sets, as $G$ is finite, we have that they
are open in $X/G$. $U$ certainly contains $\overline{x}$ as each $U_g$
contains $gx$ for some $g\in G$ which is equivalent to $x$, and with
an identical argument $V$ contains $\overline{y}$. Suppose for a
contradiction that $U\cap V$ is non-empty, take an element
$z\in~U\cap~V$ then $z\in p(U_g)$ and $z\in p(V_g)$ for each $g\in G$.

Thanks in advance.

A: Let $Gx\neq Gy$. The argument is very similar to what you have done so far!
Take $g\in G$. Since $g\cdot x \neq y$, there are open sets $U_{g},V_{g}$ such that $g\cdot x\in U_{g}$, $y\in V_{g}$ and $U_{g}\cap V_{g}=\emptyset$. Now choose the following open subsets:
$$
U=\bigcap_{g\in G}g^{-1}U_{g}, V=\bigcap_{g\in G}V_{g}.
$$
Since $G$ is finite and left translations are homeomorphisms, $U$ and $V$ are open neighbourhoods of $x$ and $y$. Notice that, for every $g$, $gU\cap V=\emptyset$.
Now, choose $p(U)$ and $p(V)$. We only need to prove that $p(U)\cap p(V)=\emptyset$.
Let $p(z)\in p(U)\cap p(V)$, so that $p(z)=p(a)=p(b)$ for some $a\in U$, $b\in V$. Therefore, for some $h\in G$, $b=ha\in V\cap hU$, which is a contradiction.
Hope this helps!


text:
Q: How to calculate means across rows of three multi-column dataframes? Let's say I have 3 data frames, each a 5x5 object as such:
set.seed(1)
x <-as.data.frame(matrix(rnorm(10),ncol=5,nrow=5))
colnames(x) <-c("a","b","c","d","e")

y <-as.data.frame(matrix(rnorm(10),ncol=5,nrow=5))
colnames(y) <-c("f","g","h","i","j")

z <-as.data.frame(matrix(rnorm(10),ncol=5,nrow=5))
colnames(z) <-c("k","l","m","n","o")

So, x, for instance, looks like:
  > x
           a          b          c          d          e
1 -0.6264538 -0.8204684 -0.6264538 -0.8204684 -0.6264538
2  0.1836433  0.4874291  0.1836433  0.4874291  0.1836433
3 -0.8356286  0.7383247 -0.8356286  0.7383247 -0.8356286
4  1.5952808  0.5757814  1.5952808  0.5757814  1.5952808
5  0.3295078 -0.3053884  0.3295078 -0.3053884  0.3295078

How can I efficiently calculate the means across rows for the 3 values in the same spot in each data frame? That is, calculate the mean for the 3 values in row 1/col 1 over the data frames, for instance. Easy to do manually, of course. For instance:
> mean(c(x$a[1],y$f[1],z$k[1]))
[1] 0.6014349

> mean(c(x$b[1],y$g[1],z$l[1]))
[1] -0.3071769

... and so on. But how can I do this efficiently in R for much larger data frames? I've tried mapply() and variations on apply() and sweep(), but no luck. I know there's a simple solution but I'm having brain-lock. Any help would be greatly appreciated!

A: I feel like I have to supply my trivial solution as an answer...
(x+y+z)/3

A: You can convert the data frames to matrices, calculate the mean, and convert the mean matrix back to a data frame format. Here is the code:
xx <- data.matrix(x)
yy <- data.matrix(y)
zz <- data.matrix(z)
mm <- (xx+yy+zz)/3
mean.df <- data.frame(mm)

A: another apporach:
rowMeans(sapply(list(x, y, z), function(x) unlist(x, use.names=FALSE)))

or, to get the 5x5 structure back and with the faster .rowMeans
rc <- dim(x)
d <- list(x, y, z)
r <- .rowMeans(sapply(d, function(x) unlist(x, use.names=FALSE)), prod(rc), length(d))
m <- matrix(r, nrow=rc[1])

A: Here is one way to generalise it while maintaining the matrix output:
apply(sapply(list(x,y,z), as.matrix, simplify="array"), 1:2, mean)
#              a           b          c           d          e
#[1,]  0.6014349 -0.30717691  0.6014349 -0.30717691  0.6014349
#[2,]  0.4518743  0.10514776  0.4518743  0.10514776  0.4518743
#[3,] -0.4607681  0.07046951 -0.4607681  0.07046951 -0.4607681
#[4,] -0.8695903  0.30628416 -0.8695903  0.30628416 -0.8695903
#[5,]  0.6914215  0.23548483  0.6914215  0.23548483  0.6914215


text:
Q: What is the origin of "pan" as a slang term for "face"? I was think of posting a picture of my ugly pan here instead of the gravatar, when I started to wonder, why is it my ugly pan? The slang term pan meaning face occurs chiefly in phrases such as ugly pan and smack in the pan, suggesting that is not very complimentary.
Green's Dictionary of Slang has several different meanings including the female pudenda, the mouth, the head and the anus but suggests no etymology.
Does anyone have any idea where the term came from?

A: The book American Slang gives the following entry for pan:

*

*The face. MUG. Too great for them to keep their pans shut. (1923+)

This seems to be when pan first entered American slang. From there, it went on to form words like deadpan (recorded in 1927). Only one site gave a hint to the actual origins, though. In this question about the origins of "deadpan", it is written that:

The key to "deadpan" is the use of "pan" as theatrical slang for "the face" (reflecting the use of "pan" to mean "skull," found as early as 1330).

Going off of this, there seems to be some support. The Word Origins page for skull says:

The Old English word for 'skull' was hēafodpanne, literally 'head-pan'. It has never been firmly established where its Middle English replacement skull came from, but is seems more than likely that it was borrowed from a Scandinavian language (Swedish and Norwegian have skalle 'skull').

So the old word for skull gave pan, which was adopted to mean face. From there, pan entered American slang in the early 1920s.

A: I suspect it's from the Hebrew פּנים, transliterated as "panim:" — oddly, a plural —, which means "face". (If there were a singular, it would be transliterated as pan.)


text:
Q: MDX using IIF and SUM At the following MDX code I want to get the aggregate of measure only for  members that are in the specified last time (like in example 01/06/2015), else I don't want them .
I tried existing and exists but without any luck.
I believe i have to use the IIF function
like:
IIF DAYTIME, MEASURE D NOT NULL THEN AGGREGATE....

(if for the specific month, measure D is bigger than 0 then SUM measure D for the specific time range)
ELSE NULL.

(Else not print it on output)
And then filter E.members where SUM measure D >1 ON ROWS.
WITH
  MEMBER A AS
    b + C
  MEMBER [Measures].[Aggregate] AS
    Aggregate
    (
        DAYTIME.[Month].&[2013-01-01T00:00:00]
      :
        [DAYTIME].[Month].&[2015-06-01T00:00:00]
     ,[Measures].[D]
    )
SELECT
  [Measures].[Aggregate] ON 0
 ,Filter
  (
    Exists
    (
      [E].MEMBERS
     ,[DAYTIME].[Month].&[2015-06-01T00:00:00]
    )
   ,
    [Measures].[Aggregate] > 1
  ) ON 1
FROM [CUBE];

A: Someone from MSDN forums reminded me the use of NONEMPTY. So first I used NONEMPTY like
Nonempty ( [E] , ( [DAYTIME].[Month].&[2015-06-01T00:00:00], [measures].[D] ) )
in order to return all E.Members who had an non-null value for measure.D on 2015-06-01
Then I filter this with another measure
I don't get correct data but I believe there is problem inside BI solution.

A: Try using Sum rather than Aggregate. Also as [DAYTIME].[Month].&[2015-06-01T00:00:00] is part of the measure [Measures].[Aggregate] you could delete the Exists function:
WITH
  MEMBER [Measures].[Aggregate] AS
    Sum
    (
        DAYTIME.[Month].&[2013-01-01T00:00:00]
      :
        [DAYTIME].[Month].&[2015-06-01T00:00:00]
     ,[Measures].[D]
    )
SELECT
  [Measures].[Aggregate] ON 0
 ,Filter
  (
    [E].MEMBERS
   ,[Measures].[Aggregate] > 1
  ) ON 1
FROM [CUBE];

Note: it is important that [Measures].[D] is related to these members [E].MEMBERS


text:
Q: Maximum execution time error in PHP script, is this a good solution to bypass it? I'm the only administrator of the database. I want to run a one time script that basically takes around 3800 scanned images (it will grow up to 10 000 thousand) and create a couple of thumbnails for each image using the PHP exec() function to execute the external program imagemagick to create those thumbnails.
I've created the script, launched it and all works perfectly! All is done on my local development server. The script takes around 11 minutes to create thousands of thumbnails. It's a one time operation that is run every other year, so the consequences are minimal.
So far so good. Here's when i running into problems.
Everything that i did on my local development server I did on the live server for testing purposes. I have a shared host account with hostgator. Running my 11 minutes long script on a shared host gives me the error 'Maximum execution time of 30 seconds exceeded...'. I did my research, tried many of the solutions found in this post (Increase max execution time for php) just to realize there is nothing i can do to change the maximum execution time of a script on a shared host.
I'm stuck. So, my question is what is the obvious solution here.
I was thinking of launching the script for every 200 images, refresh the page automatically and run the script again for the next 200 images and so on until there's no more images. This way i'm sure the 30 seconds maximum execution time allowed on my shared host is respected. It looks like a solution right off the top of my head, but i'm not sure if this is a NO NO, if i'm going to run into bigger problems, too many negatives..
Is this the obvious solution? Anyone run into the same problem? What did you guys suggest?
Thanks

A: Assuming you do have a reason to recreate the thumbnails in batch, instead of doing it at each image upload as was suggested, I'd do exactly as you did - use a script that refreshes itself - except that I wouldn't set a fixed number of images.
Rather I would have the script time itself after each image, and stop when it has reached, say, 25 seconds:
$stop = time() + 25;
while (time() < $stop) {
    ...find image to process, process it.
    if (finished()) {
        die("OK");
    }
}
// Redirect to next batch of images
die(Header('Location: ....'));

However, do check with your ISP, because your script might be either seen as an abuse of the service, or it could be mistaken for an attack. Also, enquire whether there's a preferred time of day to run this kind of maintenance.
Another, naughtier way of doing the same thing is to have the script run for a very small number of images (possibly a single one) every time someone hits the home page. This has the effect of having the extra load from the script mimic the real load on the server, avoiding embarrassing spikes or mysterious nonzero base loads. You do need to find a way of never choosing the same image from different instances of the script running in parallel (when I had to do this, I set a flag in a database).


text:
Q: How to show only table rows that have content in a Table View in Objective C This probably seems like an easy question, but I can't seem to find it.  The default behavior of the Table View seems to be to populate blank table cell rows to fill the entire screen even if you have only a few rows populated with labels.
I would like to only show rows that have labels and not when they are blank.  So for example if my Table View had only 5 labels, I would like to show only those 5 and not show rows to fill up the screen.
How do I accomplish this in the Storyboard attributes window if possible of via code?

A: Set the footer view on the table and it will accomplish what you want.
self.tableView.tableFooterView = [[UIView alloc] init];


text:
Q: Compare Values in a List and create Boolean Python I have a program in which I'm supposed to create a list of 5 numbers and then compare these items to see if they are all the same.  I am supposed to compare the numbers of the list and then return a Boolean if it is true or not.  (I'm relatively new to programming and am only allowed to use the random Library and the regular library).  If anyone could point me in the right direction, I'd really appreciate it.
I've tried things such as
if aList[0] = aList[1] and aList [2] and... aList[4]:
   Return = True.

Thanks!

A: Use a set():
def all_the_same(lst):
    # all values in aList are the same.
    return len(set(lst)) == 1

This works for any list of hashable values; strings, integers, booleans, tuples with hashable contents, floats (if they are exactly the same), etc.

A: return all(aList[0] == aList[i] for i in range(1, len(aList))

A: Here's a python3 variation that has short circuit behavior:
ix = iter(aList)
iy = iter(aList)
next(iy)
if all(x == y for x, y in zip(ix, iy)):
    do something


text:
Q: broken data texture rendering in newer three version I have code for rendering a static bitmap in three js.
This code works in v110 but not in v147. I crawled the changelog, but cannot find the difference.
Data I call the method with is a plain array of integer bitmap grey values so:
data.length === width*height and 0 < data[i] < 255
renderBitmap(data: Uint8Array, width: number, height: number): void {

    const camera = new PerspectiveCamera(45, width / height, 0.1, 10000);

    const texture = new DataTexture(data, width, height, LuminanceFormat);
    texture.flipY = true;

    const material = new MeshBasicMaterial({ map: texture });
    const geometry = new PlaneGeometry(width, height);
    const plane = new Mesh(geometry, material);

    this._dispose(ImageDataIdentifier.BITMAP);
    this.scene.add(plane);

    camera.position.z = width / (2 * Math.tan(MathUtils.degToRad(camera.fov / 2))) / camera.aspect;

    this.renderer.setSize(width, height);
    this.renderer.render(this.scene, camera);
  }

A: There are two issues in your code:

*

*As @prisoner849 mentioned in the comments, you have to set the needsUpdate to true when the DataTexture has been created.

*Second, you can't use THREE.LuminanceFormat with WebGL 2. If you want a grayscale texture, you have to expand your data to RGBA or use THREE.RedFormat and only sample the red channel in the shader. The latter option is probably not suitable for you since you use MeshBasicMaterial and not a custom shader.


text:
Q: Calling api in react with axios and search but don't know how to do it So here is the thing. I have the endpoint but don't know how to filter the response and list the result in the same way for every object.
I know this a very newbie intro question,  I appreciate any article that you guys think that can help.
import React, { useEffect, useState } from 'react';
import ReactDOM from 'react-dom';
import '../assets/styles/Shared.css';
import { MDBBtn } from 'mdbreact';
/////
import axios from 'axios';
import api from '../services/api';

class Home extends React.Component {
  render() {
    return (
      <>

              <input className="form-control mr-sm-2" type="text" placeholder="Search for vehicle" onClick={null} />
              <MDBBtn color="unique" rounded size="sm" type="submit" className="mr-auto">
                Pesquisar
              </MDBBtn>

THE SEARCH FOR THE VEHICLES

      </>
    );
  }
}

export default Home;

The data format is:
  {
    "id": "1",
    "title": "title 1",
    "model": "model 1",
    "brand": "brand 1",
    "year": 69,
    "color": 19,
    "km": 79,
    "price": 99
  },

A: To work with the returned JSON, you can use the function map().
You should filter the data in your backend because load all the information in frontend could make your app slow, but you can the function filter.
  const search = () => {
    axios.get(`${YOUR_URL}`)
      .then(res => {
        return res.data
      })
  }

  return (
    <>
    {search().map((item) => {
      return(

{ item.title }

        )
      })}
  </>
  )


text:
Q: How to slice pandas' dataframe / series into hours blocks based on index? I would like to save plots of 6h blocks from a dataframe containing data of multiple days (from 01.05.2018 to 18.05.2018).
My dataframe "EperDtPanda" has this form:
                               ldr
timestamp
2018-05-01T00:00:03.454+02:00  972
2018-05-01T00:00:08.532+02:00  972
2018-05-01T00:00:13.462+02:00  973
2018-05-01T00:00:18.467+02:00  973
2018-05-01T00:00:23.472+02:00  968
2018-05-01T00:00:28.480+02:00  972
2018-05-01T00:00:33.487+02:00  973
2018-05-01T00:00:38.484+02:00  970

My index is of type: "timestamp"
Im plotting the whole period of data, using this code:
indicies = map(lambda t: np.datetime64(t), EperEtPanda.index)
newIndextValues = map(lambda v: v[0], EperEtPanda.values)

ts = pd.Series(newIndextValues, index=indicies)
series2 = ts.resample('H').mean()
plt.plot(series2.index, series2.values)
plt.xticks(rotation='vertical');

And I get the plot attached, of 18 days of data.
Now I want to slice this plot into plots of 6h, and save the figures.
Here is the code I used to slice the graph into 6h blocks:
startDate = '2018-05-01T00:00:00+02:00'
endDate = '2018-05-18T00:00:00+02:00'
blockLength = 6
i = 0

while (str_to_ts(startDate) < str_to_ts(endDate)):
    mask = (EperEtPanda.index >= str_to_ts(startDate)) & (EperEtPanda.index <= (str_to_ts(startDate) + timedelta(hours=blockLength)))
    EperDtPanda6h = EperDtPanda.loc[mask]
    slice6h = EperDtPanda6h.plot()
    slice6h.get_figure().savefig('figure6h' + i + '.png')
    startDate = str_to_ts(startDate) + timedelta(hours=blockLength)
    i += 1

str_to_ts is a function which converts stings into timestamp:
str_to_ts =  udf (lambda d: datetime.strptime(d, "%Y-%m-%dT%H:%M:%S.%f+02:00"), TimestampType())

But it's not working..
Anyone has an idea how to get this done?

A: I think you can do:
# to ensure timestamp type for indexes (not necessary if it's already the case for you)
EperEtPanda.index = pd.to_datetime(EperEtPanda.index)
# start and end date as timestamps
startDate = pd.to_datetime('2018-05-01T00:00:00+02:00')
endDate = pd.to_datetime('2018-05-18T00:00:00+02:00')
# create all the time between start and end with a freq of 6 hours
list_time = pd.date_range(startDate, endDate, freq='6H')
# loop for with zip to have both start_time and end_time
i = 0
for start_time, end_time in zip(list_time[:-1], list_time[1:]):
    # select the 6h range with .loc and slice()
    EperDtPanda6h = EperDtPanda.loc[slice(start_time, end_time),'ldr']
    # plot and save
    EperDtPanda6h.plot().get_figure().savefig('figure6h' + i + '.png')
    i += 1

Hope it works for you


text:
Q: is that possible to set_session after session_destroy in codeigniter?   public function logout() {
        $this->session->sess_destroy();
        $sdata = array();

        $sdata['message'] = 'You are Successfully Logout !';
        $this->session->set_userdata($sdata);
        redirect('admin');
    }

I was trying to set session after destroy the session but session did not set and the $sdata['message'] = 'You are Successfully Logout !' did not showed in my admin page But when I tried this
public function logout() {
        $this->session->unset_userdata('admin_id');
        $sdata = array();
        $sdata['message'] = 'You are Successfully Logout !';
        $this->session->set_userdata($sdata);
        redirect('admin');
    }

then it worked.
what happened and what is the differences between them? any body tell me please


text:
Q: determine lag between two vector I want to find the minimum amount of lag between two vector , I mean the minimum distance that something is repeated in vector based on another one
for example for
x=[0 0 1 2 2 2 0 0 0 0]
y=[1 2 2 2 0 0 1 2 2 2]

I want to obtain 4 for x to y and obtain 2 for y to x .
I found out a finddelay(x,y) function that works correctly only for x to y (it gives -4 for y to x).
is there any function that only give me lag based on going to the right direction of the vector? I will be so thankful if you'd mind helping me to get this result

A: I think this may be a potential bug in finddelay. Note this excerpt from the documentation (emphasis mine):

X and Y need not be exact delayed copies of each other, as finddelay(X,Y) returns an estimate of the delay via cross-correlation. However this estimated delay has a useful meaning only if there is sufficient correlation between delayed versions of X and Y. Also, if several delays are possible, as in the case of periodic signals, the delay with the smallest absolute value is returned. In the case that both a positive and a negative delay with the same absolute value are possible, the positive delay is returned.

This would seem to imply that finddelay(y, x) should return 2, when it actually returns -4.
EDIT:
This would appear to be an issue related to floating-point errors introduced by xcorr as I describe in my answer to this related question. If you type type finddelay into the Command Window, you can see that finddelay uses xcorr internally. Even when the inputs to xcorr are integer values, the results (which you would expect to be integer values as well) can end up having floating-point errors that cause them to be slightly larger or smaller than an integer value. This can then change the indices where maxima would be located. The solution is to round the output from xcorr when you know your inputs are all integer values.
A better implementation of finddelay for integer values might be something like this, which would actually return the delay with the smallest absolute value:
function delay = finddelay_int(x, y)
  [d, lags] = xcorr(x, y);
  d = round(d);
  lags = -lags(d == max(d));
  [~, index] = min(abs(lags));
  delay = lags(index);
end

However, in your question you are asking for the positive delays to be returned, which won't necessarily be the smallest in absolute value. Here's a different implementation of finddelay that works correctly for integer values and gives preference to positive delays:
function delay = finddelay_pos(x, y)
  [d, lags] = xcorr(x, y);
  d = round(d);
  lags = -lags(d == max(d));
  index = (lags <= 0);
  if all(index)
    delay = lags(1);
  else
    delay = lags(find(index, 1)-1);
  end
end

And here are the various results for your test case:
>> x = [0 0 1 2 2 2 0 0 0 0];
>> y = [1 2 2 2 0 0 1 2 2 2];
>> [finddelay(x, y) finddelay(y, x)]  % The default behavior, which fails to find
                                      %   the delays with smallest absolute value
ans =

     4    -4

>> [finddelay_int(x, y) finddelay_int(y, x)]  % Correctly finds the delays with the
                                              %   smallest absolute value
ans =

    -2     2

>> [finddelay_pos(x, y) finddelay_pos(y, x)]  % Finds the smallest positive delays

ans =

     4     2


text:
Q: postman read property in json response which name is saved in array I am trying to check values of certain properties in json response in postman.
pm.expect(jsonData.property).not.equal(null);
The thing is, that I need to check multiple properties which names I have stored in an array.
var jsonData = pm.response.json();
var keys = ["id", "phoneNumber", "passwordHash"];

pm.test("All values have valid value", function(){
   for(var a = 0; a < keys.length; a++){
      pm.expect(jsonData.keys[a]).not.equal(null);
   };
});

But I am getting this error:

All values have valid type | TypeError: Cannot read property '0' of undefined

Can someone explain me, what am I doing wrong please?
Thanks for any advice.

A: You cann't use (.) dot to get a value of a unknown key, use [] bracket instead. Try this:
pm.expect(jsonData[keys[a]]).not.equal(null);

One subtle thing, in my opinion, use i (mean index) is better than a.


text:
Q: hiding gridview after reloading the webpage how can we clear the gridview when we click reload this page in browser in page load i used but this did not worked for me my requirement is after uploading to gridview if i click on reload this page my gridview should be disappeared again when i select a file it should be again uploaded how can i do this

A: When you click on the browser reload/refresh button you will lose the state of the page. Rather add a "Refresh" button to the page so you can manage the state of the page. Alternatively, just add code to run when the file is uploaded such as:
//As soon as the file is uploaded successfully
MyGridView.Enabled = false;
//Do other gridview processing here

A: //on page load
MyGridView.Visible= false;

and use on selected file
MyGridView.Visible= true;
MyGridView.Datasource = fileData;
MyGridView.Databind();


text:
Q: A simple assembly program? I've recently learned how to use MASM from MSVC++ IDE, and to test whether it works, I would like to run a short program.
However, I don't know any assembly yet (that which I do is useless: ie: even though I know what i+=1; is in C++, I can't do anything without int main()).
So where can I find a simple assembly program akin to the helloworld program used with C++? (It doesn't actually have to display "Hello, World!", it just has to do something so that I can make sure the set-up I have works).

A: Here is the MASM documentation online:
http://web.sau.edu/LillisKevinM/csci240/masmdocs/
Here is the difinitive tutorial on assembly:
http://webster.cs.ucr.edu/
I think that between the two of those you should be able to get up to speed and start writing programs.

A: To get you into a quick start I would suggest the following sites:
RADasm and WinASM.
From these sites you can find some examples, some prepackaged downloads with IDE and compiler. This way it is actually pretty easy to do some GUI-software early on but be warned, take care to read about x86 assembly. Check out wikibooks - x86 assembler.

A: Try this
global _main

_main:
mov ax, 0x01
mov bx, 0x02

inc ax
inc bx

jmp _main

Explanation:
1°_ you're saying to nasm to search for a _main label: global _main
2°_ you're declaring the _main label
3°_ you're changing the value of two cpu registers: ax and bx to 0x01 and 0x02 respectively
4°_ you're incrementing the values of ax and bx
5°_ lastly, you're jumping to _main, this mean you are in a infinite loop

A: You may find this site interesting:
Authoring Windows Applications In Assembly Language. You can download The Small Is Beautiful Starter Kit which contains a sample application to write a Windows program in assembly.


text:
Q: Нестандартная вёрстка, css "прилепить" к низу родительского

body
{
  width: 100%;
  height: 100%!important;
  min-height: 100%;
  margin: 0;
  padding: 0;
  background-color: #f0f0f0;
  color: #444;
  font-family: 'Open Sans', Helvetica, Arial, sans-serif;
  font-size: 14px;
}

#contents
{
  position: absolute;
  top: 0;
  bottom: 0;
  left: 200px;
  right: 0;
  overflow: auto;
  background-color: #0ff;
  border: 0px solid #ff0000;
}

#contentframe
{
  position: relative;
  right: 0;
  bottom: 0;
  width: 100%;
  height: 50%;
  margin: 0;
  padding: 0;
}

#lmenu
{
  position: absolute;
  width: 200px;
  min-width: 200px;
  top: 0;
  bottom: 0;
  left: 0;
  background-color: #6495ed;
}

#mapframe
{
  position: relative;
  right: 0;
  top: 0;
  width: 100%;
  height: 50%;
  min-height: 400px;
  background-color: #000;
}

#btmenu
{
  position: absolute;
  width: 100%;
  bottom: 0px;
  height: 40px;
  background-color: #ff0;
  border: 0px solid #0000ff;
}
<!DOCTYPE html>

    <meta charset="utf-8">
    <link rel="stylesheet" type="text/css" href="stylize/main_style.css">
    <title>tester</title>

    left menu

Преимущества

Покрытие. Сотни подробных схем городов России, Украины, Казахстана и Беларуси. Если официальная схема города недостаточно полная, используйте Народную карту, которую рисуют сами пользователи по спутниковым снимкам.

Дополнительная информация. Можно показать на карте автомобильные пробки и дорожные события. Или автоматически строить маршруты в России и Украине.

Управление. Управлять информацией на карте несложно.  Контент-менеджер сможет заносить данные на сайт в виде текста,  поскольку сервис геокодирования преобразует адрес в метку на карте автоматически. Также существует и обратный вариант — можно узнать адрес метки, просто кликнув в нужное место карты.

Нагрузка. Яндекс.Карты рассчитаны на миллионы пользователей, поэтому карта на вашем сайте выдержит любую нагрузку. Если вам нужно разместить на карте множество точек, вы можете их сгруппировать или использовать специальные технологии, чтобы не снижать производительность.

Индивидуальный дизайн. API Яндекс.Карт позволяет по своему усмотрению изменять внешний вид меток, всплывающих подсказок (балунов), линий и элементов управления. Также вы можете использовать расширенную библиотеку стандартных меток.

Поддержка мобильных устройств.
            С помощью Яндекс.Карт можно дополнить мобильную версию сайта. Карты подойдут для большинства мобильных устройств.

Безопасность.
            Информация, размещаемая на картах, сохраняется на сайте и не передается вовне (в том числе в Яндекс). Всё, что вы хотите показать на картах, останется вашим собственным контентом. А если ваш сайт работает по защищенному протоколу, вы можете подключиться к API Яндекс.Карт по HTTPS.

bottom menu

Нужно "прилепить" #btmenu к низу #contentframe. Никак не получается.
Спасибо.

A: Добавляем к #contentfram
position: relative;

а к #btmenu
position: absolute;
bottom: 0;
left:0;

A:

body
{
  width: 100%;
  height: 100%!important;
  min-height: 100%;
  margin: 0;
  padding: 0;
  background-color: #f0f0f0;
  color: #444;
  font-family: 'Open Sans', Helvetica, Arial, sans-serif;
  font-size: 14px;
}

#contents
{
  position: absolute;
  top: 0;
  bottom: 0;
  left: 200px;
  right: 0;
  overflow: auto;
  background-color: #0ff;
  border: 0px solid #ff0000;
}

#contentframe
{
  position: relative;
}

#lmenu
{
  position: absolute;
  width: 200px;
  min-width: 200px;
  top: 0;
  bottom: 0;
  left: 0;
  background-color: #6495ed;
}

#mapframe
{
  position: relative;
  right: 0;
  top: 0;
  width: 100%;
  height: 50%;
  min-height: 400px;
  background-color: #000;
}

#btmenu
{
  position: absolute;
  width: 100%;
  left:0px;
  bottom: 0px;
  height: 40px;
  background-color: #ff0;
  border: 0px solid #0000ff;
}
<!DOCTYPE html>

    <meta charset="utf-8">
    <link rel="stylesheet" type="text/css" href="stylize/main_style.css">
    <title>tester</title>

    left menu

Преимущества

Покрытие. Сотни подробных схем городов России, Украины, Казахстана и Беларуси. Если официальная схема города недостаточно полная, используйте Народную карту, которую рисуют сами пользователи по спутниковым снимкам.

Дополнительная информация. Можно показать на карте автомобильные пробки и дорожные события. Или автоматически строить маршруты в России и Украине.

Управление. Управлять информацией на карте несложно.  Контент-менеджер сможет заносить данные на сайт в виде текста,  поскольку сервис геокодирования преобразует адрес в метку на карте автоматически. Также существует и обратный вариант — можно узнать адрес метки, просто кликнув в нужное место карты.

Нагрузка. Яндекс.Карты рассчитаны на миллионы пользователей, поэтому карта на вашем сайте выдержит любую нагрузку. Если вам нужно разместить на карте множество точек, вы можете их сгруппировать или использовать специальные технологии, чтобы не снижать производительность.

Индивидуальный дизайн. API Яндекс.Карт позволяет по своему усмотрению изменять внешний вид меток, всплывающих подсказок (балунов), линий и элементов управления. Также вы можете использовать расширенную библиотеку стандартных меток.

Поддержка мобильных устройств.
            С помощью Яндекс.Карт можно дополнить мобильную версию сайта. Карты подойдут для большинства мобильных устройств.

Безопасность.
            Информация, размещаемая на картах, сохраняется на сайте и не передается вовне (в том числе в Яндекс). Всё, что вы хотите показать на картах, останется вашим собственным контентом. А если ваш сайт работает по защищенному протоколу, вы можете подключиться к API Яндекс.Карт по HTTPS.

bottom menu


text:
Q: Oracle Enterprise Server SOAP/Servlet/SoapRouter Does anyone know any sample Oracle SOAP XML requests that that queries the database?
For example, the url:
http://myoracle:7778/oracle/soap/soaprouter/
I'd like to program xml requests and get return xml database.
But I have no idea on the Oracle SOAP format.
Please provide an example.

A: The documentation here goes into detail about the Oracle Application Server SOAP format:
http://download-east.oracle.com/docs/cd/B15904_01/web.1012/b14027/oraclesoap.htm
It looks like it is based on Apache 2.3.1 SOAP with some minor enhancements.
You would need to create your own service (the code to fetch data from the database), then expose this web service so you can send SOAP requests to it and get responses back.  Some sample services are mentioned in the docs and should be included with the application server.


text:
Q: Is it possible to set ofFloat to multiple targets? I have this fade in function
    private void fadeIn() {
        ObjectAnimator objectAnimator = ObjectAnimator.ofFloat(ButtonA, "alpha", 0f, 1f);

        objectAnimator.setDuration(2000L);
        objectAnimator.addListener(new AnimatorListenerAdapter() {
        });
        objectAnimator.start();
}

and right now the only target is ButtonA, i have 3 more buttons (ButtonB, ButtonC ....) is there anyway i can target all four without writing this codesnippet 4 times over?

A: try this
private static void fadeIn(long duration, final View... views) {
    if (views == null) return;
    final ValueAnimator va = ValueAnimator.ofFloat(0, 1);
    va.setDuration(duration);
    va.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
        @Override
        public void onAnimationUpdate(ValueAnimator animator) {
            final float alpha = (float) animator.getAnimatedValue();
            for (View view : views) view.setAlpha(alpha);
        }
    });
    va.start();
}

how to use:
// first argument duration and then pass any number of views
fadeIn(2000, buttonA, buttonB, buttonC);


text:
Q: Scipy Interpolate splrep Data Error? I am writing the following code, pretty basic , just calling splrep in scipy.interpolate.
However it throws and error on the dataset.
Following is the code
x_nodesTrial = np.array([ 1321.,  1327.,  1329.,  1326.,  1329.,  1327.,  1328.,  1336.,
        1335.,  1326.,  1327.,  1323.,  1337.,  1338.,  1337.,  1338.,
        1338.,  1338.,  1340.,  1340.,  1337.,  1334.,  1333.,  1342.,
        1343.,  1340.,  1344.,  1343.,  1346.,  1347.,  1348.,  1346.,
        1374.,  1377.,  1372.,  1378.,  1380.,  1384.,  1390.,  1391.,
        1386.,  1397.,  1395.,  1396.,  1397.,  1398.,  1399.,  1399.,
        1399.])

y_nodesTrial = np.array([ 0.97897541,  0.60222801,  0.95832816,  1.2578326 ,  1.08685326,
        1.29256113,  0.78091064,  0.96806139,  0.92957363,  0.46117087,
        0.72456884,  1.04872371,  0.87137002,  1.03914457,  0.74450367,
        0.96806139,  0.93808315,  0.79181076,  0.84673744,  1.15069855,
        0.8782084 ,  1.14509825,  0.97970477,  0.91182705,  1.12178111,
        1.07171425,  0.58492979,  0.89831191,  1.17473401,  0.97970477,
        0.87013956,  1.1568893 ,  1.01242284,  0.7309485 ,  1.00418766,
        1.04394513,  1.08947891,  0.81053333,  1.21184629,  0.94566681,
        0.73630351,  0.86839343,  1.07495847,  0.87003695,  0.        ,
        1.01559272,  0.97504579,  1.0377689 ,  1.05694979])

k = 3
tck = inter.splrep(x_nodesTrial, y_nodesTrial, k=k, s=0)

I get the following error:

k = 3
tck = inter.splrep(x_nodesTrial, y_nodesTrial, k=k, s=0)

Traceback:
Traceback (most recent call last):

  File "<ipython-input-24-a978d88e9773>", line 2, in <module>
    tck = inter.splrep(x_nodesTrial, y_nodesTrial, k=k, s=0)

  File "C:\Anaconda\lib\site-packages\scipy\interpolate\fitpack.py", line 278, in splrep
    res = _impl.splrep(x, y, w, xb, xe, k, task, s, t, full_output, per, quiet)

  File "C:\Anaconda\lib\site-packages\scipy\interpolate\_fitpack_impl.py", line 515, in splrep
    raise _iermess[ier][1](_iermess[ier][0])

ValueError: Error on input data

Can someone help point out what is wrong with the above code/dataset ?
Appreciate the help.
Thanks

A: It's because your x-values aren't sorted from smallest to biggest


text:
Q: How to convert a string to number in scheme without removing the leading zero? I want to convert a string to a number in Scheme, but when I use the function string->number it removes the leading zero
For example
(string->number "01") gives me 1
Is there a way to convert the string so that it doesnt remove the leading zero and gives me 01 instead?

A: You can't: leading zeros are just part of the written representation of numbers, not part of the number itself. In particular 01, 1 and 00000001 are all the same number.
If you want to print numbers with leading zeros, for instance to line things up, then there are utilities which do that.  For instance in Racket, while the format / printf family of procedures cannot do this, the procedures provided by racket/format can:
> (require racket/format)
> (~a 1 #:width 2 #:align 'right #:pad-string "0")
"01"

However you will still need to deal with negative numbers yourself, which is rather annoying.


text:
Q: Why does Visual Studio open decoratedxaml in debug folder than opening my actual xaml when there is a syntax error failing the build I have a Windows Universal App. I use Visual Studio 2013 Update 2
If I have made syntactical mistakes or used a converter without declaring it's namespace at the top, VS points out errors when trying to build as usual.
But when I click on the error to Navigate to the line that is causing the error.
Instead of opening my actual xaml page residing \Pages, it opens the xaml page in \obj\x86\Debug\decoratedxaml\Pages
However this is not consistent, for some errors it opens the actual file and the decoratedxaml for some others.
This causes problems like me trying to edit the decoratedxaml by mistake and when trying to build again, the build fails and decoratedxaml will be modified to the previous version by Visual Studio.
Is this expected behavior?
Also is there a setting which I can enable so that it will always open the actual file.
I would be glad if someone can guide me in the right direction.
Thanks in Advance.


text:
Q: Spring OAuth2 Password Flow keeps failing I'm trying to enable OAuth2 Password Flow in my Spring Boot application, however, I just can't get it to run, no matter what I try.
There following are my configurations.
For the TokenStore I configured a JdbcTokenStore bean and the UserDetailsService is simply loading the user from my custom user tables.
I also added the the property security.oauth2.resource.filter-order=3.
For Spring Boot I'm using 2.0.0.RELEASE and for Spring Security 2.3.0.RELEASE.
Both the authorization server and the resource server are in a single application.
The following POST (with SoapUI) keeps failing:
http://localhost:8080/oauth/token?grant_type=password&username=hans.wurst&password=bla&client_id=androidAppClient

I get the message

Access is denied (user is anonymous);

Debug tells me that the following filters were applied:
Security filter chain: [
  WebAsyncManagerIntegrationFilter
  SecurityContextPersistenceFilter
  HeaderWriterFilter
  LogoutFilter
  BasicAuthenticationFilter
  RequestCacheAwareFilter
  SecurityContextHolderAwareRequestFilter
  AnonymousAuthenticationFilter
  SessionManagementFilter
  ExceptionTranslationFilter
  FilterSecurityInterceptor
]

Authorization server:
@Configuration
@EnableAuthorizationServer
class AuthorizationServerConfiguration : AuthorizationServerConfigurerAdapter() {

    @Autowired
    private lateinit var dataSource: DataSource

    @Autowired
    private lateinit var tokenStore: TokenStore

    @Autowired
    @Qualifier("authenticationManagerBean")
    private lateinit var authenticationManager: AuthenticationManager

    override fun configure(clients: ClientDetailsServiceConfigurer) {
        clients.jdbc(dataSource)
    }

    override fun configure(endpoints: AuthorizationServerEndpointsConfigurer) {
        endpoints
                .authenticationManager(authenticationManager)
                .tokenStore(tokenStore)
    }

}

Web security:
@Configuration
class WebSecurityConfiguration : WebSecurityConfigurerAdapter() {

    @Autowired
    @Qualifier(USER_DETAILS_SERVICE)
    private lateinit var userDetailsService: UserDetailsService

    @Bean
    @Throws(Exception::class)
    override fun authenticationManagerBean(): AuthenticationManager = super.authenticationManagerBean()

    @Throws(Exception::class)
    override fun configure(web: WebSecurity) {
        web.debug(true)
    }

    override fun configure(auth: AuthenticationManagerBuilder) {
        auth.userDetailsService(userDetailsService)
    }

    override fun configure(http: HttpSecurity) {
        http
                .authorizeRequests()
                .anyRequest()
                .authenticated()
    }
}

Resource server:
@Configuration
@EnableResourceServer
class ResourceServerConfiguration : ResourceServerConfigurerAdapter() {

    override fun configure(http: HttpSecurity) {
        http
                .authorizeRequests()
                .antMatchers("/registration", "/customer/check")
                .anonymous()
                .anyRequest()
                .authenticated()
    }

}

User details service:
const val USER_DETAILS_SERVICE = "userDetailsService";

@Transactional
@Service(USER_DETAILS_SERVICE)
class CustomerUserDetailsService @Autowired constructor(private val customerRepository: CustomerRepository) : UserDetailsService {

    @Throws(UsernameNotFoundException::class)
    override fun loadUserByUsername(username: String): UserDetails =
            customerRepository
                    .findCustomerCredentialsByUserName(username)
                    ?.let { User(it.userName, it.password, emptyList()) }
                    ?: throw UsernameNotFoundException("Could not find customer with username $username")
}

A: It appears that client androidAppClient doesn't have password grant type set in authorized_grant_types.
Check client details table in DB (oauth_client_details), make sure password grant type is set for this client. If it is set along with other grant types then make sure there are no spaces in grant types like, ('password,refresh_token').
The /oauth/token endpoint's post request expects client credentials in Base64 "clientId:clientSecret" format.
curl --request POST \
  --url http://localhost:8443/auth-service/oauth/token \
  --header 'authorization: Basic UkVXQVJEU19QT1QUxfQURNSU46cGFzc3dvcmQ=' \
  --header 'content-type: multipart/form-data; boundary=---011000010111000001101001' \
  --form username=testuser \
  --form password=password \
  --form grant_type=password


text:
Q: Is there a possibility to get here maps api autocomplete method with typo fixing? For example when putting 'barclona' autocomplete response should be 'barcelona'

A: Currently Geocoder Autocomplete API doesn't support auto correction.
What it supports :
 street types abbreviated and spelled out
 Multi-language: Returns language that matches the input best
 Special characters, e.g. umlauts, accents etc.
We will let this know to our team as suggestion.
Thank you!


text:
Q: RandomVariate with a custom distribution I have a customized distribution and I have to draw some random number from it.
How do I use RandomVariate to draw random number from a custum distribution? My naive attempt RandomVariate[mydist] fails with and Mathematica throws the error:

RandomVariate::udist: "The specification  is not a
  random distribution recognized by the system"

My distribution is:
me =511000;
M = 938000000;
c = 29979200;
en=10^8;
z = 1;
ρ = 2.33;
en = 10^6;
τ[T_?NumericQ] := T/M ;
β[T_?NumericQ] := Sqrt[1 - (1/(τ[T] + 1))^2];
wm[T_?NumericQ] := (2 me β[T]^2)/(1 - β[T]^2);
Zs[T_?NumericQ] = z (1 - Exp[-((125 β[T])/z^(2/3))]);

mydist[w_]:= 1/Σ[en] 0.307075*14/28.0855 10^6 ρ 10^-4/(β[en]^2 (w + 173)^2) (1 - (β[en]^2 (w + 173))/wm[en] + (Pi β[en] Zs[en]^2)/137 Sqrt[(w + 173)/wm[en]] (1 - (w + 173)/wm[en]))

$\Sigma[en]$ is the normalization, the integral of the rest between 1 and w[en]


text:
Q: SQL query to sum up with specific conditions I'm writing SQL query to sum up values according to group assigned. I have database like:
Table A
+----+--------+
| id | group  |
+----+--------+
|  A1| A      |
|  A2| A      |
|  B1| B      |
+----+--------+

Table B:
+----+--------+
| id | Amount |
+----+--------+
|  A1| 10     |
|  A1| 20     |
|  B1| 5      |
|  A2| 10     |
+----+--------+

I wish to obtain results like this:
+----+--------+
| id | Amount |
+----+--------+
|  A1| 40     |
|  B1| 5      |
+----+--------+

FYI I'm using MySQL as my DBMS
 The expected results will show the min id and add up the amount from the same group

A: select min(a.id) as id,
       sum(b.amount) as total
from tableB b
join tableA a on a.id = b.id
group by a.`group`

A: Simple join and group by :
SELECT MIN(a.id),sum(b.amount)
FROM TableA a
JOIN TableB b
 ON(a.id = b.id)
GROUP BY a.group

If you specificly wanted A1,B1 as ID, then please explain this logic.

A: Have you try using SUM and GROUP BY?
SELECT SUM (Amount) FROM table GROUP BY id

A: SELECT
      (select top 1 A2.id from TableA as A2 where A2.[group] = A.[group]) as id,
      sum(B.Amount) as Amount
FROM TableA as A
  left join TableB as B on B.id = A.id
group by A.[group]

This code runs on MS SQL 2012. You can independently verify it works on MYSQL or not.

A: SELECT A.id, SUM(B.amount) as amount
FROM A
INNER JOIN B ON A.id = B.id
GROUP BY A.group

More about join:
MySQL JOIN


text:
Q: Duplicate objects in core data I have a problem, my objects every time I save them are reflected in uitableview in a duplicate way, does anyone know how to solve it or if I have a problem in my code?
   import UIKit
   import CoreData
   import Foundation

  class ViewController: UIViewController {

//MARK:= Outles
@IBOutlet var tableView: UITableView!

//MARK:= variables
var context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
var items: [Entity]?
var duplicateName:String = ""

//MARK:= Overrides
override func viewDidLoad() {
    super.viewDidLoad()
    tableView.delegate = self
    tableView.dataSource = self

    fetchPeople()
    addPeople(context)
    print(" nombres: \(items?.count)")

}

override func viewWillAppear(_ animated: Bool) {

}

//MARK:= Core Data funcs

func fetchPeople(){
    do{
        self.items = try! context.fetch(Entity.fetchRequest())

        DispatchQueue.main.async {
            self.tableView.reloadData()
        }

    }catch let error as NSError{
        print("Tenemos este error \(error.debugDescription)")
    }

}

func addPeople(_ contexto: NSManagedObjectContext) {

    let usuario = Entity(context: contexto);
    usuario.nombre = "Valeria";
    usuario.edad = 25;
    usuario.eresHombre = false;
    usuario.origen = "Ensenada,B.C"
    usuario.dia = Date();
    do{
        try! contexto.save();

    }catch let error as NSError{
        print("tenemos este error en el guardado \(error.debugDescription)");
    }
    fetchPeople()

}

func deletDuplicates(_ contexto: NSManagedObjectContext){

    let fetchDuplicates = NSFetchRequest<NSFetchRequestResult>(entityName: "Persona")
   //
       //        do {
      //            items = try! (contexto.fetch(fetchDuplicates) as! [Entity])
      //        } catch let error as NSError {
  //            print("Tenemos este error en los duplicados\(error.code)")
       //        }

   let rediciendArray = items!.reduce(into: [:], { $0[$1,default:0] += 1})
    print("reduce \(rediciendArray)")
    let sorteandolos = rediciendArray.sorted(by: {$0.value > $1.value })
    print("sorted \(sorteandolos)")
    let map = sorteandolos.map({$0.key})

    print(" map : \(map)")
  }

} // End of class

I have tried to solve the error and I have investigated what it is for my array but the truth is that I have not had the solution no matter how much I look for it, if someone could help me it would be of great help.
I attach a photo of my results

I attach my code of tableview functions
 extension ViewController : UITableViewDelegate,UITableViewDataSource{

 func numberOfSections(in tableView: UITableView) -> Int {
    return 4
}

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    items?.count ?? 0
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

    let celda = tableView.dequeueReusableCell(withIdentifier: "Celda", for: indexPath);
    var detalle = "Lugar de Origen: " + self.items![indexPath.row].origen! + "\n"  +  "Edad: " + String(self.items![indexPath.row].edad) + "\n" + "Dia: " + String(self.items![indexPath.row].dia.debugDescription)

    celda.textLabel?.text = self.items![indexPath.row].nombre
    celda.detailTextLabel?.text = detalle

    return celda
}

func tableView(_ tableView: UITableView, trailingSwipeActionsConfigurationForRowAt indexPath: IndexPath) -> UISwipeActionsConfiguration? {

   let delete = UIContextualAction(style: .normal, title: "Delete") { (action, view, completionHandler) in

    let personToRemove = self.items![indexPath.row]
                   self.context.delete(personToRemove)
                   do{
                       try self.context.save()
                   }catch let error {
                       print("error \(error.localizedDescription)")
                   }
                   self.fetchPeople()
                   self.tableView.reloadData()

            }

                delete.backgroundColor = UIColor.red
                let config = UISwipeActionsConfiguration(actions: [delete])
                config.performsFirstActionWithFullSwipe = false
                return config
}

func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
    return 80
}

}

A: The problem is that numberOfSections(in tableView:) always returns 4. However, you don't seem to group your data rows in any way. Therefore, the table view displays 4 sections without headers and because you aren't checking the section number in tableView(_ tableView:, cellForRowAt indexPath:), you get four identical cells in each section.
Change 4 to 1 in numberOfSections(in tableView:) and the duplicates will go away.
P.S. On a side note, you might want to use NSFetchedResultsController instead of just fetching items into an array, it couples really well with UITableViewDataSource.


text:
Q: Двойное срабатывание JS кода Есть форма
<form id="subscribe">
 <input type="hidden" name="project_name" value="blabla">
 <input type="hidden" name="admin_email" value="blabla@blabla.ru">
 <input type="hidden" name="form_subject" value="Test text">
 <input type="text" size="60" name="E-Mail" placeholder="Введите e-mail" required>
 <button>Подписаться</button>
</form>

Есть JS, использующий Jquery для сабмита
$(document).ready(function() {
    $("#subscribe").submit(function() {
        var th = $(this);
        $.ajax({
            type: "POST",
            url: "script.php",
            data: th.serialize()
        }).done(function() {
            alert("Спасибо!");
            setTimeout(function() {
                th.trigger("reset");
            }, 1000);
        });
        return false;
    });
});

При нажатии скрипт срабатывает, но почему-то выдает 2 алерта и отправляет 2 письма. Больше подключений этого скрипта или формы с подобным id нет.
Подскажите в чем может быть проблема и почему код может срабатывать 2 раза?

A: Кажется проблема найдена. Изначально скрипт был вставлен в страницу сразу после формы, обернутой в div. Перенес его под закрытие тега body - срабатывать начал 1 раз.
Причина такого странного поведения, к сожалению, мне не понятна.

A: <form id="subscribe">
 <input type="hidden" name="project_name" value="blabla">
 <input type="hidden" name="admin_email" value="blabla@blabla.ru">
 <input type="hidden" name="form_subject" value="Test text">
 <input type="text" size="60" name="E-Mail" placeholder="Введите e-mail" required>
 <button type="button" class="submit">Подписаться</button>
</form>

По умолчанию у <button> type="submit" и тем самым вы пинаете два раза один и тот же запрос...
$(function() {
    $(".submit").on('click', function() {
        var th = $('#subscribe');
        $.ajax({
            type: "POST",
            url: "script.php",
            data: th.serialize()
        }).done(function() {
            alert("Спасибо!");
            setTimeout(function() {
                th.trigger("reset");
            }, 1000);
        });
    });
});

Вот так не должно отправлять 2 запроса


text:
Q: Custom C# HttpModule Infinite Redirect Loop I am writing a custom c# HttpModule that will handle requests from all file types. As a simple proof of concept I have setup the module by adding a reference to the httpModules section of the web config and added application extensions for the demo IIS website with a reference to the aspnet_isapi.dll so that it currently only intercepts request for ".htm" files
But even if there is no significant code in the "OnBeginRequest" event (code below) it causes an infinite redirect loop. I am using IIS 5 on XP Anyone got any ideas?
So far I have only seen HttpModule examples for use with ASPX files but surely you can configure the for any file type?

#region IHttpModule Members

        public void Dispose() { }

        public void Init(HttpApplication context)
        {
            context.BeginRequest += new EventHandler(OnBeginRequest);
        }

        ///
        ///
        ///
        ///
        public void OnBeginRequest(Object s, EventArgs e)
        {
            HttpApplication context = s as HttpApplication;

            Uri currentURL = context.Request.Url;
            string pageName = currentURL.Segments.Last().ToLower();
        }
#endregion

A: OK. The problem was actually in the HttpModule itself.
It appears that you have to use the HttpApplication context in order for it to render on the client.
For Example after you have performed all your custom logic you need to write to the context:

context.Response.Write("/n/r");

//or

context.Response.Redirect("test.htm");

Everything then renders as you would expect


text:
Q: Deference C# List pointer externally I am working in a project in which I reverse engineer a C# application that has a List. I have managed to get the raw pointer to that list externally and I'd like to iterate through it's contents in C++. I do not know how C#'s List is implemented, I've read it works in a similar way as the C++'s std::vector. How would I go about accessing the List's contents? Upon deferencing the List pointer I saw a two values that look like pointers and one that appears to be the List's length, but deferencing those pointers I couldn't get to anything the resembles the element type...
I doubt they are implemented identically, but I wonder if casting the pointer to an std::vector would work. I have the type's size which I supposed would be required to go through the elements.


text:
Q: DISCORD PY Bot isn't responding to commands, no traceback error I have a feeling that the on_message function is affecting my code however I don't know how else I can define message for the chat easter eggs (the messages about moe).
My code:
    import discord
    from discord.ext import commands
    import asyncio

    client = commands.Bot(command_prefix="*" , case_insensitive=True ,status=discord.Status.idle, activity=discord.Game("Starting up..."))
    client.remove_command("help")

    @client.event
    async def on_ready():
        await client.change_presence(status=discord.Status.do_not_disturb, activity=discord.Game("Preparing Puzzle Event"))
        print("Bot is running.")
    @client.command()
    async def hello(ctx):
      await ctx.send("Hi")

    @client.group(invoke_without_command=True)
    async def help(ctx):
        em = discord.Embed(title = "**Command List**" , color = ctx.author.color)
        em.add_field(name = "puzzle1", value = "Starts the first puzzle")
        em.add_field(name = "wisdom", value = "Gives wise wisdom")
        await ctx.send(embed = em)
    @client.command()
    async def wisdom(ctx):
        await ctx.send("Stan Loona")
    @client.command()
    async def clue(ctx):
        await ctx.send("Which puzzle do you want a clue for? \n *1 or *2")

    @client.event
    async def on_message(message):
        if message.author == client.user:
            return
        elif message.content.startswith('Moe'):
            await message.channel.send('Is an icon')
        elif message.content.startswith('moe'):
            await message.channel.send('Is an icon')
client.run(My token)

There is no traceback error, it doesn't even say the bot is online, nothing runs at all.

A: You need to add client.process_commands at the end of the on_mesage event
@client.event
async def on_message(message):
    # ...

    await client.process_commands(message)

Reference:

*

*Bot.process_commands


text:
Q: Explicit quantization of free fermionic field The canonical quantization of a scalar field $\phi(x)$ can explicitly be realized in the space of functionals in fields $\phi(\vec x)$ (here $\vec x$ is spacial variable) by operators
\begin{eqnarray}
\phi(\vec x,0)\to \mbox{ multiplication by } \phi(\vec x,0),\\
\pi(\vec x,0)\to (-i)\frac{\delta}{\delta \phi(\vec x)}.
\end{eqnarray}
Thus, as usual, $[\phi(\vec x,t),\pi(\vec y,t)]=i\delta^{(3)}(\vec x-\vec y)$.
(See e.g. $\S$ 9.1 in S. Weinberg's book "The QFT", particularly the discussion after formula (9.1.40).)

I am looking for an analogous realization of canonical quantization of a fermionic field. At the moment the case of a free fermionic field is enough for me. In addition I would be interested to know how the vacuum vector in this space looks like; more concretely I would like to know the explicit form of $\epsilon$-terms in (9.5.49) in Weinberg's book.

The discussion of the fermionic case in Weinberg's book is not as detailed as in  the scalar case.

A: I would suggest that you have a look at grassmann algebra of fermionic fields. I think it will help. Some references include: Quantization of Gauge theories by Hennnaux, Quantum Field Theory Volume 3 by Weinberg, Superfield formalism of supersymmetry (this can be found in most supersymmetry books like Wess Bagger, Buchbinder, etc). I personally haven't seen canonical quantization in these references, but I think these fermionic operators in superfield notation might help create the analogy.