text:
Q: Retaining next n rows and previous k rows with pandas merge I am merging two dfs and would like to access the first n rows of column after matching.
Where there is a match between events_df['event'] and prices_df['date']
and also a match between
events_df['ticker'] and prices_df['tic']
I would like to retain the first n values after and including the matched row from prices_df['price']
events_df

  event ticker
0 01-01-2019  MSFT
1 12-12-2018  MSFT
2 12-11-2018  MSFT
3 02-03-2019  AAPL
4 12-12-2018  AAPL
5 12-11-2018  AAPL
6 01-01-2019  AAPL

prices_df

  date tic price
0 01-01-2019 MSFT 1.0
1 02-01-2019 MSFT 1.1
2 03-01-2019 MSFT 1.2
3 04-01-2019 MSFT 1.3
4 05-01-2019 MSFT 1.4
5 01-01-2019 AAPL 2.0
6 02-01-2019 AAPL 2.1
7 03-01-2019 AAPL 2.2
8 04-01-2019 AAPL 2.3
9 05-01-2019 AAPL 2.4

I've already tried merging
merged = events_df.merge(prices_df,left_on=['ticker','event'],right_on=['tic','date'])

Expected output for n = 4 (from matching events_df['events'] index 0,6)
  date ticker price
0 01-01-2019 MSFT 1.0
1 02-01-2019 MSFT 1.1
2 03-01-2019 MSFT 1.2
3 04-01-2019 MSFT 1.3
4 01-01-2019 AAPL 2.0
5 02-01-2019 AAPL 2.1
6 03-01-2019 AAPL 2.2
7 04-01-2019 AAPL 2.3

A: Use:
#changed sample data for more general
print (prices_df)
          date   tic  price
0   01-01-2018  MSFT    1.0
1   01-01-2019  MSFT    1.0
2   02-01-2019  MSFT    1.1
3   03-01-2019  MSFT    1.2
4   04-01-2019  MSFT    1.3
5   05-01-2019  MSFT    1.4
6   01-01-2019  AAPL    2.0
7   02-01-2019  AAPL    2.1
8   03-01-2019  AAPL    2.2
9   04-01-2019  AAPL    2.3
10  05-01-2019  AAPL    2.4

#n to down, k to up
n = 2
k = 1
#get index by reset_index for avoid lost it
idx = events_df.merge(prices_df.rename_axis('idx').reset_index(),
                         left_on=['ticker','event'],
                         right_on=['tic','date'])['idx']

print (idx)
0    1
1    6
Name: idx, dtype: int64

#create groups by matching with original index, [::-1] for change ordering
s1 = prices_df.index.isin(idx).cumsum()
s2 = prices_df.index.isin(idx)[::-1].cumsum()

#repalce first and last groups to NaNs
up = np.where(s1 != 0, s1, np.nan)
lo = np.where(s2[::-1] != 0, s2[::-1] , np.nan)

#get couters compare by le (<=) and remove NaNs groups (first, last)
prices_df['um'] = prices_df.groupby(up).cumcount().le(n) & ~np.isnan(up)
prices_df['lm'] = prices_df.groupby(lo).cumcount(ascending=False).le(k) & ~np.isnan(lo)
print (prices_df)
          date   tic  price     um     lm
0   01-01-2018  MSFT    1.0  False   True
1   01-01-2019  MSFT    1.0   True   True
2   02-01-2019  MSFT    1.1   True  False
3   03-01-2019  MSFT    1.2   True  False
4   04-01-2019  MSFT    1.3  False  False
5   05-01-2019  MSFT    1.4  False   True
6   01-01-2019  AAPL    2.0   True   True
7   02-01-2019  AAPL    2.1   True  False
8   03-01-2019  AAPL    2.2   True  False
9   04-01-2019  AAPL    2.3  False  False
10  05-01-2019  AAPL    2.4  False  False

#filter by boolean indexing
mask = prices_df['um'] | prices_df['lm']
prices_df = prices_df[mask]
print (prices_df)
         date   tic  price     um     lm
0  01-01-2018  MSFT    1.0  False   True
1  01-01-2019  MSFT    1.0   True   True
2  02-01-2019  MSFT    1.1   True  False
3  03-01-2019  MSFT    1.2   True  False
5  05-01-2019  MSFT    1.4  False   True
6  01-01-2019  AAPL    2.0   True   True
7  02-01-2019  AAPL    2.1   True  False
8  03-01-2019  AAPL    2.2   True  False

A: Your merging looks okay. You just have to extract desired columns from it, because right after merging it contains all columns from both DataFrames. So:
merged = events_df.merge(prices_df, left_on=['ticker', 'event'], right_on=['tic', 'date'])
merged = merged['date', 'picker', 'price']

Then you have to filter it, so the price is less than 3 (or n if you want):
n = 3
merged = merged[merged['price'] < n]


text:
Q: MEMS microphone different output voltage at the same dB I am trying to measure noise using the ADMP401 (MEMS) sensor.
In the dynamic sound (applause, the sound of hitting the desk, etc.,) a sensor output of + -200mV is obtained. However, for the sound of a cell phone at the same dB, it gets about + -50mV.

The upper waveform is the sound of a mobile phone, and the lower waveform is the sound of a mobile phone similar to the dB of the dynamic sound.
I used a high pass filter, weighting filter, preamp, etc. to solve this, but it still has a lot of change in dynamic sound. And if the sensor recognizes the dynamic sound, clipping occurs in the negative direction. Both sounds are around 100dB.

The circuit diagram is as follows. The XPG1 part was used instead of the ADMP401 sensor.
I experimented with preamp and weighting filter circuit in front of C1, but the problem mentioned above is not caught. I've spent a lot of time trying to solve it, but it didn't work.
Can you help me solve it?

This is part of the sensor datasheet. Even if I interpret it, I am not sure where the problem is. Do I need to change the sensor or use a different filter? How to get a constant output in dB regardless of the type of sound?

As the dynamic sound mentioned above has a large change in dB in the low frequency band, a weighting filter is used to catch the low frequency.

A: You fix it by implementing the weighting used in sound pressure level meters.
Sound pressure level (SPL) meters filter the sound before measuring it.  They are not normally used with the straight microphone input.
Most SPL meters follow the A weighting curve.  There are other standards as well.
They look like this:

From the Wikipedia article
That removes a lot of frequencies that will be in your "dynamic sound."
Due to different frequency content, it is entirely possible for two sounds to measure the same loudness on an SPL meter but still have drastic differences in appearance (and voltage levels) when viewed on an oscilloscope.
Another thing that contributes to this is that SPL meters also filter the SPL measurement itself.  A short but loud noise won't read as high as a continuous but less loud noise.  You'll need a low pass filter one the output of your peak detector to mimic the time response curves for the different time weightings used.
Wikipedia has a chart of the time weightings:

Your circuit appears to have something like the A-weighting implemented but not the time weighting.

One last thing:
Different microphones have different dynamic ranges.  A sound that your SPL meter can accurately measure may cause your MEMS microphone to distort and deliver incorrect levels.
Microphones also have different frequency responses.  Your MEMS microphone loses signal below about 100 Hz and above about 10 kHz.  That will distort your A-weighting curve.

Missed the most important part.
dB is a logarithmic scale.
If you double the voltage, that looks like an enormous difference in your oscilloscope view.  It is only 3dB, though.
You'll need to implement a log amplifier in your circuit and scale the result to get correct dB readings.
It might be easier to use an ADC to sample the peak detector output and do the dB conversions in a microprocessor than to implement an accurate log amplifier.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to wait for all completed AsyncOperations on app close I'm sending messages using an asynchronous write operation, but when the app is closed I need to write 2 messages to a device, but only 1 message gets successfully written.
Each write operation is chained to a message queue, so the messages write operations are sent sequentially after each completed write operation while the message queue is full. So basically the following code might get to the first completed callback, but it doesn't reach the 2nd before the app closes. I tried adding a Windows Sleep call in between and after Async Operations, but this didn't work. I also tested waiting for the completion callback using a while loop to see if the 2nd opertation ever completes, which it never does.
    ComPtr<IAsyncOperation<GattCommunicationStatus>> writeOp;
    GattWriteOption option = GattWriteOption_WriteWithoutResponse;
    hr = customCharacteristic->WriteValueWithOptionAsync(buffer.Get(), option, &writeOp);
    hr = writeOp->put_Completed(Callback<IAsyncOperationCompletedHandler<GattCommunicationStatus>>
                (this, &DataGloveBluetooth::OnCharacteristicWriteComplete).Get());

This is only an issue on app close as it seems 2nd operation never gets to the callback. Also, the messages are too large to put together, so I need to be able to send more than 1 message.
Is there a proper way I can wait? This is some pseudo-code to help explain the ordering:
WriteMessage(LED_RESET); // adds to message queue, then calls aync op,
WriteMessage(CLOSE); // adds to message queue, async op is called once first message is sent, complete callback is never reached
Sleep(5000) // whatever sleep amount never helps the 2nd message finish


text:
Q: Groovy: remove and object from a list within itself? I'm trying to remove objects from a list when it finds that particular objects privacy
is private to the current user
     books.eachWithIndex{ obj, i ->

        if((obj.book.private).equals(true)){

          def status = bookService.getBookStatus(obj.book)

          if(!status){
               books.remove(i)
          }
        }
     }

error thrown as it tries to remove the object
ERROR errors.GrailsExceptionResolver  - null
java.util.ConcurrentModificationException
Q: is there any way to remove an object from a list within itself
or would you have to separately store the index values and remove objects from outside the each loop?

A: A more functional approach may help:
def publicBooks = books.findAll { obj ->
    !obj.book.isPrivate() || bookService.getBookStatus(obj.book)
}

Note that findAll() returns a new collection rather than modifying the existing one.

A: There is an iterator that has a .remove() method, but I don't know if that functionality has been translated into groovyesque.  It doesn't work with Java's enhanced for either.
Try iterating over it manually (with an iterator, normal old-school Java-style for loop) and use the iterator.remove()... Unless Groovy has provided you with access to the iterator, it's the only way to do it while you are iterating.

A: The hibernate filters plugin was created for exactly this kind of scenario.  I've used it on our current project to do this kind of filtering.


text:
Q: How to run two versions of ElasticSearch with custom heap size on same server? I need to run side by side two ElasticSearch instances (version 1.7 and version 5.2.2) on the same server (Widows 2012 R2). When I try to run the newer version, I receive an error:
PS C:\Program Files\Elasticsearch\elasticsearch-5.2.2\bin> .\elasticsearch.bat
Error: encountered environment variables that are no longer supported
Use jvm.options or ES_JAVA_OPTS to configure the JVM
ES_HEAP_SIZE=8g: set -Xms8g and -Xmx8g in jvm.options or add "-Xms8g -Xmx8g" to ES_JAVA_OPTS

This is caused by the fact that that there was a breaking change (described here) in the way the heap size is set. In the previous version of ElasticSearch (1.7) it was set by an environment variable:
ES_HEAP_SIZE = 8g

I tried setting up another env variable:
ES_JAVA_OPTS = -Xms8g -Xmx8g

and I also edited jvm.options file by adding
-Xms8g
-Xmx8g

but I'm still getting the same error.
Is there a way to configure heap size in ElasticSearch 5.2.2 without deleting ES_HEAP_SIZE environment variable (which I need to keep version 1.7 up and running)? If not, is it possible to set heap size in the old version in a way that would also allow the new version to run?

A: Edit: Given that jvm.options is not an option, the only thing I see is modifying your elasticsearch/bin/elasticsearch script, mostly the line:
ES_JAVA_OPTS="$(parse_jvm_options "$ES_JVM_OPTIONS") $ES_JAVA_OPTS" #default

to:
    ES_JAVA_OPTS="-Xms myXmsValue -Xmx myXmxValue -someOtherOptions someValue"
With the other options and value according to what you want.

A: Here is what I found out:
it turns out that the error I was struggling with was raised not by ElasticSearch itself, but by the batch script running the ElasticSearch (bin\elasticsearch.bat). The problematic lines are:
if not "%ES_HEAP_SIZE%" == "" set bad_env_var=1
(...)
if %bad_env_var% == 1 (
    echo Error: encountered environment variables that are no longer supported
    echo Use jvm.options or ES_JAVA_OPTS to configure the JVM
    (...)
    if not "%ES_HEAP_SIZE%" == "" echo ES_HEAP_SIZE=%ES_HEAP_SIZE%: set -Xms%ES_HEAP_SIZE% and -Xmx%ES_HEAP_SIZE% in jvm.options or add "-Xms%ES_HEAP_SIZE% -Xmx%ES_HEAP_SIZE%" to ES_JAVA_OPTS
    (...)
    exit /b 1
)

As far as I can see, this check is there in order to help people migrating from older version to the newer, pointing them to a new way of setting up the heap size. Apart from that, the environment variable ES_HEAP_SIZE is not mentioned in the script, so its' existence should not affect the ElasticSearch 5.2.2 instance. Based on these observations, the easiest fix seems to be simply commenting out the check:
rem if not "%ES_HEAP_SIZE%" == "" set bad_env_var=1

I tried it and both instances of ElasticSearch now run side by side without issues.
One additional trap to avoid is not to set up the heap size in both the file and ES_JAVA_OPTS, which leads to duplicate min heap size settings found error when deploying. Just stick to the file config.
Huge thanks to @asettouf whose answer led me to the correct solution!


text:
Q: Application_BeginRequest not firing (NOT URL rewrite) I would like to write out incoming requests for a SOAP web service.  Turns out that my Application_BeginRequest event is not firing.  It is running on IIS6 & Windows 2003, so the config change recommended elsewhere doesn't have any effect.
protected void Application_BeginRequest(object sender, EventArgs e)
{
    try
    {
        byte[] inputBytes = new byte[HttpContext.Current.Request.ContentLength];
    HttpContext.Current.Request.InputStream.Position = 0;
    HttpContext.Current.Request.InputStream.Read(inputBytes, 0, inputBytes.Length);

    string requestString = ASCIIEncoding.ASCII.GetString(inputBytes);

    Logger.Write("input: " + Convert.ToString(inputBytes.Length), Global.LOGGER_EVENT_SOURCE, 0, 0, TraceEventType.Warning);
    using (var writer = new StreamWriter(@"c:\inetpub\wwwroot\requests\testfile - " + DateTime.Now.ToString("MMddYYYYhhmmssffff") + ".xml"))
    {
        writer.Write(requestString);
        writer.Close();
    }

    // Reset stream pointer to beginning.
    HttpContext.Current.Request.InputStream.Position = 0;
}
catch (Exception ex)
{
    // Error handling; omitted here.
}

}
The code 'almost' works if I just put it inside of the web service method being called; the file is created but the request has a content length of '0'.
Thanks for any advice.

A: The most likely reason for this issue is that the site is not set as an Application.


text:
Q: How do i send an email from a workflow with the whole list item as a attachment? I am a newbie in sharepoint.
Our company has a email address that functions as a archive, I want to send a email from a workflow on a list item with the whole item as a attachment or in the email. Is there a way to do this?
Thanks for your time!

A: You can send the link to display or edit form of that item in your email. This way all the details will be stored in SharePoint and all that they have to do is click on that link to view the item.

A: If it were sufficient to only keep track of all the changes, you could set up an alert for modifications, sent to that archive mailbox.
If it needs to contain the whole "listitem" respectively all fields values, you can do that with a workflow. This should be feasible with a regular SharePoint designer workflow. If you need this for only a specific list, with a fixed set of fields (that do not change much), you can then retrieve each field value that you need in your workflow and concatenate them to an Email text, that then is sent from the workflow to that mailbox. If it needs to be more dynamic (for multiple list with different, changing sets of fields) it gets more tricky....
And if I understood your requirements (=> archive), the link to the listitem won't meet your requirements.

A: If you can use InfoPath, then there is feature to send email with screenshot of current form.


text:
Q: Oracle SQL: how to merge n lines and create additional columns in result? Table:
id race
1  elf
1  troll
2  lizard
2  elf
2  human
3  dwarf

I am looking for a request that output this:
id race1   race2   race3
1  elf     troll
2  lizard  elf     human
3  dwarf

There can be n race or a given max number of races if it's more easy
Is this possible with an sql query (not pl/sql)? (oracle if special function is needed)

A: You can use conditional aggregation if you want to do this in a simple select:
select id,
       max(case when seqnum = 1 then race end) as race_1,
       max(case when seqnum = 2 then race end) as race_2,
       max(case when seqnum = 3 then race end) as race_3,
       max(case when seqnum = 4 then race end) as race_4,
       max(case when seqnum = 5 then race end) as race_5
from (select t.*,
             row_number() over (partition by id order by id) as seqnum
      from t
     ) t
group by id;


text:
Q: Android external camera options - overlay on top of video stream, no middleman server/router I'm looking for a way to interface with an external camera from an Android device. The reason it needs to be an external camera is because I need to be able to modify the camera (remove IR filter) and I have no desire to break an on-board phone camera.
It doesn't matter how the camera connects whether it is through USB, bluetooth, WiFi, or some other communication protocol, the two devices just need to be able to talk without having a middleman server/router.
I'm looking for a solution that:

*

*Doesn't require rooting or rebuilding Android/the Linux Kernel (absolute must)

*Allows me to overlay items over the image/video (good)

*Access the video stream to do image analysis (best)

The last requirement isn't required but would be nice.
Options I have explored:

*

*USB camera: rebuilt Linux Kernel as per http://brain.cc.kogakuin.ac.jp/research/usb-e.html and tried using provided code using camera: http://www.amazon.com/gp/product/B002X3VEIE/ref=oh_o02_s00_i00_details. Did not work in the slightest bit. I later learned that the author used the CM9 mod however this really isn't an option given that it isn't practical for an app in the market.

*Bluetooth camera: Looxcie and CountourGPS look like the best options however the feed is streamed to their app and they have no API or SDK so how can one overlay on their video feed?

*IP camera: to me this looks like the most promising option but how can one access an IP cameras video feed without a middleman server/router? GoPro HD Hero2 with WiFi BacPac looks potentially promising but it isn't out yet and from what I can tell requires you to use their app similar to the bluetooth camera options. What cameras exist that allow me to connect to them and receive a direct video feed and how do I go about this programmatically?

If connection to an IP camera without the middleman is possible the code at Android and MJPEG and Getting IP Cam video stream on Android (MJEPG) looks promising.
Can I overlay on top of another apps video feed? Is it possible to connect directly to an IP camera? Any suggested options greatly appreciated.

A: I ended up opting for the IP camera option as it seemed to be the only viable option.
I was able to purchase this camera and remove the IR filter by removing the glue at the base of the lens and then breaking the IR filter out.
I was able to connect the camera to ICS using the AndroidAP hotspot and to older Android devices using an ad-hoc network setup on the camera (you have to manually set IP addresses, etc for ad-hoc and it's a pain).
As for getting MJPEG working in an app on ICS I made these modifications to the code I found on SO.
Lastly the app needs to be able to turn the AP on and off which I have not finished yet but here is some code to start with.

A: In answer to your options..
Looxcie has a onboard buffer that could potentially be tapped into, ContourGPS does not have a buffer to the best of my knowledge. Unfortunately bluetooth isn't very viable for live video/recording. They also don't publicize their bluetooth stack or communications. There are methods to "decrypt" or find out how they communicate but it would be time consuming.
Your best option is to use an IP Camera. You can use WiFi Direct, or you can use the phones tethering app. (Android is probably best). Then connect the IP Camera to the tethering app and you're all settled. Contour has a new camera that does HDMI. Then they also have a livestreamer. http://contour.com/products/live-streaming-cerevo-liveshell
The IP Method is expensive but it is a decent way to get the result that you want.


text:
Q: Logical read when use Offset in SQL When I execute this script
SET STATISTICS IO ON

SELECT
    *,
    ROW_NUMBER() OVER (ORDER BY [Date] DESC) AS [ROW_NO]
FROM
    vwTblTest
WHERE
    ([Factor] >= 139501 AND [Factor] < 139507) AND
    ...
ORDER BY
    [Date] DESC
OFFSET 0 ROWS FETCH NEXT 25 ROWS ONLY;

The vwTblTest is a view that join two table like this :
SELECT
    [tbl1].*,
    [tbl2].*
FROM
    [tbl1]
    INNER JOIN
    [tbl2] ON ([tbl2].[Factor] = [tbl1].[Tbl1Factor]
           AND [tbl2].[ID] = [tbl1].[Tbl2ID])
    LEFT JOIN
    (select Reference,
            CASE WHEN ISNULL(COUNT(Reference), 0) = 0 THEN 'False' ELSE 'True' END
              AS HasReference
     FROM [tbl3]
     GROUP BY Reference
    ) reference ON reference.Reference = [tbl2].ID

tbl1 contains about 9 million records, and it has a partition on Factor field.
If tbl2 contains 25 or more records every thing is fine, But when tbl2 contains less than 25 records statistic report show a lot of logical read to execute script.
Column [Date] is from tbl1. For cross checking with the plans:
tbl1 : doc_LetterInstances
tbl2 : doc_Letters
tbl3 : doc_LetterReferences

Statistics :

Scan count 1, logical reads 12754432, physical reads 0, read-ahead reads 0, lob logical reads 0, lob physical reads 0, lob read-ahead reads 0.

Execution Plan :

When I change script like bellow statistic report show normal logical reads. OFFSET 0 ROWS FETCH NEXT 25 ROWS ONLY was removed.
SET STATISTICS IO ON

SELECT
    *,
    ROW_NUMBER() OVER (ORDER BY [Date] DESC) AS [ROW_NO]
FROM
    vwTblTest
WHERE
    ([Factor] >= 139501 AND [Factor] < 139507) AND
    ...
ORDER BY
    [Date] DESC

Statistics :

Scan count 1, logical reads 45, physical reads 0, read-ahead reads 0, lob logical reads 0, lob physical reads 0, lob read-ahead reads 0.

Execution Plan :

What is wrong in my query?


text:
Q: Some javascript syntax that I dont understand I am working with the karma.js library right now.  I was walking through there example project and came across some code that I don't really understand.  I am sure it is easy enough, but an explanation would be very helpful in understanding what the lib is doing.  From what I can understand it is looping through the files in the __karma__ object and doing some kind of regex matching in the if statement with /Spec\.js$/.
for (var file in window.__karma__.files) {
    if (/Spec\.js$/.test(file)) {
        tests.push(file);
    }
}

If that is a regex matching, you can go from a string directly to access an object in javascript.  That is really interesting.
Thanks for the help.

A: That's a for-in loop. It looks through the enumerable properties of an object. So for instance, if you have:
var obj = {
   a: 42,
   b: 27
};

...then within the loop, file will be "a" on one pass and "b" on another (but the order is not defined).
The var in it is just declaring a variable. Note that unlike some other languages, the variable is not limited in scope to just the loop, the declaration is function-wide.
The regex, /Spec\.js$/, is checking to see if the string ends with "Spec.js". In a regex, $ matches "end of line/input". A backslash is needed before the . because an unescaped . matches any character.
More about for-in:

*

*...in the specification.

*...on my blog.

More about var:

*

*...on my blog.

A: /Spec\.js$/ is not string but a regular expression literal. What's essentially doing is:
var re = new RegExp('Spec\.js$');
re.test(file)

See MDN article on Regular Expressions for more details: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions

A: You indeed can go directly from a literal value into accessing its properties in JavaScript:
/^regex$/.test(...)

"a string".split(...)

etc. it all works.
With numbers however you need special treatment:
(1).toString()


text:
Q: django signal sending email after registering user i have a user model where after creating the model I want to send email from signal.
I have a function in my signals.py
def notify_after_registration(sender, instance, created, **kwargs):
    user = instance.username
    email_subject = 'Account confirmation'
    email_body = "some message"
    send_mail(
        email_subject,
        email_body,
        settings.EMAIL_HOST_USER,
        [instance.email,
        fail_silently=False
    )

at the bottom i have
post_save.connect(notify_after_registration, sender=User)

When I register the user user is saved but email is not sent.. What is wrong ?

A: the code from your signals.py by default is not imported anywhere, so you need to add it import in some part of your app, for example in file with models (or, one of models if your have many such files)


text:
Q: SQL Server: check if specific string exists in column There is user created table type:
CREATE TYPE [dbo].[tpSearchCriteria] AS TABLE(
    [TableName] [sysname] NOT NULL,
    [ColumnName] [sysname] NOT NULL,
    [ValueString] [nvarchar](max) NULL,
    [ValueNumeric] [decimal](19, 6) NULL,
    [ValueDate] [datetimeoffset](7) NULL,
    [Operator] [nvarchar](2) NULL,
    [OperatorGroup] [smallint] NOT NULL,
    [SortDirection] [nvarchar](2) NULL )

Every time when query is executed this table is populated with some search parameters.
In dependance of string values in column [ColumnName] I should chose different collation.
So, there is need to examine in [ColumnName] does it contain values like 'FirstName' or 'LastName'
I tried with some CASE and IF clauses but that is not working.
System using SQL Server 2014

A: select @Collation = case when exists (select 1 from @SearchCriteria where ColumnName = 'FirstName' or ColumnName = 'Surname')
                         then COALESCE(@Collation, CAST(DATABASEPROPERTYEX(DB_NAME(), 'Collation') AS nvarchar))
                   else COALESCE('SQL_Latin1_General_CP1_CI_AS', CAST(DATABASEPROPERTYEX(DB_NAME(), 'Collation') AS nvarchar))
                   end


text:
Q: Is it possible to draw line between the annotations in mkmap by using cocos2d in single view application? Hai am developing a vehicle tracking iOS app using xcode 4.5. For that I need to draw lines between annotation points. for that can I use cocos2d to draw lines? kindly guide me. Thanks in advance..

A: Yes you can do it. Below is the sample code
    CLLocationCoordinate2D coordinates[2];
    coordinates[0] = currentLocation.coordinate;
    coordinates[1] = targetLocation.coordinate;

    //add new overlay
    MKPolyline *polyLine = [MKPolyline polylineWithCoordinates:coordinates count:2];
    [navigationMapView addOverlay:polyLine];


text:
Q: Tensorflow: tf.while_loop() with vector condition The function tf.while_loop() (https://www.tensorflow.org/api_docs/python/tf/while_loop) repeats the body "b" while the condition "c" is true. For example:
import tensorflow as tf
i = tf.constant(0)
c = lambda i: tf.greater(10,i)
b = lambda i: tf.add(i, 1)
r = tf.while_loop(c, b, [i])

How can I adjust this, when the condition is a vector, e.g.
c = lambda i: tf.greater([10,10],[i,i])

?
The problem is that the above returns a vector (instead of True or False), same as e.g.
tf.greater([2,2],[1,1])

I need something that returns true when all the vector elements are true, and false otherwise. I would suggest
i = tf.constant(0)
c = lambda i: True if all(item == True for item in tf.greater([10,10],[i,i]))==True else False
b = lambda i: tf.add(i, 1)
r = tf.while_loop(c, b, [i])

But this does not work, with the following error:
TypeError: `Tensor` objects are not iterable when eager execution is not enabled. To iterate over this tensor use `tf.map_fn`.

Any ideas?

A: The solution is to use tf.reduce_all():
i = tf.constant(0)
c = lambda i: tf.reduce_all(tf.greater([10,10],[i,i]))
b = lambda i: tf.add(i, 1)
r = tf.while_loop(c, b, [i])


text:
Q: C# Regex ask for "Parameter" and return "Value" for command line parse Is it possible create Regex pattern for parse command line request?
Like:something text -PARAMETER="Hello world" something else.. -PARAMETER=HelloWorld
I want to ask for -PARAMETER and get two items "Hello world" (OR just Hello world) and second occurrence HelloWorld
Thanks
EDIT:
Sorry for an austere question. My question is what is the best method of Regex or something better for this problem.
In regex I used this pattern: -PARAMETER=".*"|-PARAMETER=.*?\s , but I mean that can be better.
One of possible method:
string command = "PARAMETER";
string pattern = $"-{command}= \".*\" | -{command}=.*?\\s";
foreach (Match _m in Regex.Matches(CommandBlockArgs, pattern, RegexOptions.IgnoreCase))
{
  Console.WriteLine(_m.Value.Replace($"-{command}=", "").Replace("\"", "").Trim());
}
// *sorry for possible error, I wrote code now by head.*

But, also I mean that this is not nice solution.
For example, for me nice method for parse command by quotation marks is:
[DllImport("shell32.dll", SetLastError = true)]
static extern IntPtr CommandLineToArgvW(
[MarshalAs(UnmanagedType.LPWStr)] string lpCmdLine, out int pNumArgs);

public static string[] CommandLineToArgs(string commandLine)
{
  int argc;
  var argv = CommandLineToArgvW(commandLine, out argc);
  if (argv == IntPtr.Zero)
    throw new System.ComponentModel.Win32Exception();
    try
    {
      var args = new string[argc];
      for (var i = 0; i < args.Length; i++)
      {
        var p = Marshal.ReadIntPtr(argv, i * IntPtr.Size);
        args[i] = Marshal.PtrToStringUni(p);
      }
      return args;
    }
    finally
    {
      Marshal.FreeHGlobal(argv);
    }
 }

But here is not my commands list. And Regex can be better.. Or combination?
*Sorry for English =)

A: So, my solution (C# 5.0):
    internal static object CallMethod(Type type, string method, string parameters)
    {
        MethodInfo m = type.GetMethod(method, BindingFlags.Static | BindingFlags.Public);
        ParameterInfo[] p = m.GetParameters();
        object[] param = new object[p.Count()];
        UInt16 i = 0;
        foreach (ParameterInfo pi in p)
        {
            string pattern = $"-{pi.Name}=\".*\"|-{pi.Name}=.*?\\s"; // -paramName=paramValue || -paramName="param Value"
            foreach (Match _m in Regex.Matches(parameters, pattern, RegexOptions.IgnoreCase))
            {
                Type paramType = pi.ParameterType;
                string value = Regex.Replace(_m.Value, $"-{pi.Name}=", "", RegexOptions.IgnoreCase).Replace("\"", "").Trim();
                param[i] = Convert.ChangeType(value, pi.ParameterType);
            }
            i++;
        }
        return m.Invoke(null, param);
    }

It works, but maybe could be better.


text:
Q: Reactjs Ant-Design Menu - change subMenu appearance I'm developing a Reactjs website and I'm using Ant-Design (antd) library. I have a Menu and I decided to use the vertical mode. Since my website has rtl layout, I need the SubMenu items to be opened in the left side of the Menu box. How can I do that?
I've prepared an image of what I really want to do:

This is my code:
<Layout className="SideMenus">
  <Menu mode="vertical" defaultSelectedKeys={['One']}>
  <Menu.Item key="One">One</Menu.Item>
  <Menu.Item key="Two">Two</Menu.Item>
  <SubMenu key="Three" title="Three">
     <Menu.Item key="Option3">Option3</Menu.Item>
     <Menu.Item key="Option4">Option4</Menu.Item>
  </SubMenu>
</Layout>

A: In Menu level styling use float right and it will automatically pop the sub menu left side
<Menu onClick={handleClick} style={{ width: 256 , float : "right"}} mode="vertical">

A: You can use ConfigProvider over Menu component:
<ConfigProvider direction="rtl"><Menu /></ConfigProvider>

A: If there is no space on the right, the menu will be automatically opened in the left side.
Have you tried vertical-right mode? I couldn't really try it, but maybe it is what you are looking for ...


text:
Q: vim auto indenting even after setting noai option I am using vim 7.2 from putty terminal.
Even if I run set noai it seems vim still trying to indent code.
I am copying my code from Notepad++ to vim.
following is from Notepad++

and following what I got in vim:

I don't have any tab in my file.
As a workaround I am opening old vi run set noai paste save and open in vim again.
Any suggestion how to correct this behavior ?

A: This has nothing to do with the noai option. What you are experiencing, is a little trouble copy-pasting a load of text with existing indents to vim.
What I usually do (I have this 'problem' a lot), is bind F4 to invpaste and then, before I paste stuff into vim, hit that key. It makes the problem go away.
nnoremap <F4> :set invpaste paste?<CR>

Read more about this using
:help paste

inside vim

A: :set paste
prevents the problem
:set nopaste
to undo the above
:set pastetoggle=<F2>
sets paste toggle key to F2


text:
Q: How to get list name through javascript? I wrote javascript for getting list items but here I'm hard coded list name as "Projects"(my list name). How can I get list name automatically with out hard coding,
function DoLogicalDelete()
{

    var clientContext = null;
    var oList = null;
    var oListItem = null;
   //var lstItmIsDeleted = null;

    var itmID = getQuerystring('ID');

    clientContext = SP.ClientContext.get_current();

    oList = clientContext.get_web().get_lists().getByTitle('Projects');

    //var oListItemID = SP.ListOperation.Selection.getSelectedItems(clientContext);

    oListItem = oList.getItemById(itmID);                         // getting ID

    clientContext.load(oListItem,"Title", "IsDeleted");            // load items to oListItem

    oListItem.set_item('IsDeleted', true);
    oListItem.update();

    clientContext.executeQueryAsync(Function.createDelegate(this, this.onQuerySucceeded),Function.createDelegate(this, this.onQueryFailed));
}

Appreciate if anyone help.
Thank you.

A: You could change
oList = clientContext.get_web().get_lists().getByTitle('Projects');

to
oList = clientContext.get_web().get_lists().getById(_spPageContextInfo.pageListId)

A: var listTitle = _spPageContextInfo.listTitle;

Works for forms in 2019 On Prem. Haven't tried in 2013/2016 but I bet it works there too.


text:
Q: Apex Test Error - Constructor not defined I am still new to Apex testing and am trying to build a test class on the following, but keep running into the error message "Constructor not defined: [MyNewCaseListController].(ApexPages.StandardController)" It is coming from the 16th line in the test class. Any ideas what I am doing wrong?
public with sharing class MyNewCaseListController {
public MyNewCaseListController(ApexPages.StandardSetController  ctrl){
    string filter = ApexPages.currentPage().getParameters().get('filterId');
    ctrl.setPageSize(50);

    List<System.SelectOption> listViews = ctrl.getListViewOptions();
    if (filter != null) {
        ctrl.setFilterId(filter);
    }
    else {

        for(System.SelectOption listView : listViews)
        {
            if (listView.getLabel() == 'Recently Viewed Cases')
                ctrl.setFilterId(listView.getValue());
        }
    }
}

@isTest public without sharing class MyNewCaseListControllerTest {
@isTest public static void TestMyNewCaseListController(){

    Case ca = new Case();
    String i = Datetime.now().format('yyyy-MM-dd');
    ca.Subject = 'Test Subject - Field Test ' + i;
    ca.Description = 'Test Description - Field Test ' + i;
    ca.Origin = 'Web Email';
    ca.Type = 'Other';
    insert ca;
    string filterId = ca.Id;
    Test.startTest();
    ApexPages.currentPage().getParameters().put('filterId',ca.id);
    MyNewCaseListController controller  = new MyNewCaseListController(new ApexPages.StandardController(ca));

    string filter = ApexPages.currentPage().getParameters().get('filterId');
    controller.setPageSize(50);

    List<System.SelectOption> listViews = ctrl.getListViewOptions();

    // Set Filter Id if passed in parameter
    if (filter != null) {
        ctrl.setFilterId(filter);
    }
    else {
        for(System.SelectOption listView : listViews)
        {
            if (listView.getLabel() == 'Recently Viewed Cases')
                ctrl.setFilterId(listView.getValue());
        }
    }
}

A: Firstly:
separate the 2 classes, this makes life easier via deployment and source control etc.
But to the issue at hand:
You are using ApexPages.StandardSetController in your Class, but your test provides ApexPages.StandardController
Yes pass the standardSetController a list. Which now I read your code more carefully you do want a list.
I am interested in what your requirement is?
But there is another issue:
In your test you are passing a Case Id as if it is a ListView FilterId.
You could do something like this in your Test Class;
    ListView LV = [SELECT Id, Name FROM ListView WHERE Name = 'MyListview Filter Name'];
filter

but your test needs to run this page twice, once with a listviewId and once without.
so that you cover the if statement and test the 'Recently Viewed Cases Listview.
You do not need 2 test methods, you just need to reset the controller within the test:
List<Case> CaseList = [SELECT id FROM Case]; //what else goes in here???
//First Page Render test no filterId
MyNewCaseListController controller  = new
MyNewCaseListController(new ApexPages.StandardSetController(CaseList));
//Second Page Render tests FilterId set from query above
ApexPages.currentPage().getParameters().put('filterId',LV.Id);
controller  = new MyNewCaseListController(new ApexPages.StandardSetController(CaseList));
//CODE NOT TESTED BY ME

Caveat and aside:
You need to ensure you maintain your list views properly thought otherwise this test class will fail (I suppose that is the point), problem is listview can be updated directly in prod and hence your test could fail a at a later date when you bring in new code, hence source control is important with these types of code bases.


text:
Q: Hot to pass state from main App.js to screen components using react navigation in react native I'm making a small app in react native, it's a basic login workflow that use a couple of screen (login and home), that are shown based on user state; in App.js i have a bunch of state that im using to enable/disbale views, buttons, show username and so on.
I have both the login screen and the home screen in external components. i'm wonder (besides using context) if there is a way to have these states (and functions) available to child screen
this is part of my code:
App.js
export default function App() {
  const [isLoading, setIsLoading] = useState(true);
  const [isLogged, setIsLogged] = useState(false);
  const [userToken, setUserToken] = useState(null);
  const [userProfile, setUserProfile] = useState(null);
  const [email, setEmail] = useState(null);
  const [password, setPassword] = useState(null);
  const [loggingIn, setloggingIn] = useState(false);
  const [error, setError] = useState(null);

  const AppStack = createStackNavigator();

  useEffect(() => {
    AsyncStorage.getItem('userProfile').then((value) => {
      if (value) {
        console.log(JSON.parse(value)),
          setUserProfile(JSON.parse(value)),
          setIsLoading(false),
          setIsLogged(true);
      } else {
        setIsLoading(false), setIsLogged(false);
      }
    });
  }, []);

  const doLogout = async () => {
---- LOGOUT CODE
}
const doLogin = async () => {
----- LOGIN CODE and UPDATE of state and asyncstorage
}
return (
    <NavigationContainer>
      <AppStack.Navigator initialRouteName="Login">
        <AppStack.Screen name="Login" component={Login} />
        <AppStack.Screen
          name="Home"
          component={Home}
          options={{ headerShown: false }}
        />
      </AppStack.Navigator>
    </NavigationContainer>
  );

Login.js
const Login = ({ loggingIn, userProfile }) => {
  console.log(userProfile);
  return (
    <View style={styles.container}>
      <Button
        title="Login to Site"
        onPress={() => doLogin()}
        disabled={loggingIn}
      >
        {userProfile && userProfile.name} Login to Site
      </Button>
    </View>
  );
};

how can access loggingIn (or even userProfile) and doLogin() function
that i set and create (and update) in App.js? there should be an easy way (beside useContext) for simple uses like this one.

A: You can pass parameters to routes. See the first section here:
https://reactnavigation.org/docs/params/
But you may instead want to move the states to their relevant screen component or other react component. Then, in the parent component, pass the values to the child component. See TestComponent.js below. Then, in the child component, we can use the props that we passed in from the parent component. See TestChildComponent.js below.
I have also provided App.js, TestNavigator.js, and TestScreen.js, so that you can just copy/paste them and test yourself.
Also, if you find yourself managing too many states with the useState hook, then you can look into using Redux for state management instead of the useState hook.

Code below:

TestComponent.js:
import React, {useState} from "react";
import {View, StyleSheet} from "react-native";
import ChildComponent from "./TestChildComponent";

const TestComponent = props => {
    const [value, setValue] = useState("Bilbo");

    return (
        <View style={styles.container}>
            <ChildComponent value={value} setValue={setValue} />
        </View>
    );
};

const styles = StyleSheet.create({
    container: {
        flex: 1,
        margin: 100,
    },
});

export default TestComponent;

TestChildComponent.js:
import React from "react";
import {StyleSheet, Text, Button, View} from "react-native";

const ChildComponent = props => {

    const buttonPressHandler = () => {
        props.setValue("Frodo");
    };

    return (
        <View style={styles.child}>
            <Text>Press Me:</Text>
            <Button title={props.value} onPress={buttonPressHandler} />
        </View>
    );
};

export default ChildComponent;

const styles = StyleSheet.create({
    child: {
        flexDirection: "row",
        marginHorizontal: 25,
        justifyContent: "center",
        alignItems: "center",
    },
});

TestNavigator.js:
import React from "react";
import {createStackNavigator} from "@react-navigation/stack";

import TestScreen from "./TestScreen";

const TestStackNavigator = createStackNavigator();

export const TestNavigator = () => {

    return (
        <TestStackNavigator.Navigator>
            <TestStackNavigator.Screen name={"Test"} component={TestScreen}/>
        </TestStackNavigator.Navigator>
    );
};

App.js
import React from 'react';
import {StyleSheet, SafeAreaView} from 'react-native';
import {NavigationContainer} from "@react-navigation/native";

import {TestNavigator} from "./TestNavigator";

export default function App() {

    return (
        <NavigationContainer>
            <SafeAreaView style={styles.safeAreaView}>
                <TestNavigator />
            </SafeAreaView>
        </NavigationContainer>
    );
}

const styles = StyleSheet.create({
    safeAreaView: {
        flex: 1,
    }
});

TestScreen.js
import React from "react";
import TestComponent from "./TestComponent";

const TestScreen = props => {

    return (
        <TestComponent />
    );
};

export default TestScreen;


text:
Q: Customizing doxygen output for the HTML Table of Contents I'm using doxygen to generate an API reference from source code, aiming to convert it into a CHM help file and eventually into a plugin for Eclipse. Unfortunately the default ordering and nesting of the classes, namespaces, etc. in the Table of Contents is not exactly ideal and I'd prefer to customize it if possible.
By default, doxygen creates two indexes/menus for navigating the generated documentation. One is the common Table of Contents on the left frame and the other is the row of buttons at the top of each individual HTML page. The latter can be comfortably customized by editing the layout xml file as described in doxygen manual (see section 'Changing the layout of pages') but so far I've seen no way to do similar modifications for the Table of Contents.
To use a precise example, I'm looking for a way to nest the three standard topics Class List, Class Hierarchy, and Class Members as subtopics inside a parent topic in the TOC, as is done by default in the menu system that's located on top of every page.
I'd imagine this is not the most unusual issue and may have a known solution available.
Thanks for your assistance!

A: I don't think there's a way to change this.
I'd probably generate, take a copy of tree.html into an editor, change the nesting of the three items by hand, diff against the original, and then run something post-build (XSL, perl script, sed, whatever's handy) to search/replace the snippet of text.


text:
Q: Firebase custom Token with CustomUserClaims I'm can currently succesfully use Firebase admin node sdk to createCustomToken.  I know I can pass the token back to the client and using signInWithCustomToken sign in a user and het the UID. However, I am using custom authentication is the first place is because I'm creating sub-users with limited permissions that adminUser allows. I was hoping to use setCustomUserClaims to attach some data to the sub-users so I can show the correct sub-user ui and set correct security rules in database. However I can't seem to figure out how I can set the customClaims beacuse I don't have the sub-user UID until I call signInWithCustomToken on the client. What is the process to do this correctly?
Code I was hoping to run right after creating a customToken for a subUser
admin.auth().setCustomUserClaims(uid, {subUser: true, viewPermisson: true}).then(() => {
});


text:
Q: Java event handler String error I am trying to make a GUI application where I am using 2-D array registered with an ActionListener. At compile time I am getting a String s = ((Button)o).getLabel(); declaration not valid here. error. In my application if you click the button every "x" label on button should toggle to "o". The code I used is:
from constructor
public ArrayDemo2()
{
    setLayout(new GridLayout(3,3));
    b= new Button[3][3];

    for(int i=0; i<b.length; i++)
    {
        for(int j=0; j<b[i].length; j++)
        {
            if(Math.random() < 0.5) add(b[i][j] = new Button("X"));
            else add(b[i][j] = new Button("O"));
            b[i][j].addActionListener(this);
        }
    }
    addWindowListener(new WindowAdapter()
    {
        public void windowClosing(WindowEvent e)
        {
            System.exit(0);
        }
    });

    setSize(600,600);
    setVisible(true);

}
    public void actionPerformed(ActionEvent e)
    {
        Object o = e.getSource();
        String s = "";
        if(o instanceof Button)
        {
        s = ((Button)o).getLabel();
        }
        if(s.equals("X"))
        ((Button)o).setLabel("O");
        else
        ((Button)o).setLabel("X");

    }

A: You can't declare a new String within an if statement without brackets.
You'd have to write:
if(o instanceof Button) {
    String s = ((Button)o).getLabel();
}

Which doesn't really make sense since the string goes out of scope immediately.  What you probably want is something like this:
String s = "";
if(o instanceof Button) {
    s = ((Button)o).getLabel();
}


text:
Q: Intuitively, why does stopping a driftless process result in a driftless process (i.e., why is a stopped martingale still a martingale)? As the title suggests, I'm asking for an intuitive explanation/idea of why a stopped martingale is still a martingale.  This result doesn't seem intuitive to me for the following reason:
If $X_{t}$ is a martingale and $\tau$ is a stopping time,then the stopped process $X_{t \wedge \tau}$ is also a martingale.  The problem I have with this is that since $\tau$ is random, the paths of the stopped process $X_{t \wedge \tau}$ will become constant at different times.
So, intuitively, when one path becomes constant, its variation is no longer contributing to the drift of the process.  Since $X_{t}$ was originally a martingale and equally likely to go up or down, after the first path stops, it seems like there would be a weight or drift in the opposite direction because the path that is now constant is no longer balancing the weight of the other path going in the opposite direction.
I hope the above intuitive description of my issue makes sense.  What's wrong with my intuition?

A: Since by definition of a stopping time the event $\lbrace \tau \leq t \rbrace$ is $\mathcal F_t$-measurable, you don't require knowledge of the future to decide whether to stop the process.
Thinking of a martingale $X_t$ as a fair game, if you could construct a stopping time such that  $ \mathbb E [X_{\tau \wedge (t + s)} \mid \mathcal F_t ] \neq X_t$, it would suggest you are able to alter the game in your favor by using knowledge of the past. This contradicts both the notion of a martingale and a stopping time.
That is the basic intuition.
It should be noted that there are exceptions to this intuition, for example that you don't in general have $\mathbb E[X_\tau \mid \mathcal F_t] = X_t$ for a martingale $X$. Conditions for when this is true is provided in the Optional Stopping Theorem.


text:
Q: no math is generated when using tikz/tikzpicture with tex4ht in mathjax mode I found another problem with math when using tex4ht and tikz. This is similar/followup to earlier question  no math is generated when using tikz/forest with tex4ht in mathjax mode  but since this affects now tikzpicture and not forest I thought it will be better to make new question instead of cluttering the old one?
Here is the problem. With the fix given in the above question now math shows up when using forest but when using tikzpicture all the math is missing.
In addition, when using \left or \right even in forest it does not render correctly in HTML.
So there are big problems when it comes to using math with tex4ht and tikz. May be it is due to using mathjax mode. But that is really the only mode I use tex4ht with now.
Here is MWE
\documentclass[11pt]{article}
\usepackage[margin=2cm]{geometry}
\usepackage{amsmath}
\usepackage{tikz,tikzpagenodes}
\usepackage{etoolbox}
\usepackage{hyperref}
\usetikzlibrary{shapes,arrows}
\usetikzlibrary{positioning,fit}
\usepackage[edges]{forest}
\begin{document}

\begin{forest}
for tree={
    draw, rounded corners, fill=blue!20,
    minimum height=1.5cm, minimum width=2cm,
    align=center, base=b,
    s sep=1cm, l sep=.5cm,
    if level<=2{edge=-latex}{edge=red},
}
[\begin{minipage}{2cm}
first order
{\begin{align*}
       f(x,y,(y')^n)&=0\\
       y'&=\left(a + b x + y\right)^{\frac{1}{n}}
\end{align*}
}
\end{minipage}
,calign=last
]
\end{forest}

\begin{tikzpicture}
\node [rectangle, minimum width=14cm]  (A)
{
\begin{minipage}{2cm}
first order
\begin{align*}
f(x,y,(y')^n)&=0\\
y'&=\left(a + b x + y\right)^{\frac{1}{n}}
\end{align*}
\end{minipage}
};
\end{tikzpicture}

\end{document}

When compiling using lualatex to pdf, this is the output

When compiled with make4ht (need to use .cfg below)
make4ht  -ulm default -a debug -c mycfg.cfg foo.tex "mathjax,htm" "-cunihtf -utf8"

Here is the .cfg file thanks to michal.h21 from the above link
\Preamble{xhtml}
\makeatletter
\AddToHook{env/forest/begin}{%
  \renewenvironment{align*}
  {\start@align \@ne \st@rredtrue \m@ne}
  {\math@cr \black@ \totwidth@ \egroup \ifingather@ \restorealignstate@ \egroup \nonumber \ifnum 0=`{\fi \iffalse }\fi \else $$\fi \ignorespacesafterend}
}
\makeatother
\begin{document}
\EndPreamble

Using TL 2022 on Linux
>which tex4ht
/usr/local/texlive/2022/bin/x86_64-linux/tex4ht
>make4ht -v
make4ht version v0.3l
>

A: The problem is the same as in the previous question. We need to restore the original version of the environment in TikZ picture. I've made a macro that saves environments before we redefine them for MathJax. You can then restore the original meaning using the \RestoreMathJaxEnvironments command. You need this version of mathjax-latex-4ht.4ht:
% mathjax-latex-4ht.4ht (2022-10-17-13:57), generated from tex4ht-mathjax.tex
% Copyright 2018-2022 TeX Users Group
%
% This work may be distributed and/or modified under the
% conditions of the LaTeX Project Public License, either
% version 1.3c of this license or (at your option) any
% later version. The latest version of this license is in
%   http://www.latex-project.org/lppl.txt
% and version 1.3c or later is part of all distributions
% of LaTeX version 2005/12/01 or later.
%
% This work has the LPPL maintenance status "maintained".
%
% The Current Maintainer of this work
% is the TeX4ht Project <http://tug.org/tex4ht>.
%
% If you modify this program, changing the
% version identification would be appreciated.
\immediate\write-1{version 2022-10-17-13:57}

\ExplSyntaxOn
\cs_new_protected:Npn \alteqtoks #1
{
  \tl_set:Nx \l_tmpa_tl {\detokenize{#1}}
  % % replace < > and & with xml entities
  \regex_replace_all:nnN { \x{26} } { & } \l_tmpa_tl
  \regex_replace_all:nnN { \x{3C} } { < } \l_tmpa_tl
  \regex_replace_all:nnN { \x{3E} } { > } \l_tmpa_tl
  % replace \par command with blank lines
  \regex_replace_all:nnN { \x{5C}par\b } {\x{A}\x{A}} \l_tmpa_tl
  \tl_set:Nx \l_tmpb_tl{ \l_tmpa_tl }
  \HCode{\l_tmpb_tl}
}
\ExplSyntaxOff

\NewConfigure{MathJaxConfig}{1}
\NewConfigure{MathJaxMacros}[1]{%
\Configure{@BODY}{\bgroup\NoFonts\ttfamily\detokenize{\(}%
  \special{t4ht*<#1}%
\detokenize{\)}\EndNoFonts\egroup}%
}

\long\def\AltlMath#1\){\expandafter\alteqtoks{\(#1\)}\)}
\long\def\AltlDisplay#1\]{\alteqtoks{\[#1\]}\]}
\long\def\AltMathOne#1${\alteqtoks{\(#1\)}$}
% this seems a bit hacky -- we need to skip some code inserted at the
% beginning of each display math
\long\def\AltlDisplayDollars#1$${\alteqtoks{\[#1\]}$$}

\newcommand\VerbMathToks[2]{%
  \alteqtoks{\begin{#2}
    #1
  \end{#2}}%
}
\ExplSyntaxOn

\seq_new:N\:savedmathjaxenvs

\newcommand\:savemathjaxenv[1]{%
  \seq_gput_right:Nn\:savedmathjaxenvs{#1}
  \expandafter\let\csname mathjax-#1\expandafter\endcsname\csname #1\endcsname
  \expandafter\let\csname mathjax-end#1\expandafter\endcsname\csname end#1\endcsname
}

\newcommand\RestoreMathJaxEnvironment[1]{%
  \expandafter\let\csname #1\expandafter\endcsname\csname mathjax-#1\endcsname%
  \expandafter\let\csname end#1\expandafter\endcsname\csname mathjax-end#1\endcsname%
}

\newcommand\RestoreMathJaxEnvironments{%
  \seq_map_function:NN\:savedmathjaxenvs\RestoreMathJaxEnvironment%
}

\cs_generate_variant:Nn \regex_extract_once:nnNTF {nV}
\newcommand\VerbMath[2][]{%
  \cs_if_exist:cTF{#2}{
    \:savemathjaxenv{#2}%
    \RenewDocumentEnvironment{#2}{+!b}{%
      \NoFonts\expandafter\VerbMathToks\expandafter{\detokenize{##1}}{#2}\EndNoFonts%
      \ifx\relax#1\relax\else%
      \refstepcounter{#1}%
      \regex_extract_once:nVNTF { label\s* \x{7B}([^\x{7D}]*)\x{7D}} {\l_tmpb_tl} \l_tmp_seq {\label{\seq_item:Nn\l_tmp_seq{2}}} {}%
      \fi
    }{}
  }{}%
}
\ExplSyntaxOff
\def\fixmathjaxtoc#1{\Configure{writetoc}{\def#1{\detokenize{#1}}}}

\AtBeginDocument{%
\VerbMath{subarray}
\VerbMath{smallmatrix}
\VerbMath{matrix}
\VerbMath{pmatrix}
\VerbMath{bmatrix}
\VerbMath{Bmatrix}
\VerbMath{vmatrix}
\VerbMath{Vmatrix}
\VerbMath{cases}
\VerbMath{subequations}
\VerbMath{aligned}
\VerbMath{alignedat}
\VerbMath{gathered}
\VerbMath{gather}
\VerbMath{gather*}
\VerbMath{alignat}
\VerbMath{alignat*}
\VerbMath{xalignat}
\VerbMath{xalignat*}
\VerbMath{xxalignat}
\VerbMath{align}
\VerbMath{align*}
\VerbMath{flalign}
\VerbMath{flalign*}
\VerbMath{split}
\VerbMath{multline}
\VerbMath{multline*}
\VerbMath[equation]{equation}
\VerbMath{equation*}
\VerbMath{math}
\VerbMath{displaymath}
\VerbMath{eqnarray}
\VerbMath{eqnarray*}
\ConfigureEnv{gather}{}{}{}{}
\ConfigureEnv{gather*}{}{}{}{}
\ConfigureEnv{multline}{}{}{}{}
\ConfigureEnv{multline*}{}{}{}{}
\fixmathjaxtoc\int
\fixmathjaxtoc\,
\fixmathjaxtoc\sin
\fixmathjaxtoc\cos
\fixmathjaxtoc\tan
\fixmathjaxtoc\arcsin
\fixmathjaxtoc\arccos
\fixmathjaxtoc\arctan
\fixmathjaxtoc\csc
\fixmathjaxtoc\sec
\fixmathjaxtoc\cot
\fixmathjaxtoc\sinh
\fixmathjaxtoc\cosh
\fixmathjaxtoc\tanh
\fixmathjaxtoc\coth
\fixmathjaxtoc\log
\fixmathjaxtoc\ln
\fixmathjaxtoc\sum
\fixmathjaxtoc\(
\fixmathjaxtoc\)
\fixmathjaxtoc\begin
\fixmathjaxtoc\end
\fixmathjaxtoc\\
\fixmathjaxtoc\exp

\@ifpackageloaded{mhchem}{%
\def\ce#1{\texttt{\detokenize{\(\ce{#1}\)}}}
}{}

}
\endinput

It can be required for all TikZ environments using this configuration (thanks to @Qrrbrbirlbel for the inspiration):
\Preamble{xhtml}
\tikzset{every picture/.append code={\RestoreMathJaxEnvironments}}
\begin{document}
\EndPreamble

And this is the result:


text:
Q: Count within a SELECT Query I'm not sure how to put together the title.
I have a simple table, converted from a website and imported into my database once a month. I use this to display and review my whisky collection.
I have no primary key, as there is one row for each bottle, the structure looks like:

ID
Brand
Name
Status

149464
Ardbeg
Blaaack
open

149464
Ardbeg
Blaaack
closed

149464
Ardbeg
Blaaack
closed

149464
Ardbeg
Blaaack
empty

130674
Ardbeg
Drum
closed

So you can see, I cannot use the ID as primary key, as it is not unique. My goal is to get the follwing table out of the data I have:

ID
Brand
Name
Open
Closed
Empty

149464
Ardbeg
Blaaack
1
2
1

130674
Ardbeg
Drum
0
1
0

Where I am currently and what I've done:
SELECT
  Brand,
  Name,
  (SELECT Count(id) FROM table WHERE STATUS = 'Open') AS Open,
  (SELECT Count(id) FROM table WHERE STATUS = 'Closed') AS Closed,
  (SELECT Count(id) FROM table WHERE STATUS = 'Empty') AS Empty
FROM
  table
GROUP BY
  id
ORDER BY
  brand

So this is not working as expected, the encapsulated SELECT will give me the total number of all open bottles in the table, not just the ones with the same ID. But I cannot think of how to change this - I thought to add another GROUP BY to the SELECT Statement, but that's leading to a syntax error.
Any hints? How to get to the table I want?


text:
Q: F# WSDL code generation I'm using VS.NET 2010 integrated shell with F# and I'm trying to consume a soap web service... How do I go about generating F# source? I tried

wsdl l:"C:\Program Files (x86)\FSharpPowerPack-2.0.0.0\bin\FSharp.Compiler.CodeDom.dll" http://localhost/?wsdl

Along with

wsdl /language:"Microsoft.FSharp.Compiler.CodeDom.FSharpCodeProvider, Microsoft.FSharp.Compiler.CodeDom, Version=1.9.2.9, Culture=neutral, PublicKeyToken=a19089b1c74d0809"

However I can't seem to get the /language switch to work.
EDIT:
taspeotis' answer got me going... This generated F# source for the web service:
gacutil -i "C:\Program Files (x86)\FSharpPowerPack-2.0.0.0\bin\FSharp.PowerPack.dll"
svcutil /language:"Microsoft.FSharp.Compiler.CodeDom.FSharpCodeProvider, FSharp.Compiler.CodeDom, Version=2.0.0.0, Culture=neutral, PublicKeyToken=a19089b1c74d0809" http://localhost/?wsdl

A: This doesn't answer your question, but you may have better luck generating C#, compiling that C# into a library DLL, and referencing that DLL from your F# code.  (The C# compiler csc.exe will be part of your .NET installation.)

A: Have you added FSharp.Compiler.CodeDom.dll to the GAC? Use gacutil.exe to do this.
3rd party edit
Here an example  gacutil.exe /l System.XML.Linq to list certain assemblies.
Besides to FSharp.Compiler.CodeDom (source) an alternative might be the FSharp.Data library
Quote from jizugu: This generated F# source for the web service:
gacutil -i
   "C:\Program Files (x86)\FSharpPowerPack-2.0.0.0\bin\FSharp.PowerPack.dll"

svcutil
  /language:"Microsoft.FSharp.Compiler.CodeDom.FSharpCodeProvider
        ,FSharp.Compiler.CodeDom, Version=2.0.0.0, Culture=neutral
        ,PublicKeyToken=a19089b1c74d0809" http://localhost/?wsdl

A: I would be surprised if the F# Code DOM provider worked with WSDL. I wrote the initial implementation some time ago while at Microsoft and we got it to work with ASP.NET, but unless it has been improved since then, it probably won't work with WSDL or XSD.
Even for ASP.NET, we had to create a separate class that included some ASP.NET specific "hacks". This was partly because the CodeDOM generated by ASP.NET was invalid (in a way) and because the CodeDOM structure is not quite compatible with F#. If you really need to get this to work, you may have to add similar hacks (by modifying the source from CodePlex)
I tink that a safer approach is to include a small C# library project that generates the reference for you or invoking the C# compiler using csc.exe as Brian suggests.


text:
Q: Overflow from off-canvas menu conflicts with parallax I'm building this website and I'm facing a very strange problem. For 2 sections in the site i'm using parallax for background pics. It's working if I don't set an overflow rule but It's not working if I'll add. The overflow properties are essential for the off-canvas menu to work properly. I took the code for the off-canvas menu from here.
The elements with the conflict with the overflow are .container and .content-wrap.
html,
body,
.container,
.content-wrap {
  overflow:hidden;
  width: 100%;
  height: 100%;
}
.content-wrap {
  overflow-y:scroll;
  -webkit-overflow-scrolling: touch;
}

The code for the parallax is
;(function($) {
    $window = $(window);

    $('*[data-type="parallax"]').each(function(){

        var $bgobj = $(this);

        $(window).scroll(function() {

            var yPos = -($window.scrollTop() / $bgobj.data('speed'));
            var coords = '50% '+ yPos + 'px';

            $bgobj.css({ backgroundPosition: coords });

        });
    });
})(jQuery);

All the js code is in the file main.js. I tried to play with the values of overflow by removing them and add them elsewhere or wrap all the content in a new element but with no luck.

A: The problem is that you are registering the scroll action to the wrong element. What scrolls in this case (after you add your overflow settings) is your content-wrap div, not the browser window. This should work:
$(".content-wrap").scroll(function() {
    $('*[data-type="parallax"]').each(function(){
        var $bgobj = $(this);

        var yPos = -($(".content-wrap").scrollTop() / $bgobj.data('speed'));
        var coords = '50% '+ yPos + 'px';

        $bgobj.css({ backgroundPosition: coords });
    });
});


text:
Q: How to match values of Array with JSON I have an Array and JSON, trying to match the JSON values with array value, if match I need to print its value.
Array:
Arr = ["a","b","c"];

JSON:
{
        "Acol": {
            "cat": [{
                "val": "d"
            }, {
                "val": "c"
            }]
        }
    }

JS:
 for (var i = 0; i < Arr.length; i++) {
        for (var j = 0; j < cate.length; j++) {
            if (Arr[i] == cate[j]) {
                console.log(cate[j].val)
            }
        }
    }

Output that needs to be printed is 'c'

A: // if you haven't parsed your JSON, parse it.
var json = '{"Acol":{"cat":[{"val":"d"},{"val": "c"}]}}'
var obj = JSON.parse(json);

// not sure, is this meant to be `cate` or `cat`? I've used `cate` because
// that was in your code. This was one of the causes of your problems. It's called
// cat in your JSON...
var cate = obj.Acol.cat;

for (var i = 0; i < Arr.length; i++) {
  for (var j = 0; j < cate.length; j++) {

    // make sure you check the `val` property here
    if (Arr[i] == cate[j].val) {
      console.log(cate[j].val)
    }
  }
}

Demo

A: Try this code
var Arr = ["a","b","c"];
var cate={
          "Acol": {
                    "cat": [
                            {
                              "val": "d"
                            },
                            {
                                  "val": "c"
                            }
                           ]
                    }
                  }

    for (var i = 0; i < Arr.length; i++)
    {
      for (var j = 0; j < cate.Acol.cat.length; j++)
      {
            if (Arr[i] == cate.Acol.cat[j].val)
            {
              console.log(cate.Acol.cat[j].val)
           }
      }
    }


text:
Q: How to set Java 7 as default? For android 4.4.4 development, I needed Java 6. But eventually I moved over to Android 5.0 development which needed Java 7. When I tried using sudo apt-get install openjdk-7-jre and sudo apt-get install openjdk-7-jdk, It succeeds and after the installation completes, I try to set Java 7 as default by using sudo update-alternatives --config java. There I see 4 options like this.
I chose the desired option i.e: java-7-openjdk-amd64. And exit.
But at the time of the compilation, it says: that I have java 1.6.x installed. And at that time when I do java -version, it says that I'm using 1.6. Then I open a new terminal window and do java -version and it says that I have 1.7.x.
How to fix this thing? Please help me out

A: I fixed it by myself by removing all the java versions and installed 1.7.x again.
Guide which I followed: http://ubuntuforums.org/showthread.php?t=2218888


text:
Q: How to use caret functions to achieve the same results as this for loop? Classification Random Forest caret I want to run monte carlo cv 100 times on my data, my data is 2 class classification
I want to use the caret package to achieve the same thing, mainly I'm confused about how to average the results of accuracy for example using caret?
# Initialize data for Binary classification
dataset$ID <- factor(dataset$ID)

# Initialize number of iterations
num_iter=100

# Vectors to store results
acc_vec<-c()

# Function with for loop

    rf <- function(dataset)
    {
      for (i in 1:num_iter)
      {
        trainIndex <-createDataPartition(dataset$ID, p=0.8,list=FALSE)
        dataset_train <-dataset[trainIndex, ]
        dataset_test <-dataset[-trainIndex, ]
        rf <- randomForest(ID~., data=dataset_train, importance=TRUE)
        x_test <- dataset_test[, -1]
        y_test <- dataset_test$ID

        predictions <- predict(rf, x_test)

        acc_vec <- append(acc_vec, accuracy(actual= y_test, predicted= predictions))

      }

      print(mean(acc_vec))
    }

A: From the same author of caret, there is the brand new environment for modelling called tidymodels, that it could be helpful to make easy modelling.
Here a canonical example, with a Monte Carlo CV.
library(tidymodels)

 # load some fake data and create train and test
data(cells)
set.seed(123)
cell_split <- initial_split(cells %>% select(-case),  strata = class)

train <- training(cell_split)
test  <- testing(cell_split)

Now you've to set up the workflow, adding the cross validation (probably you have to install the ranger - in this case- package):
# first setup your model
rf_spec <-
  rand_forest(trees = 100) %>%
  set_engine("ranger") %>%
  set_mode("classification")

Remember you can also create grids of hyperparameters for tuning.
Now you create your validation strategy:
set.seed(123)
# I've put 10, you can change parameters
cross_val_mc <- mc_cv(train, prop = .5, times = 10)

Now you define your workflow:
set.seed(123)
rf_wf <-
  workflow() %>%
  add_model(rf_spec) %>%
  add_formula(class ~ .)

And fit your resample:
set.seed(123)
rf_fit_rs <-
  rf_wf %>%
  fit_resamples(cross_val_mc)

collect_metrics(rf_fit_rs)

# A tibble: 2 x 6
  .metric  .estimator  mean     n std_err .config
  <chr>    <chr>      <dbl> <int>   <dbl> <chr>
1 accuracy binary     0.824    10 0.00308 Preprocessor1_Model1
2 roc_auc  binary     0.896    10 0.00352 Preprocessor1_Model1


text:
Q: Redirect after empty login username and password I have chosen to display a login form in the first page of my wordpress website. If the user logs in successfully, he gets redirected to a specific webpage. If he enters a wrong password, he gets redirected to the login page again. The problem happens when someone does not enter username and password: he gets redirected to the wordpress admin login page.
How can I redirect empty username logins back to the main login page ?
this is the code I am using to redirect failed attempts :
add_filter('login_redirect', '_catch_login_error', 10, 3);

function _catch_login_error($redir1, $redir2, $wperr_user)
{
    if(!is_wp_error($wperr_user) || !$wperr_user->get_error_code()) return $redir1;

    switch($wperr_user->get_error_code())
    {
        case 'incorrect_password':
        case 'empty_password':
        case 'invalid_username':
        default:
            wp_redirect(home_url()); // modify this as you wish
    }

    return $redir1;
}

A: Check for an empty user login in the $_REQUEST array:
if ( empty( $_REQUEST['user_login'] ) // && or || empty( $_REQUEST['user_pass'] )
  return $redirect_to_whereever_you_want;

But this filter is to late. It is called after the user is logged in. You have to use the 'wp_authenticate' action, this is one of the earliest action in the login process:
add_action( 'wp_authenticate', '_catch_empty_user', 1, 2 );

function _catch_empty_user( $username, $pwd ) {
  if ( empty( $username ) ) {
    wp_safe_redirect( $redirect_to_whereever_you_want );
    exit();
  }
}


text:
Q: Not Reading text from a .txt file which is present on server
Possible Duplicate:
Not Reading text from server

i am trying to read text from a .txt file which is present on server but my code is not reading text from file i am using android version 2.1 , will you please also tell me how can i handle the exception in order to caught the error.
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    TextView tv= new TextView(this);
    StringBuilder content = new StringBuilder();

    try {
        URL url = new URL("http://linktomywebsite/textfile.txt");
        BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
        String str;
        while ((str = in.readLine()) != null) {
            content.append(str +"\n");
            tv.setText(content);
        }
        in.close();
    } catch (MalformedURLException e){
    } catch (IOException e) {
        e.printStackTrace();
    }

};

A:  TextView tv= new TextView(this);

This creates a new TextView that is independent of your current visible layout.
You are not putting this newly created TextView in your layout anywhere so your result, which is contained within that TextView, will not be shown
Assuming your code works to retrieve the text from your site (it looks fine to me) this is likely why you aren't seeing any results.
Try calling
setContentView(tv);

after your try { } catch { } and see if that works

A: You must link your existing TextView in the main Layout
tv = (TextView) findViewById (R.id.myTextView);


text:
Q: Does Kafka Streams library kill idle StreamThreads? Say, KStream topology is simple: input topic -> process -> output topic. Partitions of input topic = 4.
If there is a single instance of app running with num.stream.threads=4, all 4 StreamThreads are utilized.
If a second instance is launched (with num.stream.threads=4), stream tasks are now distributed between the two. Task 0_1 and 0_2 on first instance, Task 0_3 and 0_4 on second instance.
On first instance, does kafka streams library kill the threads which were running 0_3 and 0_4 so far?

A: For your case when input topic has only 4 partitions, what will happen When starting 8 instances with num.stream.threads=1?
4 instances become idle but not be killed. They are remaining and get assign a task if any of other already assigned instance goes down.
So, same thing happens when you start multiple treads in one instances. In your case, 8 treads in 2 instances 4 per each. same scenario happen I will explained above. 4 of your threads getting idle and remain idle until it is getting a task by going down other instance.
more reference :

*

*streams-faq-scalability-maximum-parallelism

*kafka-streams-internals-StreamThread

Let's take an example. Imagine your application is reading from an input
topic that has 5 partitions. How many app instances can we run here?
The short answer is that we can run up to 5 instances of this
application, because the application's maximum parallelism is 5. If we
run more than 5 app instances, then the "excess" app instances will
successfully launch but remain idle. If one of the busy instances goes
down, one of the idle instances will resume the former's work.

You can see more information of threads by set up metrics referring this


text:
Q: Вставка видео на сайт с "custom button"
Здравствуйте. Подскажите, можно ли вставить видео с "youtube", а вместо стандартного ютуб плеера заменить кнопку "play" на такую как на скрине. Или в двух словах расскажите новичку, как это реализовано. Спасибо.

A: Добрый день. Данную задачу можно решить по средствам Youtube API. К примеру у нас есть плеер, и есть блок с нужной информацией, позиционированный строго над плеером, по клику на блок - нужно скрыть его и выполнить команду play у плеера.

var yt_frame = document.querySelector('.video__player'),
 video_placeholder = document.querySelector('.video__placeholder');

  video_placeholder.addEventListener('click',play);

function play(){
 yt_frame.contentWindow.postMessage(JSON.stringify({
                'event': 'command',
                'func': 'playVideo',
                'args': []
            }),'*');
          video_placeholder.style.display="none";
}
.video {
  position:relative;
width:400px;
height:400px;
}

.video__player {
  width:100%;
  height:100%;
}

.video__placeholder {
  position:absolute;
  width:100%;
  height:100%;
  background:red;
}

  Контент

Fiddle - https://jsfiddle.net/erm0j1tq/


text:
Q: qgis 2.8.1 date filter gives incorrect selection results I am running QGIS 2.8.1 on ubuntu 14.04 x64. I applied a date filter to a shapefile using the layer Properties_General "Query Builder" button. So the query was
 "LOCATION START DATE" >= '01/01/2014'

The selection does filter out a bunch of objects, however in the selection results I am still seeing objects with dates before 2014. I am not sure why that is.
I even tried to use a function like:
 todate("LOCATION START DATE") >= '01/01/2014'

but that gave me an error.
Is there something I am missing to get a working date filter?


text:
Q: In SQL using the COUNT function with 1 column needing 2 answers SQL CH4 the question is: "How many trips are in the states of Maine(ME) or Massachusetts (MA)?"
I tried:
SELECT STATE, COUNT(*)
FROM TRIP
GROUP BY STATE IN ('MA','ME');

The Outcome gave me:
STATE (NH) 25, (ME) 16.

I can't figure out how to get Maine and Massachusetts in the same answer.

A: I believe this is what you want (although you have not asked a clear question)-
SELECT COUNT(STATE) FROM TRIP WHERE STATE IN ('MA','ME');

A: Probably you can try this
SELECT state, COUNT(id) FROM items_by_state
GROUP BY state HAVING state IN ('MA','ME');


text:
Q: Matlab - wait for the end of a callback function I have a program using two timers. The first one allows me to communicate with a microcontroller every second and to update charts, and I use the second one to stop the program after 50 seconds if the user did not press stop button before. The problem is that I don't know how to wait the end of the execution of the callback function of the first timer before ending the program. Sometimes, it stops in the middle of the first callback. I would like to avoid that, but I don't know how. I tried to use "waitfor", but it doesn't work.
Here is a simple example with the same problem.
t = timer('ExecutionMode','fixedRate','Period', 1,'TimerFcn',@testWait);
fwait = figure('Visible','off');
start(t);
disp('start');
pause(5);
delete(fwait);
i=0;
while true
    waitfor(fwait);
    disp(int2str(i));
    pause(0.05);
    i = i + 1;
end

function testWait(src,event)
    disp('before');
    waitfor(evalin('base','fwait'));
    disp('after');
    assignin('base','fwait',figure('Visible','off'));
    pause(1);
    delete(evalin('base','fwait'));
end

Can someone help me please ! :)

A: You can try using uiwait and uiresume. Here's a code snippet for how to use it:
f = figure;
h = uicontrol('Position',[20 20 200 40],'String','Continue',...
              'Callback','uiresume(gcbf)');
disp('This will print immediately');
uiwait(gcf);
disp('This will print after you click Continue');
close(f);


text:
Q: How to know if my Calendar is shared to public in CalendarEntry In the CalendarEntry class what is the field that correspond to the share property?
I want to know if the calendar I own is public or not and if the "Share only my free/busy information (Hide details)" checkbox is checked.
Could you provide me a example, to get set or insert the public property.

A: You can read your setting via https://www.google.com/calendar/feeds/userID/settings - there you can check the Visibility setting (public/private...).
For the full .NET API to Google Calendar see http://code.google.com/apis/calendar/data/2.0/developers_guide_dotnet.html#SharingACalendar (this link directly goes to the part regarding sharing a calendar)...


text:
Q: 4 Column Full Width Link Blocks - Background Image I am creating a 4 column section and wondering how I can put an image in the background of each block. Please see the snippet below and a screenshot of how I want the final product to look.
I am not sure how I can put an image in the background of each one. Could anyone help?
Thanks in advance.

<link href="http://impression.testcre8.co.uk/assets/vendor/bootstrap/bootstrap.css" rel="stylesheet"/>
<link href="http://impression.testcre8.co.uk/assets/css/unify-components.css" rel="stylesheet"/>

Consult

Understanding your brief, campaign goals & vision.

Design

Creative concepts that bring your brief to life.

Create

Fully in-house, quality-assured production.

Deliver

Packing, dispatch & on site installation management.

A: It is possible without image.

.row {
   display: flex;
}
.block {
   display: flex;
   align-items: center;
   color: white;
   width: 25%;
   height: 40px;
   padding-left: 30px;
   position: relative;
}
.block:not(:last-child):after {
   content: "";
   position: absolute;
   top: 0;
   left: 100%;
   width: 0;
   height: 0;
   border-style: solid;
   border-width: 20px 0 20px 20px;
   z-index: 10;
}
.block:nth-child(even) {
   background-color: lightgray;
}
.block:nth-child(odd) {
   background-color: gray;
}
.block:nth-child(even):after {
   border-color: transparent transparent transparent lightgray;
}
.block:nth-child(odd):after {
   border-color: transparent transparent transparent gray;
}

1st

2nd

3rd

4th


text:
Q: Ideas to improve Haar training results Please help to get more knowledge on the my first-time haar training results.
So I want to train Haar classifier to recognize simple pen, following Dileep Kumar's article.
Using my cellphone I made 14 pen pictures. These pictures size is big about: 263x2814
Then I collected negative pictures, some of them downloaded from web, with size 640x480, and some of them made using my phone camera, with size: 1920x1080,5313x2388
Some of these negative images are really big. I have total 158 negative images.
After that create negative and positive images list and run the: createsamples command:
 perl createtrainsamples.pl positives.dat negatives.dat samples 250  "opencv_createsamples  -bgcolor 0 -bgthresh 0 -maxxangle 0.5 -maxyangle 0.5 maxzangle 0.5 -maxidev 40 -w 160 -h 20"

I am not sure here if 160 for with and 20 for height is okay or not?
And then after having samples.vec file I run the cascade training, using this command:
opencv_traincascade -data firstTry -vec samples.vec  -bg negatives.dat -numPos 250 -numNeg 99 -numStages 25 –featureType HAAR  -mode ALL -w 160  -h 20 -mem 2048

I used the same width and height, but not sure if this is something right. I took the width and height values from some reference script. After getting the cascade.xml file, I am running the detectMultiScale on my picture using the following argument:
faces = faceCascade.detectMultiScale(   image,   scaleFactor=1.4,  minNeighbors=3,   minSize=(30, 30) )

The detection does not work well. It is just detecting some parts of the pen and not the full pen.
Also when I have some photo where pen is put in environment, than pen is not being detected.
I think I need to resize all positive and negative images and make them same size, though not sure on this.
Could you please provide some opinions on what I have done wrong here and how I can improve my results.
You can find all my files here:

A: These are only based on own my experience:

*

*I think createsamples works well only when the width and height of your original image are equal. This is because when createsamples rotates your image, if the width and height are different the image gets cut (Go into your positive folder and look at the images it created. You'll see.) So my advice is... if this is your first time and you want to test createsamples (and don't know any other ways), choose a round or square object with equal width and height.

*Your number of negative and positive images are very very low... it should be in the thousands.

*As I said in #1 your -w -h should be equal (if using createsamples). And don't EVER use more than 25 for each of them (I recommend 20 20 or even 15 15). As I have experienced very very long training times without much gain in detection (actually once I experienced lower detection rate with maybe 5 or 6 times the training time).

*Resize all your negative images to be the same size before using createsamples (maybe 100x100). and resize your original image to be half or lower in width and height (maybe 50x50).

*There are some important variables you can change in traincascade command that make detection far better but they will make the training excruciatingly long:
-minHitRate 0.999 -maxFalseAlarmRate 0.1 -maxWeakCount 1000

Be warned: If you are going to use the above numbers you basically have to use LBP instead of HAAR. HAAR has better detecting but with LBP you can use better values because it takes way less time (although with these numbers and lots of images (+10000) it might still take days but use these with HAAR and I may be seeing you in a few months ). Here's how you make it LBP: -featureType LBP.
The closer -minHitRate is to 1 the better. The lower -maxFalseAlarmRate is to 0 the better. And the higher -maxWeakCount the better.
Also note that the better you set these up the less number of stages you need to go. You might have a 25-stage cascade that performs worse than a 6-stage cascade with a good set up. Also also note that your traincascade might seem like it is stuck on getting the negative images when you use these numbers (It's okay though).

*Also lighting is very important in detection. Use a room with good lighting to get better results.

On a weird note: why did you use faces = faceCascade.detectMultiScale when you want to detect pens. :D Don't make the computer more confused than it already is mate. :D


text:
Q: Duplicating a list to a list with pointers I have simplified the problem incredibly to a small runnable example of my issue, shown below:
package main

import "fmt"

type A struct {
    Name string
}

func main() {
    main_list := []A{A{"1"}, A{"b"}, A{"3"}}
    second_list := make([]*A, 0)
    fmt.Println("FIRST LIST:")
    for _, x := range main_list {
        fmt.Println(x.Name)
        second_list = append(second_list, &x)
    }
    fmt.Println("SECOND LIST:")
    for _, x := range second_list {
        fmt.Println((*x).Name)
    }
}

Which provides:
FIRST LIST:
1
b
3
SECOND LIST:
3
3
3

The simple task is creating main_list with some dummy structs. The real issue is creating references (pointers) from the values in main_list into second_list. I absolutely do not want copies of the structs, only pointers/references to the main_list structs. The second for loop iterates through the newly populated second_list and shows only the last value from main_list (3 in this example) three times.
I expect the issue arrises with the way I am using &x in the first loop. With the way I get all three values of second_list to all be the same struct instance; I am going to assume that I actually made a pointer to the for-loop's iterator (as if it were a reference?). So all the pointers in second_list will always be the last item referenced in the first loop.
The question: How could I make a pointer from what x was pointing to at that moment in the for loop?

A: You're adding the address of the same x in every call to append.
You could initialize a new x and copy the value:
for _, x := range main_list {
    x := x
    second_list = append(second_list, &x)
}

Or create a new x directly indexing the slice:
for i := range main_list {
    x := main_list[i]
    second_list = append(second_list, &x)
}

Or if you want the address of the original value in the slice, you can use:
for i := range main_list {
    second_list = append(second_list, &main_list[i])
}


text:
Q: Amazon Athena: Alter table to ignore malformed json errors This doesn't work:
ALTER TABLE 'table' SET SERDEPROPERTIES( "ignore.malformed.json" = "true");

A: The problem you are having is that Athena uses the presto language not the hive language for DDL. Think of Athen(Presto) as a subset of the Hive language while still a full featured ansi-SQL language. The command you are trying to use is not a supported DDL statement, sadly.
You will have to recreate the table adding the properties:
 CREATE EXTERNAL TABLE impressions (
        id string,
        awesomeness struct<
           modellookup:string,
           requesttime:string>
    )   PARTITIONED BY (dt string)
    ROW FORMAT  serde 'org.openx.data.jsonserde.JsonSerDe'
    with serdeproperties ( 'ignore.malformed.json'='true' )
    LOCATION 's3://myregion.awesome/awesome';

NOT THIS ONE (ignore.malformed.json not available)
CREATE EXTERNAL TABLE impressions (
        id string,
        awesomeness struct<
           modellookup:string,
           requesttime:string>
    )   PARTITIONED BY (dt string)
    ROW FORMAT  serde 'org.apache.hive.hcatalog.data.JsonSerDe'
    with serdeproperties ( 'paths'='id' )
    LOCATION 's3://myregion.awesome/awesome';

I will add for completeness that is the latest SerDe documentation

Hive JSON SerDe
The Hive JSON SerDe is used to process JSON data, most
  commonly events. These events are represented as blocks of
  JSON-encoded text separated by a new line.
You can also use the Hive JSON SerDe to parse more complex
  JSON-encoded data with nested structures. However, this requires
  having a matching DDL representing the complex data types.
OpenX JSON SerDe
This SerDe has a useful property you can specify when
  creating tables in Athena, to help deal with inconsistencies in the
  data:

*

*'ignore.malformed.json' if set to TRUE, lets you skip malformed JSON
  syntax.


text:
Q: Finding the smallest perfect power in a range Given a range $[a, b]$, how does one find the smallest perfect power contained in the range? i.e., find $a \le k^m \le b$ where $a, b \in \mathbb{R_{\ge 0}}$ and $k, m \in \mathbb{Z_{\ge 0}}, m \ge 2$.
If $N(x)$, is the counting function for perfect powers $\le x$, then $N(x) \sim \sqrt x, x \to \infty $ as squares dominate the perfect powers.
What I have so far is a procedure for searching squares in the range $[\lceil \sqrt a \rceil, \lfloor \sqrt b \rfloor]$. My intuition is to find the smallest square in this range, say $x_2^2$ and then narrow the range to $[a, x_2^2 - 1]$ and search for perfect cubes in the narrowed range and so on. We stop when the range has just one element i.e., $a$ and return the smallest perfect power that we have kept track of.
Am I right? Is there a better way?

A: This can be done without searching, merely by calculating:
The smallest perfect power larger than $a$ is the minimum of the numbers
$$
\lceil a^{1/2} \rceil^2,\ \lceil a^{1/3} \rceil^3,\ \lceil a^{1/4} \rceil^4,\ \dots,\ \lceil a^{1/k} \rceil^k
$$
where we can stop as soon as $2^k > \lceil a^{1/2} \rceil^2$ (so roughly $k=\log_2 a$). This is easy to calculate, and then one discovers whether it's less than or equal to $b$ or not (if not then there are no perfect powers in the interval).


text:
Q: Angular build fails after adding argon2 or bcrypt from npm I have an Angular project where I want to use argon2 library to encrypt passwords.
I added it to the back end, the implementation it's fine but my Angular front end app started to break.
I get a huge list of errors like:
ERROR in /<project>/node_modules/argon2/node_modules/minizlib/constants.js
Module not found: Error: Can't resolve 'zlib' in '/<project>/node_modules/argon2/node_modules/minizlib'

This is just one of the errors, I have similar errors for modules like crypto, fs, http, https, os, path, stream and many others. Same happens if I use bcrypt.
Do you know what is issue?

A: Angular doesn't support working with node js modules
Like fs and more.
U could find a package for encrypting password  from npm to do the work instead.


text:
Q: Cron job to run on every LAST Friday of every month I would like an option/option or if there is a better solution from what I am going to present here to get this task accomplished:
My first option is this, but it seems complex:
# This run on every last Friday (or whatever weekday) of the month at 1AM
0 1 * * 5 [ $(date +"\%m") -ne $(date -d 7days +"\%m") ] code.pl

Or a more explicit way, every last Friday of every month at 1AM:
0 1 25-31 1,3,5,7,8,10,12 5 code.pl
0 1 24-30 4,6,9,11        5 code.pl
0 1 22-28 2               5 code.pl

Thanks for looking and suggestions!


text:
Q: Detect if the last selected email has been marked as read and prompt to save My outlook VBA code aims at doing the following:
In the event of selection change (i.e. say the user clicks on a different email in the inbox)
If [the previously selected email was originally 'Unread' and just became 'Read'] Then
Prompt the user to save the previous email
Else
Do Nothing
End If

To do that I used the Explorer_SelectionChange event. The problem I'm facing is that outlook takes about 1 to 2 seconds before it marks the previous email as read! My code gets executed before these 2 seconds pass. Hence it always sees the previous email as unread! :(
I tried to introduce a pause to my Sub but it didn't work. Outlook waits until my code finishes including the pause before it in turn waits 1 to 2 seconds and then mark the previous email as read.
So in summary my question is: Is there an Event that identifies when the previously selected email is marked as Read?? (PS: I tried MailItem.Read Event but it is also instantaneous and applies to all 'read and unread' emails]
Here is the part of my code that specifically tries to achieve the above described functionality:
Public WithEvents myOlExp As Outlook.Explorer
Dim Flag As Integer
Dim oMail As Outlook.MailItem

Private Sub Application_Startup()
Dim objItem As Object

Set myOlExp = Application.ActiveExplorer
enviro = CStr(Environ("USERPROFILE"))

'Identify the status of the selected email at startup
For Each objItem In myOlExp.Selection
    If objItem.MessageClass = "IPM.Note" Then
        Set oMail = objItem
    End If
Next

If oMail.UnRead Then
    Flag = 1 'Means Current selection is an unread email
Else
    Flag = 0 'Means Current selection has been read before
End If

End Sub

Private Sub myOlExp_SelectionChange()
'If previous selected email was Unread
If Flag = 1 Then
    If oMail.UnRead = False Then
        MsgBox "previous email has just been read do you want to save?"
        '^^This is where the problem happens: the previously selected email is always seen as read by the code
        'because Outlook takes 1-2 seconds after the selection change event before it marks the email as read!!
    Else
        MsgBox "Previous email still marked as unread, do nothing"
        '^^I am always getting this outcom when I change selection from an unread email to another email!
    End If

    'Now identify the status of the newly selected email
    For Each objItem In myOlExp.Selection
        If objItem.MessageClass = "IPM.Note" Then
            Set oMail = objItem
        End If
    Next

    If oMail.UnRead Then
        Flag = 1 'Means Current selection is an unread email
    Else
        Flag = 0 'Means Current selection has been read before
    End If

Else
    ' Flag = 0 i.e previous email was already read
    ' Identify the status of the newly selected item.
    For Each objItem In myOlExp.Selection
        If objItem.MessageClass = "IPM.Note" Then
            Set oMail = objItem
        End If
    Next
    If oMail.UnRead Then
        Flag = 1
    Else
        Flag = 0
    End If
End If

End Sub

I hope I managed to formulate my question clearly! Any help is most appreciated.
Many Thanks

A: Once you set Flag = 1, oMail.UnRead status does not matter.
If Flag = 1 Then

    ' Remove this test
    'If oMail.UnRead = False Then

        MsgBox "...


text:
Q: Changing a Sql Job Dynamically I know how to create a job dynamically from this create-sql-server-job-automatically
The issue I have with this technique is clean up is required to delete all these jobs I create
What I am looking for is a way to pass in a parameter to a Job or change a Job step dynamically
Background
I have a series of SSIS jobs I need a tester to run.  I was shot down in creating a webpage to call a WCF service that sits on the DB Server to execute the package.  I can not use xp_cmdshell.  So the third option was calling the package through a sql job.  Now while I can create one job per package ideally I would like one job where I can pass in the package name, a config file, and maybe some dynamic variables.
Looking at this post Calling SSIS Package from Stored Procedure in SQL Server 2008
I can see how I create the dynamic package, again the concern is cleaning up the jobs.
Constraints
The reason I am going down the road of creating a job dynamically is a result of the following constraints
The testers do not have Sql installed on there machine so they do not have access
to the BIDS environment nor DTEXEC

For reasons not completely logical I am restricted from using c# and building a
WCF service that would call the package through code

I can not use xp_cmdshell due to permission and security issues.

Now if there is a better way to handle this without Sql Jobs I am open to that possibility but the main goal is to create a form (web or windows) that the tester can choose a package, run it and see the internal logs of the package run that we record.

A: For starters I proposed a 'cleaner' version on how to solve the question you linked too. Going from there it's only a small step to here : sp_add_job where you'll find the explanation for @delete_level
Value Description
----- -----------
0     Never
1     On success
2     On failure
3     Always

So in short, if you want jobs to clean up after themselves, use @delete_level 1 or 3 according to your needs.

A: You seem to have mixed up two questions here but since your real priority appears to be executing packages, why not use dtexec or dtexecui? Your testers can build them into a test script easily and that seems to be an easier solution than using jobs.
If this isn't possible for any reason then I think you will have to explain exactly what restrictions you have and why (possibly in a new question). Running packages is usually quite easy but it seems that you do not have a completely free hand to implement what you want.


text:
Q: current_timestamp redshift When I select current_timestamp from redshift, I am getting a list of values instead of one value.
Here is my SQL query
select current_timestamp
from stg.table;

Does anybody know why I am getting a list of values instead a single value?

A: This is your query:
select current_timestamp from stg.table

This produces as many rows as there are in table stg.table (since that's the from clause), with a single column that always contains the current date/time on each row. On the other hand, if the table contains no row, the query returns no rows.
If you want just one row, use a scalar subquery without a from clause:
select current_timestamp as my_timestamp

A: You will receive a row for each row in stg.table. According to the RedShift docs you should be using GETDATE() or SYSDATE() instead. Perhaps you want, e.g.:
select GETDATE() as my_timestamp