text:
Q: Screen Names from Twitter into DataFrame - R I am downloading all the Tweets (using rtweet package, version 0.7.0) that contain the user @sernac in the text of the tweet (a Chilean government entity), then extract all all the usernames (screen name) from the body of the tweet using the following function.
Tweets <-  search_tweets("@sernac", n = 50000, include_rts = F)
Names <- str_extract_all(Tweets$text, "(?<=^|\\s)@[^\\s]+")

This give me a List object with the every screen name of each text's tweet.
The first question is: How i get a data frame whith the following estructure?

X1
X2
X3
X4
X5
...
Xn

@sernac
@vtrchile
NA
NA
NA
NA
NA

@username
@playstation
@taylorswitft
@elonmusk
@instagram
NA
NA

@username2
@username5
@selenagomez
@username2
@username3
@FIFA
@xbox

@username4
@ebay
NA
NA
NA
NA
NA

Where the numbers of columns is equal to the max number of elements in a object from the list.
I tried the following fuction, but only return 4 columns, where the max elements into a object is 9.
df <- data.frame(matrix(unlist(Names), nrow=length(Names), byrow = T))

After this, I need to perform a left join between this table and a cluster  table created by me, this left join must be between the first column of the newly created database and the cluster data base , but if there is no match in the left join, it should perform a second left join, but in this case using the second column, until exhausting all the columns if there is no match when performing the left join.
This is an example of the database created by me and the final desired result:
CLUSTER DATA FRAME

screen_name
cluster

@sernac
Gov

@playstation
Videogames

@walmart
Supermarket

@SelenaGomez
Celebrity

@elonmusk
Celebrity

@xbox
Videogames

@ebay
Ecommerce

FINAL RESULT

X1
X2
X3
X4
X5
...
Xn
cluster

@sernac
@vtrchile
NA
NA
NA
NA
NA
Gov

@username
@playstation
@taylorswitft
@elonmusk
@instagram
NA
NA
Videogames

@username2
@username5
@selenagomez
@username2
@username3
@FIFA
@xbox
Celebrity

@username4
@ebay
NA
NA
NA
NA
NA
Ecommerce

I have tried to explain myself in the best way, English is not my main language, so I can explain more detail in the comments.

A: I would approach this differently.
First, if you are trying to download as many tweets as possible, set n = Inf and retryonratelimit = TRUE:
Tweets <-  search_tweets("@sernac",
                         n = Inf,
                         include_rts = FALSE,
                         retryonratelimit = TRUE)

Second, there is no need to extract screen names from the tweet text, as this information can be found in the entities column.
One way to extract mentions is to use lapply. You can then create a data frame with just the useful columns, and convert screen names to lower case for matching.
library(dplyr)

mentions <- lapply(Tweets$entities, function(x) x$user_mentions) %>%
  bind_rows(.id = "tweet_number") %>%
  select(tweet_number, screen_name) %>%
  mutate(screen_name_lc = tolower(screen_name))

head(mentions)

  tweet_number    screen_name screen_name_lc
1            1 mundo_pacifico mundo_pacifico
2            1       OIMChile       oimchile
3            1   subtel_chile   subtel_chile
4            1 ReclamosSubtel reclamossubtel
5            1         SERNAC         sernac
6            2 mundo_pacifico mundo_pacifico

Next, add a column with the lower-case screen names to your cluster data:
cluster_df <- cluster_df %>%
  mutate(screen_name_lc = str_replace(screen_name, "@", "") %>%
         tolower())

Now we can join the data frames, just on the screen_name_lc column:
mentions_clusters <- mentions %>%
  left_join(cluster_df,
            by = "screen_name_lc") %>%
  select(tweet_number, screen_name = screen_name.x, cluster)

head(mentions_clusters)

  tweet_number    screen_name cluster
1            1 mundo_pacifico    <NA>
2            1       OIMChile    <NA>
3            1   subtel_chile    <NA>
4            1 ReclamosSubtel    <NA>
5            1         SERNAC     Gov
6            2 mundo_pacifico    <NA>

This "long" format is much easier to work with for subsequent analysis than the "wide" format, and can still be grouped by tweet using the tweet_number column.
Data for cluster_df:
cluster_df <- structure(list(screen_name = c("@sernac", "@playstation", "@walmart",
"@SelenaGomez", "@elonmusk", "@xbox", "@ebay"), cluster = c("Gov",
"Videogames", "Supermarket", "Celebrity", "Celebrity", "Videogames",
"Ecommerce"), screen_name_lc = c("sernac", "playstation", "walmart",
"selenagomez", "elonmusk", "xbox", "ebay")), class = "data.frame", row.names = c(NA,
-7L))


text:
Q: Postman Authorization with petstore swagger and Prism I've been testing out stoplight prism https://stoplight.io/open-source/prism/ and using a https://petstore.swagger.io/ doc to run my mocks
I'm able to use the GET method for /pet and get mocked results back using Prism.
The swagger is requesting me to authenticate to use the PUT/UPDATE/DELETE methods.
After authenticating with the steps below. I'm still getting an error:
{
   "type":"https://stoplight.io/prism/errors#NOT_ACCEPTABLE",
   "title":"The server cannot produce a representation for your accept header",
   "status":406,
   "detail":"Unable to find content for application/json"
}

Steps:

*

*https://petstore.swagger.io/

*click authorize

*I add in a random client_id

*then add read and write scopes.

*I open my postman and select Authorization and add the following:

I click the Get New Access Token button and click the option to add token.
Then in my headers I add the following:

I add raw body

When I do my post I get the following error:
{
   "type":"https://stoplight.io/prism/errors#NOT_ACCEPTABLE",
   "title":"The server cannot produce a representation for your accept header",
   "status":406,
   "detail":"Unable to find content for application/json"
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: map, filter and own value I have: stackoverflow.com/questions/19012903/get-value-from-multi-object
but i modified this and i would like add to results string longer than 4 chars.
function isLong(val)
{
    if(val.length > 4){
       return true;
    } else {
        return false;
    }
}

var page = [{
    title: 'aaa',
    text: '111'
}, {
    title: 'bbb',
    text: '222'
}, {
    title: 'ccc',
    text: '333'
}, {
    title: 'ddd',
    text: '444'
}, {
    title: 'eee',
    text: '444'
}];

console.log([].concat.apply([], '222, 333, 4441, long1, long, long2'.split(', ').map(function (t) {
    return page.filter(function (o) {
        return o.text === t || isLong(t);
    }).map(function (c) {
        return c.title
    });
})).join(", "));

jsfiddle
but this return me all values. I try check this in line return o.text === t || isLong(t);
For this example i would like receive:

bbb, ccc, long1, long2

bbb and ccc are from object page. long1 and long2 are form my custom string separated by commas.

A: var str = '222, 333, 4441, long1, long, long2';

var strArray = str.split(', ');

var result = strArray.map(function(s){
    return isLong(s) ? s : page.filter(function(o){ // if word has > 4 chars return word else try to match with page array
       return o.text == s;
    }).map(function(c){
      return c.title;  // if matched return title
    })[0]; // select first match
}).filter(function(u){
    return u;  // remove undefined results
});

console.log(result);

Example: http://jsfiddle.net/YrZNq/6/


text:
Q: Why is node failing to find SubmitEvent? I am trying to add unit tests using jest to my React application.
I have the following code in my test, but when I run it, I am getting "ReferenceError: SubmitEvent is not defined".
taskInputForm.dispatchEvent(new SubmitEvent("submit"), { bubbles: true });

A: SubmitEvent is relatively recent, maybe the browser you used is not up to date.
https://developer.mozilla.org/en-US/docs/Web/API/SubmitEvent/SubmitEvent


text:
Q: facebook lint tool fail to load open graph different between Fetched url and Canonical URL I got this url
//www.nasl.com/nasltv/watchvod/id/874146/marcos_senna_nyc_nasl_player_of_the_week_%7C_week_5
When you try to te
https://developers.facebook.com/tools/debug/og/object?q=http%3A%2F%2Fwww.nasl.com%2Fnasltv%2Fwatchvod%2Fid%2F874146%2Fmarcos_senna_nyc_nasl_player_of_the_week_%257C_week_5%3Fflash
You get a different cannonical URL
//www.nasl.com/nasltv/watchvod/id/874148/nasl_weekly_rewind_%7C_week_5
This was the url first used for start testing the open graph implementation so is my hipotesys to be something cache related and facebook crawl time out
Has you can see this are the og meta defined
view-source:http://www.nasl.com/nasltv/watchvod/id/874146/marcos_senna_nyc_nasl_player_of_the_week_%7C_week_5?flash

<meta property="og:url" content="http://www.nasl.com/nasltv/watchvod/id/866185/marcos_senna_nyc_nasl_player_of_the_week_%7C_week_5">
<meta property="og:type" content="movie" />
 <meta property="og:video:height" content="275" />
<meta property="og:video:width" content="486" />

<meta property="og:video" content="http://www.nasl.com/ptvFlash/unifiedplayer/sva_adaptive_omniture_1_5/release/UnifiedPlayerV2.swf?configXML=http%3A%2F%2Fwww.nasl.com%2Fxml%2Fconfig.xml&clipId=874146&setPlayerType=vod&selectedBandwidth=low&resourceLocalePath=%2FptvFlash%2Funifiedplayer%2Fassets%2Fresources%2F&useInitialSplashScreen=true&splashScreen=http%3A%2F%2Fwww.nasl.com%2F/javaImages/4b/dd/0,,~12836171,00.jpeg">
<meta property="og:video:secure_url" content="https://secure.nasl.com/ptvFlash/unifiedplayer/sva_adaptive_omniture_1_5/release/UnifiedPlayerV2.swf?configXML=https%3A%2F%2Fsecure.nasl.com%2Fxml%2Fconfig_secure.xml&clipId=874146&setPlayerType=vod&selectedBandwidth=low&resourceLocalePath=%2FptvFlash%2Funifiedplayer%2Fassets%2Fresources%2F&useInitialSplashScreen=true&splashScreen=https%3A%2F%2Fsecure.nasl.com%2F/javaImages/4b/dd/0,,~12836171,00.jpeg">
<meta property="og:video:type" content="application/x-shockwave-flash">

But is allways taken the content from the URL
//www.nasl.com/nasltv/watchvod/id/874146/marcos_senna_nyc_nasl_player_of_the_week_%7C_week_5
Another insight is this is behind an Akamai CDN
Does any have any insights on this?
Thanks in advance for your help

A: Because og:url on https://developers.facebook.com/tools/debug/og/object?q=http%3A%2F%2Fwww.nasl.com%2Fnasltv%2Fwatchvod%2Fid%2F874146%2Fmarcos_senna_nyc_nasl_player_of_the_week_%257C_week_5%3Fflash is http://www.nasl.com/nasltv/watchvod/id/874148/nasl_weekly_rewind_%7C_week_5 . Facebook will use og:url as the canonical url.

A: This was an error on the id for the meta URL not a cache problem


text:
Q: Extract longitudinal pixel values from raster.list, save to data frame I have a list of rasters of the same location for multiple years. The change in pixel value over time represents the time series of pixel.
To further analyses, I need to extract the values over time per every pixel, and store it in data frame, where row = #pixel, column = year
Dummy data:
library(raster)

# create raster data from scratch
# create empty raster
y1<-raster(ncol = 3, nrow = 3)

values(y1)<-1:9

projection(y1)<-CRS("+init=epsg:4326")

# create and diversify the rasters
y2<-y1+10
y3<-y1+20
y4<-y1+30

# make list of rasters
y.list<-list(y1, y2,y3,y4)

# plot all rasters at once
par(mfrow = c(2,2))

for(i in 1:length(y.list)) {
  plot(y.list[[i]])
}

How the dataframe should look like:

         y1  y2  y3  y4
pixel1   1   10  20  30
pixel2
...
pixel9   9   19  29  39

How to extract unique pixel values over time, and convert individual pixel data to data frame??

A: Try
as.data.frame(raster::stack(y.list))

You can also extract the time series directly for individual cells, i.e.
extract(raster::stack(y.list), 1)  ## the first pixel
# layer.1 layer.2 layer.3 layer.4
# [1,]       1      11      21      31

The raster package has a lot of functionality already built-in, so it's worth digging into it to see what's there. A good overview can be found with
?"raster-package"

and there's a long-form document to read as a vignette
vignette("Raster")

The vignette is also online here: https://cloud.r-project.org/web/packages/raster/vignettes/Raster.pdf

A: I found another great answer here !
https://stackoverflow.com/questions/19833784/how-to-extract-values-from-rasterstack-with-xy-coordinates?rq=1
at he same time, so here it is !
No need to put rasters into the list of rasters - just create raster stack !!
Than, just simply use raster::extract to create a time series of each pixel value over time !
the whole script:
library(raster)

# create raster data from scratch
# create empty raster
y1<-raster(ncol = 3, nrow = 3)

values(y1)<-1:9

projection(y1)<-CRS("+init=epsg:4326")

# recreate and diversify the rasters
y2<-y1+10
y3<-y1+20
y4<-y1+30

# create raster stack
# create raster stack
s<-stack(y1, y2, y3, y4)

# plot rasters
plot(s)

# extract raster values - return a matrix of values in each pixel
# row = pixel, column = layer (year)
mat <- raster::extract( s , 1:ncell(s) )

tadaaaa !!!!
> mat
  layer.1 layer.2 layer.3 layer.4
 [1,]       1      11      21      31
 [2,]       2      12      22      32
 [3,]       3      13      23      33
 [4,]       4      14      24      34
 [5,]       5      15      25      35
 [6,]       6      16      26      36
 [7,]       7      17      27      37
 [8,]       8      18      28      38
 [9,]       9      19      29      39


text:
Q: Grounding the chassis with capacitor My question involves chassis grounding to earth ground.
My PCB circuit is a simple signal generator using a microcontroller. It has a separate 'ground' from earth ground, supplied by a floating 5VDC source. (I guess we would call this a digital ground?)
The PCB is to be installed inside a metal chassis (aluminum, I believe). Inside, there is a 15VDC converter. As a signal generator, it outputs a signal with reference to the +5V.
Unfortunately, the device that uses this output signal is grounded to the earth ground, not the digital ground.
The signal, which is supposed to drive a motor, ends up having severe noise problems.
What I found out was that if I provide the chassis (not the circuit ground) a capacitative ground to the earth ground by connecting a capacitor from the chassis to the earth ground pin, the noise problem disappears. However, if I connect the earth ground DIRECTLY to the chassis, the circuit is shorted.
So my question would be, is it normal/safe to ground the chassis of a circuit with digital ground using only a capacitor? If not, is there a better way to fix the noise issue?
Also, even with the capacitor to the earth ground, whenever a large machinery sharing the same earth ground turns on, my device shorts for an instant, and resets the microcontroller. Is this caused by a large current draw from the big machinery? But how so, if only the earth ground is common?

A: After some experimentation, I found out that it is indeed okay to have capacitative coupling between chassis and earth ground. In the question, I wrote,

if I connect the earth ground DIRECTLY to the chassis, the circuit is shorted.

This is not true, and it was actually caused by me shorting the 5V supply accidentally.
There were several problems at hand. First, my DC voltage supply was isolated and floating off some weird value. This meant that the 'negative' of the supply wasn't actually connected to the earth ground. As stated in the question, I wanted to drive a motor that was connected to earth ground. Fortunately, the motor only required a differential voltage, hence it functioned okay.
Another issue was the microcontroller resetting whenever a large machinery turned on. This was solved by putting bypass capacitors between all VCC and GND connections (even for the LCD screen that I have as well). Thanks to @Horta for the suggestion!
Although, it still is a mystery to me why there was voltage fluctuation within the earth ground in the first place.
Thank you everyone for your help!

A: if you are concerned about noise interference, use decoupling capacitors as follows:
Let's discuss an audio amplifier with power supply, assembled in a metal box. The power supply consists of a transformer powered with 120Vrms HOT and NEUTRAL.  The metal transformer is bolted to the metal cabinet. Metal of the transformer touches the metal cabinet. The ground of the AC input is wire-connected to the metal chassis. The secondary of the transformer has 2 windings (with a center tap).  A full wave rectifier is used to get  +55Vdc,  middle winding is common=0Vdc, and -55Vdc.  These voltages power the amplifier.  The amplifier LEFT channel uses +55 (common=0Vdc) and -55. A speaker has a red and black wire, with a RED/BLK connector. The output of the amplifier is AUDIO OUT; (the red wire goes to the red connector of the speaker and the common=0Vdc goes to the black connector of the speaker. Same description applies to the right channel.  To minimize OVERALL noise, use a metal film 0.15 uF capacitor on the following locations:  capacitor between +55V to chassis,  +55 to 0Vdc-common,  -55 to chassis,  -55 to common,  and one capacitor between common and chassis.  These capacitors help dissipate high frequency noise to chassis (aka chassis GROUND). Use a good multimeter to measure isolation resistance across each capacitor; it should be high (~ 2 meg), which includes the capacitor in parallel with the resistive measurement (+55V to chassis,  +55 to 0Vdc, -55 to chassis,  -55 to 0Vdc, and 0Vdc to chassis)


text:
Q: iOS - What happens I lost my APNs Key file? I just created the APNs Key file from Apple Developer website. It was saying "Don't lost this key". I already have a backup but what happens if I lost it?
It is also saying I just need one APNs Key for all apps.
Can I create more than one APNs Key or should I go with just one? If I lost this am I going to can't send notifications for just that app or none of my apps?
Thanks in advance.

A: You can have MULTIPLE .p8 files. The .p8 file is used to generate a JWT Token on the server side and that is used to send push notifications via HTTP2 to Apple's APNS server. Only problem is that if you lose it, you have to regenerate a new one on the server side. It doesn't affect existing apps at all because it's bound to the bundleId, applicationId, and developer account.
In other words, it's not a certificate that the app has to be re-signed with or anything.
Scenario to make it simpler:

*

*I create an app called MyApp with BundleId: com.SO.myApp.

*I create an APNS .p8 file with account RT8NCD.

*On the server side, I use this .p8 file to send notifications to com.SO.myApp via HTTP2 and JWT Token generation.

*I release the app to the AppStore.

*I then LOST the .p8 file and can't send push to my app which is already on the store!
What do I do?

*

*I go into the developer portal and re-create a NEW .p8 file with the same AppId and BundleId and same account.

*Then on the server side I use this .p8 file to send push notifications to the devices registered in my database.

*I do not need to release a new app or new version or anything.

So in other words, there's not really any consequences to losing it.. but it's not a good idea to get into the practice of losing keys, certificates, etc.. Seriously.
P.S. I cannot guarantee that this behaviour won't change in the future. It's Apple. Try not to lose things.

A: you can create one APN key per app (one for development one for production) but also you can recreate it, and all devices which was registered with all APN will be supported by new key


text:
Q: Map an instance using function in Scala Say I have a local method/function
def withExclamation(string: String) = string + "!"

Is there a way in Scala to transform an instance by supplying this method? Say I want to append an exclamation mark to a string. Something like:
val greeting = "Hello"
val loudGreeting = greeting.applyFunction(withExclamation) //result: "Hello!"

I would like to be able to invoke (local) functions when writing a chain transformation on an instance.
EDIT: Multiple answers show how to program this possibility, so it seems that this feature is not present on an arbitraty class. To me this feature seems incredibly powerful. Consider where in Java I want to execute a number of operations on a String:
appendExclamationMark(" Hello! ".trim().toUpperCase()); //"HELLO!"

The order of operations is not the same as how they read. The last operation, appendExclamationMark is the first word that appears. Currently in Java I would sometimes do:
Function.<String>identity()
    .andThen(String::trim)
    .andThen(String::toUpperCase)
    .andThen(this::appendExclamationMark)
    .apply(" Hello "); //"HELLO!"

Which reads better in terms of expressing a chain of operations on an instance, but also contains a lot of noise, and it is not intuitive to have the String instance at the last line. I would want to write:
" Hello "
    .applyFunction(String::trim)
    .applyFunction(String::toUpperCase)
    .applyFunction(this::withExclamation); //"HELLO!"

Obviously the name of the applyFunction function can be anything (shorter please). I thought backwards compatibility was the sole reason Java's Object does not have this.
 Is there any technical reason why this was not added on, say, the Any or AnyRef classes?

A: You can do this with an implicit class which provides a way to extend an existing type with your own methods:
object StringOps {
  implicit class RichString(val s: String) extends AnyVal {
    def withExclamation: String = s"$s!"
  }

  def main(args: Array[String]): Unit = {
    val m = "hello"
    println(m.withExclamation)
  }
}

Yields:
hello!

A: If you want to apply any functions (anonymous, converted from methods, etc.) in this way, you can use a variation on Yuval Itzchakov's answer:
object Combinators {
  implicit class Combinators[A](val x: A) {
    def applyFunction[B](f: A => B) = f(x)
  }
}

A: A while after asking this question, I noticed that Kotlin has this built in:

inline fun <T, R> T.let(block: (T) -> R): R

Calls the specified function block with this value as its argument and returns
  its result.

A lot more, quite useful variations of the above function are provided on all types, like with, also, apply, etc.


text:
Q: JavaScript to retrieve table fields to modal window for editing? So essentially what i am trying to achieve is a table that will have Edit and Delete button, which in turn will display a modal window either a form for Edit or Dialog for Delete. I can work out the delete one myself however the Edit one is harder.
This is my current Table:

          UserID
          Position
          Lol Region
          Name
          Email
          Edit
          Delete

    <?php
      foreach ($customers as $customer): ?>
        <tr id="<?php echo $customer->user_id; ?>">
          <?php echo $customer->user_id; ?>
          <?php echo $customer->type; ?>
          <?php echo $customer->region; ?>
          <?php echo $customer->full_name; ?>
          <?php echo $customer->email; ?>

<button class="btn btn-primary btn-xs" data-title="Edit" data-toggle="modal" data-target="#edit" ></button>

<button class="btn btn-danger btn-xs" data-title="Delete" data-toggle="modal" data-target="#delete" ></button>

      <?php endforeach;
    ?>

And my Modal Form:

  <button type="button" class="close" data-dismiss="modal" aria-hidden="true"></button>

Edit Customers Details

    <input class="form-control " type="text" placeholder="">

    <input class="form-control " type="text" placeholder="">

    <textarea rows="2" class="form-control" placeholder=""></textarea>

    <button type="button" class="btn btn-warning btn-lg" style="width: 100%;"> Update</button>

Since i am not that good at Javascript i will just assume perhaps i have to select the nearest values in the tr that contains the button clicked but i am unsure.
Advice how to got about this? -- Note the form will POST to a PHP file, and thus i will somehow need to redraw the table since its a DataTable.
Thanks

A: you have a lot to do its better to access data via class or id ..ill modify your html as this
 <?php
      foreach ($customers as $customer): ?>
        <tr id="<?php echo $customer->user_id; ?>">
          <?php echo $customer->user_id; ?>
          <?php echo $customer->type; ?>
          <?php echo $customer->region; ?>
          <?php echo $customer->full_name; ?>
          <?php echo $customer->email; ?>

<button class="btn btn-primary btn-xs edit" data-title="Edit" data-toggle="modal" data-target="#edit" ></button>

<button class="btn btn-danger btn-xs delete" data-title="Delete" data-toggle="modal" data-target="#delete" ></button>

      <?php endforeach;
    ?>

and give you edit and delete a class too
and then with jQuery
$(document).ready(function(){
   $('.edit').click(function(){
     alert($(this).closest('tr').find('.userid').html()); //you will get the userid
     //same way you can get the remaining values ,just change the find parameter with its classname
   //now assign it to the form value
  $('#your_model_form_value_username').val($(this).closest('tr').find('.username').html());
//same way do the rest
   });
});


text:
Q: Mobile to controller secure bluetooth ble communication We seek your help in implementing bluetooth on our smart home controller. Our current scenarios is described below:

*

*We want secure communication between our embedded linux controller(our smart home hub) and user's mobile phones running android/iOS.Our system is in home automation.

*The hub in turn communicates with home devices that support a different protocol - we need to make communication between hub and mobile devices using bluetooth.

*Currently there is not direct communication between our hub and mobile phone except through the internet.

*We will use Bluetooth 4.x, not 5 for hardware support on the controller.

*We are using nodejs on our controller and standard bluethooth OS libraries on android/iOS. We are open to suggestions.

Our main concern is to establish secure communication between phone and the hub. With this regard we are looking for implementation guidance on pairing  and communicating securely. We have been able to establish unsecure communication - exposing characteristics and services on the hub. Our understanding of the bluetooth protocol is limited and we have only used libraries available for users.
Please provide specific pointers as to what we should do and what is possible.


text:
Q: Invalid character string partly recognized? c++ BLUF: In this function, \' prompt the error message but not \?, Why?
char key[] = "\a\b\f\n\r\t\v\\\'\"#%&*;:<>\?/{|}~";
        if (strpbrk(*local_str, key) != NULL )
        {
            vico_param_out->out_valid = false;
            AfxMessageBox("L'identifiant de numérisation est invalide. Vous avez saisi des caractères qui ne peuvent pas faire partie d'un nom de fichier windows (\"#%&*;:<>\?\\/{|}~). Veuillez faire les corrections nécessaires.");
        }

This snippet of code is supposed to check if one of the invalid caracters is in the input string (*local_str). Works well with some of them, but if some characters like \? are in *local_str. it accepts it and do not show the error message. I dont understand whats happening.
Example:
ABC is valid
AB' is not valid, prompt mesage for correction
AB? is not valid but falls through
A'? is not valid but also falls through.
Please help. I am indepted to this community.
EDIT: Problem solved. I would seem that this function works but another process which I was unaware of was catching the keys in local_str as shortcuts before the call to my function, hence the weird behavior. I moved my function to be evaluated when each keystroke is inputed.
My deepest apologies for annoyance.
Thanks you everyone.

A: Running this code, all three invalid string produce the error message.
int _tmain(int argc, _TCHAR* argv[])
{
    char local_str[] = "A'?";
    char key[] = "\a \b \f \n \r \t \v \\ \? \' \" \" # % & * ; : < > \? \\ \' / { | } ~  ";
        if (strpbrk(local_str, key) != NULL )
        {
            cout << ("L'identifiant ......");
        }

    return 0;
}

My only guess is that there may be some mismatch between US-en and FR-fr character sets.

A: A simple program calling strpbrk with your given input does not produce the problem. Try changing to char const key[] to see if key is getting modified between uses.

A: My apologies. The code is working fine afterall. Another process was intercepting local_str before my code was executed and throw a silent exception and skipped my function all together.
I moved my code to be executed before that said process and it should be fixed tomorrow morning.


text:
Q: Sum the values of a form and add that result to the database I want to make a form that has 3 number radio values, supposedly look like this:

And I'd like for those 3 values to sum and display the sum of those values to then save them into the database.
forms.py:
class FormTest(forms.Form):
    CHOICES = [
        ('0', '0'),
        ('1', '1'),
        ('2', '2'),
        ('3', '3'),
        ('4', '4'),
        ('5', '5'),
    ]
    num1 = forms.ChoiceField(widget=forms.RadioSelect, choices=CHOICES)
    num2 = forms.ChoiceField(widget=forms.RadioSelect, choices=CHOICES)
    num3 = forms.ChoiceField(widget=forms.RadioSelect, choices=CHOICES)
    total = num1 + num2 + num3

models.py:
class Test(models.Model):
    num1 = models.IntegerField()
    num2 = models.IntegerField()
    num3 = models.IntegerField()

class Dato(models.Model):
    dato = models.IntegerField()

views.py:
def formtest(request):
    """
    if request.method == 'GET':
        return render(request, 'testform.html', {
        'form': FormTest()
    })
    else:
        Test.objects.create(
            num1=request.POST["num1"],
            num2=request.POST["num2"],
            num3=request.POST["num3"]
        )
        return redirect('forms')
    """
    if request.method == 'GET':
        return render(request, 'testform.html', {
        'form': FormTest(),
    })
    else:
        Dato.objects.create(
            dato=request.POST['dato']
        )
        return redirect('forms')

testform.html:
{% extends 'layouts/base.html' %}
{% block content %}

Test Form

    <form method="post">
        {% csrf_token %}
        {{ form.as_p }}
        <button>Save</button>
    </form>

    {{ totalsum }}

{% endblock %}

urls.py:
from django.urls import path
from . import views

urlpatterns = [
    #path('', views.index),
    path('', views.index, name="index"),
    path('about/', views.about, name="about"),
    path('hello/<str:username>', views.hello, name ="hello"),
    path('projects/', views.projects, name="projects"),
    path('tasks/', views.tasks, name="tasks"),
    path('create_task/', views.create_tasks, name="create_task"),
    path('create_projects/', views.create_project, name="create_projects"),
    path('formtest', views.formtest, name="forms")
]

I know I'm not allowed to sum ChoiceFields on its own but I have no idea what to actually do to make it work, I guess I could try a Javascript but I don't know how to incorporate it, correctlly... Help? Please?

A: I just could not reproduce the visual in the same way, by using a custom styling in the template, although it is pretty close.
To make it work you need to retrieve the data from the request.POST (in this case via django form). To save the object you can just create an object instance using the form cleaned_data kwargs:
Test.objects.create(**form.cleaned_data)

which is equivalent to:
Test.objects.create(
    num1=form.cleaned_data.get('num1'),
    num2=form.cleaned_data.get('num2'),
    num3=form.cleaned_data.get('num3')
)

But, to do an operation with the data, first, you need  to retrieve it from the form's cleaned_data object. This data comes in string format, so it is necessary to parse / convert into an integer in order to do the wanted operation:
number1 = int(form.cleaned_data.get('num1'))
number2 = int(form.cleaned_data.get('num2'))
number3 = int(form.cleaned_data.get('num3'))
total = number1 + number2 + number3

One possible solution:
models.py
from django.db import models

class Test(models.Model):
    num1 = models.IntegerField()
    num2 = models.IntegerField()
    num3 = models.IntegerField()

    # Not really necessary, just to show on template
    def __str__(self):
        total = self.num1 + self.num2 + self.num3
        return f'{self.num1} + {self.num2} + {self.num3} = {total}'

forms.py (Optionally, you can explore model form for a cleaner solution)
from django import forms

CHOICES = [
        ('0', '0'),
        ('1', '1'),
        ('2', '2'),
        ('3', '3'),
        ('4', '4'),
        ('5', '5'),
    ]

class SimpleForm(forms.Form):
    num1 = forms.ChoiceField(
        required=True,
        widget=forms.RadioSelect({'class': 'myfieldclass'}),
        choices=CHOICES,
        initial=0
    )

    num2 = forms.ChoiceField(
        required=True,
        widget=forms.RadioSelect({'class': 'myfieldclass'}),
        choices=CHOICES,
        initial=0
    )

    num3 = forms.ChoiceField(
        required=True,
        widget=forms.RadioSelect({'class': 'myfieldclass'}),
        choices=CHOICES,
        initial=0
    )

views.py
from django.shortcuts import render
from .forms import SimpleForm
from .models import Test

def select_number(request):
    total = None
    tests = Test.objects.all()

    if request.method == 'POST':
        form = SimpleForm(request.POST)
        if form.is_valid():
            # Save obj
            Test.objects.create(**form.cleaned_data)
            # cast data to interger, to show current test result
            number1 = int(form.cleaned_data.get('num1'))
            number2 = int(form.cleaned_data.get('num2'))
            number3 = int(form.cleaned_data.get('num3'))
            total = number1 + number2 + number3
    else:
        form = SimpleForm()
    context = {'form': form, 'total': total, 'tests': tests}
    return render(request, 'select_number.html', context)

select_number.html
{% extends 'base.html' %}

{% block content %}

    <form action="{% url 'core:select-number'%}" method="post">
        {% csrf_token %}

            {{form}}

        <button type="submit">Sum Up</button>
    </form>

    {% if total %}
        The total of the current sum is {{total}}
    {% endif %}

My tests list

    {% for test in tests %}
        {{test}}

    {% endfor %}
{% endblock content %}

urls.py
from django.urls import path
from core import views

app_name = 'core'

urlpatterns = [
    path('select/number/', views.select_number, name='select-number'),
]

Of course, it is possible to do all of that with Javascript using AJAX. Usually used when you do not want to your page to be entirely reloaded when sending a request to a view.


text:
Q: Is css_parser parsing inline CSS incorrectly? I have a HTML file with inline CSS:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">

<TITLE>Page 1</TITLE>

<META http-equiv="Content-Type" content="text/html; charset=UTF-8">

<nobr>Sample   </nobr>

<nobr>HTML</nobr>

I am trying to parse the inline CSS using Ruby's css_parser library. Note that the inline CSS has 2 classes .ft0 and .ft1.
My code is:
require 'css_parser'
parser = CssParser::Parser.new
parser.load_file!('filename.html')
puts parser.to_s

Which outputs:
<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">\n\n   \n<TITLE>Page 1</TITLE>\n<META http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\">\n
\n

<nobr>Sample   </nobr>

<nobr>HTML</nobr>

'

doc = Nokogiri::HTML(html)

stylesheet = doc.at('style').content
parser = CssParser::Parser.new
parser.add_block!(stylesheet)
puts parser.find_by_selector(".ft0")

Which outputs:
font-size: 108px; font-family: Helvetica; color: #000000;


text:
Q: How to create identity column when importing data from Excel into MS SQL Server (with Import and Export Wizard)? I need to import great amount of data from excel into MS SQL Server, using the Import/ Export Wizard. Then I'll continue importing more data into the same table on a weekly basis.
The bad thing is that my excel data doesn't have an identity column, which to use as a primary key. The only option with what available is to use 2 string columns as a primary key, which is not a good idea.
Is there a way the sql server to add auto-identity column (integer) when importing the data, and what's the trick?  I prefer such a column to be automatically added, because I'll need to import big amount of data into the same table on a weekly basis.
I tested a couple of times (with no success) and looked for a solution in the internet, but didn't found an answer to that particular question. Thanks in advance!

A: You can create the table first along with the new identity column.
CREATE TABLE YourTable
(
  id INT IDENTITY,
  col1....
  col2....
  col3....
  PRIMARY KEY(id)
)

Then run the import/export wizard. When you get to the destination section pick your newly created table and map all the fields except the identity column. After the import you can check the table and see the id column has been populated.

A: Column names in Excel sheet should be same as that of sql Table.
Map Excel columns with that of SQL table columns by Clicking Edit Mapping.
Just don't map that (identity) column of sql table to anything .
In Import-Export Wizard don't check Enable identity insert Checkbox. (Leave that
 un selected).
and go ahead import .. This worked for me. !!!!!
Previously when i used to check Enable identity insert it used to give me error.

A: I had a similar issue. I have a SQL table with an identity column (auto increment ID value) defined. I needed to import an Excel spreadsheet into this table.
I finally got it to work via the following:

*

*Do NOT add a column to the Excel spreadsheet for your identity column in the SQL table.

*When you run the import wizard and get to the Edit Mappings step, do NOT select the Enable identity insert checkbox. This, in particular, was tripping me up.


text: Q: I have difficulty understanding why the condition is necessary in this linear algebra problem Let $\mathbb{K}$ be a field of cardinality not equal to 2 and we consider the linear functionals on $\mathbb{K}^{3}$, $f_{1}(X)=x+y-z$, $f_{2}(X)=x-y+z$, $f_{3}(X)=x+y-z$. The point of the problem is to show that $f_{1}$, $f_{2}$ and $f_{3}$ form a basis of $\left(\mathbb{K}^{3}\right)^{*}$ and to find its dual basis. I have solved the problem and got $\left(\frac{1}{2}, 0,-\frac{1}{2}\right)$, $\left(\frac{1}{2},-\frac{1}{2}, 0\right)$ and $\left(0, \frac{1}{2}, \frac{1}{2}\right)$ as the dual basis. But I have difficulty understanding why the condition $\mathbb{K}$ be a field of cardinality not equal to 2 necessary in this problem.


text:
Q: Погрешность спидометра Нужно решить следующую задачу:
Человек нечаянно сломал стрелку на спидометре, после чего вставил свою стрелку в спидометр, но вышло так, что эта стрелка имеет погрешность, и не показывает настоящую скорость авто, то есть имеет погрешность в одну из сторон. Затем человек провел замеры (одна поездка с разной скоростью), и получил следующие результаты:
Первая поедка заняла 5 часов

*

*Проехал первые 4 км со скоростью -1 км/час

*Дальше ехал 4 км со скоростью 0 км/час

*Дальше ехал 10 км со скоростью 3 км/час
Погрешность, которую высчитал водитель в этом случае составила 3.0 км/час (было дано в условии, я не высчитывал это сам, ибо не знаю как)
То есть выходит, что первые 4 км он ехал 2 км/час , слеудющие 4 км ехать 3 км/час, остальные 10 км ехал 3 км/час.
Аналогично, ещё пример:
Общее время езды - 10 часов

*

*Проехал первые 5 км со скоростью 3 км/час

*Дальше ехал 2 км со скоростью 2 км/час

*Дальше ехал 3 км со скоростью 6 км/час

*Дальше ехал 3 км со скоростью 1 км/час
Погрешность: -0.508653377
Хочу понять лишь как решать такое, думал уже очень долгое время, идей нет, по этому пишу сюда. Заранее спасибо за ответ!

A: Ну пусть эта погрешность d. Разберем первую задачу.
Он ехал со скоростью d-1 4км за время 4/(d-1), потом 4 со скоростью в за время 4/d, потом еще 10/(d+3).
Итого 4/(d-1)+4/d+10/(d+3) = 5
Ищем отсюда d, находим, что d == 3.

A: Вот смотрите - известно общее время и длины участков. Значит, можно составить уравнение
5/(3+x) + 2/(2+x) +.. =10 часов

Здесь x - неизвестная поправка


text:
Q: Flex/AIR pinch zoom centreing image I am developing an application with flex/air and I need to centre an image in the view port while pinch zooming.
I start with an image of 3008x2000 at 1:1 scale, I then want to be able to zoom in and out on a certain area of the image with a combination of scaling and repositioning on the screen.
Does anybody have a working method of doing this smoothly? I keep messing with the math but am having no luck.


text:
Q: Getting the interface to block in PyGTK I'm trying to write a WiFi management interface using Python and PyGTK.
The user sees a list of available networks in a gtk.TreeView. S/he then has an option to rescan the wireless networks by clicking a button. For whatever reason, the rescanning process is really quick. So quick in fact, that it feels like nothing has happened on clicking the button, even though the list of networks is indeed being rescanned.
What I'd like to do is to add a couple of seconds of delay, where the interface blocks and I display a gtk.Spinner so that the user sees that the gtk.TreeView I use to display the list of networks is cleared and repopulated.
Obviously, time.sleep() isn't the right way. Is there an elegant way of doing this?

A: Regarding LOC the shortest answer i could come up with:
from threading import Thread
import gobject

gobject.threads_init()

time_to_wait = 2.0      # time in seconds
nonblocking_wait = Thread(target=sleep, args=(timetowait,))
nonblocking_wait.start()

while nonblocking_wait.is_alive():
    nonblocking_wait.join(.05)
    gtk.main_iteration_do(True)     # blocks if no event is pending

On a second glance i realized, that for some readers the relevance of the sleep-thread might be obscure. It's purpose is to establish a maximum timelimit of time_to_wait + 0.05 seconds (+ overhead)! you could do it with a counter or similar approaches, but this way you prevent an useless load on the cpu in idle loops.
This way gtk can still handle draw-updates.
any progressbar-updates or whatever must be placed into the while loop.


text:
Q: How to run Android Studio with specified JDK, but without changing JAVA_HOME environment variable? I'm using some sort of Java apps that use JAVA_HOME environment variable, but need that environment variable is set to 32-bit version of JDK. I'm using 64-bit Windows. When i start Android Studio i get error like below. I've set env variables like ANDROID_STUDIO_JDK and JDK_HOME pointing to jdk 64bit, but i see that JAVA_HOME has higher priority and error is the same. What can i do? In eclipse environment i can set this in eclipse.ini. Is something like that for new Android Studio (build 135.1623071) ?

No JVM installation found. Please install a 64 bit JDK. If you already
  have a JDK installed define a JAVA_HOME variable in Computer > System
  Properties > System Settings > Environment Variables.


text:
Q: Can multiple RetrieveRequest objects be set in a single Retrieve? I'm using the PHP library for the ExactTarget API.
I want to pull a subscriber and the subscriber's lists in one API call.  Is it possible?  What are the allowances and limitations of retrieve.  Thanks!

A: That is not possible.  The RetrieveRequest in SOAP only supports a single object.  It would need to be two requests, one for the Subscriber object, then another for the ListSubscriber object to find the lists they are on.


text:
Q: Good Way to verify RavenDB imported large amounts of data from SQL Server? I'm using a console application to migrate large amounts of data from SQL Server to RavenDB.
What is the best way to verify the data in RavenDB was imported from SQL Server?
I tried to create lists of objects from RavenDB and compare it a list of the same object from Sql.
The problem I run into is that the data is too large to put all of it into a collection to compare even if I query for specific data.
I can only retrieve small amounts of data at a time from RavenDB (only a list of 128) directly in the console application.  I know that can be overridden on the server side, but that is something I can not do.  I thought perhaps an index could help me in this situation?

A: Moyler,
You can page through the data and compare it.


text:
Q: RealmObject not saving data I am saving data to a RealmObject then adding it to my Realm. After leaving the activity and returning the RealmObject is retrieved and the EditText are loaded with the appropriate data. All the EditText but one, Company Address, are loading correctly and I can't figure out why when all save and loading information is the same. Any ideas?
Activity
public class NewLocation extends ActionBarActivity {

    public EditText editCoName;
    public EditText editCoAddress;
    public EditText editCoContact;
    public EditText editSqFt;
    public EditText editTaxed;
    public EditText editConcerns;
    private Realm realm;
    public CompanyInfo companyInfo;

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

        findViewById(R.id.button3).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                SaveInfo();
                Intent i = new Intent(NewLocation.this, RoomList.class);
                startActivity(i);
            }
        });

        editCoName = (EditText) findViewById(R.id.CoName);
        editCoAddress = (EditText) findViewById(R.id.CoAddress);
        editCoContact = (EditText) findViewById(R.id.CoContact);
        editSqFt = (EditText) findViewById(R.id.SqFt);
        editTaxed = (EditText) findViewById(R.id.Taxed);
        editConcerns = (EditText) findViewById(R.id.Concerns);

        //initialize realm and make CompanyInfo object if there is not already one
        realm = Realm.getInstance(this);
        CompanyInfo result = realm.where(CompanyInfo.class).findFirst();
        if (result == null){
            realm.beginTransaction();
            companyInfo = realm.createObject(CompanyInfo.class);
            companyInfo.setName(editCoName.getText().toString());
            companyInfo.setAddress(editCoAddress.getText().toString());
            companyInfo.setContact(editCoContact.getText().toString());
            companyInfo.setTaxed(editTaxed.getText().toString());
            companyInfo.setSqFt(editSqFt.getText().toString());
            companyInfo.setConcerns(editConcerns.getText().toString());
            realm.commitTransaction();
        }
        else {
            editCoName.setText(result.getName());
            editCoAddress.setText(result.getAddress());
            editCoContact.setText(result.getContact());
            editTaxed.setText(result.getTaxed());
            editSqFt.setText(result.getSqFt());
            editConcerns.setText(result.getConcerns());
        }

    }

    @Override
    protected void onResume() {
        super.onResume();
        LoadInfo();
    }

    @Override
    protected void onPause() {
        super.onPause();
        SaveInfo();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        realm.close();
    }

    public void SaveInfo() {
        //save all info from the page

        companyInfo = realm.where(CompanyInfo.class).findFirst();

        realm.beginTransaction();
        companyInfo.setName(editCoName.getText().toString());
        companyInfo.setAddress(editCoAddress.getText().toString());
        companyInfo.setContact(editCoContact.getText().toString());
        companyInfo.setTaxed(editTaxed.getText().toString());
        companyInfo.setSqFt(editSqFt.getText().toString());
        companyInfo.setConcerns(editConcerns.getText().toString());
        realm.copyToRealmOrUpdate(companyInfo);
        realm.commitTransaction();

    }

    public void LoadInfo() {
        //load info fom the CompanyInfo and put it into EditTexts

        companyInfo = realm.where(CompanyInfo.class).findFirst();
        if (companyInfo != null) {
            editCoName.setText(companyInfo.getName());
            editCoAddress.setText(companyInfo.getAddress());
            editCoContact.setText(companyInfo.getContact());
            editTaxed.setText(companyInfo.getTaxed());
            editSqFt.setText(companyInfo.getSqFt());
            editConcerns.setText(companyInfo.getConcerns());
        }

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_new_location, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        switch(item.getItemId())
        {
            case R.id.home:
                startActivity(new Intent(getApplicationContext(), MainPage.class));
                break;
        }
        return super.onOptionsItemSelected(item);
    }

}

CompanyInfo class
public class CompanyInfo extends RealmObject{
    @PrimaryKey
    private String Name;
    @Ignore
    private String Address;
    private String Contact;
    private String sqFt;
    private String taxed;
    private String concerns;
    private RealmList<Rooms> rooms = new RealmList<>();

    public RealmList<Rooms> getRooms() {
        return rooms;
    }

    public void setRooms(RealmList<Rooms> rooms) {
        this.rooms = rooms;
    }

    public String getName() {
        return Name;
    }

    public String getAddress() {
        return Address;
    }

    public String getContact() {
        return Contact;
    }

    public String getSqFt() {
        return sqFt;
    }

    public String getTaxed() {
        return taxed;
    }

    public String getConcerns() {
        return concerns;
    }

    public void setName(String coName) {
        this.Name = coName;
    }

    public void setAddress(String coAddress) {
        this.Address = coAddress;
    }

    public void setContact(String coContact) {
        this.Contact = coContact;
    }

    public void setSqFt(String sqFt) {
        this.sqFt = sqFt;
    }

    public void setTaxed(String taxed) {
        this.taxed = taxed;
    }

    public void setConcerns(String concerns) {
        this.concerns = concerns;
    }

}

A: You have an @Ignore annotation on CompanyInfo#Adresse, remove it and Realm will save the adress.


text:
Q: Analyzing a non linear circuit with two sources I want to analyze this circuit. V1 is a) +15V b) +10V c) -5V
I need V2, V3, I1, I2, I3
Uz=6,8V
UF=0,7V
And I hate to say this, but I'm absolutely lacking any approach. I don't know how to manage V1.

simulate this circuit – Schematic created using CircuitLab


text:
Q: Powershell is not returning the right values for csv I have a small script to grad PC battery power and write to a text file (I tried export-csv) every 60 seconds.  However, the script just keeps writing the same value to the file and does not change or increment is properly.
$csvfile = "c:\Users\PC-battery.csv"
$Battstatus = (Get-WmiObject -Class Win32_Battery).estimatedchargeremaining
while ($true)
    {
        "$Battstatus" | Add-Content $csvfile
    Start-Sleep -Seconds 60
    }

A: The issue you have is that the value of $Battstatus is never updated after the first time you set it. You're asking the system for the battery status once and then entering an infinite loop where you just refer back to that one value.
Instead, you'll want to retrieve the value inside the loop, like so:
$csvfile = "c:\Users\PC-battery.csv"
while ($true)
    {
        $Battstatus = (Get-WmiObject -Class Win32_Battery).estimatedchargeremaining
        $Battstatus | Add-Content $csvfile
        Start-Sleep -Seconds 60
    }

I also took the quotes off your variable reference as I don't think they were necessary (unless I'm misunderstanding the value of the variable, you can put them back on if you need them).
Also of note: Add-Content just appends to a file, it isn't CSV aware. You can take advantage of PowerShell's use of objects and put all the battery info into a proper CSV like this:
$csvfile = "c:\Users\PC-battery.csv"
while ($true)
    {
        $Battstatus = Get-WmiObject -Class Win32_Battery
        $Battstatus | Export-Csv $csvfile -NoTypeInformation -Append
        Start-Sleep -Seconds 60
    }

(untested, might have some quirks)


text:
Q: F# object lists For a project of mine, I need a list that can carry multiple types, and I don't want to do any casting, so I've tried using obj lists. Here's some example code to show something that should work, but for some reason doesn't:
type Fruit() =
  member this.Kind = "I'm a tasty fruit!"

type Apple() =
  inherit Fruit()
  member this.Kind = "I'm a crispy apple!"

type Cherry() =
  inherit Fruit()
  member this.Kind = "I'm a juicy cherry!"

> (new Fruit()).Kind
val it : string = "I'm a tasty fruit!"

... // And so on; it works as expected for all three fruits

> let aFruit = [new Fruit()]
val aFruit : Fruit list = [FSI_0002+Fruit]

> aFruit.Head.Kind                          // Works just fine
val it : string = "I'm a tasty fruit!"

> let fruits : obj list = [new Fruit(); new Apple(); new Cherry]
val fruits : obj list = [FSI_0002+Fruit; FSI_0002+Apple; FSI_0002+Cherry]

> fruits.Head                               // Okay, so we can extract items just fine. It also kept the property!
val it : obj = FSI_0002+Fruit {Kind = "I'm a tasty fruit!";}

> it.Kind                                   // This doesn't work. Why? What am I missing?
 error FS0039: The field, constructor or member 'Kind' is not defined

A: The problem is that it has type obj as the list is an obj list and obj has no .Kind member.  You can use the parent type - like
let fruits : Fruit list = [new Fruit(); new Apple(); new Cherry()];;

val fruits : Fruit list = [FSI_0003+Fruit; FSI_0003+Apple; FSI_0003+Cherry]

and then access it with:
fruits.Head.Kind;;
val it : string = "I'm a tasty fruit!"


text:
Q: How to add sum of rows of a matrix into vector? Since the question would be a bit long, ill add that here, I also want to add a row in a vector to the Finald vector.
MatrixXf ProdA(7, 7);;
VectorXf Intd(7);
VectorXf Finald(7);
ProdA <<
    7, 5, 1, 9, 11, 2, 0,
    5, 2, 8, 3, 11, 3, 3,
    3, 9, 0, 1, 3, 1, 7,
    6, 0, 1, 9, 11, 33, 3,
    3, 5, 3, 3, 4, 3, 3,
    3, 9, 1, 1, 0, 1, 15,
    6, 2, 6, 2, 5, 12, 3,

Intd << 4, 5, 2, 12, 4, 1, 6;

Finald << 0, 0, 0, 0, 0, 0, 0;

for (int i = 0; i < 7; i++){
    Finald.row(i) += ProdA.rowwise().sum();
        Finald.row(i) += Intd.row(i);
}

So far this is what I have got. Obviously I get an error if I put i in rowwise. So as an example, I want to add the first row of ProdA , and the first number of Intd into the first space in the Finald vector, and then loop through every row of ProdA and Intd, and sum them all into Finald.
Thanks in advance!

A: I'm not 100% certain that I correctly understand your problem, but the way I understood it, this should work:
VectorXf ones(7);
ones << 1, 1, 1, 1, 1, 1, 1;

Finald = ProdA * ones + Intd;

I'm not sure if your matrix library (which seems to be Eigen) stores vectors as row or column vectors. So you might have to use ones.transpose() instead.


text:
Q: How do I install turicreate with anadonda on windows 10 I am trying to install Turicreate on windows 10 with anaconda and python 3.7and pip version 19.3
Command: **conda create -n virtual_environment_name anaconda
           conda activate virtual_environment_name
           pip install -U turicreate**

in anaconda virtual environment.
This gives the following error:
File "<string>", line 1, in <module>
      File "C:\Users\MeghaNandini\Anaconda3\envs\vireve\lib\tokenize.py", line 447, in open

buffer = _builtin_open(filename, 'rb')

FileNotFoundError: [Errno 2] No such file or directory:
'C:\\Users\\MEGHAN~1\\AppData\\Local\\Temp\\pip-install-mwo8zqcl\\turicreate\\setup.py'

Please help me to resolve the issue.

A: Turi-create is not directly supported in Windows.  You must use the WSL linux environment, see the WSL install guide.

*

*Install WSL. I would suggest the latest Ubuntu distro as a lot of software has easy installation on ubuntu and it's widely used.

*Open a command line and use the bash command to start the linux bash shell.  Note that python 2 may still be the default, so if you want to use python 3, use the python3 command where it says python.

*Install pip:

*

*sudo apt update

*sudo apt install python3-pip

*Create a virtual env as usual

*

*sudo pip install virtualenv,

*virtualenv venv.

*cd venv

*Follow the turi linux install instructions.


text:
Q: updating random dates to a single column (dates repeates) Okay, first I identify the date integer for the particular date, onwards from which i need to update the random values into the dpm_dateto column :
Query :
select to_char(to_date('15/05/2013','dd/mm/yyyy'), 'J') from dual;

Result:
2456428

Now, I try to update the dpm_dateto column using the query below:
update t_dailypm
set dpm_dateto =
     (select to_date(trunc(dbms_random.value(2456428,2456428+76)), 'J') from dual)
where dpm_loc = 'P2' and dpm_department like '%IN%';

Result:
900 rows updated.

But, the problem is that each distinct value in dpm_dateto column is updated with the same date. I can't get my head around this. Kindly help.

A: Don't use a subquery.

Just set=your_expression, like in the below example.
Oracle optimises the subquery and evaluates it only once, but the expression will be evaluated for each row:
create table xyz(
  abc date
);

insert into xyz
select sysdate from dual
connect by level < 6;

select * from xyz;

ABC
--------
13/07/17
13/07/17
13/07/17
13/07/17
13/07/17

and now:
update xyz set abc = to_date(trunc(dbms_random.value(2456428,2456428+76)), 'J');

select * from xyz;

ABC
--------
13/06/14
13/07/23
13/07/26
13/06/24
13/07/10


text:
Q: FORTRAN 95 accuracy for division of very large numbers I wrote a subroutine to calculate binomial coefficients (n choose k) that will be used for large values of n and moderate values of k (hence near the maximum for a given n).  The subroutine code is
!
!   Subroutine to calculate combinatoric term (n choose x)
!
subroutine COMBO(m,y,combin)
implicit none
integer m,y,b1,b2,maxx,minn
real (kind=16) combin,temp1,temp2
temp1 = real(1,16)
temp2 = real(1,16)
maxx = MAX(y,m-y)
minn = MIN(y,m-y)
do b1 = maxx+1,m
temp1 = temp1*real(b1,16)
enddo
do b2 = 1,minn
temp2 = temp2*real(b2,16)
enddo
combin = temp1/temp2
end subroutine COMBO

This works well for moderately large values.  However, if I use n = 100 and k = 55 I get the following
61448471214136179596720592959.998
The decimal part is clearly wrong, since combinations are always whole numbers. The main program is
program chkint
implicit none
integer i,j,n,k
real (kind=16) cmb

print*,"what is n?"
read*,n
print*,"what is k?"
read*,k

call combo(n,k,cmb)
print*,cmb

end

BTW: kind = 16 is quad precision on my machine.
Thanks

A: Depending on the magniitude of integers you're using, there may be portable means of using extended precision integers on your system. The standard module ISO_FORTRAN_ENV should define a number of integer kinds (INT8, INT16, INT32, INT64, etc.) As of Fortran 2008 these are contained in the array INTEGER_KINDS but implementation of this seems spotty at present.
If you're still running out of room, you have two choices: reformulate your problem to work within the precision you have or look for an extended- or arbitrary precision math library. Happily, a number of such libraries are listed at LBNL under http://crd-legacy.lbl.gov/~dhbailey/mpdist/
Update:
selected_int_kind is an alternate dynamic means of creating extended precision values, but you still need to know which 'kind' values are accepted by the compiler. For example:
program kind_int
    use iso_fortran_env, only: output_unit, INT8, INT16, INT32, INT64!, &
!        INTEGER_KINDS

    implicit none

    integer :: i

1   format(A)
2   format('Kind name = ', A5, T20, 'kind value = ',I2,                &
        T40, 'maximum = ', I19)
3   format('Available kind values: ', I2, *(', ', I2))
    continue

    write(output_unit, 1) 'Maximum value of supported integer kinds:'
    write(output_unit, 2) 'INT8 ', INT8,  huge(1_INT8)
    write(output_unit, 2) 'INT16', INT16, huge(1_INT16)
    write(output_unit, 2) 'INT32', INT32, huge(1_INT32)
    write(output_unit, 2) 'INT64', INT64, huge(1_INT64)
    write(output_unit, 2) '16   ', 16, huge(selected_int_kind(16))
    write(output_unit, 2) '32   ', 32, huge(selected_int_kind(32))

!    write(output_unit, 3) INTEGER_KINDS

    stop
end program kind_int

gives the following with gfortran on a linux64 system:
Maximum value of supported integer kinds:
Kind name = INT8   kind value =  1     maximum =                                      127
Kind name = INT16  kind value =  2     maximum =                                    32767
Kind name = INT32  kind value =  4     maximum =                               2147483647
Kind name = INT64  kind value =  8     maximum =                      9223372036854775807
Kind name = ik32   kind value = 16     maximum =  170141183460469231731687303715884105727
Kind name = ikxx   kind value = 16     maximum =  170141183460469231731687303715884105727

Selected int kind value =  1           kind value =    1
Selected int kind value =  2           kind value =    1
Selected int kind value =  3           kind value =    2
Selected int kind value =  4           kind value =    2
Selected int kind value =  5           kind value =    4
Selected int kind value =  6           kind value =    4
Selected int kind value =  7           kind value =    4
Selected int kind value =  8           kind value =    4
Selected int kind value =  9           kind value =    4
Selected int kind value = 10           kind value =    8
Selected int kind value = 11           kind value =    8
Selected int kind value = 12           kind value =    8
Selected int kind value = 13           kind value =    8
Selected int kind value = 14           kind value =    8
Selected int kind value = 15           kind value =    8
Selected int kind value = 16           kind value =    8
Selected int kind value = 17           kind value =    8
Selected int kind value = 18           kind value =    8
Selected int kind value = 19           kind value =   16
Selected int kind value = 20           kind value =   16
Selected int kind value = 21           kind value =   16
Selected int kind value = 22           kind value =   16
Selected int kind value = 23           kind value =   16
Selected int kind value = 24           kind value =   16
Selected int kind value = 25           kind value =   16
Selected int kind value = 26           kind value =   16
Selected int kind value = 27           kind value =   16
Selected int kind value = 28           kind value =   16
Selected int kind value = 29           kind value =   16
Selected int kind value = 30           kind value =   16
Selected int kind value = 31           kind value =   16
Selected int kind value = 32           kind value =   16
Selected int kind value = 33           kind value =   16
Selected int kind value = 34           kind value =   16
Selected int kind value = 35           kind value =   16
Selected int kind value = 36           kind value =   16
Selected int kind value = 37           kind value =   16
Selected int kind value = 38           kind value =   16
Selected int kind value = 39           kind value =   -1

With minor modification, the program yields the following using ifort on the same system:
Maximum value of supported integer kinds:
Kind name = INT8   kind value =  1     maximum =                                      127
Kind name = INT16  kind value =  2     maximum =                                    32767
Kind name = INT32  kind value =  4     maximum =                               2147483647
Kind name = INT64  kind value =  8     maximum =                      9223372036854775807

Selected int kind value =  1           kind value =    1
Selected int kind value =  2           kind value =    1
Selected int kind value =  3           kind value =    2
Selected int kind value =  4           kind value =    2
Selected int kind value =  5           kind value =    4
Selected int kind value =  6           kind value =    4
Selected int kind value =  7           kind value =    4
Selected int kind value =  8           kind value =    4
Selected int kind value =  9           kind value =    4
Selected int kind value = 10           kind value =    8
Selected int kind value = 11           kind value =    8
Selected int kind value = 12           kind value =    8
Selected int kind value = 13           kind value =    8
Selected int kind value = 14           kind value =    8
Selected int kind value = 15           kind value =    8
Selected int kind value = 16           kind value =    8
Selected int kind value = 17           kind value =    8
Selected int kind value = 18           kind value =    8
Selected int kind value = 19           kind value =   -1

As Vladimir F suggests, you can get some extra precision by using selected_int_type but it will vary with hardware and compiler and may or may not give you enough precision depending on the problem.


text:
Q: Simple CSS Width Issue i AM new to web development (1 month) and for some reason, a simple CSS issue i am finding hard to understand.
I have 2 DIVs:

        My Company logo/slogan

With CSS:
.full {
    width: 100%;
}

.banner {
    background: red;
    height: 45px;
}

What i don't understanding is, why does DIV with banner not consume the entire page width? Even though its parent, full, has width: 100% ??
I have had to apply margin-left and right to take full width e.g:
http://jsfiddle.net/4eaGv/2/
Thanks

A: It is related with the User agent styles which every browser applies to the html elements by default. To avoid it we need to reset these values. Like in your case you need to reset these values for body element
body
{
    padding:0;
    margin:0;
}

Now try your code. it will work.
Demo

A: This is because the browser applies padding inside a frame. You can overcome this by using a CSS Reset. In your case, simply adding  * { padding: 0; margin: 0 } works.
http://jsfiddle.net/4eaGv/6/

A: You have to set width on the banner div to 100%
.banner {
    background: red;
    height: 45px;
    width: 100%;
}

And if you have some padding, set the padding and margin to html/body to 0.
body
{
   padding: 0;
   margin: 0;
}

http://jsfiddle.net/4eaGv/4/

A: All browsers inherently give certain elements styling.
Just add this CSS to your code :
* {
    margin: 0;
    padding: 0;
    border: 0;
}

Some people leave out border, but I like to put it in because I find IE often adds a border to certain  elements
Updated fiddle : http://jsfiddle.net/4eaGv/3/

A: Web pages by default have a little margin/padding. Most CSS starts with:
html, body {margin: 0; padding: 0}

By the way, if you did that, divs automatically expand to fit their parent containers, i.e. 100% width wouldn't be necessary.

A: You need to reset the body.
body {

margin : 0px !important;
 padding : 0px !important;
}

With your existing css.


text:
Q: Search all of Google with Google Python API I will be using python. My plan is to make a program that searches a bunch of things, and sees how many search results google has for it. But I can only figure out how to get custom search engine to kind of work.
In python, how do I use the Google API to do a simple search using Google's main search engine? As I understand, the answer to this has changed within in the last few years as google has made a push to the google app engine.

A: Recently I was also looking for Google Search API and was misguided by a lot of outdated information. Here is what I found on Google Developers website: https://developers.google.com/api-client-library/python/apis/customsearch/v1
According to the docs your function will be something like
from googleapiclient.discovery import build

def google_results_count(query):
    service = build("customsearch", "v1",
                    developerKey="[put your API key here]")

    result = service.cse().list(
            q=query,
            cx='[put your CSE key here']
        ).execute()

    return result["searchInformation"]["totalResults"]

print google_results_count('Python is awesome')

Unfortunately, using CSE API will give you different result count from the one you get using web search. In the example above I got 2 680 000 in Python and approx. 21 000 000 for the same query on Google.com
Here is an explanation why: https://support.google.com/customsearch/answer/70392?hl=en
Getting the API and CSE keys and all the limitations of CSE is a whole different story, I highly recommend you looking at this answer: https://stackoverflow.com/a/11206266/1704272 and the next one below for the alternatives.
Another approach is to parse the HTML response from Google.com which will give you the most complete results but it is not very reliable because Google changes the HTML markup. And more important this is against their TOS, more to read here: Is it ok to scrape data from Google results?
My conclusion.
You have three options:

*

*Use Google CSE API (free). Use this, if you need to stay legal and you are sure you won't exceed the limit. Can not be used in public application.

*Use paid API (Google or any other, less expensive). It is legal to use this for any public application but be ready to pay for that.

*Scrape Google web page. This will give you the best results but I would use this option only for private needs.


text:
Q: Difference between pthread and fork on gnu/Linux What is the basic difference between a pthread and fork w.r.t. linux in terms of
implementation differences and how the scheduling varies (does it vary ?)
I ran strace on two similar programs , one using pthreads and another using fork,
both in the end make clone() syscall with different arguments, so I am guessing
the two are essentially the same on a linux system but with pthreads being easier
to handle in code.
Can someone give a deep explanation?
EDIT : see also a related question

A: In C there are some differences however:
fork()

*

*Purpose is to create a new process, which becomes the child process of the caller

*Both processes will execute the next instruction following the fork() system call

*Two identical copies of the computer's address space,code, and stack are created one for parent and child.
Thinking of the fork as it was a person; Forking causes a clone of your program (process), that is running the code it copied.

pthread_create()

*

*Purpose is to create a new thread in the program which is given the same process of the caller

*Threads within the same process can communicate using shared memory. (Be careful!)

*The second thread will share data,open files, signal handlers and signal dispositions, current working directory, user and group ID's. The new thread will get its own stack, thread ID, and registers though.
Continuing the analogy; your program (process) grows a second arm when it creates a new thread, connected to the same brain.

A: You should look at the clone manpage.
In particular, it lists all the possible clone modes and how they affect the process/thread, virtual memory space etc...
You say "threads easier to handle in code": that's very debatable. Writing bug-free, deadlock-free multi-thread code can be quite a challenge. Sometimes having two separate processes makes things much simpler.

A: On Linux, the system call clone clones a task, with a configurable level of sharing.
fork() calls clone(least sharing) and pthread_create() calls clone(most sharing).
forking costs a tiny bit more than pthread_createing because of copying tables and creating COW mappings for memory.


text:
Q: Generate Signed APK Wizard generates APK with debugging enabled So after I do generate signed APK wizard in android studio I get an APK file.  But when I try to upload the file to android developer console I get an error saying the file is debuggable.  So my question is how can I get Android Studio to generate an APK that I can upload to the android market?

A:
Support for a true debug build. Developers no longer need to add the
  android:debuggable attribute to the  tag in the manifest
  — the build tools add the attribute automatically. In Eclipse/ADT, all
  incremental builds are assumed to be debug builds, so the tools insert
  android:debuggable="true". When exporting a signed release build, the
  tools do not add the attribute. In Ant, a ant debug command
  automatically inserts the android:debuggable="true" attribute, while
  ant release does not. If android:debuggable="true" is manually set,
  then ant release will actually do a debug build, rather than a release
  build.

remove the android:debuggable="true" tag from the manifest file and generate the signed apk file with the same keystore generated before.
for more details, see here

A: Using Android Studio 0.3.7:
First make sure you have into you <application> entry of the AndroidManifest.xml the following entry android:debuggable="false"
Then go to the Build menu option, and choose "Generate Signed APK". Create a key store or use an existing one, click "Next", change destination if desired. and decide if you want to use ProGuard or not, then click "Finish". And you have now you APK ready for production :).

A: Have you tried to have this in androidmanifest.xml:
<application
    android:debuggable="true"
    . . .>
</application>


text:
Q: How to implement a "pop down" like in gmail I'm trying to implement a pop down panel like on the top bar of Gmail.  If you click on the Setting icon, your name, or the Share link, a panel drops down...is there a jquery plugin or something that will allow me to quickly implement something to give a similar effect?

A: If you want a non jQuery cross browser solution I made this for someone on here yesterday:
http://jsfiddle.net/Paulpro/H4CLU/
It drops down when you click button and hides when you click it again, or anywhere in the document that isn't part of the drop down.
Only thing you'd need to change is probably some CSS stuff to style it nicely.

A: Yes, I suggest to use jQuery (everytime you use JS). It is really easy to create a layer like this:

content

show

A: Here's a jsFiddle that show how you can implement something like this.
Basically, you're capturing clicks on the body element, if they clicked on settings, you show the "panel" div. If they clicked something else, you hide it.
JS:
$(function() {
    $('body').click(function(e) {
        if ($(e.target).attr('id') == 'settings') {
            $('#panel').show();
        } else {
            $('#panel').hide();
        }
    });
});

HTML:
Settings

Option 1

Option 2

Option 3

CSS:
#panel { display: none;  border: 1px solid #000;}


text:
Q: Change the direction of travel of the vertex in a circular Graph With the function Graph and the option GraphLayout --> "CircularEmbedding", i manage to obtain the graph drawn in the way i want.
But, the vertex are given not in the order I want.
How i can change the direction of travel of the vertex in a circular Graph ?
Of course, i can change the order of the list given in argument.
But, if there is an option to direcly change the direction of travel i would be interested.
Thank you in advance for your help

A: In older versions of Mathematica, "CircularEmbedding" used the graph's own vertex ordering to place vertices along the circle.
In more recent versions (I don't recall which, perhaps 12.1?), the layout is optimized to reduce the number of edge crossings. To restore the old behaviour, use
GraphLayout -> {"CircularEmbedding", "OptimalOrder" -> False}

This is in the documentation.
Alternatively, use IGLayoutCircle from my IGraph/M package.
IGraph/M also has a function to easily reorder the vertices of a graph while retaining all graph properties: IGReorderVertices[yourPreferredOrder, graph]. This makes it easy to control the ordering.


text:
Q: Deserialize Json with unknown count plugin I'm trying deserialize Json with unknown count iteration. I get menu structure in this format:
[{
    "id": 15,
    "item": "menuTop",
    "child": {
        "id": 16,
        "item": "subMenu",
        "child": {
            "id": 17,
            "item": "Result",
            "child": null
        }
    }
}]:

It's part of my json, so I have to check the last object that says child: null. Otherwise, it may has got more or less number of iteration.
Here is my code. But it doesn't work. I'm not sure if my class item is correct, especially property child
var result = JsonConvert.DeserializeObject<MenuItem>("mySerializedString");

    class MenuItem
    {
        public long id { get; set; }
        public string item { get; set; }
        public List<MenuItem> child { get; set; }
    }

A: You must deserialize as List<MenuItem> and child must be a MenuItem not List
var result = JsonConvert.DeserializeObject<List<MenuItem>>(json);

class MenuItem
{
    public long id { get; set; }
    public string item { get; set; }
    public MenuItem child { get; set; }
}

UPDATE
As @Alexei Levenkov pointed out to me, and thank you, there are some tools that can create C# classes from a json file.
There are web sites where you can paste your json and it generate the C# classes you need to deserialize your json, for example json2charp
At this Stackoverflow question you can find more infos.


text:
Q: I get fatalExceptionError while uploading file, but file still uploads fine I am uploading image and also sending some parameters with it. I am getting errors in my logcat while doing so.
Here is my code
public class Camera extends Activity {
ImageView ivUserImage;
Button bUpload;
Intent i;
int CameraResult = 0;
Bitmap bmp;
public String globalUID;
UserFunctions userFunctions;
String photoName;
InputStream is;

int serverResponseCode = 0;
ProgressDialog dialog = null;

@Override
protected void onCreate(Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    super.onCreate(savedInstanceState);
    setContentView(R.layout.camera);

    userFunctions = new UserFunctions();
    globalUID = getIntent().getExtras().getString("globalUID");
    Toast.makeText(getApplicationContext(), globalUID, Toast.LENGTH_LONG).show();
    ivUserImage = (ImageView)findViewById(R.id.ivUserImage);
    bUpload = (Button)findViewById(R.id.bUpload);
    openCamera();
}

private void openCamera() {
    i = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
    startActivityForResult(i, CameraResult);
}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {

    super.onActivityResult(requestCode, resultCode, data);

    if(resultCode == RESULT_OK) {
        //set image taken from camera on ImageView
        Bundle extras = data.getExtras();
        bmp = (Bitmap) extras.get("data");
        ivUserImage.setImageBitmap(bmp);

        //Create new Cursor to obtain the file Path for the large image
         String[] largeFileProjection = {
                 MediaStore.Images.ImageColumns._ID,
                 MediaStore.Images.ImageColumns.DATA
         };

         String largeFileSort = MediaStore.Images.ImageColumns._ID + " DESC";
         //final String photoName = MediaStore.Images.ImageColumns.BUCKET_DISPLAY_NAME;
         Cursor myCursor = this.managedQuery(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, largeFileProjection, null, null, largeFileSort);

         try {
             myCursor.moveToFirst();
             //This will actually give you the file path location of the image.
             final String largeImagePath = myCursor.getString(myCursor.getColumnIndexOrThrow(MediaStore.Images.ImageColumns.DATA));
             //final String photoName = myCursor.getString(myCursor.getColumnIndexOrThrow(MediaStore.Images.ImageColumns.BUCKET_DISPLAY_NAME));
             //Log.e("URI", largeImagePath);

             File f = new File("" + largeImagePath);

             photoName = f.getName();

             bUpload.setOnClickListener(new View.OnClickListener() {

                    public void onClick(View v) {
                        dialog = ProgressDialog.show(Camera.this, "", "Uploading file...", true);
                         new Thread(new Runnable() {
                                public void run() {
                                     runOnUiThread(new Runnable() {
                                        public void run() {
                                            //tv.setText("uploading started.....");
                                            Toast.makeText(getBaseContext(), "File is uploading...", Toast.LENGTH_LONG).show();
                                        }
                                     });
                                 if(imageUpload(globalUID, largeImagePath)) {
                                     Toast.makeText(getApplicationContext(), "Image uploaded", Toast.LENGTH_LONG).show();
                                 } else {
                                     Toast.makeText(getApplicationContext(), "Error uploading image", Toast.LENGTH_LONG).show();
                                 }
                                 //Log.e("Response: ", response);
                                 //System.out.println("RES : " + response);
                                }
                              }).start();
                        }
                });
         } finally {
             myCursor.close();
         }
         //Uri uriLargeImage = Uri.withAppendedPath(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, String.valueOf(imageId));
         //String imageUrl = getRealPathFromURI(uriLargeImage);
    }
}

public boolean imageUpload(String uid, String imagepath) {
    boolean success = false;
    //Bitmap bitmapOrg = BitmapFactory.decodeResource(getResources(), R.drawable.ic_launcher);
    Bitmap bitmapOrg = BitmapFactory.decodeFile(imagepath);
    ByteArrayOutputStream bao = new ByteArrayOutputStream();
    bitmapOrg.compress(Bitmap.CompressFormat.JPEG, 90, bao);

    byte [] ba = bao.toByteArray();
    String ba1=Base64.encodeToString(ba, 0);

    ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
    nameValuePairs.add(new BasicNameValuePair("image",ba1));
    nameValuePairs.add(new BasicNameValuePair("uid", uid));

    try {
        HttpClient httpclient = new DefaultHttpClient();
        HttpPost httppost = new HttpPost("http://www.example.info/androidfileupload/index.php");
        httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
        HttpResponse response = httpclient.execute(httppost);
        HttpEntity entity = response.getEntity();
        if(response != null) {
            success = true;
        }
        is = entity.getContent();
    } catch(Exception e) {
        Log.e("log_tag", "Error in http connection "+e.toString());
    }
    dialog.dismiss();
    return success;
}

Here is my logcat
06-23 11:54:48.555: E/AndroidRuntime(30601): FATAL EXCEPTION: Thread-11
06-23 11:54:48.555: E/AndroidRuntime(30601): java.lang.OutOfMemoryError
06-23 11:54:48.555: E/AndroidRuntime(30601):    at java.lang.String.<init>(String.java:513)
06-23 11:54:48.555: E/AndroidRuntime(30601):    at java.lang.AbstractStringBuilder.toString(AbstractStringBuilder.java:650)
06-23 11:54:48.555: E/AndroidRuntime(30601):    at java.lang.StringBuilder.toString(StringBuilder.java:664)
06-23 11:54:48.555: E/AndroidRuntime(30601):    at org.apache.http.client.utils.URLEncodedUtils.format(URLEncodedUtils.java:170)
06-23 11:54:48.555: E/AndroidRuntime(30601):    at org.apache.http.client.entity.UrlEncodedFormEntity.<init>(UrlEncodedFormEntity.java:71)
06-23 11:54:48.555: E/AndroidRuntime(30601):    at com.zafar.login.Camera.imageUpload(Camera.java:155)
06-23 11:54:48.555: E/AndroidRuntime(30601):    at com.zafar.login.Camera$1$1.run(Camera.java:119)
06-23 11:54:48.555: E/AndroidRuntime(30601):    at java.lang.Thread.run(Thread.java:1019)
06-23 11:54:53.960: E/WindowManager(30601): Activity com.zafar.login.DashboardActivity has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView@405db540 that was originally added here
06-23 11:54:53.960: E/WindowManager(30601): android.view.WindowLeaked: Activity com.zafar.login.DashboardActivity has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView@405db540 that was originally added here
06-23 11:54:53.960: E/WindowManager(30601):     at android.view.ViewRoot.<init>(ViewRoot.java:266)
06-23 11:54:53.960: E/WindowManager(30601):     at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:174)
06-23 11:54:53.960: E/WindowManager(30601):     at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:117)
06-23 11:54:53.960: E/WindowManager(30601):     at android.view.Window$LocalWindowManager.addView(Window.java:424)
06-23 11:54:53.960: E/WindowManager(30601):     at android.app.Dialog.show(Dialog.java:241)
06-23 11:54:53.960: E/WindowManager(30601):     at android.app.ProgressDialog.show(ProgressDialog.java:107)
06-23 11:54:53.960: E/WindowManager(30601):     at android.app.ProgressDialog.show(ProgressDialog.java:90)
06-23 11:54:53.960: E/WindowManager(30601):     at com.zafar.login.Camera$1.onClick(Camera.java:110)
06-23 11:54:53.960: E/WindowManager(30601):     at android.view.View.performClick(View.java:2538)
06-23 11:54:53.960: E/WindowManager(30601):     at android.view.View$PerformClick.run(View.java:9152)
06-23 11:54:53.960: E/WindowManager(30601):     at android.os.Handler.handleCallback(Handler.java:587)
06-23 11:54:53.960: E/WindowManager(30601):     at android.os.Handler.dispatchMessage(Handler.java:92)
06-23 11:54:53.960: E/WindowManager(30601):     at android.os.Looper.loop(Looper.java:130)
06-23 11:54:53.960: E/WindowManager(30601):     at android.app.ActivityThread.main(ActivityThread.java:3691)
06-23 11:54:53.960: E/WindowManager(30601):     at java.lang.reflect.Method.invokeNative(Native Method)
06-23 11:54:53.960: E/WindowManager(30601):     at java.lang.reflect.Method.invoke(Method.java:507)
06-23 11:54:53.960: E/WindowManager(30601):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:907)
06-23 11:54:53.960: E/WindowManager(30601):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:665)
06-23 11:54:53.960: E/WindowManager(30601):     at dalvik.system.NativeStart.main(Native Method)
06-23 11:54:55.190: I/Process(30601): Sending signal. PID: 30601 SIG: 9

A: Solution
After adding try and catch inside thread it works. Here is where I added try catch
public void run() {
       try {
                //Toast.makeText(getBaseContext(), "File is uploading...", Toast.LENGTH_LONG).show();
                if(imageUpload(globalUID, largeImagePath)) {
                     Toast.makeText(getApplicationContext(), "Image uploaded", Toast.LENGTH_LONG).show();
                } else {
                     Toast.makeText(getApplicationContext(), "Error uploading image", Toast.LENGTH_LONG).show();
                }
        } catch (Exception e) {

        }

}


text:
Q: How to show multiple image with button click All I'm trying to do is get 20 images (all the same image with the same class name) to appear on the click of a single 'button' (the 'button' is actually a div). I tried trying to hide the 'tick' image themselves and that was a no go, so decided to put the image inside a div, still nothing.
I have searched Stack Overflow for solutions, which I've found a couple of similar things, but nothing does what I need it to.
The Button

Reveal Answers

CSS
.tick, .tick > img{
    width: 40px;
    height: 40px;
    margin: auto;
}
.tick{
    display: none;
}

JS example question with 'tick' in the correct answer
{
      question: "How many different ways are there to commit a Quidditch foul?",
      answers: {
          a: "50",
          b: "150",
          c: "350",
          d: "700

"
      },
      correctAnswer: 'd'
    },

JS
function displayTicks(){
  const divArray =
  Array.from(document.getElementsByClassName('tick'));
  const displayStyle = divArray[0].display.style === 'none' ? 'block' : 'none';
divArray.forEach(div => {
div.style.display = displayStyle;
});
}

I can get them all appear (or not) via the CSS, but I just want to toggle it with the 'reveal' button.

A: the mistake is in this line:
const displayStyle = divArray[0].display.style === 'none' ? 'block' : 'none';

it should be like this:
const displayStyle = divArray[0].style.display === 'none' ? 'block' : 'none';


text:
Q: checkbox checked id and name value push array angularjs I get proper and name values for checkbox by parent ng repeat. Problem is, when checked check box I need to push id and name values in one array. Also if uncheck remove that id and name values.

            <input type="checkbox" class="tableBox" value="{{user.partyId}}" name="{{user.first_name}}" ng-checked="userBox" ng-model="userModel" ng-change="getIndex(user.partyId,user.first_name,userModel)" />

          {{user.first_name}}
          {{user.email}}
          {{user.phone_number}}


text:
Q: Insert certain tag attributes in user input in php I am taking post as input from user. User can input  tag in the post. What I need to do is, if any user input any  tag then I have to insert a class like  and save to database.
How can I do this easy way? I am using strip_tags() to remove all tags except  in user input.

A: You can do that using a regex, but it's hard to find a good one that always works. See this thread.
What you can use, is HTMLPurifier. I use it to cleanup all posted information. You can select which tag to keep, wich attribute to keep for each tag, etc ..

HTML filter that guards against XSS and ensures standards-compliant output.

One thing you can do with HTMLPurifier, is extend the core code and then, for a given tag, extends the class to add a class for each entity.
You can check this (quick) example where user wants to convert this:

This is a paragraph

Another one

Into this:

This is a paragraph

Another one

Edit:
Here is a quick and dirty example that you can test on your own:
<?php

require_once 'lib/library/HTMLPurifier.auto.php';

class HTMLPurifier_AttrTransform_AnchorClass extends HTMLPurifier_AttrTransform
{
    public function transform($attr, $config, $context)
    {
      // keep predefined class
      if (isset($attr['class']))
      {
        $attr['class'] .= ' myclass';
      }
      else
      {
        $attr['class'] = 'myclass';
      }

      return $attr;
    }
}

$dirty_html = '

';

$options = array(
  'HTML' => array(
    'Allowed' => 'a[href|target|class]')
);
$config     = HTMLPurifier_Config::create($options);
$htmlDef    = $config->getHTMLDefinition(true);

$anchor     = $htmlDef->addBlankElement('a');
$anchor->attr_transform_post[] = new HTMLPurifier_AttrTransform_AnchorClass();

$purifier   = new HTMLPurifier($config);

$clean_html = $purifier->purify($dirty_html);

var_dump($clean_html);

It outputs:
string '

' (length=135)

I use a custom configuration to keep some attributes in  tag, that's why it removes style but not target. You can check the documentation about that.


text:
Q: Waiting for web call to finish before continuing code in Unity3d I've read many articles but I don't seem to get it. I have this code working now because I hardcode a 3 second delay so there is enough time for the web call to finish so when the score is displayed there is data. But what I really want is to have the web call finish and THEN display the score. Help ?
 IEnumerator Start()
{
    client = new MobileServiceClient(_appUrl, _appKey);
    table = client.GetTable<Highscore>("Highscores");
    yield return StartCoroutine(ReadItems());
    DisplayScores();
}

void Update()
{

}

public void btn_GoBack()
{
    Application.LoadLevel("StartScene");
}

private void OnReadItemsCompleted(IRestResponse<List<Highscore>> response)
{
    if (response.StatusCode == HttpStatusCode.OK)
    {
        Debug.Log("OnReadItemsCompleted data: " + response.Content);
        List<Highscore> items = response.Data;
        Debug.Log("Read items count: " + items.Count);
        Scores = items;
    }
    else
    {
        Debug.Log("Error Status:" + response.StatusCode + " Uri: " + response.ResponseUri);
    }
}

private IEnumerator ReadItems()
{
    table.Read<Highscore>(OnReadItemsCompleted);
    yield return new WaitForSeconds(3);
}

private void DisplayScores()
{
    txtHighScores.text = "";
    int numberOfScores = Math.Min(Scores.Count, 5);

    for (int i = 0; i < numberOfScores; i++)
    {
        string name = Scores[i].username.ToString();
        string score = Scores[i].score.ToString();

        txtHighScores.text += (i + 1).ToString() + ". " +
                              " - " + name + "\r\n" +
                              score.ToString().PadLeft(4, '0');
    }
}

A: It is important to pass a parameter with Startcorutine method,
Otherwise it gives error.
So try my fix in your code.
 IEnumerator Start()
{
    client = new MobileServiceClient(_appUrl, _appKey);
    table = client.GetTable<Highscore>("Highscores");
    yield return StartCoroutine(ReadItems(2.0f)); //delay
    DisplayScores();
}

IEnumerator ReadItems(float delay)
{
    yield return new WaitForSeconds(delay);
    table.Read<Highscore>(OnReadItemsCompleted);

}

A: *

*Remove the method call for "DisplayScores()" from Start()

*And insert DisplayScores() as the last line of method callback OnReadItemsCompleted

*And then you should remove the line yield return new WaitForSeconds(3);


text:
Q: Bootstrap 3 carousel code I need to create Bootstrap 3 carousel, it needs to have image on the right side of the slide and text on the left side of the slide, but I simply can not make it, whatever code i tried it either bugged or didn't worked.
Tried this:

TEXT

TEXT

TEXT

And it didnot worked. I need something like this http://www.dodaj.rs/f/18/29/4TNTTm5d/untitled.png

A: Found out what was problem, it seems that my .item class was pretty messed up, i fixed it and it worked.


text:
Q: How do I convert my asynctask to Rxjava? I am trying to convert the following 2 asynctasks to rxjava, but not sure how to go about it. Any ideas? :
 new AsyncTask<Void, Void, Void>() {
                @Override
                protected Void doInBackground(Void... params) {

                    /* Shutdown video players */
                    Set<Map.Entry<String, PlayerBundle>> entries = videoPlayerPool.entrySet();
                    for (Map.Entry<String, PlayerBundle> entry : entries) {
                        PlayerBundle bundle = entry.getValue();
                        bundle.player.release();
                    }

                    /* Shutdown audio players */
                    entries = audioPlayerPool.entrySet();
                    for (Map.Entry<String, PlayerBundle> entry : entries) {
                        PlayerBundle bundle = entry.getValue();
                        bundle.player.release();
                    }

                    videoStreamer.stopStream();
                    videoStreamer.release();

                    audioStreamer.stopStream();
                    audioStreamer.release();

                    return null;
                }

                @Override
                protected void onPostExecute(Void aVoid) {
                    cb.event(new Spin.Event<Void>());
                }
            }.execute();

and :
new AsyncTask<Void, Void, Void>() {
            @Override
            protected Void doInBackground(Void... params) {
                Set<Map.Entry<String, Participant>> entries = pool.entrySet();
                for (Map.Entry<String, Participant> entry : entries) {
                    Participant participant = entry.getValue();
                    participant.release();
                }
                return null;
            }

            @Override
            protected void onPostExecute(Void aVoid) {
                cb.event(new Spin.Event<Void>());
            }
        }.execute();

I have already included the rxjava in my gradle, but not sure how to go about converting this

A:     Observable.defer(new Func0<Observable<Void>>() {
        @Override
        public Observable<Void> call() {
            /* Shutdown video players */
            Set<Map.Entry<String, PlayerBundle>> entries = videoPlayerPool.entrySet();
            for (Map.Entry<String, PlayerBundle> entry : entries) {
                PlayerBundle bundle = entry.getValue();
                bundle.player.release();
            }

            /* Shutdown audio players */
            entries = audioPlayerPool.entrySet();
            for (Map.Entry<String, PlayerBundle> entry : entries) {
                PlayerBundle bundle = entry.getValue();
                bundle.player.release();
            }

            videoStreamer.stopStream();
            videoStreamer.release();

            audioStreamer.stopStream();
            audioStreamer.release();

            return Observable.just(null);
        }
    })
    .doOnCompleted(new Action0() {
        @Override
        public void call() {
            cb.event(new Spin.Event<Void>());
        }
    })
    .subscribeOn(Schedulers.computation())
    .subscribe();

    Observable.defer(new Func0<Observable<Void>>() {
        @Override
        public Observable<Void> call() {
            Set<Map.Entry<String, Participant>> entries = pool.entrySet();
            for (Map.Entry<String, Participant> entry : entries) {
                Participant participant = entry.getValue();
                participant.release();
            }
            return Observable.just(null);
        }
    }).doOnCompleted(new Action0() {
        @Override
        public void call() {
            cb.event(new Spin.Event<Void>());
        }
    })
    .subscribeOn(Schedulers.computation())
    .subscribe();