text:
Q: How to make a sensor bypass a resistor? I have a very basic circuit question.
I bought these LED bracelets with the intent of modifying them. The idea is to make it so the LED brightness would be dimmer than normal when switched on (by adding a resistor in series.) Then I would have a vibration sensor that would make the LEDs go back to normal brightness when it senses motion.
I thought that if I added the sensor in parallel with the resistor, it would bypass the resistor, since the circuit would choose the path of least resistance.
I got the resistor to dim it the way I want, but the sensor in parallel doesn't seem to do anything. I tested the sensor separately so I know it works. What's the right way to do this?
Additionally, in testing the sensor separately, I observed that the LED only stays on for a fraction of a second. What can I do to make the lights stay on longer, like at least half a second?
The bracelet has another switch mode to make the lights slow fade on and off. If there was a way for it to toggle a single slow fade on/off on motion, that would be  a desired behavior too, but I wouldn't know how to do that.
The board has a 6V battery, 2 LEDs, 2 resistors, 1 capacitor, and a 6pin chip, though I don't know in what order they are.
This is the vibration sensor I got. It has a spring in a cylinder with 2 pins. uxcell SW-58010P High Sensitivity Spring Electronic Vibration Sensor Switch Straight Pin 10Pcs

A: This appears to be what is inside your sensor.
The centre conductor makes contact with the spring when the sensor is touched.

On resistance is probably low - in the order of a few ohms - but occurs intermittently and for short periods. To alter an LEDs brightness you need to extend the period for which the vibration sensing lasts.

A low tech solution would be to have the sensors turn on a relay with a capacitor across the relay coil to hold the relay on. This is functionally the same as the circuit below but uses fewer and simpler to use parts. The relay requires as low an operate current as practical.  I can specify component values for an example circuit if this is of interest.
R1 is shown as a short circuit. Using sat 10 Ohms here will reecuce capacitor inrush current and possibly increase sensir lifetime.
The relay could be a miniature reed relay.
Example only This reed relay in stock at Digikey for $1.91 in 1's, operates at <= 3.75V and releases at >= 0.5V and draws 10 mA at 5V coil voltage. C1 of 1000 uF will probably give you in the 0.5 1s hold in time with a 5V battery. Size is ~~= 20 x 5 x 8 mm - nit utterly tiny but probably bearable.
You could wind your own using a reed switch - many turns of fine wire on the switch body - posiblywith manet biasing to get more sensitivity.

simulate this circuit – Schematic created using CircuitLab

Here is a simple circuit that would probably meet your need.
MOSFET NFET1 is turned on when its gate is pulled high by sensor closure.
C1 charges almost instantaneously to battery voltage.
When the switch opens C1 keeps the FET turned on and is discharged by R3.
R3 and C1 together control the "bright up" period.
LED current is limited by R1 and R2 in series.
When the FET is on it shorts R2 and allows increased LED current.
R4 is shown as 0 Ohms - a wire link - if desired a low resistor value would limit sensor current and possibly proling its lifetime.
FET NFET1 is almost any small N Channel MOSFET - we can discuss suitable FETs if you wish to proceed with this design.
Cost of components other than battery, LED, sensor and on/off switch is not much over $1. The switch can be obtained from  scrap electronic equipment or toys. If bought new it might cost as much as the other small parts combined, depending on source.

simulate this circuit

A: I love Russell McMahon's idea, it's definitely the right way to go, but if you want to try something simpler:

simulate this circuit – Schematic created using CircuitLab
It needs a big capacitor to work properly, a super-capacitor, and R3 must be beefy too, at 1W.
When vibrations happen, the sensor switch closes, discharging the capacitor, bringing the voltage across it to 0V, maximising the current through the LED.
When vibrations stop, and the sensor switch is open, the capcitor slowly charges, reducing the total voltage available for the R1 and the LED, dimming the LED.
Discharging is about 50 times faster (with the values of R2 and R3 shown), so the effect will be that the capacitor takes a couple of seconds to discharge (for maximum brightness) but a lot longer to charge again, dimming the LED.
This circuit is horribly inefficient, and R3 will get hot, but it could work.


text:
Q: Fill incomplete time series in data.table Question: In data.table is there any way to fill an incomplete date sequence with zeros? For instance, in the toy example some dates does not show up and I want to have a complete date sequence with y = 0 for these cases. Is there something like a forward fill?
Remark: Note I do not want to use merges where you create first the full date sequence and then merge it back to the initial data.table object (I think this is inefficient and rather slow).
library(data.table)

dt <- data.table(
  x = c("2020-03-28", "2020-03-29", "2020-03-31", "2020-04-05"),
  y = c(1, 5, 3, 70)
)

## Output:
            x  y
1: 2020-03-28  1
2: 2020-03-29  5
3: 2020-03-31  3
4: 2020-04-05 70

## Desired Output:
            x  y
1: 2020-03-28  1
2: 2020-03-29  5
3: 2020-03-30  0
4: 2020-03-31  3
5: 2020-04-01  0
6: 2020-04-02  0
7: 2020-04-03  0
8: 2020-04-04  0
9: 2020-04-05 70

A: How about this?
# convert to data.table's integer date type
dt[ , x := as.IDate(x)]
# find the range of dates
date_bounds = range(dt$x)
# construct a sequence of all dates
#   NB: this will be integers as attributes are stripped
all_dates = date_bounds[1L]:date_bounds[2L]

# construct a table with the missing dates,
#   with y filled to 0
missing = data.table(
  # as.IDate uses the right origin for integer input
  x = as.IDate(setdiff(all_dates, dt$x)),
  y = 0
)

dt = rbind(dt, missing)
#             x     y
#        <IDat> <num>
# 1: 2020-03-28     1
# 2: 2020-03-29     5
# 3: 2020-03-31     3
# 4: 2020-04-05    70
# 5: 2020-03-30     0
# 6: 2020-04-01     0
# 7: 2020-04-02     0
# 8: 2020-04-03     0
# 9: 2020-04-04     0

Afterwards you can setorder(dt, x) if you want the dates to be in order

A: Use CJ and tidyr::full_seq to create a join data table.
dt[, x := as.Date(x)]                               # convert x to the Date type
dt2 <- dt[CJ(x = tidyr::full_seq(x, 1)), on = .(x)] # create the full sequence
dt2[is.na(y), y := 0]                               # fill NAs with 0s
dt2

#             x  y
# 1: 2020-03-28  1
# 2: 2020-03-29  5
# 3: 2020-03-30  0
# 4: 2020-03-31  3
# 5: 2020-04-01  0
# 6: 2020-04-02  0
# 7: 2020-04-03  0
# 8: 2020-04-04  0
# 9: 2020-04-05 70

A: You could use complete from tidyr :
library(dplyr)
library(tidyr)

dt %>%
  mutate(x = as.Date(x)) %>%
  complete(x = seq(min(x), max(x), by = "day"), fill = list(y = 0))

#     x           y
#  <date>     <dbl>
#1 2020-03-28     1
#2 2020-03-29     5
#3 2020-03-30     0
#4 2020-03-31     3
#5 2020-04-01     0
#6 2020-04-02     0
#7 2020-04-03     0
#8 2020-04-04     0
#9 2020-04-05    70

A: You could also try this:
dt[, x := as.IDate(x)]
dt[.(seq(min(x), max(x), 1)), .(y = fifelse(is.na(y), 0, y)), .EACHI, on = "x"]

#             x     y
# 1: 2020-03-28     1
# 2: 2020-03-29     5
# 3: 2020-03-30     0
# 4: 2020-03-31     3
# 5: 2020-04-01     0
# 6: 2020-04-02     0
# 7: 2020-04-03     0
# 8: 2020-04-04     0
# 9: 2020-04-05    70

redpajama_set_name: RedPajamaStackExchange


text:
Q: ECMAscript export in Node.js Im creating an NFL football simulator in nodejs and am having trouble exporting one of my variables.  As you can see in my get_teams.js i make many HTTP requests.  I then process the responseArr and format the data.  Where I am running into an issue is when I try and export the sorted_teams_array.  you can find this code at the very bottom of get_teams.js.
I then try and import this array into tester.js and console log it.  I will eventually use this file to inject a mongo database with the array, but for now am just trying to console log it and cannot get it to work.  I am using the --experimental-modules in my npm scripts when I run npm run tester, and still nothing.  Any help would be great!  I am a noobie so please no hate!
get_teams.js
import axios from 'axios';
import Nfl_team from '../models/teamModel.js';
import Offensive_stats from '../models/offensiveStatsModel.js';
import Defensive_stats from '../models/defensiveStatsModel.js';
import Game_stats from '../models/gameStatsModel.js';
import colors from 'colors';
import dotenv from 'dotenv';
dotenv.config();

const teams = {};

function get_teams() {
  axios.all([
    axios.get(`https://api.sportsdata.io/api/nfl/fantasy/json/Standings/${process.env.SEASON}?key=${process.env.API_KEY}`),

    // ... many more gets

  ])
  .then(function (responseArr) {

    responseArr[0].data.forEach(element => {
        teams[element.Team] = new Nfl_team(element.Team, element.Name, element.Wins, element.Losses, element.Ties,
          element.Percentage, element.DivisionWins, element.DivisionLosses, element.DivisionTies,
          element.PointsFor, element.PointsAgainst)
    });

    // many more forEach blocks on responseArr[1, 2, 3...]

    /* power rating algorithm logic
    _____________________________________________ */

   const teams_array = Object.entries(teams);

   export const sorted_teams_array = teams_array.sort((a, b) => {
      if (a[1].average_victory_margin > b[1].average_victory_margin) return -1;
      if (a[1].average_victory_margin < b[1].average_victory_margin) return 1;
      return 0;
    })

    console.log(sorted_teams_array);

    teams_array.forEach(element => {
      console.log(`average victory margin for ${element[0]} = ${element[1].average_victory_margin}`)
    });

  })
  .catch(function (error) {
    // handle error
    console.log(error);
  })
}

get_teams();

tester.js
import { sorted_teams_array } from './get_teams';

console.log(sorted_teams_array);

/// returns
(node:58769) ExperimentalWarning: The ESM module loader is experimental.
internal/modules/esm/resolve.js:61
  let url = moduleWrapResolve(specifier, parentURL);
            ^

Error: Cannot find module /Users/jojovera/Documents/nflSIMULATION/teams/get_teams imported from /Users/jojovera/Documents/nflSIMULATION/teams/tester.js
    at Loader.defaultResolve [as _resolve] (internal/modules/esm/resolve.js:61:13)
    at Loader.resolve (internal/modules/esm/loader.js:94:40)
    at Loader.getModuleJob (internal/modules/esm/loader.js:240:28)
    at ModuleWrap.<anonymous> (internal/modules/esm/module_job.js:42:40)
    at link (internal/modules/esm/module_job.js:41:36) {
  code: 'ERR_MODULE_NOT_FOUND'
}

package.json
{
  "name": "optionsscript",
  "version": "1.0.0",
  "description": "",
  "main": "app.js",
  "type": "module",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "start": "node --experimental-modules app.js",
    "afc_west": "node --experimental-modules ../nflSIMULATION/teams/afc_west.js",
    "get_teams": "node --experimental-modules ../nflSIMULATION/teams/get_teams.js",
    "tester": "node --experimental-modules ../nflSIMULATION/teams/tester.js",
    "get_offensive_stats": "node --experimental-modules ../nflSIMULATION/teams/get_offensive_stats.js",
    "get_defensive_stats": "node --experimental-modules ../nflSIMULATION/teams/get_defensive_stats.js",
    "get_victory_margin": "node --experimental-modules ../nflSIMULATION/teams/get_victory_margin.js",
    "power_rank": "node --experimental-modules ../nflSIMULATION/teams/power_rank.js"
  },
  "author": "",
  "license": "ISC",
  "dependencies": {
    "axios": "^0.21.0",
    "cheerio": "^1.0.0-rc.5",
    "colors": "^1.4.0",
    "dotenv": "^8.2.0",
    "express": "^4.17.1",
    "jsonwebtoken": "^8.5.1",
    "nodemon": "^2.0.6",
    "stats-lite": "^2.2.0",
    "terminal-kit": "^1.44.0",
    "tofixed": "^1.0.0"
  }
}

A: As addressed in the comments and chat, there were two issues: ESM isn't supported in Node 12, so an update to 15 fixed that. The other issue is that nothing was validly exported from get_teams: import and export are top-level keywords, and the export was taking place inside a .then. These minor changes allow the function to be imported and its result used in the tests:
export function get_teams() {
  return axios.all([
    /// rest of code

      return sorted_teams_array;
    })
    .catch(function (error) {
      // handle error
      console.log(error);
    })
}

Usage example:
import { get_teams } from './get_teams'

get_teams.then((teams) => {
  teams.forEach(console.log)
})


text:
Q: Who am I at the server side of Google RPC (gRPC)? I am authenticating the client using gRPC's client-side SSL/TLS. How do I find out on the server side which user it is?

A: Use context->Auth_Context()->FindPropertyValues("x509_pem_cert") in C++ to get the peer's (client's) certificate and the client id (SAN?) in the cert.


text:
Q: Adding tensorboard to federated setting I am new in using TensorBoard, and I want to add it to this project:
https://github.com/TalwalkarLab/leaf
My specific case is the FE-MNIST model, which is in here:
https://github.com/TalwalkarLab/leaf/blob/master/models/femnist/cnn.py
The challenge of adding tensorboard to Federated Setting for people who do not know the setting is that in here, have a server that aggregate the models, and we have random number of clients that does the training, and they have a Client_id.
I want to have a tensorboard folder for each of the clients, and log for the server model (which no training is done there)
I want to know how to access layers weights and biases, and store them based on the client ids, which is the place that is calling the training.
I have seen How do I use tensor board with tf.layers?
in here it says that we can use
Code
for var in tf.trainable_variables():
    tf.summary.histogram(var.name, var)
merged_summary = tf.summary.merge_all()

(which I am not sure where should I add it)
How can I pass the client id to a session, so it can store in the respective folders?

A: You can check the usage of tensorboard here.
In Tensorflow 2.x, Based on the documentation:
When training with Keras's Model.fit(),
Adding the tf.keras.callbacks.TensorBoard callback ensures that logs are created and stored. Additionally, enable histogram computation every epoch with histogram_freq=1
model = create_model()
model.compile(optimizer='adam',
              loss='sparse_categorical_crossentropy',
              metrics=['accuracy'])

log_dir = "logs/fit/" + datetime.datetime.now().strftime("%Y%m%d-%H%M%S")
tensorboard_callback = tf.keras.callbacks.TensorBoard(log_dir=log_dir, histogram_freq=1)

model.fit(x=x_train,
          y=y_train,
          epochs=5,
          validation_data=(x_test, y_test),
          callbacks=[tensorboard_callback])

Or another option is
def add_hist(train_vars, step):
    for i in train_vars:
        name = i.name.split(":")[0]
        value = i.value()
        tf.summary.histogram(name, value, step)

for epoch in range(EPOCHS):
  for (x_train, y_train) in train_dataset:
    train_step(model, optimizer, x_train, y_train, epoch)
  with train_summary_writer.as_default():
    tf.summary.scalar('loss', train_loss.result(), step=epoch)
    tf.summary.scalar('accuracy', train_accuracy.result(), step=epoch)
    add_hist(model.trainable_variables, epoch)


text:
Q: value is not updating in the firebase using react I am trying to update a value in the firestore but it isn't working. I could retrieve the same data from the firebase but just couldn't update it. In the same way i have updated another document in another page but this isn't updating.
I have almost thought of it in all different way but could not get the solution.
How it should work:
i retrieve a number (loc_qty) from the firestore and i should increment and store it back in the same field
How actually it works:
i am able to retrieve a number (loc_qty) from the firestore and i am able to increment it but couldn't store back the new value that is incremented
The following is the corresponding code:
const [{ basket, user }, dispatch] = useStateValue();
var qty = 0;
var local_qty = 0;

const addtoBasket = () => {

  db.collection('users').doc(user.uid).collection('products_loc_qty').doc(props.id).onSnapshot((snapshot) => {
    qty = snapshot.data().loc_qty;
  })
  local_qty = qty + 1;

  if (props.quantity >= local_qty) {
    console.log(local_qty, props.id, user.uid)

    db.collection('users').doc(user.uid).collection('products_loc_qty').doc(props.id).update({
      loc_qty: parseInt(local_qty),
    })

    dispatch({
      type: 'ADD_TO_BASKET',
      item: {
        id: props.id,
        title: props.title,
        price: props.price,
        rating: props.rating,
        image: props.image,
        quantity: 1
      }
    });
  }
}

I would be very glad if anyone could help me out .. stuck here all evening


text:
Q: parse results in MySQL via REGEX I'm a bit confused on the functionality of the REGEX support for MySQL and I have yet to find a solid example on how to separate a result with REGEX within an sql statement.
Example:
How could I pull data from a table emails that looks something like...
+-------------------------+
|Emails                   |
|-------------------------|
|Some.email@yourDomain.com|
+-------------------------+

and return something through an sql statement that looks like...
+------------------------------+
|Username   |  Domain    | TLD |
|-----------|------------|-----|
|some.email | yourdomain | com |
+------------------------------+

A: MySQL doesn't have built-in functionality to do what you're asking for. It would be possible by defining some new functions, but it's probably easier to just do it in whatever programming language you're accessing the database through.
For something as simple as an email address though, you shouldn't need to use regular expressions at all, you can use the SUBSTRING_INDEX() function, as:
SELECT
    SUBSTRING_INDEX(email, '@', 1) AS Username,
    SUBSTRING_INDEX(SUBSTR(email, LOCATE('@', email)), '.', 1) AS Domain,
    SUBSTRING_INDEX(email, '.', -1) AS TLD
FROM users;

In words, that's:

*

*Username = everything before the first '@'

*Domain = everything between the first '@' and the first '.'

*TLD = everything after the last '.'

A: You can also try,
select substring_index(email, '@', 1) username
       ,substring_index(substring_index(email, '@', -1), '.',1) domain
       ,substring_index(email, '.', -1) tld
from
( select 'Some.email@yourDomain.com' email ) E

Uses only substring_index. 1st substring_index everything to the left of '@', 3rd (inner substring_index) to the right of '@' which then parsed by 2nd substring to get domain, and finally last one pulls everything to the right of '.'


text:
Q: Hide some products from woo-commerce products list I have a specific product type that I want to hide from Product Listing page for admins. Each product is basically a dynamically created product by our customers. We want to receive orders against them but don't want them to populate our listing here.

A: In your screenshot, there is not specified particular product hide based on category/Tag-based. You can hide products using the "Catalog Visibility" setting. If the product creating  dynamically then you should pass "catalog visibility" hidden value so that product is not listed

We can use the following code snippet added to the functions.php file to hide the product from the shop page:
/**
 * Hide WooCommerce product by category from the shop page.
 *
 * @param $q
 */

add_action( 'woocommerce_product_query', 'njengah_hide_product_by_category_shop_page' );

function njengah_hide_product_by_category_shop_page( $q ) {

    $tax_query = (array) $q->get( 'tax_query' );

    $tax_query[] = array(
           'taxonomy' => 'product_cat',
           'field' => 'slug',
           'terms' => array( 'uncategorised','auto-parts'), // Don't display products in the 'auto parts' category on the shop page.
           'operator' => 'NOT IN'
    );

    $q->set( 'tax_query', $tax_query );

}


text:
Q: How to write a unit test spec for a provider using http request in ionic2? I want to test my provider class, so I am unable to write spec for providers.
My provider is as follows:
service.ts
//imports are done correctly.

@Injectable()
export class Service {

   constructor(private http: Http) { }

    getGoogle():Observable<any> {
        console.log("Inside service");
        return this.http.get('https://jsonplaceholder.typicode.com/posts/1');
    }
}

My page.ts is as follows:
page.ts
//imports are done correctly.

export class Page1 {

  constructor(private service: Service, private navCtrl: NavController) { }
  async get() {
    console.log("inside get method");
    const data =  await this.service.getGoogle().toPromise();
      console.log('The response is' , data);
       }
}

service.spec.ts
//imports are done correctly

describe('Service', () => {
    let comp: Service;
    let fixture: ComponentFixture<Service>;
    let de: DebugElement;

    beforeEach(async(() => {
        TestBed.configureTestingModule({
            declarations: [],
            imports: [
                IonicModule.forRoot(Service)

            ],
            providers: [Http]
        }).compileComponents();

    }));
    beforeEach(() => {
        fixture = TestBed.createComponent(Service);
        comp = fixture.componentInstance;
        de = fixture.debugElement;
    });
    afterEach(() => {
        fixture.destroy();
    });
it('test the http request to te server', ()=>{
             //code to test http request of the Service class

});

});

All the imports are done correctly, only the logic to test the getGoogle() with http.get() needs to be tested.
Please help or share some links or tell me some steps in order to do testing of this ionic2 content.
Thank you

A: This Rangle tutorial is a great place to start.
You can mock your providers like this
class MockService {
  public data = 'Test data';

  getGoogle() {
    return Observable.of(this.data);
  }
}

Provide it to TestBed
TestBed.configureTestingModule({
  declarations: [
    Page1
  ],
  providers: [
    { provide: Service, useClass: MockService }
  ]
});

And use tick and fakeAsync to simulate the async operation
it('should get', fakeAsync(() => {
  comp.get();
  tick();
  // If you want to assign the data to a class variable. If not, change the
  // condition for whatever you want to test the method to do.
  expect(comp.data).toEqual('Test data');
}));


text:
Q: What would it take to spark through electrical tape? Forgetting for a moment that wires can get hot, and that electrical tape can melt because of it: I've been wondering how much voltage/amperage it would take to spark through your standard house hold electrical tape. While the electrical tape is an insulator, nothing is a perfect insulator, right? It's just a matter of resistance, isn't it?

A: You're looking for the dielectric breakdown voltage of electrical tape. For this 3M brand it's 10kV.
So, if you get to about 10,000 volts, it'll spark through. For the equivalent thickness of air (0.216mm) it would only take 648 volts to spark.
Once it's been sparked through once, the insulating properties for that spot are probably greatly reduced. It'd require much less to spark through the same spot again.
The resistance is another matter. It's rated at 1e6 megohms, so some very very small current will flow at any voltage.


text:
Q: How can I rectify my selection and insertion sort algorithms I wrote selection and insertion sort algorithms that are giving me wrong unsorted outputs. Here is my code for the selection sort:
public class SelectionSort {

    public static void main(String[] args) {

        int[] arr = {23,43,45,3,54,55,23,12,22};

        int min;
        int temp = 0;

        for(int i = 0; i < arr.length-1; i++)
        {
            min = i;
            for(int j = i+1; j<arr.length; j++)
            {
                if(arr[j] < arr[min])
                {
                    min = j;

                }
                temp = arr[j];
                arr[j] = arr[min];
                arr[min] = temp;
            }

        }

        for(int i = 0; i < arr.length; i++)
        {
            System.out.print(arr[i]+" ");
        }

    }

}

Output: 45 55 54 43 23 23 22 12 3

This is not sorted and I want it to sort in ascending order.
Here is my insertion sort:
public class Insertion {

    public static void main(String[] args) {

        int[] arr = {2,4,6,5,4,3,5,3};

        for(int i = 1; i < arr.length; i++)
        {
            int temp = arr[i];

            int j = i;

            while( j > 0 && arr[j-1] > arr[j])
            {
                arr[j] = arr[j-1];
                j = j-1;
            }
            arr[j] = temp;
        }

        for(int i = 0; i < arr.length; i++)
        {
            System.out.print(arr[i] + " ");
        }

    }
}

Output: 2 4 5 4 3 5 3 6

A: In your selection sort, let's focus on this part of the code:
    for(int i = 0; i < arr.length-1; i++)
    {
        min = i;
        for(int j = i+1; j<arr.length; j++)
        {
            if(arr[j] < arr[min])
            {
                min = j;

            }
            temp = arr[j];   // <---
            arr[j] = arr[min];
            arr[min] = temp;
        }
    }

The high-level idea behind selection sort is to find the smallest element in the range [i, n) and then swap it with the element at position i. Notice that with the code you have here, you're constantly swapping the current index with the index of the min, which isn't the swap that you want to make. As a hint, make at most one swap per iteration of the outer loop, and have that swap be between position i and position min. If you're swapping earlier than this, you'll get the wrong answer.
For your insertion sort, there's a more subtle error. Here's where the error is:
while( j > 0 && arr[j-1] > arr[j])
{
    arr[j] = arr[j-1];
    j = j-1;
}
arr[j] = temp;

Notice that whenever the current element compares less than the element before it, you overwrite the current element with the element before it, then decrement j. However, you don't update arr[j-1] with the current element, so in the next comparison, you're comparing the element that used to be in position j-1 with the element that's in position j-2, rather than comparing the current element against the element in position j-2. To fix this, update the comparison to always compare against temp rather than arr[j]:
while( j > 0 && arr[j-1] > temp)
{
    arr[j] = arr[j-1];
    j = j-1;
}
arr[j] = temp;


text:
Q: Check if a child PID is waiting for an Scanf I have a code that in some point fork a child.
The child only code is a scanf.
The parent process needs to monitor the state of tis child process:
1) running
2) waiting for input in scanf
3) terminated
Check for termination or not is simples with waitpid and WNOHANG. The problem is that i dont know how to distinguish if the child process is waiting for input or not.
PS.: My case have a limitation that i cannot send information from child to its parent. Otherwise i could just use variables before and after the scanf.
PS.: I'm under linux
How can i check if a child process entered in a state of waiting for a scanf input ( or IO in general ) ?

A: Are you using <Windows.h>? Is this what you're trying to find?

WaitForInputIdle
Waits until the specified process has finished processing its initial input and is waiting for user input with no input pending, or until the time-out interval has elapsed.

HANDLE hProc;
// get hProc here
WaitForInputIdle(hProc, INFINITE); // wait forever until input idle
// do something here

More info about the API can be found here:
https://msdn.microsoft.com/en-us/library/windows/desktop/ms687022(v=vs.85).aspx

A: The concepts of processes and IO are generally disjunct. There are no signals that are exchanged between child and parent process, except for unix (kill) signals sent to the parent pid, that propagate to the children.
Waitpid just waits for termination of a child pid, returning its status code.
If you want to exchange data between parent and child you need to create a pipe (see man -s 2 pipe) between both processes, see the manual page for an example.
If you want to use scanf (input from stdin) in the child, you need to bind the pipefd[0] to the stdin file descriptor 0 (or STDIN_FILENO).
Now you can use select or poll in the parent process to check if the child is ready to read data sent by the parent to pipefd[1].
If you use printf or some other stdio.h method to write to the child (via STDOUT_FILENO for example), the IO on the parent might block anyway, even if select or poll told that the child is ready to receive the data, if the child reads too slow or stops reading too early and the output buffer is full (which has a default size of 4096 bytes, I think).
A unistd.h write call might return a value
nw = write(pipefd[1], buffer, nbytes);

nw < nbytes if the child did not read that many (nbytes) bytes of input.
So be carefull with the tripping hazards when doing asynchronous communication. Check the CSP (Communicating Sequential Processes) method as a different and more stable approach to communication, that uses synchronous communication, when you understood the asynchronous methods.


text:
Q: animateWithDuration not being run at all I have a ViewController WITHOUT autolayout, and I'm trying to animate some of the buttons. I have some UIView animateWithDuration code in the ViewDidAppear, and everything there works great. But when I want to animate the view out, nothing animates.
Here's the code sequence. Button tapped, calls loginFacebook, that logs into Facebook and then [self doneWithLogin] is called. :
- (IBAction)loginFacebook:(id)sender {
        [self loginFacebook];
}

-(void)loginFacebook{
    //Login to Facebook to get name, photo

    NSArray *permissions = [[NSArray alloc] initWithObjects:
                            @"user_photos",
                            @"user_status",
                            nil];

       [FBSession openActiveSessionWithReadPermissions:permissions
                                       allowLoginUI:YES
                                  completionHandler:^(FBSession *session,
                                                      FBSessionState state,
                                                      NSError *error) {

                                      if(!error){

                                          [self getFacebookData];
                                      }
                                      if(error){

                                          UIAlertView *alert = [[UIAlertView alloc] initWithTitle: @"Oops." message: @"Something went wrong with Facebook." delegate: nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
                                          [alert show];

                                      }

                                  }];

}

-(void)getFacebookData{
    if (FBSession.activeSession.isOpen) {
        [[FBRequest requestForMe] startWithCompletionHandler:
         ^(FBRequestConnection *connection,
           NSDictionary<FBGraphUser> *user,
           NSError *error) {
             if (!error) {

                 UserData *userData = [UserData sharedManager];
                 userData.userName = user.name;
                   NSString *photo = [NSString stringWithFormat:@"https://graph.facebook.com/%@/picture?type=square", user.username];

                 userData.userPhoto = photo;

                 //now store data in nsuserdefault
                 NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];

                 [defaults setObject:userData.userName forKey:@"name"];
                 [defaults setObject:userData.userPhoto forKey:@"photo"];

                 [defaults synchronize];

                 //should show animations and user info
                 [self doneWithLogin];

             }
             if(error){
                                 UIAlertView *alert = [[UIAlertView alloc] initWithTitle: @"Oops." message: @"Something went wrong with Facebook." delegate: nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
                 [alert show];

             }
         }];

    }

}

-(void)doneWithLogin{
[SVProgressHUD dismiss];
UserData *userData = [UserData sharedManager];
NSLog(@"done with login called");
   NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];

[defaults setObject:@"YES" forKey:@"loggedIn"];
[[NSUserDefaults standardUserDefaults] synchronize];

NSLog(@"animation starting");
[UIView animateWithDuration: 1.0f
                      delay: 0.0f
                    options: UIViewAnimationOptionCurveEaseIn
                 animations:^{
                     logo.alpha = 0.0;
                     facebookButton.alpha = 0.0;
                     twitterButton.alpha = 0.0;
                     guestButton.alpha = 0.0;

                     NSLog(@"animation started");
                 }
                 completion:^(BOOL finished){
                     statusLabel.numberOfLines = 2;
                     statusLabel.lineBreakMode = NSLineBreakByWordWrapping;
                     statusLabel.text = [NSString stringWithFormat:@"Have a good time, %@", userData.userName];
                     [UIView animateWithDuration: 0.7f
                                            delay: 0.0f
                                          options: UIViewAnimationOptionCurveEaseIn
                                       animations:^{

                                           statusLabel.alpha = 1.0;
                                       }
                                       completion:^(BOOL finished){
                                           [self performSelector:@selector(dismissView:) withObject:self afterDelay:1];

                                       }
                                ];
                 }];

}
The animation starting log appears, but the animation started log doesn't. Nothing animates, and then after some time the dismissView selector is called.
Any idea what's going on?

A: Are you sure you're on the main queue in doneWithLogin? I'm not familiar with the FB APIs, but when I see flakey UIKit code, that is one of the first things I check.


text:
Q: New-AzureRmADGroup doesn't have a way to indicate if a group is security enabled? I feel like I am missing something.  I am looking to use New-AzureRmADGroup to create new groups in bulk -- the issue is I cannot see how to enable or disable a group as security enabled.  Is this not possible?

A: AFAIK the command you are using New-AzureRmADGroup will always create a Security group.
So if you check the created group's properties using PowerShell, you will always find SecurityEnabled: True
You can create another type of group, i.e. an "Office 365" group using Azure Portal or a completely different PowerShell command (also a different module) i.e. New-UnifiedGroup (documentation)
Here's a quick link to Microsoft Documentation on creating Azure AD Groups and the two types. (Link)

*

*Security groups are good to manage access to Azure resources as a group instead of individual users. More info here: Manage access to resources with Azure Active Directory groups

*If you're interested in Office 365 groups and related PowerShell Commands, more info here: Office 365 Groups and Manage Office 365 Groups with PowerShell


text:
Q: how to resolve this error in promtheus.yml file Facing error in promtheus.yml file

"Error loading config (--config.file=/etc/prometheus/prometheus.yml)" file=/etc/prometheus/prometheus.yml err="parsing YAML file /etc/prometheus/prometheus.yml: yaml: line 7 field static config not found in type config.scrapeconfig

this is my prometheus.yml file
global:
  scrape_interval: 5s
  external_labels:
    monitor: 'devopsage-monitor'
scrape_configs:
  - job_name: 'prometheus'
    static_configs:
      - targets: ['localhost:9090']   # your server ip
  - job_name: 'node-exporter'
    static_configs:
      - targets: ['localhost:9100']   # your server ip

A: You can try this configuration to solve this problem.

global:
  scrape_interval: 5s
  external_labels:
    monitor: 'devopsage-monitor'
scrape_configs:
  - job_name: 'prometheus'
    static_configs:
      - targets:
          - localhost:9090   # your server ip
  - job_name: 'node-exporter'
    static_configs:
      - targets:
          - localhost:9100   # your server ip


text:
Q: How to parallelize gsub currently in a for loop in R? I'm fairly new to trying to run parallel processes in R because most of the data I work with just isn't that large. However, I am no working with a larger set of data where I am attempting to 'find and replace' a set of about 2000 names from 9000 survey comments. I've created a for loop using gsub that gets the job done, but it takes quite a long time:
completed <- 0

for (name in names){
  text_df$text <- sapply(text_df$text, gsub, pattern=paste0("(?<=\\W|^)", name, "(?=\\W|$)"), replacement="RemovedLeader", ignore.case=TRUE, perl=TRUE)
  completed <- completed + 1
  print(paste0("Completed ", completed," out of ", length(names)))
}

From what I understand, this should be a fairly simple process to run in parallel, yet I'm having a bit of trouble. I've tried running this using parSapply, but I'm having a hard time re-writing the gsub (which itself is currently in an sapply in the for loop) to work outside of the for loop. Thanks for the help.

A: This is not a task for parallelization yet.
Since you have to reapply again and again the name replacements.
apply-Family functions are using lists and lists are very slow in R.
Avoid lists, by using vectorization.
In this special case I would advise:
Gain speed by putting all speed work to the regex module.
E.g. take the 200 names and put them into one regex search pattern.
names <- c("a", "b", "c", "d", "e")
texts <- c("this is a thing", "a b and an a", "this is a c cat", "B c d acd", "e A e ead")

# one regex pattern to replace all names at once
pattern = paste0("(?<=\\W|^)(", paste(names, collapse="|"), ")(?=\\W|$)")

# use regex's speed
gsub(pattern = pattern, replacement = "RemovedLeader", x = texts, ignore.case = TRUE, perl = TRUE)

# [1] "this is RemovedLeader thing"
# [2] "RemovedLeader RemovedLeader and an RemovedLeader"
# [3] "this is RemovedLeader RemovedLeader cat"
# [4] "RemovedLeader RemovedLeader RemovedLeader acd"
# [5] "RemovedLeader RemovedLeader RemovedLeader ead"

Parallelize using parallel package
Just to demonstrate you how you would solve this problem with parallelization:
names <- c("a", "b", "c", "d", "e")
texts <- c("this is a thing", "a b and an a", "this is a c", "B c d", "e A e")

# Before parallelization, think about over which sequence
# you can parallelize this procedure - which components in a sequence
# are independent?

# In this case the single strings of the texts are independent from each other.

# so write a function for one string to be fully processed as desired.

# let's define a function which applies the name replacements on one text piece.
replace_names <- function(names, string) {
    for (name in names) {
        string <- gsub(pattern = paste0("(?<=\\W|^)", name, "(?=\\W|$)"),
                       x = string,
                       replacement = "RemovedLeader",
                       ignore.case = TRUE,
                       perl = TRUE)
    }
    string
}

# Let us then apply this replacement for one string
# over the entire texts vector - for your case: `texts = text_df$texts`

# 0. load the `parallel` package
require(parallel) # install.packages("parallel")

# 1. prepare a cluster
cl <- parallel::makeCluster(parallel::detectCores() - 1)

# 2. export all variables and functions needed for the calculation to cluster
parallel::clusterExport(cl=cl, varlist=list(replace_names = "replace_names",
                                              names = "names",
                                              texts = "texts"))

# 3. run and get results type in console: `parallel::` and then TAB to see all
# available functions
# use `?<functionname>` and RET to see more details about the functions
new_texts <- parallel::parSapply(cl, texts, function(txt) replace_names(names, txt))

# 4. don't forget to stop the cluster to give resources free
stopCluster(cl = cl)

The output:
                                   this is a thing
                     "this is RemovedLeader thing"
                                      a b and an a
"RemovedLeader RemovedLeader and an RemovedLeader"
                                   this is a c cat
         "this is RemovedLeader RemovedLeader cat"
                                         B c d acd
   "RemovedLeader RemovedLeader RemovedLeader acd"
                                         e A e ead
   "RemovedLeader RemovedLeader RemovedLeader ead"

So you can basically parallelize over the single strings in the text-vector.
Parallelize using foreach-doParallel-parallel packages (no export of variable and functions required - better for automatization)
names <- c("a", "b", "c", "d", "e")
texts <- c("this is a thing", "a b and an a", "this is a c", "B c d", "e A e")

replace_names <- function(names, string) {
    for (name in names) {
        string <- gsub(pattern = paste0("(?<=\\W|^)", name, "(?=\\W|$)"),
                       x = string,
                       replacement = "RemovedLeader",
                       ignore.case = TRUE,
                       perl = TRUE)
    }
    string
}

# 0. load the `parallel` package
require(parallel) # install.packages("parallel")
require(doParallel)
require(foreach)

# 1. prepare a cluster and register it for doParallel
cl <- parallel::makeCluster(parallel::detectCores() - 1)
registerDoParallel(cl) # no need for exporting variables!

# 2. run foreach and %dopar%
new_texts <- foreach::foreach(txt=texts) %dopar% replace_names(names, txt)
# rule for combining result can be given -> instead as list, bind result with `c` to a vector:
new_texts_vec <- foreach::foreach(txt=texts, .combine=`c`) %dopar% replace_names(names, txt)

# 3. don't forget to stop the cluster to give resources free
parallel::stopCluster(cl = cl)

Abstraction over parallelization using foreach and doParallel packages
####################
# define papply
####################

papply <- function(sequential,
                   monadic_func,
                   exclude_cores=1,
                   cores=NULL,
                   ...) {
    # prepare cluster
    cl <- parallel::makeCluster(
        if (is.null(cores)) {
            parallel::detectCores() - exclude_cores
        } else {
            cores
        })
    # register
    registerDoParallel(cl)
    # run job
    res <- foreach::`%dopar%`(foreach::foreach(x=sequential, ...),
                              do.call(monadic_func, list(x)))
    parallel::stopCluster(cl=cl)
    res
}

###################
# define p_star_apply
###################

p_star_apply <- function(list_of_args_list,
                         multiadic_func,
                         exclude_cores=1,
                         cores=NULL,
                         ...) {
    # prepare cluster
    cl <- parallel::makeCluster(
        if (is.null(cores)) {
            parallel::detectCores() - exclude_cores
        } else {
            cores
        })
    # register
    registerDoParallel(cl)
    # run job
    res <- foreach::`%dopar%`(foreach::foreach(argsl=list_of_args_list, ...),
                              do.call(multiadic_func, argsl))
    parallel::stopCluster(cl=cl)
    res
} # works!

You can use it like this:

###################
# usage papply
# - for parallelization of a monadic function
# - arguments can be any type of sequence
# - define by .combine=`list` or .combine=`c`
#   whether output bound to a list or a vector e.g.
###################

# prepare monadic function (=takes exactly 1 necessary arguments)
replace_names <- function(string, .names=names) {
    for (name in .names) {
        string <- gsub(pattern = paste0("(?<=\\W|^)", name, "(?=\\W|$)"),
                       x = string,
                       replacement = "RemovedLeader",
                       ignore.case = TRUE,
                       perl = TRUE)
    }
    string
}

# call papply by giving for sequential the sequence of arguments
# and for monadic_func the appropriate monadic function:
papply(sequential = texts,
       monadic_func = replace_names,
       .export="names", # this is necessary for replace_names' default argument
       .combine=`c`) # this makes results be bound as vector

# for the `...` argument consult documentation by ?foreach::foreach

And p_star_apply a more universal form, where multiple
arguments are successively given to a function, allowing
a lot of freedom.
Just that the arguments in the correct order are packed into
a list of lists.
###################
# usage p_star_apply
# - for parallelization of multiadic functions
# - arguments must be ordered as list or argument lists
#   named or unnamed (if unnamed, argument order must be correct)
# - define by .combine=`list` or .combine=`c`
#   whether output bound to a list or a vector e.g.
###################

# prepare multiadic function
# in this case dyadic (takes 2 necessary arguments)
dyadic_replace_names <- function(string, .names) {
    for (name in .names) {
        string <- gsub(pattern = paste0("(?<=\\W|^)", name, "(?=\\W|$)"),
                       x = string,
                       replacement = "RemovedLeader",
                       ignore.case = TRUE,
                       perl = TRUE)
    }
    string
}

# prepare list of arguments lists
# (named elements or unnamed if in correct order)
argsl_lists <- lapply(texts, function(t) list(t, names))

p_star_apply(list_of_args_list=argsl_lists,
             multiadic_func=dyadic_replace_names) # returns as list

p_star_apply(list_of_args_list=argsl_lists,
             multiadic_func=dyadic_replace_names,
             .combine=`c`) # returns as vectors
# showing that `dot-dot-dot` artument, capable to forward the
# arguments for the `foreach()` part!


text:
Q: Scons missing builtin Builder for "Jar" I'm using an (admittedly aged) version of Scons (2.0.1; upgrading possible but might be difficult), and I'm having trouble with the "Jar" builder. Specifically, it isn't available, and I don't know why. The "JavaClassFile" builder is available and works correctly, but it can't build my jar, failing with this error:
scons: Reading SConscript files ...
AttributeError: 'SConsEnvironment' object has no attribute 'Jar':
  File "/home/fred/comms/SConstruct", line 183:
    envWithJava.Jar(target='util/myproject.jar', source=['util/myproject.class', 'util/jasypt.jar', 'util/bcprov-ext-jdk15on-152.jar', 'util/Manifest.txt'])
The relevant SConstruct excerpt:
env.Jar(target='util/myproject.jar', source=['util/myproject.class', 'util/jasypt.jar', 'util/bcprov-ext-jdk15on-152.jar', 'util/Manifest.txt'])
"BUILDERS:" from env.Dump() does not list "Jar", but has numerous others, and builds C, C++, Flex and other sources fine.
I'm mainly looking for a way to debug what's happening inside of Scons to make it skip the builder. The jar command is in the same dir as javac, and that builder works, so it doesn't seem path related. The Python files that have the Jar references are present in the lib used by Scons.
Any ideas?

A: My guess is that you either have no "jar" executable installed (can you call it on the command line?), or it's located in a path that hasn't been properly propagated to your Environment. See also #1 of the "most asked FAQs" at http://scons.org/wiki/FrequentlyAskedQuestions and the very java-specific bug report at http://scons.tigris.org/issues/show_bug.cgi?id=2730 .


text:
Q: How to create a global function that affects all or specific UIButton instance types? I want to create a global function that affects either all UIButton instances or only those of a certain UIButton type which would update the corner radius or border property.  I'm familiar with UIAppearances however my client would like to have a global file where they could update changes on the fly as if it were a CSS stylesheet.  So far I've been able to make extensions of UIColor and UIFont which returns specific colors and fonts however I can't figure out how this would work for UIButton instances.  Here is what I've thought of so far however I don't think this would work:
@objc extension UIButton {

    func changeUIButtonBorder() -> UIButton {
        self.layer.borderWidth = 3
        self.layer.borderColor = UIColor.white.cgColor
        return self
    }

}

A: What you're doing is great, and it does work for UIButton instances. But there is no need to return anything. In the extension, self is the button. So it can just change itself.
@objc extension UIButton {
    func changeUIButtonBorder() {
        self.layer.borderWidth = 3
        self.layer.borderColor = UIColor.white.cgColor
    }
}

You can now call changeUIButtonBorder on any UIButton instance.
@IBOutlet var myButton : UIButton!
override func viewDidLoad() {
    super.viewDidLoad()
    myButton.changeUIButtonBorder()
}

However, there is no magical way to shoutcast to all UIButtons that they should call that method; you'll have to deal with them one at a time.
The "magical" way is, as @Sh_Khan suggests, to make a UIButton subclass that calls changeUIButtonBorder in its own initializer. You would then simply have to make sure that all your buttons are instances of that subclass.
For example, here's a UIButton subclass that's always red (assuming that all instances come from the storyboard):
class RedButton : UIButton {
    override func awakeFromNib() {
        super.awakeFromNib()
        self.backgroundColor = .red
    }
}


text:
Q: CORS issue with C# Servicestack and NodeJS I am having an issue with CORS through Servicestack C# API. I have an angularjs application that is being served up through a nodejs back-end running on a Microsoft Server. NodeJS serves up the angular project just fine and node itself has no issue contacting the Servicestack service that I have running on a different domain but on the same server. The issue comes when I need to make a Microsft Active Directory call to get the current active user. In order to correctly make this call I have to call the Servicestack service from my angularjs project. When I make that call I get No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://domain1:8080' is therefore not allowed access I have other projects that I can make this same call from just fine but for some reason I can't seem to make this one work.
Angularjs call (http://domain1:8080):
 $http.get("http://domain2/dochelper/GetActiveAccount?format=json", { headers: { "siteprefix": prefix } })
        .then(function successCallback(resp) {
            console.log(resp.data);
        }, function errorCallback(resp) {

        });

Servicestack request:
[Route("/GetActiveAccount")]
public class GetActiveAccount
{
    public string Id { get; set; }
}

[Authenticate]
public AccountDTO Get(GetActiveAccount request)
{
    AccountDTO obj = new AccountDTO();

    var ses = this.GetSession() as AuthUserSession;

    return obj;
}

Servicestack CORS config:
            Plugins.Add(new CorsFeature(allowOriginWhitelist: new[] { "http://winexpresstest:8080" },
                allowedMethods: "GET, POST, PUT, DELETE, OPTIONS",
                allowedHeaders: "Content-Type, Authorization, Session-Id, ViewPort-Width, ViewPort-PixelRatio, Accept-Ranges, Pragma, Cache-Control, If-Modified-Since, Access-Control-Allow-Origin, siteprefix",
                allowCredentials: true));

            Plugins.Add(new AuthFeature(() => new AuthUserSession(), new ServiceStack.Auth.IAuthProvider[] {
               new AspNetWindowsAuthProvider(this) {
                    LoadUserAuthFilter = LoadUserAuthInfo,
                    AllowAllWindowsAuthUsers = true
                },
            }));

        }

A: You'll want to specify the origins in the white list to have the domain explicitly listed in the Access-Control-Allow-Origin HTTP Response header, e.g:
Plugins.Add(new CorsFeature(allowOriginWhitelist: new [] { "http://domain1:8080" },
    allowedMethods: "GET, POST, PUT, DELETE, OPTIONS",
    allowCredentials: false));


text:
Q: Jenkins restart error: org.jenkinsci.plugins.GithubAuthorizationStrategy For more than one year we have never restarted our jenkins.
And now after restart we got this error:
hudson.util.HudsonFailedToLoad: org.jvnet.hudson.reactor.ReactorException: java.io.IOException: Unable to read /var/jenkins_home/config.xml
    at hudson.WebAppMain$3.run(WebAppMain.java:244)
Caused by: org.jvnet.hudson.reactor.ReactorException: java.io.IOException: Unable to read /var/jenkins_home/config.xml
    at org.jvnet.hudson.reactor.Reactor.execute(Reactor.java:269)
    at jenkins.InitReactorRunner.run(InitReactorRunner.java:47)
    at jenkins.model.Jenkins.executeReactor(Jenkins.java:1062)
    at jenkins.model.Jenkins.<init>(Jenkins.java:905)
    at hudson.model.Hudson.<init>(Hudson.java:85)
    at hudson.model.Hudson.<init>(Hudson.java:81)
    at hudson.WebAppMain$3.run(WebAppMain.java:227)
Caused by: java.io.IOException: Unable to read /var/jenkins_home/config.xml
    at hudson.XmlFile.unmarshal(XmlFile.java:165)
    at jenkins.model.Jenkins.loadConfig(Jenkins.java:2917)
    at jenkins.model.Jenkins.access$700(Jenkins.java:324)
    at jenkins.model.Jenkins$16.run(Jenkins.java:2935)
    at org.jvnet.hudson.reactor.TaskGraphBuilder$TaskImpl.run(TaskGraphBuilder.java:169)
    at org.jvnet.hudson.reactor.Reactor.runTask(Reactor.java:282)
    at jenkins.model.Jenkins$7.runTask(Jenkins.java:1038)
    at org.jvnet.hudson.reactor.Reactor$2.run(Reactor.java:210)
    at org.jvnet.hudson.reactor.Reactor$Node.run(Reactor.java:117)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    at java.lang.Thread.run(Thread.java:745)
Caused by: jenkins.util.xstream.CriticalXStreamException: org.jenkinsci.plugins.GithubAuthorizationStrategy : org.jenkinsci.plugins.GithubAuthorizationStrategy
---- Debugging information ----
message             : org.jenkinsci.plugins.GithubAuthorizationStrategy
cause-exception     : com.thoughtworks.xstream.mapper.CannotResolveClassException
cause-message       : org.jenkinsci.plugins.GithubAuthorizationStrategy
class               : hudson.model.Hudson
required-type       : hudson.model.Hudson
converter-type      : hudson.util.RobustReflectionConverter
path                : /hudson/authorizationStrategy
line number         : 8
version             : not available
-------------------------------
    at hudson.util.RobustReflectionConverter.doUnmarshal(RobustReflectionConverter.java:356)
    at hudson.util.RobustReflectionConverter.unmarshal(RobustReflectionConverter.java:270)
    at com.thoughtworks.xstream.core.TreeUnmarshaller.convert(TreeUnmarshaller.java:72)
    at com.thoughtworks.xstream.core.AbstractReferenceUnmarshaller.convert(AbstractReferenceUnmarshaller.java:65)
    at com.thoughtworks.xstream.core.TreeUnmarshaller.convertAnother(TreeUnmarshaller.java:66)
    at com.thoughtworks.xstream.core.TreeUnmarshaller.convertAnother(TreeUnmarshaller.java:50)
    at com.thoughtworks.xstream.core.TreeUnmarshaller.start(TreeUnmarshaller.java:134)
    at com.thoughtworks.xstream.core.AbstractTreeMarshallingStrategy.unmarshal(AbstractTreeMarshallingStrategy.java:32)
    at com.thoughtworks.xstream.XStream.unmarshal(XStream.java:1189)
    at hudson.util.XStream2.unmarshal(XStream2.java:114)
    at com.thoughtworks.xstream.XStream.unmarshal(XStream.java:1173)
    at hudson.XmlFile.unmarshal(XmlFile.java:163)
    ... 11 more
Caused by: com.thoughtworks.xstream.mapper.CannotResolveClassException: org.jenkinsci.plugins.GithubAuthorizationStrategy
    at com.thoughtworks.xstream.mapper.DefaultMapper.realClass(DefaultMapper.java:79)
    at com.thoughtworks.xstream.mapper.MapperWrapper.realClass(MapperWrapper.java:30)
    at com.thoughtworks.xstream.mapper.DynamicProxyMapper.realClass(DynamicProxyMapper.java:55)
    at com.thoughtworks.xstream.mapper.MapperWrapper.realClass(MapperWrapper.java:30)
    at com.thoughtworks.xstream.mapper.PackageAliasingMapper.realClass(PackageAliasingMapper.java:88)
    at com.thoughtworks.xstream.mapper.MapperWrapper.realClass(MapperWrapper.java:30)
    at com.thoughtworks.xstream.mapper.ClassAliasingMapper.realClass(ClassAliasingMapper.java:79)
    at com.thoughtworks.xstream.mapper.MapperWrapper.realClass(MapperWrapper.java:30)
    at com.thoughtworks.xstream.mapper.MapperWrapper.realClass(MapperWrapper.java:30)
    at com.thoughtworks.xstream.mapper.MapperWrapper.realClass(MapperWrapper.java:30)
    at com.thoughtworks.xstream.mapper.MapperWrapper.realClass(MapperWrapper.java:30)
    at com.thoughtworks.xstream.mapper.MapperWrapper.realClass(MapperWrapper.java:30)
    at com.thoughtworks.xstream.mapper.MapperWrapper.realClass(MapperWrapper.java:30)
    at com.thoughtworks.xstream.mapper.ArrayMapper.realClass(ArrayMapper.java:74)
    at com.thoughtworks.xstream.mapper.MapperWrapper.realClass(MapperWrapper.java:30)
    at com.thoughtworks.xstream.mapper.MapperWrapper.realClass(MapperWrapper.java:30)
    at com.thoughtworks.xstream.mapper.MapperWrapper.realClass(MapperWrapper.java:30)
    at com.thoughtworks.xstream.mapper.MapperWrapper.realClass(MapperWrapper.java:30)
    at com.thoughtworks.xstream.mapper.MapperWrapper.realClass(MapperWrapper.java:30)
    at com.thoughtworks.xstream.mapper.MapperWrapper.realClass(MapperWrapper.java:30)
    at com.thoughtworks.xstream.mapper.SecurityMapper.realClass(SecurityMapper.java:71)
    at com.thoughtworks.xstream.mapper.MapperWrapper.realClass(MapperWrapper.java:30)
    at com.thoughtworks.xstream.mapper.MapperWrapper.realClass(MapperWrapper.java:30)
    at com.thoughtworks.xstream.mapper.MapperWrapper.realClass(MapperWrapper.java:30)
    at hudson.util.XStream2$CompatibilityMapper.realClass(XStream2.java:282)
    at com.thoughtworks.xstream.mapper.MapperWrapper.realClass(MapperWrapper.java:30)
    at com.thoughtworks.xstream.mapper.MapperWrapper.realClass(MapperWrapper.java:30)
    at org.jenkinsci.jruby.JRubyMapper.realClass(JRubyMapper.java:34)
    at hudson.util.xstream.MapperDelegate.realClass(MapperDelegate.java:43)
    at com.thoughtworks.xstream.mapper.MapperWrapper.realClass(MapperWrapper.java:30)
    at com.thoughtworks.xstream.mapper.CachingMapper.realClass(CachingMapper.java:48)
    at hudson.util.RobustReflectionConverter.determineType(RobustReflectionConverter.java:461)
    at hudson.util.RobustReflectionConverter.doUnmarshal(RobustReflectionConverter.java:327)
    ... 22 more

A: We had the exact same problem today. An exception with: Caused by: com.thoughtworks.xstream.mapper.CannotResolveClassException: org.jenkinsci.plugins.GithubAuthorizationStrategy
I found a solution here: https://issues.jenkins-ci.org/browse/JENKINS-34434
The solution was to delete github-oauth.jpi.disabled in the plugins folder.
Cheers, Tobias


text:
Q: Wicket 1.5 - Browser Pdf Print from freemaker template to byte[] Im looking for a simple way to allow my application's user to print a PDF I generate after they click on a button. In the "onClick" of Button, I make some operation and then call a method like this
Map<String,Object> m = new TreeMap<String,Object>();
m.put("paper", paperObject);
Template t = getConfiguration().getTemplate(TEMPLATE_NAME_CONSTANT);
String html = FreeMarkerTemplateUtils.processTemplateIntoString(t,m);
ByteArrayOutputStream os = HtmlToPdfRenderer.print(html);
return os.toByteArray();

I don't want to leave the original page.
Thanks.

A: Use a ResourceLink instead of a button. Pass it a custom subclass of ByteArrayResource like this:
new ResourceLink("id", new ByteArrayResource("application/pdf", null, filename) {
    @Override byte[] getData(Attributes att) {
        // generate your PDF here
        return byteArray;
    }
}

Clicking on this link will generate the PDF and send it to the browser.
Alternatively, create a subclass of AbstractResource instead of ByteArrayResource, since AbstractResource is a bit more flexible.


text:
Q: jQuery select2 More than one of the same type in mulitple select I am using select2 (which can be found here), and I want to have a multiple select box. To do this, <select multiple></select> is used. But the problem with this is that you cannot have more than one of the same option. For example:
<select multiple>
    <option>First Option</option>
    <option>Second Option</option>
    <option>Third Option</option>
</select>

And I want to have 2 of the Second Option's selected. How do I do this? Also, how would I get the value of this <select multiple>?
Note: I am not able to use more than one <select>

A: It is not clear what you ask.
Here are my variants:
If you want to have one multiple select with the same option (if you choose one, it appears in selected, but also stays in List - you described this requirement in comment.
I guess it is not possible simple with select2. You have to look for another control.
If you want to have two multiple selects with the same options.
You have to add some classes to your original select.
And then do $('.my-select1').select2(); and do $('.my-select2').select2();
In this case you would be able to select values using selector .my-select1 and .my-select2.
See https://jsfiddle.net/hfmeey2z/1/ as example of two multiple selects with the same values.
If you want to have one multiple select with two options with the same Name.
You have to use different "value" attribute for each option.
 <option value="JAN">January</option>
 <option value="JAN2">January</option>

https://jsfiddle.net/hfmeey2z/2/


text:
Q: In ServiceNow, how do I rollback to a pre-"Wait for condition" state in a workflow? In my ServiceNow workflow for a catalog item, I have a stage for customer acceptance. When the customer rejects the item, it triggers a workflow event and rolls back the workflow to the point where it's waiting for a state again. Or at least, that's the idea. But no matter what I'm doing, the rolled back workflow skips the "Wait for condition" activity immediately.
This is a screenshot of the workflow section in question.
What am I doing wrong?

A: I know this is an old post but perhaps the below suggestion can help in similar cases:
The thing wit 'Wait for Condition' is that once it has been evaluated, it will not be checked again until there has been a new update to the record on which the workflow runs.
I assume this could be the cause here, one you roll back, if the record itself does not get updated, it skips that activity. You can easily check if that was the case by adding some activity after the roll back to e.g. set a worknote on the record or just 'run script' with the setForceUpdate() function (this updates the record without changing any fields values).
I'm not 100% sure it is the fix to the above problem as there could be many other factors involved and only small part of WF was posted, but definitely something worth checking.
I hope you found the solution by now!


text:
Q: Java, rounding a double to two decimal places I'm trying to round a double to the nearest two decimal places however, it is just rounding to the nearest full number.
For example, 19634.0 instead of 19634.95.
This is the current code I use for the rounding
double area = Math.round(Math.PI*Radius()*Radius()*100)/100;

I can't see where i am going wrong.
Many thanks for any help.

A: Well, Math.round(Math.PI*Radius()*Radius()*100) is long. 100 is int.
So Math.round(Math.PI*Radius()*Radius()*100) / 100 will become long (19634).
Change it to Math.round(Math.PI*Radius()*Radius()*100) / 100.0. 100.0 is double, and the result will also be double (19634.95).

A: Do you actually want want to round the value to 2 places, which will cause snowballing rounding errors in your code, or simply display the number with 2 decimal places? Check out String.format(). Complex but very powerful.

A: You can use a DecimalFormat object:
DecimalFormat df = new DecimalFormat ();
df.setMaximumFractionDigits (2);
df.setMinimumFractionDigits (2);

System.out.println (df.format (19634.95));

A: You might want to take a look at the DecimalFormat class.
double x = 4.654;

DecimalFormat twoDigitFormat = new DecimalFormat("#.00");
System.out.println("x=" + twoDigitFormat.format());

This gives "x=4.65". The difference between # and 0 in the pattern is that the zeros are always displayed and # will  not if the last ones are 0.

A: The following example came from this forum, but seems to be what you are looking for.
 double roundTwoDecimals(double d) {
      DecimalFormat twoDForm = new DecimalFormat("#.##");
      return Double.valueOf(twoDForm.format(d));
 }


text:
Q: Activate window from taskbar
Possible Duplicate:
Can you make a Borderless Application Main Window in Windows, without WS_POPUP style?

I have a form with BorderStyle:=bsNone;
How can I activate the minimized form by clicking on a it in task bar?

A: I'm guessing you're using an older version of Delphi (I've just done my testing on Delphi 2010, and I'm guessing you're using something older because in my version I don't need to do anything, restoring the window just works).
Problem 1: How do you MINIMIZE a border-less form? A border-less form doesn't have an "minimize" button! Are you sure it's minimized and it's not actually hidden? I've just attempted this, and I was only able to minimize the form by placing a button on it and running this code from the button:
ShowWindow(Handle, SW_MINIMIZE);

If I clicked on the application's button in my Windows 7 taskbar it came right up without problem. This brings us to the second problem.
Problem 2: What version of Delphi are you using? What version of Windows? Unfortunately it matters. There were changes in what Windows did with the taskbar button, and those changes prompted more changes in what Delphi does to support the taskbar button.
If you're on some old version of Delphi and on some new version of Windows you might try dropping a TApplicationEvents on your form, and from it's OnRestore event do this:
ShowWindow(Handle, SW_SHOW or SW_RESTORE);

A: The solution is to do
type
  TForm1 = class(TForm)
  private
  protected
    procedure CreateParams(var Params: TCreateParams); override;
    { Private declarations }
  public
    { Public declarations }
  end;

where
procedure TForm1.CreateParams(var Params: TCreateParams);
begin
  inherited;
  Params.Style := Params.Style or WS_MINIMIZEBOX;
end;

exactly as David did in the old question about this topic.


text:
Q: Shader that transforms a mercator projection to equirectangular? I am trying to make a shader in Unity taking a mercator projection texture as a source and converting it to an equirectangular projection texture.
Input example:

Output example:

This example does the opposite with an equirectangular as source.
If you look at the source of the above example:
 // mercator
 float latClamped = clamp(lat, -1.4835298641951802, 1.4835298641951802);
 float yMerc = log(tan(PI / 4.0 + latClamped / 2.0)) / PI2;
 float xMerc = xEqui / 2.0;
 vec4 mercatorPos = vec4(xMerc, yMerc, 0.0, 1.0);

Can anyone help to reverse this so I'm able to go from a mercator map as a source to equirectangular (or even better, azimuthal).
Looking for a way to do 2D texture deformations going from x/y to longitude(x)/latitude(y) and back.
I appreciate your input.

A: If you want to output the equirectangular projection, you need to convert from equirectangular coordinates to mercator coordinates and then sample the mercator projection at those coordinates.

This is what it would look like in a fragment shader from uvs:
//uv to equirectangular
float lat = (uv.x) * 2 * PI;    // from 0 to 2PI
float lon = (uv.y - .5f) * PI;  // from -PI to PI

// equirectangular to mercator
float x = lat;
float y = log(tan(PI / 4. + lon / 2.));

// bring x,y into [0,1] range
x = x / (2*PI);
y = (y+PI) / (2*PI);

// sample mercator projection
fixed4 col = tex2D(_MainTex, float2(x,y));

The same thing applies to the azimuthal projection: You can go from azimuthal coordinates -> equirectangular -> mercator and sample the image. Or you can find a formula to go directly from azimuthal -> mercator. The wiki pages have a bunch of formulas to go back and forth between projections.  Here is a full shader to play around with. Input is a mercator projection and outputs a equirectangular or azimuthal projection (choose from the dropdown menu)
Shader "Unlit/NewUnlitShader 1"
{
    Properties
    {
        _MainTex ("Texture", 2D) = "white" {}
        [Enum(Equirectangular,0,Azimuthal,1)]
        _Azimuthal("Projection", float) = 0

    }
    SubShader
    {
        Tags { "RenderType"="Opaque" }
        LOD 100

        Pass
        {
            CGPROGRAM
            #pragma vertex vert
            #pragma fragment frag

            #include "UnityCG.cginc"

            struct appdata
            {
                float4 vertex : POSITION;
                float2 uv : TEXCOORD0;
            };

            struct v2f
            {
                float2 uv : TEXCOORD0;
                float4 vertex : SV_POSITION;
            };

            sampler2D _MainTex;
            float4 _MainTex_ST;
            float _Azimuthal;

            v2f vert (appdata v)
            {
                v2f o;
                o.vertex = UnityObjectToClipPos(v.vertex);
                o.uv = TRANSFORM_TEX(v.uv, _MainTex);
                return o;
            }
#define PI 3.141592653589793238462f
#define PI2 6.283185307179586476924f

            float2 uvToEquirectangular(float2 uv) {
                float lat = (uv.x) * PI2;   // from 0 to 2PI
                float lon = (uv.y - .5f) * PI;  // from -PI to PI
                return float2(lat, lon);
            }

            float2 uvAsAzimuthalToEquirectangular(float2 uv) {
                float2 coord = (uv - .5) * 4;

                float radius = length(coord);
                float angle = atan2(coord.y, coord.x) + PI;

                //formula from https://en.wikipedia.org/wiki/Lambert_azimuthal_equal-area_projection
                float lat = angle;
                float lon = 2 * acos(radius / 2.) - PI / 2;
                return float2(lat, lon);
            }

            fixed4 frag(v2f i) : SV_Target
            {
                // get equirectangular coordinates
                float2 coord = _Azimuthal ? uvAsAzimuthalToEquirectangular(i.uv) : uvToEquirectangular(i.uv);

                // equirectangular to mercator
                float x = coord.x;
                float y = log(tan(PI / 4. + coord.y / 2.));
                // brin x,y into [0,1] range
                x = x / PI2;
                y = (y + PI) / PI2;

                fixed4 col = tex2D(_MainTex, float2(x,y));

                // just to make it look nicer
                col = _Azimuthal && length(i.uv*2-1) > 1 ? 1 : col;

                return col;
            }
            ENDCG
        }
    }
}


text:
Q: Creating histogram plot I have a 2D array. Lets say column 1 (a distribution), ranges from 0-2, column 2, ranges from 2-4, column 3, from 4-6 etc. I want to have a histogram plot for each of the columns, colored by the range, so for
column 1, blue-0 and red-2,
column 2, blue-2 and red-4,

...and so on.

A: Please have a look at matplotlib.pyplot.hist.

A: I'm not sure but I think you could have a look at matplotlib.


text:
Q: Transporter animation rotation in AnyLogic I have a transporter fleet defined by an agent type that has a certain 3D animation (cube with one open side).  The agent itself is set up to disable animation rotation, as Id like the animation to maintain the same orientation.
When I seize the transporter, unit.isAutomatic...Rotation() shows false as per the agent setup.  However, once the transporter starts moving (MoveByTransporter block) and goes onto a section of path that is a different orientation) the thing still rotates.  Am I doing something wrong here or is it a bug?

A: Might be a feature, not a bug.
You can try to override it in your 3D animation properties. Switch to a dynamic value (so it is recomputed all the time) and enter some rad value you want:

A: To quote the very helpful AnyLogic Support - its not a feature of transporters yet (the disabling rotation bit).  Their suggested workaround - which does work - is to basically counteract the rotation as it happens:
In the transporter agent: create a group; add all the drawn/3D elements to it, and then set the rotation to -getRotation().


text:
Q: Action Script: How do I write a DataGrid programatically? I have this code but I am trying to convert this to actionscript so I render this programaticaly but I failed. how do i write this on AS?
<mx:DataGrid  allowMultipleSelection="true" id="dg_disk" dataProvider="{people}" height="100%" width="100%" selectedIndex="0" x="50" y="50">
        <mx:columns>
            <mx:DataGridColumn dataField="name"         id="empname"     headerText="EmpName"/>
            <mx:DataGridColumn dataField="title"     id="title" headerText="Title"/>
            <mx:DataGridColumn dataField="description"         id="desc"        headerText="Description"/>
           </mx:DataGridColumn>
        </mx:columns>

    </mx:DataGrid>

A: This is part of a programm I have written. The mSessionLogDG is the DataGrid (in this case we add dynamic columns to already existing ones).
private function createColumns() : void {
            var _columnArray : Array = mSessionLogDG.columns;
            var _initialOffset : uint = _columnArray.length;
            // TODO
            if ( _initialOffset > CreateCommentNamesCommand.MAX_NO_COMMENTS ) return;

            this.mOffset = _initialOffset;

            var _headerLabel : String = '';
            for ( var i : uint = 0; i < CreateCommentNamesCommand.MAX_NO_COMMENTS; i++ )
            {
                var _dataColumn : DataGridColumn = new DataGridColumn();
                _dataColumn.headerText = this.createCommentNamesCommand.labelArray[i];
                _dataColumn.setStyle( "paddingLeft", "3" );
                _dataColumn.setStyle( "textAlign", "left" );
                _dataColumn.setStyle( "customID", i );
                _dataColumn.width = 160;
                _dataColumn.labelFunction = labelFunc;
                _dataColumn.sortCompareFunction = SessionDescriptionXmlVo.mCommentCompareFunctionArray[i];
                _dataColumn.itemRenderer = new ClassFactory( SessionCommentItemRenderer );
                _dataColumn.visible = false;
                _dataColumn.minWidth = 160;
                _columnArray.push( _dataColumn );
                mColumnArray[i] = _dataColumn;
            }

            mSessionLogDG.columns = _columnArray;
        }

A: Something like:
var empname:DataGridColumn = new DataGridColumn();
empname.dataField = "name";
empname.headerText="EmpName";

var title:DataGridColumn = new DataGridColumn();
…

var desc:DataGridColumn = new DataGridColumn();
…

var dg_disk:DataGrid = new DataGrid();
dg_disk.allowMultipleSelection = true;
dg_disk.percentWidth = 100;
dg_disk.percentHeight = 100;
dg_disk.x = 50;
dg_disk.y = 50;
dg_disk.columns = [empname, title, desc];
dg_disk.dataProvider = people;
dg_disk.selectedIndex = 0;

someContainer.addElement(dg_disk);

A: var dg_disk : DataGrid = new DataGrid();
dg_disk.allowMultipleSelection = true;
BindingUtils.bindProperty(this, "people", dg_disk, "dataProvider");
dg_disk.percentHeight = 100;
dg_disk.percentWidth = 100;
dg_disk.selectedIndex = 0;
dg_disk.x = 50;
dg_disk.y = 50;
var empname : DataGridColumn = new DataGridColumn();
empname.dataField = "name";
empname.headerText = "EmpName";
var title : DataGridColumn = new DataGridColumn();
title.dataField = "title";
title.headerText = "Title";
var desc : DataGridColumn = new DataGridColumn();
desc.dataField = "description";
desc.headerText = "Description";
dg_disk.columns = [empname, title, desc];
addChild(dg_disk);

A: This will do the trick:
private function createDataGrid():void{
    var dg:DataGrid = new DataGrid(); // create your grid
    dg.id="dg_disk"
    dg.percentHeight = 100;
    dg.percentWidth=100;
    dg.x = 50;
    dg.y=50;
    dg.selectedIndex = 0; //set its properties

    dg.columns = createDgColumns(); // Add columns to your grid

    addChild(dg); // Add the grid to the display list
}

private function createDgColumns():Array{
    var columns:Array = [];

    var empColumn:DataGridColumn = new DataGridColumn();
    empColumn.dataField="name";
    empColumn.headerText="EmpName";

    var titleColumn:DataGridColumn = new DataGridColumn();
    titleColumn.dataField="title";
    titleColumn.headerText="Title";

    var descColumn:DataGridColumn = new DataGridColumn();
    descColumn.dataField="description";
    descColumn.headerText="Description";

    columns.push(empColumn);
    columns.push(titleColumn);
    columns.push(descColumn);

    return columns
}

A: var myGrid:AdvancedDataGrid = new AdvancedDataGrid();
var adgColumn:AdvancedDataGridColumn = new AdvancedDataGridColumn();
adgColumn.headerText = "Header Text";
adgColumn.dataField = "header_text";
var columnArr:Array = new Array();
columnArr.push(adgColumn);
myGrid.columns = columnArr;

this.addChild(myGrid);


text:
Q: Spring boot, The file can not be read, Use jar package when starting Spring boot, The file can not be read, Use jar package when starting.
When I use the .war start the way everything is normal
This is war maven pom.xml
<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-resources-plugin</artifactId>
    <version>2.6</version>
    <configuration>
        <nonFilteredFileExtensions>
            <nonFilteredFileExtension>xls</nonFilteredFileExtension>
            <nonFilteredFileExtension>xlsx</nonFilteredFileExtension>
            <nonFilteredFileExtension>p12</nonFilteredFileExtension>
        </nonFilteredFileExtensions>
    </configuration>
</plugin>

But use java -jar

I want to start with java -jar, Now what do I need to do?
spring boot version 1.4.4
public void generater(HttpServletResponse response, boolean testMode) {
        ExcelTemplateEnum excelTemplate = this.exportTemplate();
        FileInputStream is = null;
        Workbook workbook = null;
        try {
            String templateFilePath = this.getTemplateFilePath(excelTemplate);
            URL url = ExeclExportHandler.class.getClassLoader().getResource(templateFilePath);
            is = new FileInputStream(url.getFile());
            ExcelTransformer transformer = this.getExcelTransformer();
            // 渲染导出数据
            if (isMultipleBeans()) {
                List<Map<String, Object>> data = this.renderDataList();
                this.checkExportParam(data);
                workbook = transformer.transform(is, getTemplateSheetNamesList(), getSheetNamesList(), data);
            } else {
                Map<String, Object> data = this.renderData();
                this.checkExportParam(data);
                workbook = transformer.transform(is, data);
            }
            if (testMode) {
                ...
            } else {
                ExcelHelper.setExcelHeader(response, excelTemplate.outname());
                workbook.write(response.getOutputStream());
                response.flushBuffer();
            }
        } catch (Exception e) {
            ...
        } finally {
            IOUtils.closeQuietly(is, workbook);
        }
    }

error line 75

    is = new FileInputStream(url.getFile());

A: You have to access the resource by Class.getResourceAsStream(), since you can't access files packed in a jar:
is = this.getClass().getResourceAsStream(templateFilePath)

If it works with a war it is just luck, since your servlet/J2EE-container seems to unpack your war... which is not the case with all containers (due to the spec it is up to the container whether it will unpack the the war or not). Means with a different container you will get also get this Exception with the war.


text:
Q: Ownership of table in template I've created a PostgreSQL database template that I want users to be able to copy and play around with. The problem is that apparently they don't get enough privileges for the tables that are copied from the template. For instance, if a user does:
create database my_copy template that_template;
\c my_copy
create index my_index on a_table_in_the_template(a_column);

It results in an error ERROR:  must be owner of relation a_table_in_the_template. If I'm not mistaken, this has worked before, but now it doesn't. I'm running server 9.4.10.
Is there an easy fix, or do I need to look for another way for users to copy the database to play around with, instead of using template?


text:
Q: Dataset datatable formatting rows Hi i have a dataset which contains a table retrieved from sql. It has 'product' column and 'price' column. I got the dataset and binded to grid. Now i want to make the grid's price column to be formatted to 2 decimal places(validation). Any idea please.
I should not change the select query since its an SP which gives me the dataset.

A: if you neither want to use Bound-Field nor change select query than as much i know you have two options left to accomplish this. First is, do value change in your dataset before binding to grid using any loop  and the second option is alter values in grid on RowDataBound Event...
By altering value in Dataset:
 foreach(dataRow[] dr in dataset.tables[your table index])
 {
  // max. two decimal places
   string val =   String.Format("{0:0.##}",Convert.ToDecimal(dr[column index]));
   dr[column index] = val;
 }

By altering value in Grid:
  protected void mygrid_OnRowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            mygrid.cell[cell index].Text =   String.Format("{0:0.##}",Convert.ToDecimal(dataset.tables[table index][column index][Row Index]));

        }
    }

Now if you want apply validation for data insert and update you can apply RegularExpressionValidator at your textBox ...
   <EditItemTemplate>
  <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
    <asp:RegularExpressionValidator ID="RegularExpressionValidator1" runat="server"     ErrorMessage="RegularExpressionValidator"
        ControlToValidate="TextBox1" ValidationExpression="^\d{1,2}([.]\d{1})$"> ValidationGroup="MyVal"</asp:RegularExpressionValidator>

Now you have to apply

ValidationGroup="MyVal"

also on click control on which you'll perform its editing and update..

A: Try this:
<asp:BoundField DataField="Price" DataFormatString="{0:C2}" HeaderText="Price" />

You need to add the "DataFormatString" property to the bound field as shown above. This formats currency values to two decimal places. Check this article.
DataField refers to the name of the column in the datatable, whereas the HeaderText refers to the text which would be shown as the header of the column in grid.


text:
Q: Installing munin-node in an AWS Instance running Amazon Linux Can I use the procedure described here (http://munin-monitoring.org/wiki/LinuxInstallation) for RedHat or I need to use a different one?

A: Yes.
...additional text here to pad out to the 30 char minimum.


text:
Q: Вывести sidebar только на главной странице сайта WordPress На сайте уже подключен (зарегистрирован) сайдбар. Мне надо в него добавить новый блок с текстом и ссылками. И еще необходимо чтобы этот блок выводился только на главной странице.
Зарегистрировала сайдбар sidebar3 в functions.php. Создала отдельный файл sidebar3.php:

<?php if ( !function_exists('dynamic_sidebar') || !dynamic_sidebar('Sidebar3') ) : ?>
<?php endif; ?>

В home.php указала путь:
<?php include (TEMPLATEPATH . '/sidebar3.php'); ?>

В админке на странице виджеты добавила текст и ссылки в виджете Sidebar3.
Но сайдбрар не выводится. Что не правильно делаю? Как вывести дополнительный сайдбар но только на главной странице?

A: Нужно сделать проверку is_front_page

      <?php if ( !function_exists('dynamic_sidebar') || !dynamic_sidebar('Sidebar3') ) : ?>
     <?php endif; ?>

Если Вы зарегистрировали sidebar, создайте для него шаблон к примеру sidebar-main.php и подключите его <?php is_front_page(get_sidebar('main')); ?>

A: Добрый день!
Создайте файл sidebar-main.php в папке темы и разместите следующий код:
<?php
    //Проверяем наличие сайдбара и выводим его виджеты
    if ( !function_exists('dynamic_sidebar') || !dynamic_sidebar("Simple Sidebar") ) :
    endif;
?>

В файл functions.php в папке вашей темы добавьте код:
<?php
    //Создаём сайдбар в теме (регистрируем)
    if ( function_exists('register_sidebar') )
    register_sidebar(array(
        'id' => 'sidebar-1',
        'name' => 'Simple Sidebar',
        'before_widget' => '
',
        'after_widget' => '
',
        'before_title' => '
',
        'after_title' => '
',
    ));

?>

В шаблоне страницы (front-page.php, home.php) добавьте код в нужном месте вывода сайдбара:
<?php
    //Проверяем, главная ли страница у нас показывается
    if(is_front_page())
    {
        //Выводим сайдбар из файла sidebar-main.php
        get_sidebar('main');
    }

?>

Дополнительная информация для вас
<?php include (TEMPLATEPATH . '/sidebar3.php'); ?>

Подключение файлов через include в wordpress не приветствуется, используйте функцию get_template_part();
Полезные ссылки:
is_front_page()
get_sidebar()
get_template_part()


text:
Q: Figuring out RGB or HEX color from xcolor I have defined a color using:
\definecolor{canvascolor}{rgb}{0.643,0.690,0.843}

Then this is used with this command like canvascolor!75!white from xcolor. This is actually done in the beamer theme wkbeamer.
I know the mix of these two colors but how do I output the RGB color of this to match in a paint program. This I figure should be easy. I looked through the xcolor manual and couldn't find how to do this. I also looked through to just see how it determines or algorithm it uses for the new RGB color from the mix but didn't see this. I didn't read the whole manual but from a quick look through I couldn't find the algorithm for this or tried outputting the color with a couple commands but none I could get working.

A: \documentclass{article}
\usepackage{xcolor}
\definecolor{canvascolor}{rgb}{0.643,0.690,0.843}
\colorlet{canvas75}{canvascolor!75!white}
\begin{document}
\noindent\ttfamily
\color{canvas75}RGB colour canvascolor!75!white\\
html : \convertcolorspec{named}{canvas75}{HTML}\HTMLcolour
\HTMLcolour\\
cmyk : \convertcolorspec{named}{canvas75}{cmyk}\CMYKcolour
\CMYKcolour

\end{document}

A: The \extractcolorspec macro will define a macro that contains the specification for a color; we can use it and the companion \convertcolorspec to define a macro containing the specifications for another model:
\definecolor{canvascolor}{rgb}{0.643,0.690,0.843}
\extractcolorspec{canvascolor!75!white}{\test}
\expandafter\convertcolorspec\test{HTML}\test

Now \test will expand to BBC4E1.
The first definition of \test will be {rgb}{0.73225,0.7675,0.88225} so this is good for putting it after \convertcolorspec, but we have to expand it first.
Use two different macros if you also need to keep the first specification around.
We can implement this in a function
\newcommand{\getColorSpec}[3][\getColorSpecTemp]{%
  \extractcolorspec{#3}\getColorSpecTemp
  \expandafter\convertcolorspec\getColorSpecTemp{#2}#1}

With \getColorSpec{HTML}{canvascolor!75!white} the specification will be stored in \getColorSpecTemp; with
\getColorSpec[\HTMLcolor]{HTML}{canvascolor!75!white}

the same specification will be stored in \HTMLcolor.


text:
Q: How do I repsent OneToMany relationship in JPA with multiple tables inbetween? At a high level, I have a class "MainClass" that has a list of "OtherEntity". There are essentially two join tables. The two join tables have meta-data in them that other components use but I have not defined entities for as we don't need them outside of a join operation. But basically MainClass => TableOne => TableTwo => OtherEntity
My entity definitions
@Entity
public class MainClass {

    // other stuff ...

    // how to?
    @OneToMany
    private List<OtherEntity> otherEntities;
}

@Entity
public class OtherClass { // other stuff ... }

My schema (legacy and cannot be modified)
table MainClass
    PK id
    ...

table TableOne
    PK id
    FK main_class_id
    FK table_two_id

table TableTwo
    PK id
    FK table_one_id
    FK other_entity_id

table OtherEntity
     PK id
     ...

I'd like avoid creating entities for TableOne and TableTwo if I could.

A: Consider using @SecondaryTable it should work for legacy schemas, using this annotation you can have fields in one entity, and just define which ones will form part of other table, but you only have 2 entities.
Check this tutorial
Idea is split fields from one entity in different tables without need the creation of other entities, just define which fields are in which table.
@SecondaryTables{@SecondaryTable(name="XX")}

and to move fields between tables use
@Column(table="XX")

In your config try something like this.
@Entity
@SecondaryTables{@SecondaryTable(name="TableOne"), @SecondaryTable(name="TableTwo")}
table MainClass
    PK id
    @Column(table="TableOne")
    FK main_class_id
    @Column(table="TableOne")
    FK table_two_id

    @Column(table="TableTwo")
    PK id
    @Column(table="TableTwo")
    FK table_one_id
    @Column(table="TableTwo")
    FK other_entity_id

For ID in middle tables consider remove @Id and set it automatically, it should work !!

A: The issue is a design problem that will eventually be addressed. We have a database view that provides a unified look up table. In the database layer we can assign the pieces individually.
@Entity
public class MainClass {

    @OneToMany
    @JoinTable(name = "TheViewName",
        joinColumns = @JoinColumn(name = "id", insertable = false, updatable= false),
        inverseJoinColumns = @JoinColumn(name = "other_id", insertable = false,
            updatable = false))
    private List<OtherEntity> otherEntities;
}

This means I cannot assign a new other entity to the MainClass and persist both. I have to do two separate operations to get things finalized. But, that will go away when we refactor the schema.
Alternatively, we could create entities for the other two tables to make the operations more transparent.


text:
Q: Jersey redirect to a default URI when resource does not exist I'm building a RESTful Web Service using Jersey 2.22, and I have the following scenario:
When I try to make a request to a path that does not exist (it's not implemented in the resources package at all), it'll send back a 404 status, because the resource wasn't found (obviously).
If this situation happens, I'd like to forward to a default URI, like sending back to index.html, for example.
But since it's a resource that is not implemented yet, where should I write this validation? Should it be in my class that extends from Application/ResourceConfig and has the @ApplicationPath annotation ? Could anyone show me a way or a documentation, or even a post that it's explicitly said?

A: You can handle 404 error code in your web.xml file -
    <error-page>
       <error-code>404</error-code>
       <location>/index.html</location>
    </error-page>

Details can be referred to How to specify the default error page in web.xml?


text:
Q: Getchar() skips the first value scanned in while loop I am trying to select all individual values scanned (cannot use arrays or strings) one at a time. For now, it skips the first value implemented by the user and I do not know why. I would like the loop to stop when getchar reaches "=" which will be at the end of the scanned value.
int main () {
char c;
while(scanf("%c", &c) != '=') {
 c=getchar();
 printf("print ");
 putchar(c);

 }
return 0;
}

In the terminal, when I input "a=" I only receive the "=" instead of "a". Can someone help?

A: The condition in the while loop and the following call of getchar do not make a sense.
while(scanf("%c", &c) != '=') {
 c=getchar();
 //...

For example *The C Standard, 7.21.6.4 The scanf function)

3 The scanf function returns the value of the macro EOF if an input
failure occurs before the first conversion (if any) has completed.
Otherwise, the scanf function returns the number of input items
assigned, which can be fewer than provided for, or even zero, in the
event of an early matching failure.

And the read character by the call of scanf is not outputted.
You should write
char c;
while( scanf(" %c", &c) == 1 && c != '=') {
 printf("print %c", c);
}

Pay attention to that this call of scanf
scanf( " %c", &c)

will skip white space characters. If you want to output any character then you need to remove the blank before the conversion specifier like
scanf( "%c", &c)
       ^^^^

If you want to use getchar then the loop will look like
int c;
while( ( c = getchar() ) != EOF && c != '=') {
 printf("print %c", c);
}

In this case as you see the variable c must be declared as having the type int.

A: The scanf() function returns the number of fields that were successfully converted and assigned.
You can read more here: https://www.ibm.com/docs/en/i/7.3?topic=functions-scanf-read-data
In your case, it will return 1 if c is scanned and assigned successfully, else 0.
The above documentation is platform-specific, but the below approach can still be applicable everywhere.
If you want your loop to end when the char is "=", then you can simply compare with if condition and break the loop:
int main () {
char c;
while(1) {
 c=getchar();
 if (c == '=') {
   break;
 }
 printf("print ");
 putchar(c);

 }
return 0;
}


text:
Q: DllMain behaves oddly with g++ on Cygwin I'm using gcc v4.8.3 on Cygwin.  I'm unsure how DllMain() is supposed to behave in this context.
When I compile the same code with mingw, it works as expected, and I get the output:
Hello from DllMain
Hello from main
I'm a _WIN32
I'm a __MINGW32__
I'm a __cplusplus
Calling workhorse
Hello from workhorse
ret 1
Hello from DllMain

When I compile it with g++ in Cygwin, I get
Hello from DllMain

and nothing more.  Help!  I suppose I could live without DllMain() in the g++ version, but it seems like I'm only a small step away.
Here is DLL code (dds.cpp):
 #include "dll.h"

 // #ifdef USE_DLLMAIN
 extern "C" BOOL APIENTRY DllMain(
   HMODULE               hModule,
   DWORD                 ul_reason_for_call,
   LPVOID                lpReserved)
 {
   printf("Hello from DllMain\n");
   return TRUE;
 }
 // #endif

 int STDCALL workhorse()
 {
   printf("Hello from workhorse\n");
   return TRUE;
 }

Here is the header file (dll.h):
 #include <windows.h>
 #include <stdio.h>

 #if defined(_WIN32) || defined(__CYGWIN__)
 #    define DLLEXPORT __declspec(dllexport)
 #    define STDCALL __stdcall
 #else
 #    define DLLEXPORT
 #    define STDCALL
 #endif

 #ifdef __cplusplus
 #    define EXTERN_C extern "C"
 #else
 #    define EXTERN_C
 #endif

 EXTERN_C DLLEXPORT int STDCALL workhorse();

Here is the main program (dtest.cpp):
 #include "dll.h"

 int main()
 {
   printf("Hello from main\n");

 #ifdef _WIN32
   printf("I'm a _WIN32\n");
 #endif
 #ifdef __CYGWIN__
   printf("I'm a __CYGWIN__\n");
 #endif
 #ifdef __MINGW32__
   printf("I'm a __MINGW32__\n");
 #endif
 #ifdef __cplusplus
   printf("I'm a __cplusplus\n");
 #endif

   printf("Calling workhorse\n");
   printf("ret %d\n", workhorse());

 }


text:
Q: Two column flex layout, align content towards the middle With this code:

.row {
  display: flex;
  text-align: center;
}

.col {
  flex: 1;
}

Left

Some longer text

Right

Some longer text

I get output like
------------------------------------------------------------------
|            Left               |             Right              |
|       Some longer text        |       Some longer text         |
------------------------------------------------------------------

(dashed lines imaginary to show containers).
What I want is for the elements in each column to stay centered relative to one another but to be biased towards the the column divider, with a bit of padding, e.g.
------------------------------------------------------------------
|                 Left        |       Right                      |
|           Some longer text  |  Some longer text                |
------------------------------------------------------------------

How can I achieve this?

A: Please find the attached fiddle
You can use align-items: center for vertical center alignment or and then for horizontal alignment, use align-self on particular element to flex-start, flex-end or center.
Just adding the css code here.
.row {
  display: flex;
  margin: 0 -15px;
}

.col {
    flex: 1;
    flex-flow: column wrap;
    align-items: center;
    display: flex;
    padding: 0 15px;
}
.col:first-child h1,
.col:first-child h2{
align-self: flex-end;
}
.col:last-child h1,
.col:last-child h2{
align-self: flex-start;
}

A: You could just justify-content as center in the row.

.row {
  display: flex;
  text-align: center;
  justify-content: center;
}
.col {
  padding: 0.5rem;
}

Left

Some longer text

Right

Some longer text

A: A simple solution would be to put padding on the columns. Left padding on the left column and right padding on the right column. This example uses percentages. A limitation of this is when the text is longer it will wrap and not take up the full width of its container. You mention padding in your question, so it's possible you tried this.
Example

.row {
  display: flex;
}

.col {
  flex: 1;
  text-align: center;
}

.col:nth-child(1) {
  padding-left: 20%;
}

.col:nth-child(2) {
  padding-right: 20%;
}

/*for example*/
.col {
  border: solid 1px #FEF;
  padding: 20px;
}

Left

Some longer text

Right

Some longer text

Really long text that might break break break break break break break break break break break break break break break break everything!


text:
Q: Loss function provide NAN gradient I used histogram loss as a loss function for my model but it provide NAN gradient.
Code snippet (loss function):
def histogram_loss(y_true, y_pred):
    h_true = tf.histogram_fixed_width( y_true, value_range=(-1., 1.), nbins=20)
    h_pred = tf.histogram_fixed_width( y_pred, value_range=(-1., 1.), nbins=20)
    h_true = tf.cast(h_true, dtype=tf.dtypes.float32)
    h_pred = tf.cast(h_pred, dtype=tf.dtypes.float32)
    return K.mean(K.square(h_true - h_pred))

Error messages:
ValueError: An operation has `None` for gradient. Please make sure that all of your ops have a gradient defined (i.e. are differentiable). Common ops without gradient: K.argmax, K.round, K.eval.

why I got value error (NAN gradient) ?

A: The gradient of tf.histogram is None... It's not a differential function
x = tf.Variable(np.random.uniform(0,10, 100), dtype=tf.float32)

with tf.GradientTape() as tape:
    hist = tf.histogram_fixed_width(x, value_range=(-1., 1.), nbins=20)
    hist = tf.cast(hist, dtype=tf.dtypes.float32)

grads = tape.gradient(hist, x)
grads