text:
Q: How to insert and update SQL Server DateTime in a date column using Entity Framework Core in .NET Core I have a table that contains a LastUpdateOn column, I would like to keep SQL Server current date & time (using GETDATE()) in this column whenever I am doing insert or update operation in my table.
In ADO.NET, we used to call GETDATE() function in insert/update statements, but how we can achieve the same thing using Entity Framework Core?
Reason to store SQL Server date time is we do not want to store the application server date time in LastUpdateOn column as application will be running from different servers and their clock might be not in Sync so we want to store common time from all the places(app servers).

A: There are two quick solutions for this on top of my head:

*

*Simple put the value as default to GetDate() on this columns and pass null to EF when inserting or update;

*Create a function that calls GetDate()  before an inserting/update and use this as the value;
Edit:

*Create a new EF configuration for DateTime values that get the GetDate() function before inserting/update and automate the process;

A: So as I moved away from stored procedures (where I used "GetDate()" or "CURRENT_TIMESTAMP" alot)... I embraced the c#/middleware layer.
I do a "null check" and set it on the c# code (in the entity framework data layer code)
Below shows DateTime.  DateTime.MinValue means "somebody did not explicitly set it".
 myEntityFrameworkEntity.InsertDate = parameterInsertDateValue == DateTime.MinValue ? DateTime.Now : parameterInsertDateValue;

There are other variations, but the idea is the same.  Did the "caller" explicitly set the property, or did they not set it, let me write a value on their behalf.
Now, sometimes I don't care what the caller set.  If it is a LastUpdatedDate , you can just "force it" as well (always set it to DateTime.Now)....
// i don't care what the parameters are, i always update it in this layer
myEntityFrameworkEntity.LastUpdatedDate = DateTime.Now;

Also, instead of using DateTime(.Now) directly... I use this:
https://github.com/vfabing/Chronos.Net
You "inject" a DateTime-PROVIDER .. that can be mocked for Unit-Tests.
Here is a more complete example to show my EF code (for Rest-Services that needs "disconnected" entities).
    public const int ExpectedAddSingleOrUpdateSingleOrDeleteSingleSaveChangesAsyncRowCount = 1;

    public async Task<EmployeeEfEntity> UpdateAsync(
        EmployeeEfEntity inputEmployee,
        CancellationToken token)
    {
        int saveChangesAsyncValue = 0;

        /* find the object in the db-context using the object surrogate-primary-key (since this is an update) */
        EmployeeEfEntity foundEntity =
            await this.entityDbContext.EmployeeEfEntitys.FirstOrDefaultAsync(
                item => item.EmployeeEfEntityKey == inputEmployee.EmployeeEfEntityKey,
                token);

        if (null != foundEntity)
        {
            /* update the found-entity with the properties of the input object */

            /* the "normal" properties of the employee */
            foundEntity.EmployeeBadgeNumber = inputEmployee.EmployeeBadgeNumber;

            /* if the insert-date was explicit, use it, otherwise default to date-time.now */
            foundEntity.InsertDate = inputEmployee.InsertDate == DateTime.MinValue ? DateTime.Now : inputEmployee.InsertDate;

            /* we do not care about the input parameters, we always set it to "now" */
            foundEntity.LastUpdated = inputEmployee.LastUpdated == DateTime.Now;

            this.entityDbContext.Entry(foundEntity).State = EntityState.Modified;
            saveChangesAsyncValue = await this.entityDbContext.SaveChangesAsync(token);
            if (ExpectedAddSingleOrUpdateSingleOrDeleteSingleSaveChangesAsyncRowCount != saveChangesAsyncValue)
            {
                throw new ArgumentOutOfRangeException(
                    string.Format(ErrorMsgExpectedSaveChangesAsyncRowCount, saveChangesAsyncValue),
                    (Exception)null);
            }
        }
        else
        {
            ArgumentOutOfRangeException argEx = new ArgumentOutOfRangeException(
                string.Format(ErrorMsgPrimaryEntityNotFound, inputEmployee.EmployeeEfEntityKey),
                (Exception)null);

            this.logger.LogError(argEx);
        }

        return foundEntity;
    }

My code actually uses the Chronos.Net (injected) date-time-provider, but I removed it to keep the code simpler for this answer.

A: Since you're using Entity framework, which aimed at allowing database usage to be handled in C# more, I would just use DateTime.Now (DateTime.UtcNow if you want UTC time).
Set LastUpdateOn to DateTime.Now or DateTime.Utc.Now each time you enter/upate a record.
If you really want to use SQL server's GETDATE() method, then write a stored procedure that takes an interger (the id of the record to update) and use it to set LastUpdateOn for the field with the specified id to the value of GETDATE().


text:
Q: CAS w/ SPNEGO Authentication error I'm trying to set up CAS SSO with SPNEGO on a Windows environment. I've followed all the instructions in http://jasig.github.io/cas/4.0.x/installation/SPNEGO-Authentication.html but the authentication process fails.
This is the output from the cas.log:
2015-03-04 11:36:22,732 DEBUG [org.jasig.cas.support.spnego.web.flow.SpnegoNegociateCredentialsAction] - Authorization header not found. Sending WWW-Authenticate header
2015-03-04 11:36:22,738 DEBUG [org.jasig.cas.web.support.CasArgumentExtractor] - Extractor did not generate service.
2015-03-04 11:36:22,738 DEBUG [org.jasig.cas.support.spnego.web.flow.SpnegoCredentialsAction] - SPNEGO Authorization header found with 1800 bytes
2015-03-04 11:36:22,739 DEBUG [org.jasig.cas.support.spnego.web.flow.SpnegoCredentialsAction] - Obtained token: `'A+ '50'1 $0"   *†H'÷  *†H†÷
+'7
¢''`'ÿ   *†H†÷ n'î0'ê ¡¢     £'a'0' ¡    STU.EDU¢$0" ¡0HTTPrenato-pc.stu.edu£'Ò0'Π¡¢'À'¼';Kù«î  Qx‹¦ô¨Oö©$É(L)AµyaC²}wÚ(W+ˆeŽ»vj[èAe¿…íZÍ®CŸ"ÑúD€'É'5©–k¼/Οêý7¨ÊÙþÅ'B´;Ñ€ã⽿ÌWat,ó5LJýÅÙ{¡3ê"G¦GÄ¥IyǤé¯Õ?9k`Zz!;cºE•Û[·˜Œª|{´:t%j¡ía"??H£³òØ×ë÷œoG ¦]+é<Ìàʨ®2›Uòx|㨱: a%ÆÔaJ6_½B:"õ¯Fܪ"\N+¼ª
çšòÓ%Öá?xõyƒ;࿺õ$ÀŒã=»@›¹õç4 ²m>"¥U,»G!Ô½‰ô—C÷ȇݽo"ß;=ÿ™fáÉÁ¸^ŽÒÛÇÔa~µ'üë‡³× ]Kôp2jž¬ÔP^§2§€jöù)4LLª˜"Œ'¸"S8'½óÞ°ÊæÏ'R<%2Iÿ{'E§½6¨FÌkÙ"<¡ãyŽù g]ü.B&²Äõ-ò\¿%:ØydˆTÈÊ jù® Æ®XŠ0EC§×CôèG?]b Ž#6"¾(3z`ñ×ðCWµkm¦<9µÓ^4éÐ5«›éÿÄ»«_™1åÁÖZÉ}ÁªG€0±½H¿Ì%oÎW‡Hj{¨8ÕÉ÷>Í8?×ÙZW)'¤žtK2é^A$(k¦ÒÇFñޤǰ¬@ÒÑÕHYXëªöϳgšÙK!9r(a9«ÐÜçPÓ¯ù[ºò«w¹Åm_#ÐÐyÚnVêø?ª3"›' Š§‰¦É"˜3iÅ_ûĦ¬8€ËókOŠ2uSkÒ[àù†hG³õí:aÌIUg´‹§ñÍSŸr2a?¥C"Ãpv2ÃÚ"Fk•W%\$Žò³ÇÁ8B@ðŠj‡xŒx ÈÛtSE½QMÓ¡x™I?•æW§'¶¿èà?
†ÏÅÎœßù›Ôžå?Ÿ'˜'e¾B¿L?$$8Ú`¼@p©‰ú0}´ðŒÎ`hâĤ?    M   ¶>[UMC*Ö#ã½Xùd…!#$?
=²^cÌZ…&þ³P#q[©ƒB^t?PjÁWd~…©?¥ZƒêQ!)h:="öy(‹?©½ä‡£ú]´1ìEØxÆ7‹BÞôÒ‹Ámr}kß½Ø&Ãxšö+ h((Ÿçå|?¼ÈNZô{hÎŽŒ_ª?}žl?_¼áa¤?¼0?¹ ¢?±?®ú4"kuñO§Bq9¸A¦0c©?0ƒòÕ'N¶~)¨$TyÚì%µÈÓÉÌ\üšzǘř?$QSªØºrÝž :Ä®6¤2ì¦Ä74Œù‰pÆäL?÷z¸çz'ì3Ó$ߢݨ?þNVo™qí—§ˆ´u¨Þ"Âè?É×&'c΢Y& «JèÈYU£§(¯…Ô°'/~ðÁó±ò"™F²"Ä8"ú

This is the output from the tomcat server:
04-Mar-2015 11:34:00.187 SEVERE [http-nio-8443-exec-6] org.apache.catalina.core.StandardWrapperValve.invoke Servlet.service() for servlet [cas] in context with path [/cas] threw exception [Handler processing failed; nested exception is java.lang.ExceptionInInitializerError] with root cause
 java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast to [Ljava.lang.Byte;
    at org.jasig.cas.support.spnego.util.SpnegoConstants.<clinit>(SpnegoConstants.java:52)
    at org.jasig.cas.support.spnego.authentication.principal.SpnegoCredential.isTokenNtlm(SpnegoCredential.java:133)
    at org.jasig.cas.support.spnego.authentication.principal.SpnegoCredential.<init>(SpnegoCredential.java:79)
    at org.jasig.cas.support.spnego.web.flow.SpnegoCredentialsAction.constructCredentialsFromRequest(SpnegoCredentialsAction.java:79)
    at org.jasig.cas.web.flow.AbstractNonInteractiveCredentialsAction.doExecute(AbstractNonInteractiveCredentialsAction.java:73)
    at org.springframework.webflow.action.AbstractAction.execute(AbstractAction.java:188)
    at org.springframework.webflow.execution.ActionExecutor.execute(ActionExecutor.java:51)

04-Mar-2015 10:41:58.240 SEVERE [http-nio-8443-exec-5] org.apache.catalina.core.StandardWrapperValve.invoke Servlet.service() for servlet [cas] in context with path [/cas] threw exception [Handler processing failed; nested exception is java.lang.NoClassDefFoundError: Could not initialize class org.jasig.cas.support.spnego.util.SpnegoConstants] with root cause
 java.lang.NoClassDefFoundError: Could not initialize class org.jasig.cas.support.spnego.util.SpnegoConstants
    at org.jasig.cas.support.spnego.authentication.principal.SpnegoCredential.isTokenNtlm(SpnegoCredential.java:133)
    at org.jasig.cas.support.spnego.authentication.principal.SpnegoCredential.<init>(SpnegoCredential.java:79)
    at org.jasig.cas.support.spnego.web.flow.SpnegoCredentialsAction.constructCredentialsFromRequest(SpnegoCredentialsAction.java:79)
    at org.jasig.cas.web.flow.AbstractNonInteractiveCredentialsAction.doExecute(AbstractNonInteractiveCredentialsAction.java:73)
    at org.springframework.webflow.action.AbstractAction.execute(AbstractAction.java:188)

I'm guessing that SPNEGO authentication is failing at Step 5 (Negotiate w/ SPNEGO Token). Does anyone know how to troubleshoot this? Thanks!

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to use multiple data frame inputs for Mapdeck add_scatterplot within R Shiny? I'm finding Mapdeck to be a really cool alternative mapping method when working with large datasets in r shiny.  However I'm finding it difficult to pass in multiple datasets in order to expand the complexity of the resulting map.
For Example: I'm trying to populate the tooltip to create a popup with 'two' items by pulling in information from a second data frame (to illustrate a 1-to-many relationship).  But I can't get it to work.  Any thoughts?
Data sample
Map_DF <- data.frame("Point_ID" = 1:3, "Latitude" = c(38.05, 39.08, 40.05), "Longitude" = c(-107.00, -107.05, -108.00))
PointUse_DF <- data.frame("Point_ID" = c(1, 1, 2, 2, 3), "PointUse" = c("farm", "house", "farm", "house", "farm"))

The Code.
# ################################################################################################
# ################################################################################################
# # Sec 1a. Needed Libaries & Input Files

library(shiny)
library(shinydashboard)
library(mapdeck)
library(dplyr)

################################################################################################
################################################################################################
#UI
ui <- dashboardPage(
    dashboardHeader(),
    dashboardSidebar(),
    dashboardBody(
        mapdeckOutput(outputId = 'mapA')
    )
)

################################################################################################
################################################################################################
server <- function(input, output) {

    ##The MapDeck Token
    key <- '## put your own token here ##'
    set_token(key) ## set your access token

    ### The Map
    output$mapA <- renderMapdeck({
     mapdeck() %>%
            add_scatterplot(
                data = Map_DF,
                lat = "Latitude",
                lon = "Longitude",
                layer_id = 'Point_ID',
                tooltip = c("Point_ID",
                             PointUse_DF$PointUse[Map_DF$Point_ID]  # the idea of passing in a a key and returning multiple items
                            )
             )
    })

}

################################################################################################
################################################################################################
shinyApp(ui = ui, server = server)

A: The tooltip renders a column of the data object inside the popup.
So whatever you want displayed in the popup has to already exist on the data
with your example you need to create the tooltip column
# Using data.table to rshape the data to give a comma-separated list of 'PointUse' values
library(data.table)

dt <- setDT( PointUse_DF )[, .(info = paste0(PointUse, collapse = ", ")), by = Point_ID]

## Now you can put this onto the map object

Map_DF <- merge(
  x = Map_DF
  , y = dt
  , by = "Point_ID"
  , all.x = T
)

mapdeck() %>%
  add_scatterplot(
    data = Map_DF,
    lat = "Latitude",
    lon = "Longitude",
    layer_id = 'Point_ID',
    radius_min_pixels = 3,
    tooltip = "info"
    )
  )


text:
Q: How should I construct an NSDictionary with multiple keys? I have a situation where I want to map a pair of objects to a dictionary of information. I'd like to avoid creating an NSDictionary of NSDictionaries of NSDictionaries since that's simply confusing and difficult to maintain.
For instance if I have two classes, Foo and Bar, I want {Foo, Bar} -> {NSDictionary}
Are there other options than just making a custom class (just to be used as the dictionary key) based on the two types in question? Maybe something akin to STL's pair type that I just don't know about?

A: Like you said, you can create a Pair class:
//Pair.h
@interface Pair : NSOpject <NSCopying> {
  id<NSCopying> left;
  id<NSCopying> right;
}
@property (nonatomic, readonly) id<NSCopying> left;
@property (nonatomic, readonly) id<NSCopying> right;
+ (id) pairWithLeft:(id<NSCopying>)l right:(id<NSCopying>)r;
- (id) initWithLeft:(id<NSCopying>)l right:(id<NSCopying>)r;
@end

//Pair.m
#import "Pair.h"
@implementation Pair
@synthesize left, right;

+ (id) pairWithLeft:(id<NSCopying>)l right:(id<NSCopying>)r {
 return [[[[self class] alloc] initWithLeft:l right:r] autorelease];
}

- (id) initWithLeft:(id<NSCopying>)l right:(id<NSCopying>)r {
  if (self = [super init]) {
    left = [l copy];
    right = [r copy];
  }
  return self;
}

- (void) finalize {
  [left release], left = nil;
  [right release], right = nil;
  [super finalize];
}

- (void) dealloc {
  [left release], left = nil;
  [right release], right = nil;
  [super dealloc];
}

- (id) copyWithZone:(NSZone *)zone {
  Pair * copy = [[[self class] alloc] initWithLeft:[self left] right:[self right]];
  return copy;
}

- (BOOL) isEqual:(id)other {
  if ([other isKindOfClass:[Pair class]] == NO) { return NO; }
  return ([[self left] isEqual:[other left]] && [[self right] isEqual:[other right]]);
}

- (NSUInteger) hash {
  //perhaps not "hashish" enough, but probably good enough
  return [[self left] hash] + [[self right] hash];
}

@end

Edit:
Some notes on creating objects that can be keys:

*

*They have to conform to the NSCopying protocol, since we don't want the key to change out from underneath us.

*Since the Pair itself is copied, I make sure the objects in the pair are also copied.

*Keys have to implement isEqual:.  I implement the hash method for good measure, but it's probably not necessary.

A: You could try NSMapTable, then your key can be pretty much anything, perhaps a pointer to a structure if you want.
(Addendum to the comments below: NSMapTable was once not on iOS, but is available as of iOS 6.)

A: Is using something to the effect of
[NSString stringWithFormat:@"%@ %@", [obj1 key_as_string], [oj2 key_as_string]]
no good for you, where key_as_string is part of your object class? i.e. make a key from a string.


text:
Q: How to exclude in file all rows which contains date or brackets How to exclude in file all rows which contains date and bracket
In my case:
2015-01-16 12:51:34,787 | [D] | query.Selao | ref:5463| 13 | Selao .select | Binding 4 to 432| [ACTIVE] ExecuteThread: '0' for queue: 'weblogic.kernel.Default (self-tuning)'
java.lang.NullPointerException
        at com.api.base.dataaccess.elen(elen.java:424)
2015-01-16 12:51:34,788 | [D] | query.Selao | ref:5464| 14 | Selao .select | Binding 5 to 433| [ACTIVE] ExecuteThread: '0' for queue: 'weblogic.kernel.Default (self-tuning)'
   <list>
    <Filters class="com.base.Filter">
     <Negated value="false"/>
    </Filters>
   </list>

Expected after exclude:
java.lang.NullPointerException
        at com.api.base.dataaccess.elen(elen.java:424)

A: egrep -v '([0-9]{4}(-[0-9]{2}){2})|(\[.*\])' YourFile

but what about <LIST> in your post ? there is no date nor bracket but not in expected output ?
if bracket are not [] but <>
egrep -v '([0-9]{4}(-[0-9]{2}){2})|(<.*>)' YourFile

for all the 3
egrep -v '([0-9]{4}(-[0-9]{2}){2})|(<.*>)|(\[.*\])' YourFile

A: Use awk,
$ awk '!/[0-9]{4}-[0-9]{2}-[0-9]{2}|<.*>/' file
java.lang.NullPointerException
        at com.api.base.dataaccess.elen(elen.java:424)

OR
grep -v '[0-9]\{4\}-[0-9]\{2\}-[0-9]\{2\}\|<.*>' file

A: How about a sed solution to delete all lines that contain specific patterns:
sed '/20[0-9][0-9]-[0-9]/d;/\<.*\>/d' file


text:
Q: What is supposed to be entered after "login as" in PuTTy for SSH? When I open up PuTTy, it says "login as".  What is supposed to be entered?
Thanks in advance,
John

A: your username on the remote machine. probably not "root" since the account should be locked for remoteaccess.

depending on your linux distribution you set up an account during installation. use that one. otherwise you can add an user from commandline/gui. but again it depends on your linux distribution.

A: The user name you want to login as... After that it will try and pub/priv key pairs it has (if support), other authentication (like kerberos), then password auth.


text:
Q: Opengl float buffer I'm writing my first ray tracer. I want to make it work in real-time.
I want to use opengl for display.
I want to write my screen to floating point buffer and display the buffer.
What extension and/or buffer type I need?
Thanks in advance!

A:
I'm writing my first ray tracer. I want to make it work in real-time.

Ambitious!

I want to use opengl for display. I want to write my screen to floating point buffer and display the buffer.

OpenGL can read from float buffers directly, e.g.
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, width, height, 0, GL_RGB, GL_FLOAT, data);

But OpenGL may choose any internal format that matches your selection. GL_RGB internal format can be anything that can somehow store RGB data. You can be specific about what you want. For example GL_RGB16 tells OpenGL you want 16 bits resolution per channel. The implementation may choose to use 24 bits per channel, as this allows for 16 bit to be stored. But ultimately the implementation decides, which internal format it will be, based on the constraints you put upon it.
Floating point framebuffers and textures are supported in OpenGL through extensions GL_ARB_texture_float, GLX_ARB_fbconfig_float, WGL_ARB_fbconfig_float, but due to patent issues not all OpenGL implementations implement it (ATI and NVidia do).


text:
Q: Passing a pointer to a function as a parameter - C++ I have a list of functions from which the user chooses one to be used. This function is then passed as a parameter for some other function.
For example:
// Declare some functions here

int main() {
    // Declare some pointer
    int choice;
    cout << "1 - functionA, 2 - functionB..." << endl;
    cin >> choice;
    switch (choice) {
        case 1:
        // Assign pointer to functionA address
        break;
        case 2: //etc
        // Assign pointer to functionB address
        break;
        //etc
    }
    float x; float y; float z;
    float value = BigFunc(//ChosenFunction, x, y, z);
    cout << value << endl;
    return 0;
}

float BigFunc(//ChosenFunction(returns a float), float x, float y, float z) {
    // Some code
    float a = OtherFunc(//ChosenFunction, x, y, z);
    // Some code
    return a;
}

float OtherFunc(//ChosenFunction, float x, float y, float z) {
    for (//some for loop) {
    return b += ChosenFunction(x);
    }
    return b;
}

I have used comments to indicate areas where some code would be. The functions from which the user can choose are functions which take 1 float argument, perform some mathematical operations on that value and then return it.
I have seen some examples online however they are all very specific and have not helped me very much. I have tried to keep the example in this post as general as possible so that hopefully others that stumble across it can learn from it too.
I have attempted to use pointers to accomplish this task however it has been to no avail. Online I have seen people using float (*pointer)(float) however I am unfamiliar with using a pointer like this. I have also seen people using typedef however once again I am unsure of how to implement that here.
Any help or pointers (pun) in the right direction would be much appreciated!
Sean.
Edit: The question which this has been tagged as a duplicate of is similar however I did look at that question before and I felt that it does not sufficiently resolve this problem. The program which I am writing is more complicated than this case however I have kept it simpler so that others can find this post helpful after I am finished with it.


text:
Q: $.ajax POST Undefined index Apologies in advance for any mistakes. This is my first post on StackOverflow.
So basically I have a php function. Inside it is a jQuery click function with a variable, into which I'm saving the clicked element's text. I'm trying to send that variable's value to my Uredi.php file, via $.ajax function, to save it into a php variable. However, I'm getting an "Undefined index" error. Help would be greatly appreciated. Thank you.
Here's the code:
PHP function:
public function uredi()
{
?>
<script>
$('.edit').click(function(){

$('.naslov_edit').val($(this).text());
$('#on_top').hide();
var refId = $(this).text();
    $.ajax({
        url: 'uredi.php',
        type: "POST",
        data: {id: refId},
        success: function(data){
            alert(data);
        }
    });

});
</script>
<?php
}

Uredi.php:
<?php
include 'Funkcije.php';

$uredi = new urejanje();
$uredi->uredi();

$id = $_POST['id'];
echo $id;
?>

Funkcije.php is the file with the uredi() function.
EDIT: Thank you everyone for helping. I figured out the problem. Turns out I just had to clean up my code a bit.

A: Why are you assigning $(this).text() to var id and then not using it in the $.ajax()? Remember scope and what doe $(this) actually reference within the $ajax()? I would also shy away from naming variables "id" Try:
var refId = $(this).text();
$.ajax({
    url: 'uredi.php',
    type: "POST",
    //dataType: 'json',
    data: {id: refId},
    success: function(data){
        alert(data);
    }
});

A: Use this;
$.ajax({
    url: 'uredi.php',
    type: "POST",
    data: "id=" + refId,
    success: function(data){
        alert(data);
    }
});

A: perhaps you meant to read the post vars before initializing the class and maybe even pass Id in?
  $id = $_POST['id'];
  $uredi = new urejanje();
  $uredi->uredi($id);

In any case I think You'll need to show us whats inside Funkcije.php


text:
Q: ADS8598S - how to connect to a MCU - general Architecture question For a future project I'd like to use the ADS8598S from Texas Instruments, which is a "higher speed" 8 Channel simultanously sampling ADC with 18 Bits and a max. Sample rate of 200 kSPS per Channel. Until now, I just used low speed devices like DACs running at 5 or 10 kHz or ADCs with Sample Rates up to 20 kHz together with STM32F4, F7 or G4 MCUs. However, I never used something really fast with a high(er) channel count. So I am wondering "how to I get this amount of data into a Microcontroller?".
The whole DAQ chain would be: sample the voltages with the ADC, transfer it into a Microcontroller / Microprocessor, convert the data into voltages, eventually scale and calibrate the voltages and send it out via high speed USB or Ethernet (e.g. 100 Mbit Ethernet).
That's the plan, but it has a lot of issues:
When I run that ADC at the maximum sample Rate of 200 kS per channel, I get (at least) 18 x 200k x 8 = 28.8 MBit per second of Data, if I would use the SPI interface. But that is no option anyway, because the SPI on the ADC only supports SPI clock rates up to 20 MHz.
This means: I have to use the parallel output, if I want to use the full sample rate and here the trouble starts. Let's assume I use a STM32H7 MCU with 550 MHz Master Clock, I had to set up a Timer generating a clock with a decent speed (> 1 MHz) and an interrupt to read the GPIO lines. Most probably even such a fast MCU would be completely busy with this job, leaving no room for other tasks like scaling and data transfer. Overall that sounds like a bad idea to me – even without almost no know how in this area.
The STM32H7 has OctoSPI, which – theoretically – would fit to the "parallel Byte" output of the ADC. But I could not find any application notes or application examples using the OctoSPI in that way. Furthermore OctoSPI seems to be more or less be designed for connections to Flash memory.
So the question is: Generally, which architecture is used to approach such a task?
Connect the ADC to a DSP, which shifts the data into a (shared) RAM and use a MCU to read the data from the RAM (e.g. OctoSPI via DMA), process them and send them out? Something like that?
I have no idea, so any recommendation, how I can get into this topic, or any general advice how to setup such a system would be highly appreciated!

A: The CPU has "Parallel synchronous slave interface (PSSI)" with a 16-bit bus, and the ADC has a matching 16-bit mode.  It looks as though this would be the fastest and possibly the simplest way to get the data across at speed.
My suggestion is to look into this interface.

*

*It looks like 60 ns x 8 channels = 480 ns / sample + overheads to transmit from device to CPU.

*Which is approximately 2 MS/S

Basic timing of ADC transfer

Overview of PSSI mechanism

Networking
If you're doing continuous sampling, my suggestion would be Static IP address, UDP broadcasts with raw samples as this is the easiest thing to do.  It's just a "data blaster": you plug it in, it samples everything, and broadcasts.  Which means on the client (laptop) you can just run tcpdump/wireshark and you'll see the packets.
Ie, just get the bytes off the ADC, into the ethernet device as simple UDP packets to some fixed port.  Then use a private network (ie, direct cable between Nucleo and laptop).
Once you have that working, then

*

*DHCP / ARP etc

*Some method to control target IP address

*Some method for selecting which channels if necessary

*Some method to do scaling, timestamping etc.

There are lots of Nucleo H7 evaluation boards with various differences but which include 10/100 ethernet; available around 20-30 euro.
Materials

*

*ADS8598S datasheet (200 KS/sec)

*ADS8598H datasheet (500 KS/sec, same interface timing.)

*STM32H7 reference see chapter 35

*Nucleo 144 evaluation board with 10/100 Mbit/sec ethernet

*Another

*Application note How to configure and use the PSSI on the STM32H7

*ST Tutorial about STM32H7 with ethernet

*Video series on ethernet with STM32 youtube  This is good and very detailed, albeit with a very dull voice.


text:
Q: Should the writing style be corrected by editors? Some people put a bunch of sentences in one paragraph. Others like to separate their writing a bit more and would write the same thing in 2 or 3 paragraphs. Some people use a lot of abbreviations, while others like to spell out everything they say. Some people don't capitalize their sentences, others like to use a lot of italics to highlight the stress of a sentence. Some use contractions like "I'm", some do not.
These kind of things make the writing style more individual and personal and give each user a sort of own "voice". They are not grammatical or spelling errors that make questions harder to read. Why, then, do people feel the need to edit posts to meet the editor's own criteria for what's standard and "professional"? I understand that Stack Exchange is supposed to be a source of objective knowledge and a resource to use for many years. But must we kill all individuality in the process?

A:
These kind of things make the writing style more individual and personal and give each user a sort of own "voice".

Keep in mind that this is a Q&A site dedicated to collecting useful info for everyone.  This isn't a political or literature forum, where no one is concerned about this (and would not be able to edit your posts anyway).  When posts on here are written very cleanly and require little to no additional time to parse the general meaning, it helps make this info more useful to others.  It also shows that this is a more "formal" site and not just another help forum.  We like it to stay this way, which is why users are allowed to edit other posts (with or without peer review).
You shouldn't feel offended if anyone edits your posts in such a way.  If one user somehow makes it worse, then another can come and fix it.  On the other hand, if someone just leaves a rude comment about the post's clarity, then that comment should be flagged for removal.

A:
they are not grammatical or spelling errors that make questions harder to read

I disagree with that. Using capitals and paragraphs the right way actually makes the post easier to read. And that is exactly what we want! We want a useful, clear Q/A knowledge base.
Of course, we value every single user contributing, and we shouldn't remove all personal style from a post, but making it easier to read is a good thing. Some users here have helped me to to improve the readability of my posts, and I appreciate that a lot.
Personally I have trouble sometimes reading posts on Seasoned Advice. I love cooking, but I am not very familiar with all abbreviations. If I can write those out to make it easier for me to read, and for future users, we have made the site better, for everyone.

A: Your choice not to use capitalisation and other generally accepted good grammatical style is really no different to someone who doesn't know any better.
The official language of this site is English. If I read quantcast correctly then less than 50% of the people who visit this site have English as a first language. Many questions and answers are poorly written because of a poor understanding of English language, its usage and the vagaries of its grammar. These usually get 'fixed up'.
Someone editing your posts to conform with more normal English usage should be expected (it's encouraged, we have badges for editing). There are even tools to help do this.


text:
Q: sql function to create sequential for repeated item- I would like to know if there is an easy sql function to do a sequential classification for each duplicate record as shown in the image:
enter image description here

A: Looks like one of analytic functions, such as row_number (or perhaps rank).
Sample data:
SQL> with test (product, value) as
  2    (select 'A', 100 from dual union all
  3     select 'B', 100 from dual union all
  4     select 'C', 100 from dual union all
  5     select 'A', 100 from dual union all
  6     select 'B', 100 from dual union all
  7     select 'A', 100 from dual union all
  8     select 'D', 100 from dual union all
  9     select 'D', 100 from dual union all
 10     select 'F', 100 from dual union all
 11     select 'F', 100 from dual union all
 12     select 'F', 100 from dual
 13    )

Query:
 14  select product, value,
 15    row_number() over (partition by product order by null) classification
 16  from test
 17  order by product;

PRODUCT         VALUE CLASSIFICATION
---------- ---------- --------------
A                 100              1
A                 100              2
A                 100              3
B                 100              1
B                 100              2
C                 100              1
D                 100              1
D                 100              2
F                 100              1
F                 100              2
F                 100              3

11 rows selected.

SQL>


text:
Q: Differentiability and decay of magnitude of fourier series coefficients I want to know the answer/references for the question on decay of Fourier series coefficients and the differentiability of a function. Does the magitude of fourier series coefficients {$a_k$} of a differentiable function in $L^2 (\mathbb{R})$ (or in any suitable space) decay as fast as or faster than $k^{-1}$. I want to know if there any such theorem ? Also about the converse statement. ?

A: Here are some references:

*

*Katznelson's Introduction to Harmonic Analysis, p. 22 onwards (He covers the one dimensional case.)

*Grafakos' Classical Fourier Analysis, p. 176 onwards (This covers the torus of arbitrary dimensions case; see below for samplers.)

*This pdf of Braunling's "Fourier Series on the $n$-dimensional Torus".

*That pdf.

*Observe that the correspondence between regularity and decay provided by Fourier transform is also at the core of Sobolev theory, and one might argue Sobolev spaces is the proper setting for this discussion. In this regard the possibilities are vast (e.g. Folland would be a valid starting point).

Here are some samplers from the Grafakos book I list above:
Fix $d\in \mathbb{Z}_{\geq 1}$ as the dimension; and denote the Fourier transform of a function $f:\mathbb{T}^d\to \mathbb{C}$ by
$$\widehat{f}:\mathbb{Z}^d\to \mathbb{C},\quad n\mapsto \int_{\mathbb{T}^d}f(x)e^{-2\pi i\; n\;\bullet\; x}dx.$$
Theorem (Riemann-Lebesgue): $$\forall f\in L^1(\mathbb{T}^d):\lim_{|n|\to\infty}  |\widehat{f}(n)| = 0.$$
Theorem (Slow Decay? Sure.): $$\forall d_\bullet: \mathbb{Z^d}\to [0,\infty[: \lim_{|n|\to\infty} d_n = 0,\quad \exists g=g(d_\bullet)\in L^1(\mathbb{T}^d),\forall n\in \mathbb{Z}^d: |\widehat{g}(n)|\geq d_n.$$
Theorem (Decay from Regularity): Let $s\in \mathbb{Z}_{\geq0}$. Then
$$\forall f\in C^s(\mathbb{T}^d):\lim_{|n|\to\infty} (1+|n|^s)|\widehat{f}(n)|=0.$$
Theorem (Regularity from Decay): Let $s\in \mathbb{Z}_{> d}$. Then
$$\forall f\in L^1(\mathbb{T}^d):(1+|n|)^s|\widehat{f}(n)|=O_{|n|\to\infty}(1)\implies f\in C^{s-d}(\mathbb{T}^d).$$
(Here the conclusion is in the sense of "coinciding with a function almost everywhere".)
One convenient soft version of this whole discussion is that a function on the torus is $C^\infty$ iff its Fourier coefficients decay faster than any polynomial.
As a final remark observe the effect of the dimension when going from decay to regularity: Heuristically the growth of the group $\mathbb{Z}^d$ contributes to decay a priori and hence ought to be deducted from the final regularity of the function.

A: There is even a quantitative version of this principle: If $f$ is in $C^r\bigl({\mathbb R}/(2\pi{\mathbb Z})\bigr)$ and if $f^{(r)}$ is of bounded variation $V$ on a full period then the complex Fourier coefficients of $f$ satisfy the estimate
$$|c_k|\leq {V\over 2\pi k^{r+1}}\qquad(k\ne0)\ .\qquad(*)$$
In order to prove this for $r=0$ one needs the following
${\it Lemma}.\ $ Let $f$ and $g$ be continuous and $2\pi$-periodic. If $f$ is of bounded variation $V$ and $g$ has a periodic primitive $G$ of absolute value $\leq G^*$ then
$$\left|\int_{-\pi}^\pi f(t)g(t)\>dt\right|\leq V\>G^*\ .$$
This is easy to prove by partial integration when $f$ is in $C^1$ and requires some work otherwise. In order to prove (*) for arbitrary $r\geq0$ proceed by induction.

A: I think it will be useful for you if you look at the book of Stein & Shakarachi [Fourier Analysis: An Introduction] from p.42 first big paragraph to p.44, and then look at Excercise(10)p.61 in the same book.


text:
Q: get data-attributes with jQuery containing " When getting data-Attributes using jQuery's .data() and this data-attribute contains the HTML-Entitys for double quotes, it fails to convert it to a JSON-Object. As you see below, it's simply seen as no valid JSON and therefore treats it like a string:

var dataAsString = $("[data-someprop]").data("someprop");
var dataAsString2 = $("[data-someprop2]").data("someprop2");

var dataAsJSON = $("[data-anotherprop]").data("anotherprop");

$(".target1").append(typeof(dataAsString));
$(".target2").append(typeof(dataAsString2));
$(".target3").append(typeof(dataAsJSON));

How may i pass double quotes through JSON-Objects in data-attributes?
edit: Added a 3rd example to show, that it's not the line-breaks.

A: The issue appears to be caused by the line-breaks in the HTML Encoded JSON string version. The below works fine:

var dataAsString = $("[data-someprop]").data("someprop");
var dataAsString2 = $("[data-someprop2]").data("someprop2");
var dataAsString3 = $("[data-someprop3]").data("someprop3");
var dataAsString4 = $("[data-someprop4]").data("someprop4");

$(".target1").append(typeof(dataAsString) + ' - ' + dataAsString.key);
$(".target2").append(typeof(dataAsString2) + ' - ' + dataAsString2.key);
$(".target3").append(typeof(dataAsString3) + ' - ' + dataAsString3.key);
$(".target4").append(typeof(dataAsString4) + ' - ' + dataAsString4.key);


text:
Q: ODBC Oracle connector: getSchema for stored procedure parameters I need to retrieve parameter information for Oracle stored procedures, using ODBC connector.
A very simple stored procedure example:
create or replace
PROCEDURE          TESTPROC(param1 IN INTEGER)
AS
  BEGIN
    //body
  END TESTPROC;

Now i want to retrieve parameters information for "TESTPROC".
The first solution I tried was to use the OdbcCommandBuilder. I constructed an OdbcCommand with command type: stored procedure, and the command text: procedure name(e.g. TESTPROC). Then I used derive function like this: "OdbcCommandBuilder.DeriveParameters(cmd);"
The problem is that I get an invalid cast exception when calling this function: "Specified cast is not valid."; with stack trace:
   at System.Data.Odbc.OdbcDataReader.GetInt16(Int32 i)
   at System.Data.Odbc.OdbcCommandBuilder.DeriveParametersFromStoredProcedure(OdbcConnection connection, OdbcCommand command)
   at System.Data.Odbc.OdbcCommandBuilder.DeriveParameters(OdbcCommand command)

The error also reproduces if I declare the parameter type as NUMERIC.
The weird part is that i can get the correct parameters information if the parameters are of type char or string. It seems that there is a bug when trying to convert Oracle numeric types.
I also tried to obtain the schema for procedure parameters like this, but with no success:
string[] restrictions = new string[3];
restrictions[0] = null;
restrictions[1] = null;
restrictions[2] = "MyOwner.TESTPORC";

DataTable dt = conn.GetSchema(OdbcMetaDataCollectionNames.ProcedureParameters, restrictions);

Here the problem is that I can't retrieve any rows in the DataTable, and I guess this happens because of the same type conversion problem.
I'd like to find out if there are some workarounds to resolve this issue.
The platform I'm using is Windows 8 x64, and the Oracle client is instantclient_12_1


text:
Q: Handling line feed in ANTLR4 grammar with Python target I am working on an ANTLR4 grammar for parsing Python DSL scripts (a subset of Python, basically) with the target set as the Python 3. I am having difficulties handling the line feed.
In my grammar, I use lexer::members and NEWLINE embedded code based on Bart Kiers's Python3 grammar for ANTLR4 which are ported to Python so that they can be used with Python 3 runtime for ANTLR instead of Java. My grammar differs from the one provided by Bart (which is almost the same used in the Python 3 spec) since in my DSL I need to target only certain elements of Python. Based on extensive testing of my grammar, I do think that the Python part of the grammar in itself is not the source of the problem and so I won't post it here in full for now.
The input for the grammar is a file, catched by the file_input rule:
file_input: (NEWLINE | statement)* EOF;

The grammar performs rather well on my DSL and produces correct ASTs. The only problem I have is that my lexer rule NEWLINE clutters the AST with \r\n nodes and proves troublesome when trying to extend the generated MyGrammarListener with my own ExtendedListener which inherits from it.
Here is my NEWLINE lexer rule:
NEWLINE
 : ( {self.at_start_of_input()}? SPACES
   | ( '\r'? '\n' | '\r' | '\f' ) SPACES?
   )
   {
    import re
    from MyParser import MyParser
    new_line = re.sub(r"[^\r\n\f]+", "", self._interp.getText(self._input))
    spaces = re.sub(r"[\r\n\f]+", "", self._interp.getText(self._input))
    next = self._input.LA(1)

    if self.opened > 0 or next == '\r' or next == '\n' or next == '\f' or next == '#':
        self.skip()
    else:
        self.emit_token(self.common_token(self.NEWLINE, new_line))

        indent = self.get_indentation_count(spaces)
        if len(self.indents) == 0:
            previous = 0
        else:
            previous = self.indents[-1]

        if indent == previous:
            self.skip()
        elif indent > previous:
            self.indents.append(indent)
            self.emit_token(self.common_token(MyParser.INDENT, spaces))
        else:
            while len(self.indents) > 0 and self.indents[-1] > indent:
                self.emit_token(self.create_dedent())
                del self.indents[-1]
   };

The SPACES lexer rule fragment that NEWLINE uses is here:
 fragment SPACES
 : [ \t]+
 ;

I feel I should also add that both SPACES and COMMENTS are ultimately being skipped by the grammar, but only after the NEWLINE lexer rule is declared, which, as far as I know, should mean that there are no adverse effects from that, but I wanted to include it just in case.
SKIP_
 : ( SPACES | COMMENT ) -> skip
 ;

When the input file is run without any empty lines between statements, everything runs as it should. However, if there are empty lines in my file (such as between import statements and variable assignement), I get the following errors:
line 15:4 extraneous input '\r\n    ' expecting {<EOF>, 'from', 'import', NEWLINE, NAME}
line 15:0 extraneous input '\r\n' expecting {<EOF>, 'from', 'import', NEWLINE, NAME}

As I said before, when line feeds are omitted in my input file, the grammar and my ExtendedListener perform as they should, so the problem is definitely with the \r\n not being matched by the NEWLINE lexer rule - even the error statement I get says that it does not match alternative NEWLINE.
The AST produced by my grammar looks like this:

I would really appreciate any help with this since I cannot see why my NEWLINE lexer rule woud fail to match \r\n as it should and I would like to allow empty lines in my DSL.

A:
so the problem is definitely with the \r\n not being matched by the
  NEWLINE lexer rule

There is another explanation. An LL(1) parser would stop at the first mismatch, but ANTLR4 is a very smart LL(*) : it tries to match the input past the mismatch.
As I don't have your statement rule and your input around line 15, I'll demonstrate a possible case with the following grammar :
grammar Question;

/* Extraneous input parsing NL and spaces. */

@lexer::members {
  public boolean at_start_of_input() {return true;}; // even if it always returns true, it's not the cause of the problem
}

question
@init {System.out.println("Question last update 2108");}
    :   ( NEWLINE
    |     statement
              {System.out.println("found <<" + $statement.text + ">>");}
        )* EOF
    ;

statement
    :   'line ' NUMBER NEWLINE 'something else' NEWLINE
    ;

NUMBER : [0-9]+ ;
NEWLINE
    : ( {at_start_of_input()}? SPACES
       | ( '\r'? '\n' | '\r' | '\f' ) SPACES?
      )
   ;

SKIP_
    :   SPACES -> skip
    ;

fragment SPACES
    :   [ \t]+
    ;

Input file t.text :
line 1
   something else

Execution :
$ export CLASSPATH=".:/usr/local/lib/antlr-4.6-complete.jar"
$ alias
alias a4='java -jar /usr/local/lib/antlr-4.6-complete.jar'
alias grun='java org.antlr.v4.gui.TestRig'
$ hexdump -C t.text
00000000  6c 69 6e 65 20 31 0a 20  20 20 73 6f 6d 65 74 68  |line 1.   someth|
00000010  69 6e 67 20 65 6c 73 65  0a                       |ing else.|
00000019
$ a4 Question.g4
$ javac Q*.java
$ grun Question question -tokens -diagnostics t.text
[@0,0:4='line ',<'line '>,1:0]
[@1,5:5='1',<NUMBER>,1:5]
[@2,6:9='\n   ',<NEWLINE>,1:6]
[@3,10:23='something else',<'something else'>,2:3]
[@4,24:24='\n',<NEWLINE>,2:17]
[@5,25:24='<EOF>',<EOF>,3:0]
Question last update 2108
found <<line 1
   something else
>>

Now change statement like so :
statement
//  :   'line ' NUMBER NEWLINE 'something else' NEWLINE
    :   'line ' NUMBER         'something else' NEWLINE // now NL will be extraneous
    ;

and execute again :
$ a4 Question.g4
$ javac Q*.java
$ grun Question question -tokens -diagnostics t.text
[@0,0:4='line ',<'line '>,1:0]
[@1,5:5='1',<NUMBER>,1:5]
[@2,6:9='\n   ',<NEWLINE>,1:6]
[@3,10:23='something else',<'something else'>,2:3]
[@4,24:24='\n',<NEWLINE>,2:17]
[@5,25:24='<EOF>',<EOF>,3:0]
Question last update 2114
line 1:6 extraneous input '\n   ' expecting 'something else'
found <<line 1
   something else
>>

Note that the NL character and spaces have been correctly matched by the NEWLINE lexer rule.
You can find the explanation in section 9.1 of The Definitive ANTLR 4 Reference :

$ grun Simple prog ➾ class T ; { int i; } ➾EOF ❮ line 1:8 extraneous
  input ';' expecting '{'
A Parade of Errors • 153
The parser reports an error at the ; but gives a slightly more
  informative answer because it knows that the next token is what it was
  actually looking for. This feature is called single-token deletion
  because the parser can simply pretend the extraneous token isn't there
  and keep going.
Similarly, the parser can do single-token insertion when it detects a
  missing token.

In other word, ANTLR4 is so powerful that it can resynchronize the input with the grammar even if several tokens are mismatching. If you run with the -gui option
$ grun Question question -gui t.text

you can see that ANTLR4 has parsed the whole file, despite the fact that a NEWLINE is missing in the statement rule, and that the input does not match exactly the grammar.

To summary : extraneous input is quite a common error when developing a grammar. It can come from a mismatch between input to parse and rule expectations, or also because some piece of input has been interpreted by another token than the one we believe, which can be detected by examining the list of tokens produced by the -tokens option.


text:
Q: insert array string values to database single field not id $lid= mysql_insert_id();

 $lid= mysql_insert_id();
$cityid = trim(ucwords(strtolower(mysql_real_escape_string($_POST['city']))));

$ids = array();
foreach($_POST['place'] as $val)
{
    $ids[] = (int) $val;
}
$ids = implode(',', $ids);

$sql3 = mysql_query("INSERT INTO `city_place`(`state_id`,`city_id`,`spaid`) VALUES ('$cityid','$ids',$lid)");

instead of that city_id i want to store string values?

A: your query is working fine.
you should change data type of "city_id" from int to varchar.

A: $lid= mysql_insert_id();

$lid= mysql_insert_id();
$cityid = trim(ucwords(strtolower(mysql_real_escape_string($_POST['city']))));

$ids = array();
foreach($_POST['place'] as $key =>$val) // change this line
{
    $ids[] = (int) $key; // change this line
}
$ids = implode(',', $ids);

$sql3 = mysql_query("INSERT INTO `city_place`(`state_id`,`city_id`,`spaid`) VALUES     ('$cityid','$ids',$lid)");


text:
Q: Handling quoted expressions in Z3 I'm currently working with Z3's unsat_core functionality in the context of a model checking class at university.
The issues arises when trying to work with the assumptions that Z3 provides me with in the core:
E.g.:
z3::expr_vector unsat_core = exp_solver.unsat_core();
for(auto const c : unsat_core) {
  DEBUG << "\n" << c;
}

prints a list containing, for example, such an expression:
|(let ((a!1 (bvnot (ite (= current_state_V0 ((_ zero_extend 1) #b11)) #b1 #b0))))
 (let ((a!2 (bvnot (bvand a!1 (bvnot ((_ extract 2 2) current_state_V0))))))
 (let ((a!3 (bvor a!2
                 (ite (= next_state_V0 (bvadd current_state_V0 #b001)) #b1 #b0)
                 (bvnot #b1))))
  (= a!3 #b1))))|

We add and track expressions via this wrapper:
void add_and_track(z3::solver& s, z3::expr_vector const &v)
{
  check_context(s, v);
  for (unsigned i = 0; i < v.size(); ++i)
  {
    s.add(v[i], v[i].to_string().c_str());
  }
}

I now need to encode these assumptions with my primed variables and I intend to use z3::expr::substitute for that, but that does not seem to work.
DEBUG << unsat_core[0];
z3::expr foo = unsat_core[0].substitute(V0, V1);
DEBUG << unsat_core[0];
DEBUG << foo;

all DEBUG calls print out the exact same (quoted) expression from above.
V0 and V1 are z3::expr_vectors containing the variables and the primed variables, and DEBUG is a wrapper around std::cout.
My best guess is that these expressions are 'quoted'  https://www.lri.fr/~conchon/TER/2013/2/SMTLIB2.pdf#page=22 Is this correct?
What I would like to achieve is either to be able to substitute or the extract the expression that is, as I am guessing, quoted.


text:
Q: Accessing string representations of constant field values in java I am using an imported class with has constant field values set using:
public static final int BLUE = 1;
public static final int GREEN = 2;

etc.
Is there any way of getting a string representation of the constant field value from the int value?
i.e. given the value 2 I want to get a string of GREEN.
P.S. This isn't my class so I can't use ENUMs

A: I think your friend here would be enums
public enum Color {
  BLUE(1), GREEN(2);
}

Now if you try to get Color.BLUE.ordinalValue() it will return 1 and if you say Color.BLUE.name() it will return BLUE.
You can also declare private variables in the enum just like a pojo class and initialize them un the constructor. You can write getter methods to return those variables.

A: If you can change the class which contains these constants, it would be better to make it an enum with a value() method.
Otherwise, I would suggest building a Map<Integer, String> once using reflection, and then just doing map lookups:
Map<Integer, String> valueToStringMap = new HashMap<>();
for (Field field : Foo.class.getFields()) {
    int modifiers = field.getModifiers();
    if (field.getType() == Integer.class && Modifier.isPublic(modifiers)
        && Modifier.isStatic(modifiers)) {
        valueToStringMap.put((Integer) field.get(null), field.getName());
    }
}


text:
Q: how to add a shared commandbar in windows phone 8.1 Hello I am making my first official Windows Phone 8.1 app. I was wondering how do I add a shared command bar across my entire app. The way I have been doing it is copy and pasting the xaml from each page to the next. I have a feeling this is very inefficient I just don't know how to do it and where to add it(as in what page).
thank you for any help.

A: Try adding CommandBar to the resources of Application (in App.xaml). Then you can simply set it from the resource on each page:
<Application.Resources>
  <CommandBar x:Key="GlobalCommandBar"/>
</Application.Resources>

<Page
  x:Class="..."
  BottomAppBar={StaticResource GlobalCommandBar}>
</Page>

A: Two ways that come to my mind:
a) first is to do it like at MSDN - basicly you extend the Page class and in OnLoaded ecent add application bar on the fly. Then change all your pages in the app to the extended one.
b) other method is little more complicated (as far as I remember I saw it also somewhere at MSDN) and needs more steps, but maybe will be helpful:

*

*you will need to change what is in your Window.Current.Content - in most apps it's Frame, let's make it Page with our common application bar and this Page content will be our new rootFrame (all app pages will be put into that frame). Here we will need to change a little OnLaunched event, below the code for extended page and the launch event:
<Page x:Class="Example81.PageWithAppBar"
      xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
      xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">

      <Frame Name="rootFrame"></Frame>

      <Page.BottomAppBar>
         <CommandBar>
           <AppBarButton Icon="Help" Label="Ask"/>
         </CommandBar>
      </Page.BottomAppBar>
</Page>

// we need to expose the frame
public sealed partial class PageWithAppBar : Page
{
    public Frame RootFrame { get { return rootFrame; } }
    // rest ...

// app.xam.cs launched event
PageWithAppBar rootPage;
public CommandBar MyAppBar { get { return rootPage.BottomAppBar as CommandBar; } }
protected override void OnLaunched(LaunchActivatedEventArgs e)
{
    rootPage = Window.Current.Content as PageWithAppBar;
    if (rootPage == null)
    {
        rootPage = new PageWithAppBar();

        rootPage.Language = Windows.Globalization.ApplicationLanguages.Languages[0];
        Window.Current.Content = rootPage;
    }
    if (rootPage.RootFrame.Content == null)
        rootPage.RootFrame.Navigate(typeof(MainPage), e.Arguments);

    Window.Current.Activate();
}

*we also shouldn't forget about other things - like back key pressed, we changed a little our app organization, so this will also change:
private void HardwareButtons_BackPressed(object sender, BackPressedEventArgs e)
{
    Frame frame = rootPage.RootFrame;
    if (frame == null)
        return;

    if (frame.CanGoBack)
    {
        frame.GoBack();
        e.Handled = true;
    }
}

*then you can normaly navigate in your other pages, to access your app bar I've exposed above a property in App class, you can use it like this:
((App.Current as App).MyAppBar.PrimaryCommands[0] as AppBarButton).Label = "New label";

The second way is little more complicated, also it needs some more improvement and probably some changes in NavigationHelper and SuspensionManager. A working sample with the code above you can find at GitHub.


text:
Q: CSS: Issue with horizontal width in dropdown menu I am having an issue with a CSS dropdown menu, which you can see here: studio-scs.de.
Under one point only (portfolio) there is a dropdown menu leading to further points.
The problem is I need those to be the same width like the PORTFOLIO button.
If I give that a fixed width like for example "width: 6.3rem;", it would look alright,
but only as long as nobody has a different type installed on his computer, because
those buttons are variable to its length, which makes them nicer to look at.
Let us say, someone has a different type installed, the width of 6.3 rem might not be
the same amount like the space above (PORTFOLIO button).
Luckily the dropdown menu buttons/words are all shorter than portfolio. So, I think
there might be a solution to this issue.
Here is the code used:
#nav {display: block; float: left; margin: 0 auto; width: 100%; font-size: 0.75rem;}
#nav ul, div.menu ul {list-style: none; margin: 0; padding: 0;}
#nav li, div.menu li {float: left; position: relative;}
#nav ul ul {display: none; position: absolute; top: 3.4rem; left: 0; float: left; width: auto; z-index: 99999;}
#nav a {color: #333; display: block; padding: 0 1.1rem; text-decoration: none; font-weight: normal; background: rgba(255, 255, 255, .7); margin: 0 0 0 2px;}
#nav ul li:hover > ul {display: block;}
#nav li:hover > a, #nav ul ul :hover > a {color: #888; background: rgba(255, 255, 255, .9);}
     #nav ul ul a {background: rgba(255, 255, 255, .7); text-align: center; line-height: 1rem; width: inherit; padding: 10px 15px; height: auto; margin: 2px 0 0 2px}
#nav ul li.current_page_item > a, #nav ul li.current-menu-ancestor > a, #nav ul li.current-menu-item > a, #nav ul li.current-menu-parent > a {background: rgba(255, 255, 255, .8);}

The line that I put further into the field, is the line with the dropdown menu/options.
I tried to solve it with width: inherit;, but that did not help either.

A: You can use JS to compare the widths of the parent element and its the submenu. And than to change the widths to the largest one.
$(document).ready(function (){

  $('.menu-item-has-children').each(function(){
    var parent = $(this);
    var child = parent.children('.sub-menu');
    if(parent.width() >= child.width()){
      child.width( parent.width() );
    } else {
      parent.width( child.width() );
    }
 });

});

And change the CSS styles:
ul.sub-menu li {
    float: none;
    width: 100%;
    display: block;
}
ul.sub-menu li > a {
    width: auto; /* or just remove this line from your code */
}

Edit:
The javascript is slightly modified and here is a working pen

A: It was easier than thought:
#nav ul.sub-menu {width: 100%;}
#nav ul.sub-menu li {float: none; display: block;}

... solved the problem without any need for JS.


text:
Q: How to create image in python and save it I want to create an image and store it as a file using python.
I expect the output to be an image with color blocks of black or white, and the image must have 6x6 blocks of random of white or black color blocks.

A: You can use this code to solve that problem:
#Import all libraries we will use
import random
import numpy as np
import cv2

#let's create a 6 x 6 matrix with all pixels in black color
img = np.zeros((6,6,3),np.uint8)

#let's use "for" cycle to change colorspace of pixel in a random way
for x in range(6):
    for y in range(6):
        #We use "0" for black color (do nothing) and "1" for white color (change pixel value to [255,255,255])
        value = random.randint(0,1)
        if value == 1:
            img[x,y] = [255,255,255]

#save our image as a "png" image
cv2.imwrite("6_x_6.png",img)


text:
Q: How to check for wrong datetime entries (python/pandas)? I have an excel dataset containing datetime values of worked hours entered by employees. Now that the end of the year is near they want to report on it, however it is full of wrong entries. Thus I need to clean it.
Herebelow some examples of wrong entries.
What would be your approach when facing such datasets?
I first converted date column to datetime using df['Shiftdatum'] = pd.to_datetime(df.Shiftdatum, format='%Y-%m-%d', errors='coerce')
In below's sampledata it shows a NaT
How do I filter out these NaT's including the row's index?
[Timestamp('2019-03-11 00:00:00'),
 Timestamp('2019-03-11 00:00:00'),
 Timestamp('2019-03-11 00:00:00'),
 Timestamp('2019-03-11 00:00:00'),
 Timestamp('2019-03-11 00:00:00'),
 Timestamp('2019-03-11 00:00:00'),
 Timestamp('2019-03-11 00:00:00'),
 Timestamp('2019-03-11 00:00:00'),
 Timestamp('2019-03-11 00:00:00'),
 Timestamp('2019-03-11 00:00:00'),
 Timestamp('2019-03-11 00:00:00'),
 Timestamp('2019-03-11 00:00:00'),
 Timestamp('2019-03-11 00:00:00'),
 Timestamp('2019-03-11 00:00:00'),
 Timestamp('2019-03-11 00:00:00'),
 Timestamp('2019-03-11 00:00:00'),
 NaT,
 Timestamp('2019-03-12 00:00:00')

Initial sample data:
{0: '2019-03-11 00:00:00',
 1: '2019-03-11 00:00:00',
 2: '2019-03-11 00:00:00',
 3: '2019-03-11 00:00:00',
 4: '2019-03-11 00:00:00',
 5: '2019-03-11 00:00:00',
 6: '2019-03-11 00:00:00',
 7: '2019-03-11 00:00:00',
 8: '2019-03-11 00:00:00',
 9: '2019-03-11 00:00:00',
 10: '2019-03-11 00:00:00',
 11: '2019-03-11 00:00:00',
 12: '2019-03-11 00:00:00',
 13: '2019-03-11 00:00:00',
 14: '2019-03-11 00:00:00',
 15: '2019-03-11 00:00:00',
 16: '33/11/2019',
 17: '2019-03-12 00:00:00',
 18: '2019-03-12 00:00:00',
 19: '2019-03-12 00:00:00'}

A: IIUC,
you could handle this in a number of ways, you could use pd.to_datetime(column,errors='coerce') and assign your data to a new column
then with the new column, you could filter by NaT and get the unique outliers,
lets say this was the result :
data = ['033-10-2019', '100-03-2019','1003-03-2019','03-10-2019']

df = pd.DataFrame({'date_time' : data})
df['correct'] = pd.to_datetime(df['date_time'],errors='coerce')
print(df)
       date_time    correct
0   033-10-2019        NaT
1   100-03-2019        NaT
2  1003-03-2019        NaT
3    03-10-2019 2019-03-10

now - we need to grab the unique NaT values in the date_time col
errors = df.loc[df['correct'].isnull()]['date_time'].unique().tolist()
out : ['033-10-2019', '100-03-2019', '1003-03-2019']

this is the boring bit, you'll need to go through and fix the errors and pass the correct value into a dictionary :
correct_dict = {'033-10-2019' : '03-10-2019', '100-03-2019' : '03-10-2019', '1003-03-2019' : '10-03-2019'}

then map the values back into your dataframe :
df['correct'] = df['correct'].fillna(pd.to_datetime(df['date_time'].map(correct_dict)))
print(df)
      date_time    correct
0   033-10-2019 2019-03-10
1   100-03-2019 2019-03-10
2  1003-03-2019 2019-10-03
3    03-10-2019 2019-03-10

If you just want to remove the NaT values you can just dropna whilst subsetting your column
df = df.dropna(subset=['correct'])

A:
How do I filter out these NaT's including the row's index?

if the requirement is to find out the invalid date entries, you can try series.isna() after pd.to_datetime() with series where():
df=pd.DataFrame.from_dict(d,orient='index',columns=['Shiftdatum'])
#d is the dictionary in the question

s=pd.to_datetime(df.Shiftdatum, format='%Y-%m-%d', errors='coerce').isna()
e=df.Shiftdatum.where(s).dropna()

16    33/11/2019


text:
Q: Configures locale not being considered My software relies in the windows locale configuration to work properly.
My customers have always the pt-br locale setted up and it works fine that way.
In one user´s windows there is the pt-br locale setted properly but somehow my software gets all the us configurations. (. as decimal sepparator, $ as currency symbol and so on).
Is there any way for me to force the locale globally in my software?

A: Since you have delphi-7 you can do as follows:

Application.UpdateFormatSettings := false;

This prevents the system to update your application with windows default values.
Then define at application startup:
DecimalSeparator := '.'; // Or whatever preference you have
CurrencyString := '$'; // Or something else
...
etc

In Delphi 2006 and higher this method is deprecated and the use of TFormatSettings is prefered. It also deals with reentrancy problems if parts of the applications needs to change the format settings during execution.

A: Having the same problem I found your post.
I also found this thread (http://social.technet.microsoft.com/Forums/en-US/w7itprogeneral/thread/b4f90f07-206c-494b-8d14-ee17bfa689e0) that helped me.
Here's the method:

If you open "Regional and Language Options" from the control panel
  (the globe icon) / intl.cpl, and reselect your locale it will likely
  solve the problem.
1) Open Regional and Language Options
2) Under "Format" pick anything else. (eg: English (United States)).
3) Press "Apply"
4) Under "Format" pick your desired locale (eg: English (United
  Kingdom)).
5) Press OK.

A: Under Windows Seven, the locale of non Unicode apps (like Delphi 7) is not set in the main tab of the Control Panel.
You will have to go to "Administrative" tab, then select "Change system locale".

See this article.


text:
Q: Regular expression for repeating pattern I have the following input text:
pagelimit=50&filtercolumn=Datacenter&filtervalue=abfg1&filtercolumn=MachineType&filtervalue=fg&filtercolumn=GPG&filtervalue=IPMI
I want to get back

*

*filtercolumn=Datacenter&filtervalue=abfg1

*filtercolumn=MachineType&filtervalue=fg

*filtercolumn=GPG&filtervalue=IPMI
There may be an unlimited amount of these.
I have tried a few things. I'm currently trying something like this:
(?:((filtercolumn=.*&filtervalue=.*)+)?)

But of course it doesn't work. I get:

*

*filtercolumn=Datacenter&filtervalue=abfg1&filtercolumn=MachineType&filtervalue=fg&filtercolumn=GPG&filtervalue=IPMI

*filtercolumn=Datacenter&filtervalue=abfg1&filtercolumn=MachineType&filtervalue=fg&filtercolumn=GPG&filtervalue=IPMI

A: Try this \bfiltercolumn=[^&]*&filtervalue=[^&]*
https://regex101.com/r/sasmXL/2


text:
Q: When using SWD interface, is the reset pin necessary? When using the SWD interface, is the reset pin is necessary?
In JTAG, there are 5 pins TCK, TMS, TDO, TDI and RST but usually SWD is a 2 wire interface. So I am confused about this.

A: Yes, eventhough the name is Single Wire Debug, you will usually need 4 connections:

*

*SWDIO (to transmit data from the programmer to the target)

*SWDCLK (to clock the data that is being transmited)

*RST (to perform a reset of the target)

*GND (for the signals to be referenced to something)

The reset is kind of optionnal if you are willing to press a reset button manually if the target get stuck/freezes.


text:
Q: How do I iterate through a method with no parameters in hash table of an array? [Java] So I can get through the lists that have parameters by setting the index to c[h] going off i, but I'm not sure how to do it without parameters. How would I go about iterating through without this index? For omit and print.
  {

private int howmany;
private int[] c;
int counter = 0;

public Intcoll7()
  {
    c = new int[23];
    howmany = 0;
  }

public Intcoll7(int i)
  {
    double z = (i % 23);
    int y = (int) z;

    while (!isprime(y))
      {
        y--;
      }
    howmany = 0;
  }

public void insert(int i)
  {
    int h = i % 23;
    int H = h;

    if (c[h] == 0)
      {
        c[h] = i;
        howmany++;
      } else if (c[h] == i) ; else
      {
        if (h < c.length - 1)
          {
            h++;
          } else
          {
            h = 0; // why does h = 0?
          }
        while ((h != H) && (c[h] != 0) && (c[h] != i))
          {
            if (h < c.length - 1)
              {
                h++;
              } else
              {
                h = 0;
              }
          }
        if (h != H)
          {
            if (c[h] == 0)
              {
                c[h] = i;
                howmany++;
              }
          } else
          {
            System.out.println("Table Full");
            System.exit(1);
          }
      }
  }

public boolean belongs(int i)
  {
    //address
    int h = i % 23;

    int H = h; // what

    if (c[h] == 0)
      {
        return false;
      } if (c[h] == H)
      {
        return true;
      }
      else
        {
          return false;
        }

  }

public void omit(int i)
  {
    int h = i % 23;

    if (c[h] == i)
      {
        if (counter == 3)
          {
            //crate new array
          }
        c[h] = i * (-1);
        counter++;
      }
  }

private static boolean isprime(int n)
  {
    int i = 2;
    boolean result = true;

    while ((i <= n / 2) && result)
      {
        if (n % i == 0)
          {
            result = false;
          } else
          {
            i++;
          }
      }
    return (result);
  }

public void print()
  {
    System.out.println();
    //int x = c[z];
    //System.out.println(x);
  }
  }


text:
Q: Datagridview math operation with next row data I have datagridview with 7 columns. But its not bind to any database. Rows will be added from few textboxes line by line when i press the "Add" button on my form. But i have a problem with my 6th column data(Cells[5]).
current row 6th column data value = next row 2nd column value - current row 2nd column value
I can do this with excel very easily. but how can i do this on a datagridview? codes are welcome.
here is my code.
    private void FEAdd_Click(object sender, EventArgs e)
   {
       int n = dgvFE.Rows.Add();
       dgvFE.Rows[n].Cells[0].Value = dateTimePicker1.Value.ToString("dd-MM-yyyy");
       dgvFE.Rows[n].Cells[1].Value = MtrtextBox1.Text.ToString();
       dgvFE.Rows[n].Cells[3].Value = PltrtextBox11.Text.ToString();
       dgvFE.Rows[n].Cells[4].Value = BvtextBox12.Text.ToString();

       foreach (DataGridViewRow row in dgvFE.Rows)
       {
           dgvFE.Rows[row.Index].Cells[2].Value = Math.Round((Double.Parse(dgvFE.Rows[row.Index].Cells[4].Value.ToString()) / Double.Parse(dgvFE.Rows[row.Index].Cells[3].Value.ToString())), 2).ToString();

           if (n >1)
           {
               dgvFE.Rows[row.Index-1].Cells[5].Value = Math.Round((Double.Parse(dgvFE.Rows[row.Index].Cells[1].Value.ToString()) - Double.Parse(dgvFE.Rows[row.Index-1].Cells[1].Value.ToString())), 2).ToString();
           }

       }

   }

I get below error,
An unhandled exception of type 'System.ArgumentOutOfRangeException' occurred in mscorlib.dll
Additional information: Index was out of range. Must be non-negative and less than the size of the collection.

A: You have 5 column and you write cells[5]. it must be cells[4].

A: dgvFE.Rows[row.Index-1] throws exception for row №0. so add an index check
private void FEAdd_Click(object sender, EventArgs e)
{
   int n = dgvFE.Rows.Add();
   dgvFE.Rows[n].Cells[0].Value = dateTimePicker1.Value.ToString("dd-MM-yyyy");
   dgvFE.Rows[n].Cells[1].Value = MtrtextBox1.Text.ToString();
   dgvFE.Rows[n].Cells[3].Value = PltrtextBox11.Text.ToString();
   dgvFE.Rows[n].Cells[4].Value = BvtextBox12.Text.ToString();

   foreach (DataGridViewRow row in dgvFE.Rows)
   {
       row.Cells[2].Value = Math.Round((Double.Parse(row.Cells[4].Value.ToString()) / Double.Parse(row.Cells[3].Value.ToString())), 2).ToString();

       if (n > 0 && row.Index > 0)
       {
           dgvFE.Rows[row.Index-1].Cells[5].Value = Math.Round((Double.Parse(row.Cells[1].Value.ToString()) - Double.Parse(dgvFE.Rows[row.Index-1].Cells[1].Value.ToString())), 2).ToString();
       }

   }
}


text:
Q: R: Fast way to group matrix rows by considering only the place of NA values I am trying to group the rows of a matrix by their unique placement of NA values within each columns.
For example with the following matrix:
1, 2, NA, 3 NA
2, 5, NA, 4, 5
3, 2,  1, 0, 7
5, 3, NA, 9, 3
0, 2,  1, 4, 6

The answer would be:
1, 2, 3, 2, 3

Indicating that there were 3 distinct groups and i.e. rows 2 and 4 were in the same group.
The trouble is that I can not come up with a quick way to achieve this. Here is my current implementation:
mat <- matrix(rnorm(10000*100), ncol=100)
mat[sample(length(mat), nrow(mat))] <- NA

getNAgroups <- function(x) {
  allnas  <- t(!is.na(x))
  nacases <- unique(allnas, MARGIN=2)
  groups  <- numeric(nrow(x))
  for(i in 1:ncol(nacases)) {
    groups[colMeans(allnas == nacases[,i]) == 1] <- i
  }
  groups
}

Which is a bit too slow for the purposes I have in mind:
system.time(getNAgroups(mat))
   user  system elapsed
  7.672   1.686   9.386

A: Here is one way using match on list of NA position:
mat <- matrix(c(1, 2, NA, 3, NA,
2, 5, NA, 4, 5,
3, 2,  1, 0, 7,
5, 3, NA, 9, 3,
0, 2,  1, 4, 6), 5, byrow = TRUE)

categ <- apply(is.na(mat), 1, which)
match(categ, unique(categ))

A: We can paste the values together row-wise and match it to get unique index.
vals <- apply(is.na(mat), 1, toString)
match(vals, unique(vals))
#[1] 1 2 3 2 3

A: If performance is the concern, I would give the following code a try:
library(dplyr)
getNAgrps = function(df){
  df = df %>%
    dplyr::mutate(NAgrp = '')
  lapply(1:nrow(df),function(i){
    df$NAgrp[i] <<- paste0(which(is.na(df[i,])),collapse=",")
  })

  return(df)
}

This function takes the input as a dataframe. To convert your matrix to dataframe:
library(dplyr)
dat = as_data_frame(mat)

The performance is as follows:
> system.time(getNAgrps(mat))
   user  system  elapsed
  0.005  0.000   0.006

Let me know if it works.
Note: Instead of giving integer groups, this will return character vectors with the positions of NAs separated by commas.

A: In case you don't mind the order you can use interaction to find groups.
tt <- interaction(as.data.frame(is.na(mat)), drop = TRUE)
unclass(tt)
#[1] 3 2 1 2 1

Or a maybe a more performant way is using sweep and rowSums but works only up to 30 columns.
tt  <- is.na(mat)
tt <- rowSums(sweep(tt, 2, cumprod(rep(2L,ncol(tt))), "*"))
match(tt, unique(tt))
#[1] 1 2 3 2 3

Or you can use the bit library, which is not faster but follows the previous idea and works for many rows and might help when memory will limit.
library("bit")
tt <- apply(is.na(mat), 1, as.bit)
match(tt, unique(tt))
#[1] 1 2 3 2 3

#For many columns
tt <- apply(apply(is.na(mat), 1, as.bit), 2, paste, collapse=" ")
match(tt, unique(tt))
#[1] 1 2 3 2 3

Alternatively packBits could be used like:
tt  <- is.na(mat)
tt <- cbind(tt, matrix(TRUE, nrow(tt), ncol=(8 - ncol(tt) %% 8)))
tt <- packBits(t(tt))
tt <- split(tt, rep(seq_len(nrow(mat)), each=length(tt)/nrow(mat)))
match(tt, unique(tt))
#[1] 1 2 3 2 3

or a more performant version using raw2hex from PKI or encryptr.
library(PKI) #or library(encryptr)
tt  <- is.na(mat)
tt <- cbind(tt, matrix(TRUE, nrow(tt), ncol=(8 - ncol(tt) %% 8)))
tt <- raw2hex(packBits(t(tt)))
tt <- matrix(tt, ncol = nrow(mat))
tt <- apply(tt, 2, paste, collapse="")
match(tt, unique(tt))
[1] 1 2 3 2 3

A: set.seed(42)
mat <- matrix(rnorm(10000*100), ncol=100)
mat[sample(length(mat), nrow(mat))] <- NA

getNAgroups_Orig <- function(x) {
  allnas  <- t(!is.na(x))
  nacases <- unique(allnas, MARGIN=2)
  groups  <- numeric(nrow(x))
  for(i in 1:ncol(nacases)) {
    groups[colMeans(allnas == nacases[,i]) == 1] <- i
  }
  groups
}

getNAgroups_GKi <- function(mat) {
  tt  <- is.na(mat)
  tt <- rowSums(sweep(tt, 2, cumprod(rep(2L,ncol(tt))), "*"))
  match(tt, unique(tt))
}

getNAgroups_Clemsang <- function(mat) {
  categ <- apply(is.na(mat), 1, which)
  match(categ, unique(categ))
}

getNAgroups_RonakShah <- function(mat) {
  vals <- apply(is.na(mat), 1, toString)
  match(vals, unique(vals))
}

library("bit")
getNAgroups_bit <- function(mat) {
  tt <- apply(apply(is.na(mat), 1, as.bit), 2, paste, collapse=" ")
  match(tt, unique(tt))
}

getNAgroups_GKi2 <- function(mat) {
  tt  <- is.na(mat)
  tt <- cbind(tt, matrix(TRUE, nrow(tt), ncol=(8 - ncol(tt) %% 8)))
  tt <- packBits(t(tt))
  tt <- split(tt, rep(seq_len(nrow(mat)), each=length(tt)/nrow(mat)))
  match(tt, unique(tt))
}

library(PKI) #or library(encryptr)
getNAgroups_GKi3 <- function(mat) {
  tt  <- is.na(mat)
  tt <- cbind(tt, matrix(TRUE, nrow(tt), ncol=(8 - ncol(tt) %% 8)))
  tt <- raw2hex(packBits(t(tt)))
  tt <- matrix(tt, ncol = nrow(mat))
  tt <- apply(tt, 2, paste, collapse="")
  match(tt, unique(tt))
}

system.time(getNAgroups_Orig(mat))
#       User      System verstrichen
#      6.928       1.316       8.244

system.time(getNAgroups_GKi(mat))  ###IS NOT WORKING CORRECT DUE TO TOO MANY COLUMNS
#       User      System verstrichen
#      0.016       0.000       0.016

system.time(getNAgroups_Clemsang(mat))
#       User      System verstrichen
#      0.045       0.004       0.049

system.time(getNAgroups_RonakShah(mat))
#       User      System verstrichen
#      0.347       0.000       0.347

system.time(getNAgroups_bit(mat))
#       User      System verstrichen
#      0.239       0.000       0.240

system.time(getNAgroups_GKi2(mat))
#       User      System verstrichen
#      0.119       0.000       0.119

system.time(getNAgroups_GKi3(mat))
#       User      System verstrichen
#      0.046       0.000       0.046


text:
Q: How to request Android user to enable Bluetooth through a click? from http://developer.android.com/guide/topics/connectivity/bluetooth.html i know that i need to the following to request the user to enable his BT:
if (!mBluetoothAdapter.isEnabled())
{
Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
}

but the question is how to use it in a class? why does my code crash whenever click on the button of this activity:
public class Opponents extends Activity
{
      private final static int REQUEST_ENABLE_BT=1;
      BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();

      @Override
      protected void onCreate(Bundle savedInstancesState)
      {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.opponents);

        final Button button1 = (Button) findViewById(R.id.button1);
        button1.setOnClickListener(new View.OnClickListener()
        {
          public void onClick(View view)
          {
            if(!mBluetoothAdapter.isEnabled())
            {
              Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
              startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
            }
          }
        });
}

A: Before you call the following method
!mBluetoothAdapter.isEnabled()

on the adapter, you have to make sure mBluetoothAdapter is not null. In your case it must be null and crashing. And if mBluetoothAdapter is null, the android documentation says that the device doesn't support Bluetooth.

A: Did you set proper permissions in your AndroidManifest.xml file?
For sure, you will need BLUETOOTH permission.
<manifest ... >
  <uses-permission android:name="android.permission.BLUETOOTH" />
  ...
</manifest>

In addition, as documentation says:

If you want your app to initiate device discovery or manipulate
  Bluetooth settings, you must also declare the BLUETOOTH_ADMIN
  permission.

If you want to enable one of these features you will need the following code:
<manifest ... >
  <uses-permission android:name="android.permission.BLUETOOTH" />
  <uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
  ...
</manifest>


text:
Q: Faster algorithms for convex hulls I was interested in the following:
Given two polyhedra $P_1, P_2$  specified in the form:
$$ P_1 = \{x : A_1x \le b_1 \} $$
$$ P_2 = \{x : A_2x \le b_2 \} $$
Whereas $x \in R^n$ and $b_1, b_2$ are real vectors of same "height" dimension as $P_1$ and $P_2$ respectively.
How does one determine the convex hull $C$ of these two polyhedra. Given in the form
$$ C = \{ x : Qx \le \tau \} $$
Whereas $Q, \tau$ should be the minimum number of inequalities necessary to specify the set.
I had posted this question on OR Exchange, which recommended Fourier-Motzkin elimination in conjunction with a simple scheme for including every-point in the hull.
My one qualm is this doubled the number of variables. And running Fourier-Motzkin would take exponential time to reduce the "excess" variables.
Is there a procedure that that doesn't take exponential time which maintains the same number of variables?

A: No, I don't think you will find a guaranteed fast algorithm, as the problem appears intractable in general, if I understand the below paper correctly. A quick search led me to, e.g.,

On the Hardness of Computing Intersection, Union and Minkowski Sum of
  Polytopes, by Hans Raj Tiwary

A: You cannot avoid an exponential blow-up in the number of resulting constraints.
As an example, let us look at cross-polytope $P_3$ in $\mathbb{R}^n$. It is the convex hull of all vertices obtained by all permutations of $(\pm1,0,\dots,0)$. Hence, it has $2n$ vertices and $2^n$ facets (see https://en.wikipedia.org/wiki/Cross-polytope) and its $\mathcal{H}$-representation $Qx \leq \tau$ has at least $2^n$ rows. On the other hand, the two simplices $P_1$ and $P_2$, where
$$P_1 = conv\{(0,\dots,0), (1,0,\dots,0), (0,1,0,\dots,0), \dots, (0,\dots,0,1)\}$$
$$P_2 = conv\{(0,\dots,0), (-1,0,\dots,0), (0,-1,0,\dots,0), \dots, (0,\dots,0,-1)\},$$
have $n+1$ vertices and also $n+1$ facets. Hence, their (minimal) $\mathcal{H}$-representations $A_1x \leq b_1$ and $A_2x \leq b_2$ have $n+1$ rows each. It is crucial to note that the convex hull of $P_1$ and $P_2$ is exactly the cross-polytope $P_3$. This shows that in your setting (unless I missed something about the "specific application") it is impossible to have a procedure which does not take exponential time at worst.


text:
Q: Entity Framewrok 5 fluent mapping for many to many with 3 entities I have the following scenario that is giving me a hard time:
public class SegUser
{
      public string IdUser { get; set; }

      public List<SegRol> SegRoles { get; set; }

      public virtual List<SegApps> Apps{ get; set; }
}

public class SegRole
{
     public virtual int IdRole { get; set; }

     public virtual List<SegUer> SegUsers { get; set; }

    public virtual List<SegApp> Apps { get; set; }

}

public class SegApp
{
      public virtual int IdApp{ get; set; }

      public virtual List<SegUser> Users { get; set; }

      public virtual List<SegRole> Roles { get; set; }

}

In my database I have those 3 tables and an extra table with 3 PKs (one for each entity) to establish the relationship between those 3 entities.
How can I achieve the mapping with Entity Framework 5 fluent API.
I've already tried:
    private void MapSegUser()
    {
        //mapping of another fields

        entityConfiguration
            .HasMany(x => x.SegRoles)
            .WithMany(x => x.SegUsers)
            .Map(mc =>
            {
                mc.MapLeftKey("id_role");
                mc.MapRightKey("id_user");
                mc.ToTable("seg_users_roles");
            });

        entityConfiguration
            .HasMany(x => x.Apps)
            .WithMany(x => x.Users)
            .Map(mc =>
            {
                mc.MapLeftKey("id_app");
                mc.MapRightKey("id_user");
                mc.ToTable("seg_users_roles_apps");
            });

    }

   private void MapSegApp()
    {
        //mapping of another fields

          entityConfiguration
            .HasMany(x => x.Users)
            .WithMany(x => x.Apps)
            .Map(mc =>
            {
                mc.MapLeftKey("id_user");
                mc.MapRightKey("id_app");
                mc.ToTable("seg_users_roles_apps");
            });

    }

     private void MapSegRole()
    {
        //mapping of another fields

        entityConfiguration
            .HasMany(x => x.SegUsers)
            .WithMany(x => x.SegRoles)
            .Map(mc =>
            {
                mc.MapLeftKey("id_user");
                mc.MapRightKey("id_role");
                mc.ToTable("seg_users_roles");
            });
    }


text:
Q: How to add a Deployable container to my class path? I got a TestRunner class that runs all my tests from jUnit AllTests(TestSuite), which contains all the tests (UTests.java) that are needed for my application...
public class TestRunner {

public static void main(String[] args) {
      Result result = JUnitCore.runClasses(AllTests.class);

      for (Failure failure : result.getFailures()) {
         System.out.println(failure.toString());
      }

      System.out.println(result.wasSuccessful());
   }
}

@RunWith(Suite.class)
@SuiteClasses({ UTests.class })
public class AllTests {

}

@Test public void testAddStudent() {
StudentBean sb = new StudentBean();
Student s1 = new Student(4, "Ognjen", "Car");
System.out.println(s1.toString());

Boolean s = sb.addStudent(s1);
System.out.println(s1);

assert (s == true);
// fail("Not yet implemented");
}

StudentBean.java
@PersistenceContext
EntityManager em;

@Override
public Boolean addStudent(Student s) {
try{
    Student s1 = new Student(10,"asd", "asd"); //for testing...later I ll delete it
    em.persist(s);
    em.flush();

} catch (Exception ex) {
    ex.printStackTrace();
}

    return true;
}

Once I run the TestRunner class, there are 2 errors, that appear to be one....
1st At the console:
test.UTests: DeploymentScenario contains a target (_DEFAULT_) not matching any defined Container in the registry.
Please include at least 1 Deployable Container on your Classpath.

false
2nd At the JUnit console:
org.jboss.arquillian.container.test.impl.client.deployment.ValidationException: DeploymentScenario contains a target (_DEFAULT_) not matching any defined Container in the registry.
Please include at least 1 Deployable Container on your Classpath.
at org.jboss.arquillian.container.test.impl.client.deployment.DeploymentGenerator.throwNoContainerFound(DeploymentGenerator.java:250)
at org.jboss.arquillian.container.test.impl.client.deployment.DeploymentGenerator.throwTargetNotFoundValidationException(DeploymentGenerator.java:243)
at org.jboss.arquillian.container.test.impl.client.deployment.DeploymentGenerator.validate(DeploymentGenerator.java:102)
at org.jboss.arquillian.container.test.impl.client.deployment.DeploymentGenerator.generateDeployment(DeploymentGenerator.java:84)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at org.jboss.arquillian.core.impl.ObserverImpl.invoke(ObserverImpl.java:96)
at org.jboss.arquillian.core.impl.EventContextImpl.invokeObservers(EventContextImpl.java:99)
at org.jboss.arquillian.core.impl.EventContextImpl.proceed(EventContextImpl.java:81)
at org.jboss.arquillian.core.impl.ManagerImpl.fire(ManagerImpl.java:145)
at org.jboss.arquillian.core.impl.ManagerImpl.fire(ManagerImpl.java:116)
at org.jboss.arquillian.core.impl.EventImpl.fire(EventImpl.java:67)
at org.jboss.arquillian.container.test.impl.client.ContainerEventController.execute(ContainerEventController.java:100)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at org.jboss.arquillian.core.impl.ObserverImpl.invoke(ObserverImpl.java:96)
at org.jboss.arquillian.core.impl.EventContextImpl.invokeObservers(EventContextImpl.java:99)
at org.jboss.arquillian.core.impl.EventContextImpl.proceed(EventContextImpl.java:81)
at org.jboss.arquillian.test.impl.TestContextHandler.createClassContext(TestContextHandler.java:92)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at org.jboss.arquillian.core.impl.ObserverImpl.invoke(ObserverImpl.java:96)
at org.jboss.arquillian.core.impl.EventContextImpl.proceed(EventContextImpl.java:88)
at org.jboss.arquillian.test.impl.TestContextHandler.createSuiteContext(TestContextHandler.java:73)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at org.jboss.arquillian.core.impl.ObserverImpl.invoke(ObserverImpl.java:96)
at org.jboss.arquillian.core.impl.EventContextImpl.proceed(EventContextImpl.java:88)
at org.jboss.arquillian.core.impl.ManagerImpl.fire(ManagerImpl.java:145)
at org.jboss.arquillian.core.impl.ManagerImpl.fire(ManagerImpl.java:116)
at org.jboss.arquillian.test.impl.EventTestRunnerAdaptor.beforeClass(EventTestRunnerAdaptor.java:87)
at org.jboss.arquillian.junit.Arquillian$2.evaluate(Arquillian.java:202)
at org.jboss.arquillian.junit.Arquillian.multiExecute(Arquillian.java:431)
at org.jboss.arquillian.junit.Arquillian.access$200(Arquillian.java:55)
at org.jboss.arquillian.junit.Arquillian$3.evaluate(Arquillian.java:219)
at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
at org.jboss.arquillian.junit.Arquillian.run(Arquillian.java:167)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:86)
at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:459)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:678)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:382)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:192)

The error is asking to add a Deployable container to my class path, and I have no idea how to do it...
Can you help me?

A: You have to add some dependencies in your pom. It would look like that:
<dependency>
    <groupId>org.jboss.arquillian.container</groupId>
    <artifactId>arquillian-weld-ee-embedded-1.1</artifactId>
    <version>1.0.0.CR9</version>
    <scope>test</scope>
</dependency>
<dependency>
    <groupId>org.jboss.weld</groupId>
    <artifactId>weld-core</artifactId>
    <version>2.3.5.Final</version>
    <scope>test</scope>
</dependency>
<dependency>
    <groupId>org.slf4j</groupId>
    <artifactId>slf4j-simple</artifactId>
    <version>1.6.4</version>
    <scope>test</scope>
</dependency>

Source: http://arquillian.org/guides/getting_started_pt/

A: Add the following dependencies:
     <dependencies>
                <dependency>
                    <groupId>org.jboss.spec</groupId>
                    <artifactId>jboss-javaee-7.0</artifactId>
                    <version>1.0.3.Final</version>
                    <type>pom</type>
                    <scope>provided</scope>
                </dependency>
                <dependency>
                    <groupId>org.jboss.arquillian.container</groupId>
                    <artifactId>arquillian-weld-ee-embedded-1.1</artifactId>
                    <version>1.0.0.CR9</version>
                    <scope>test</scope>
                </dependency>
                <dependency>
                    <groupId>org.jboss.weld</groupId>
                    <artifactId>weld-core</artifactId>
                    <version>2.3.5.Final</version>
                    <scope>test</scope>
                </dependency>
                <dependency>
                    <groupId>org.slf4j</groupId>
                    <artifactId>slf4j-simple</artifactId>
                    <version>1.6.4</version>
                    <scope>test</scope>
                </dependency>
            </dependencies>

then Right-click on the project go to properties then click on maven under active maven profile paste this "arquillian-weld-ee-embedded".
if you are using some other conatiner use that in maven active profile.


text:
Q: How to semplify this database schema and query? This is my database schema:
Post:
-id
-title
-body
-date

User:
-id
-name
-password

Category:
-id
-title

Post_Category:
-id
-id_post
-id_category

Post_User:
-id
-id_user
-id_post

Post_Like:
-id
-id_user
-id_post

Comment:
-id
-id_user
-id_post
-body

"Like" in my project works like "facebook likes".
In homepage I need to get latest 50 post with informations about categories, users, likes, comments.
Is there a way to avoid this complex query that join these 7 tables ?


text:
Q: How can I improve performance of a 'LIKE'-linked LEFT JOIN (Oracle SQL) I'm having some problems with performance of a join that uses LIKE to make the join. An example setup is described below.  Table1 grows over the period of the day up to a few thousand rows.  Table2 is a lookup table and is constant in size with just a few dozen entries. As more data is added to Table1, the query performance worsens massively to a point where it becomes effectively unusable.
I have indexes on Table1.Entity and Table2.EntityJoin
I've build the tables this way, with wildcarded EntityJoin values so the front end can define filters that map similar entity names to a particular group.  It appeared to me it would be more efficient from a user's point of view to be able to use wildcards rather than have to define every single entity name from Table1 in Table2 (note, this structure is a massively simplified view for sake of example).
I've read through a few similar posts regarding join performance, but didn't see any that use LIKE in the way I'm trying to use it.
Table1:
------------------------
Entity
------------------------
AnEntity1
AnEntity2
OtherEntity1
Other3Entity
Other12Entity
MoreEntities2
EvenMore3Entities5
------------------------

Table2:
---------------------------------
EntityJoin     | JoinName
---------------------------------
An%            | SomeVal
Other%         | SomeVal
More%          | SomeOtherVal
---------------------------------

Query
select
    *
from
    Table1 T1
    left join Table2 T2
        on T1.Entity like T2.EntityJoin;

A: Best what you can expect with your query is
Full Table Scan on table 1
and a nested loop to table 2.
This is because you have to check every entry in t1 if it matches to any entry in t2.
T2 like
---------------------------------
EntityJoin     | JoinName
---------------------------------
An%            | SomeVal
A%             | SomeVal
AnE%           | SomeOtherVal
---------------------------------

would be possible and entries:
AnEntity1
AnEntity2

would triple.
So you have to think about what can be done to be more selective.


text:
Q: Multiple CKEditors with different height I need to have 10 CKEditors in a page, all with the same customized configurations, but 9 of them with height 100, and one with size 250. This is how I initialize the CKEditors now:
for(var i = 1; i < 9; i++)
    CKEDITOR.replace('editor' + i, {
        customConfig : 'my_configs/small_box.js'
    });

    CKEDITOR.replace('editor0', {
        customConfig : 'my_configs/small_box.js'
        height: 250
    });

With this code all I see are text boxes, not the CKEditor instances.

A: Solution posted on behalf of the OP:
The code was missing a comma.


text:
Q: Retrieving common data on different forms Lets take an example of WinForms applcation and making invoice. On the Invoice form we retrieve a list of products, so the user will be ale to pick products for current invoice. Lets also consider that during this process user realizes that he needs to add a new product (or edit current) to ProductList before he can place it in invoice. So he opens a ProductForm where all the products are retreived (again).
It could also be in opposite order, that user first edits Products, and then without closing the Products Form, opens new Invoice. The principle is that data is two times loaded, and effectively its the same data.
What is the propper way to handle this scenario, so we can tell one form that data is already loaded, and to retrieve that data from memory? And when all the consumers (Forms) of the data are closed, then also the data should be released from memory? Or I am going in wrong direction, and there is a better way?
Thanks,
Goran

A: If the Controls that are using the data are all child controls of a shared Parent control, then you could just pass around the datacontext, so that they all shared the same datacontext.
However, the general use case with databases, which is what backs EF in most cases, is to read the data in each time that it is needed.
A solution to this if as you say you already have the item being used in one form is to just take a Refrence to that item into your new form.
So in the case Where you have an invoice which has a Product List and you want to add to the product list, you could pass the product list from the invoice to the opening product list.
There are some issues with this:

*

*If another user changes the datasource while one has opened it (a.k.a. Concurrency)

*Handling save don't save scenarios where they may have made a change in one area that they don't actually want added to the data.

However, unless it is a true performance issues, I would just load the data every time. You can simplify this a lot by using the repository pattern, so you can just call a single method to get a list of products or an invoice, or whatever part of data you need.

A: Definitelly go with data loaded "twice" or you will introduce much worse problems.
Sharing data means sharing ObjectContext. Even in WinForms application this is considered as bad approach. Check this article (it is about NHibernate but the description is valid for EF as well).
The problem is that ObjectContext is unit of work. If share context between two windows you can easily get into situation where you modify data in first window (without saving them!) and you continue in second window where you push save button but it will save data from both windows! You can't selectively save data only from one window when you share the context.


text:
Q: List comprehension in Python? I have this list :
a = [1,2,3,4,5]
I want to delete each element from the list. This is how I'm doing.
for i in range(0,len(a)):
    del a[0]

Can I use list comprehension in this? such as del a[0] for i in range(0,len(a))

A: List comprehensions are for creating lists, not destroying them. They are not the right tool for this job.
If you want to clear the contents of a list, the quickest way is
del a[:]

This is a slice deletion. The omitted beginning and ending points default to the start and end of the list.
Note that frequently, it's better to just replace the list with a new one:
a = []

This works even if a didn't already exist, and modifications to the new list won't interfere with any other parts of the code that needed the old list. These attributes are often, though not always, desirable.

A: You wouldn't usually do this with a loop at all. To clear an existing list, use a[:] = [].

A: No, you cannot del components in a list comprehension. Why would you want to do that in the first place? A list comprehension is for creating a list, not for modifying.
You can replace the list with a different one created with a list comprehension.
The reason is that a list comprehension needs an expression. But del is a statement.

A: List comprehension (coming from functional programming, where nothing is ever mutated) is for building lists. Since it appears you want to clear out the elements of an existing list (and not creating a new list with only some of the elements etc.), list comprehension is not the right tool.
That said, list comprehension can be abused to do it:
[a.pop() for i in range(len(a))]

NOTE: This is a bad idea (since it uses list comprehenstion for something completely different than what it is intended for) and I would strongly recommend you do not use it.