text:
Q: Short story about outworlder human cloning himself, using matter conversion to uplift world I'm trying to remember a short short in the Golden Age of SF (1920s-1950s) where the following was written:

*

*human from offworld came to a colony planet

*human was an agent sent to uplift world into interstellar civilization

*human needed to change politics, manufacturing, science, and schools upon the world

*human first cloned himself to be different people, one for each area of study that needed to be changed in the world

*I specifically remember the agent using a matter conversion device to change the economy of the world.  He was laughing as he pushed an encyclopedia book into the device's input hopper with the result being more and larger jewel-quality diamonds coming out the other side.  This wasn't matter duplication or even molecular disassemble/reassemble, but transmutation in real-time.  The agent fully intended on crashing the economy to change it.

*I think the short story did not end with the planet's population joining the interstellar civilization, but it was inferred.

Very old short story, told in the classic Golden Age SF style.  No idea as to whom the author was.

A: The story is "High Yield Bondage" by Hayford Pierce, published in the August 1975 Galaxy Science Fiction Magazine.
One of the salient facts not mentioned in the question is that the story is dominated by discussion of the financial transactions the agent makes as part of his uplift plan. Hence the punning title: "high yield bonds" while he is in "bondage".

human from offworld came to a colony planet
The alien was close to human, but it turned out not actually related:

... beings in brown uniforms, apparently from evolutionary stock similar to Huntleader Riderson's, got out to point instruments and take rock samples."
...
"Professor Camptargo will be extremely vexed: his lifelong determination to prove that the entire galaxy's sentient population is derived from the Great Migration of 31.000 years ago has already been proven suspect. As the first expedition into this arm since the Black Collapse and the Interregnum of 27.000 years ago, we have already learned that the beings of this world are not of our stock."

human was an agent sent to uplift world into interstellar civilization
human needed to change politics, manufacturing, science, and schools upon the world
This is not correct. He was sent to survey the planet, but crashed, and found it necessary to uplift the planet in order to effect repairs to the ship.

"I have determined the extent of the damage to the ship and have conceived a basic plan regarding its repairs .... At the least, it is the unsuspected subjugation of the geo-political unit in which we find ourselves. At the most, merely the conquest of the planet."

human first cloned himself to be different people, one for each area of study that needed to be changed in the world

"Your brothers, Hunt, those extra hands I promised you some time ago."
"My broth— Oh. Clones. You've been growing them in the vat."

The clones varied slightly...

One was shorter than himself and darker, the other taller and thinner. By their facial traits they might have been his cousins.

because it would be bad if they were identical

"It would be inconvenient in our dealings with this world, for us to seem as identical as we are."

I specifically remember the agent using a matter conversion device to change the economy of the world. He was laughing as he pushed an encyclopedia book into the device's input hopper with the result being more and larger jewel-quality diamonds coming out the other side. This wasn't matter duplication or even molecular disassemble/reassemble, but transmutation in real-time.
The device was referred to as a duplicator, but you're right about its operation -- it required feedstock.  Here's the diamonds quote:

He placed an uncut diamond into a softly humming machine. A beautifully cut gem popped out. He smiled. He looked about, found a hefty one-pound tome issued by the South African Chamber of Commerce; South Africa, An Industrial Profile.  He stuffed the book in. A pound of cut diamonds spewed forth. He laughed aloud.

The agent fully intended on crashing the economy to change it.
As I said earlier, the point was to repair the ship, and to do that, the planet had to be uplifted:

The real problem was the betwixt-and-between state of this world's technology. High enough to have invented double-entry bookkeeping, the creditcard economy, the IRS Gestapo; low enough to be incapable of producing a simple main-drive and gravitationless chamber for an old-fashioned SpaceMaster-Scout Mark IV. Without some well-directed inspiration it would be three or four hundred years before this planet's technology could effect the necessary repairs.

I think the short story did not end with the planet's population joining the interstellar civilization, but it was inferred.

"The Earthlings are mounting their first expedition to Centauri next year. One of these days, when they land in the University football stadium he'll be even less pleased."


text:
Q: How to get the hours difference between two date objects? I got two Date objects and I want to calculate the difference in hours.
If the difference in hours is less than 18 hours, I want to push the date object into an array.
Javascript / jQuery, doesn't really matter; what works the best will do.

A: Try using getTime (mdn doc):
var diff = Math.abs(date1.getTime() - date2.getTime()) / 3600000;
if (diff < 18) { /* do something */ }

Using Math.abs() we don't know which date is the smallest. This code is probably more relevant:
var diff = (date1 - date2) / 3600000;
if (diff < 18) { array.push(date1); }

A: The simplest way would be to directly subtract the date objects from one another.
For example:
var hours = Math.abs(date1 - date2) / 36e5;

The subtraction returns the difference between the two dates in milliseconds. 36e5 is the scientific notation for 60*60*1000, dividing by which converts the milliseconds difference into hours.

A: Use the timestamp you get by calling valueOf on the date object:
var diff = date2.valueOf() - date1.valueOf();
var diffInHours = diff/1000/60/60; // Convert milliseconds to hours

redpajama_set_name: RedPajamaStackExchange


text:
Q: Porque no me funciona google acount al generar apk Hice una app con autenticación de google mediante firebase, al ejecutar la app desde Android studio todo me corre perfectamente, al generar la apk y ejecutar desde la misma no me inicia sesión, pueden decirme porque puede ser

A: Cuando generas el APK y lo firmas con la llave que creaste, debes obtener los datos de esta llave para poder ponerlo en Firebase y que tu app sepa sobre este SHA1
Desde el terminal ubica keytool (se suele ubicar en C:\Program Files\Java\jdk1.7.0_25\bin>) y debes ingresar el siguiente comando para obtener el SHA1 de produccion
keytool -list -v -keystore {nombre_de_la_llave} -alias {alias_keystore}

Por ejemplo
keytool -list -v -keystore C:\Users\MG\Desktop\test.jks -alias test

una vez que hagas esto se va a mostrar el SHA1 de esta llave, lo copias, vas a Firebase , vas a la configuracion de tu proyecto , agregas un nuevo SHA1 y pones este que acabas de copiar, de esta forma cuando tu app la ejecutes creada para produccion va a poder identificarse con Firebase


text:
Q: Angular2+: Toggling element in multiple divs I have multiple div's with toggling  elements.  However, in my attempt, when I click on one div's (i.e. fa-bookmark), it toggles all of the other div's corresponding .
What I want is to be able to toggle the  in each individual div and not affect the other div's.
My HTML:

/*Repeat above HTML*/

My TS:
export class FlagsComponent implements OnInit {

  constructor() { }

  ngOnInit() {
  }
  items = {
    'flag': { flagStatus: false },
    'bookmark': { flagStatus: false },
    'alarmClock': { flagStatus: false }
  };
  flagActive(item) {
    console.log(this.items[item]);
    this.items[item].flagStatus = !this.items[item].flagStatus;
  }
}

A: you can use in one div
[hidden]="flag"

and in other div
[hidden]="!flag"

and make a click event

and your function look like
function flagActive(){
 this.flag = !this.flag
}

A: Use Directive if you want to repeat Div
@Directive({
  selector: '[appToggle]',
  exportAs:'appToggle'
})
export class ToggleDirective {
  toggle:boolean=false;
  constructor() { }

  @HostListener('click') onClick(){
     this.toggle=!this.toggle;
  }

}

Then use Different template variable for different div

    {{bookmark | json}}
    {{alarm | json}}

/*Repeat above HTML*/

    {{bookmark1 | json}}
    {{alarm1 | json}}

Example:https://stackblitz.com/edit/stackoveflow-toggle-div


text:
Q: persistLong not working even if I put literal inside - ClassCastException I've a quite strange problem. First please take a look at my code. I have made my custom class which extends EditTextPreference, and I overrode onClick(DialogInterface, which) method.
@Override
    public void onClick(DialogInterface dialog, int which) {
        super.onClick(dialog, which);

        switch(which) {
        case DialogInterface.BUTTON_POSITIVE:

            long currentDelay = (Long.parseLong(getEditText().getText().toString())*1000);

            if(currentDelay < 0.5) {

                getEditText().setText("1000");
                currentDelay = 1000;
            }

            persistLong(currentDelay); // Crashes (Even if I put literal inside)
            persistString(getEditText().getText().toString()); // It works
        break;

        }

If onclick method is executed, persistLong always crashes my program and it throws ClassCastException. Even if I put literal in parameters (like ,persistLong(4000) ). On the other way, persistString works just fine.
What could be the problem here? Any suggestions?
EDIT: My LogCat: Line 59 is where persistLong method is.
03-05 15:51:14.212: E/AndroidRuntime(22739): FATAL EXCEPTION: main
03-05 15:51:14.212: E/AndroidRuntime(22739): java.lang.ClassCastException: java.lang.String
03-05 15:51:14.212: E/AndroidRuntime(22739):    at android.app.ContextImpl$SharedPreferencesImpl.getLong(ContextImpl.java:2939)
03-05 15:51:14.212: E/AndroidRuntime(22739):    at android.preference.Preference.getPersistedLong(Preference.java:1388)
03-05 15:51:14.212: E/AndroidRuntime(22739):    at android.preference.Preference.persistLong(Preference.java:1359)
03-05 15:51:14.212: E/AndroidRuntime(22739):    at com.callandsmsled.MyEditTextPreference.onClick(MyEditTextPreference.java:59)
03-05 15:51:14.212: E/AndroidRuntime(22739):    at com.android.internal.app.AlertController$ButtonHandler.handleMessage(AlertController.java:159)
03-05 15:51:14.212: E/AndroidRuntime(22739):    at android.os.Handler.dispatchMessage(Handler.java:99)
03-05 15:51:14.212: E/AndroidRuntime(22739):    at android.os.Looper.loop(Looper.java:130)
03-05 15:51:14.212: E/AndroidRuntime(22739):    at android.app.ActivityThread.main(ActivityThread.java:3835)
03-05 15:51:14.212: E/AndroidRuntime(22739):    at java.lang.reflect.Method.invokeNative(Native Method)
03-05 15:51:14.212: E/AndroidRuntime(22739):    at java.lang.reflect.Method.invoke(Method.java:507)
03-05 15:51:14.212: E/AndroidRuntime(22739):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:864)
03-05 15:51:14.212: E/AndroidRuntime(22739):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:622)
03-05 15:51:14.212: E/AndroidRuntime(22739):    at dalvik.system.NativeStart.main(Native Method)


text:
Q: Multiple arrays with same indexs in php Hi I want to save records from array in php.I get arrays like
Array
(
    [0] => Make
    [1] => Model
    [2] => Year
    [3] => SKU
)

Array
(
    [0] => HTC
    [1] => Diamond
    [2] => 2008
    [3] => HTC Touch Diamond
)

Array
(
    [0] => Samsung
    [1] => M-900
    [2] => 2007
    [3] => MM-A900M
)

Array
(
    [0] => AT&T
    [1] => PDA
    [2] => 2002
    [3] => 8525PDA
)

Array
(
    [0] => AT&T
    [1] => PDA
    [2] => 2003
    [3] => 8525PDA
).

The above data coming from foreach loop like foreach($data as $row){ print_r($row);}.Now i want to save lower records against first array indexs like make,model,year and sku.The array index( make,model,year,sku) can be less or more means dynamic.How can i do that ? Thnaks

A: Try this :
$cnt = 0;
$res = array();
foreach($data as $row){
   if($cnt ==0){
      $key   = array();
      $key   = $row;
      $cnt++;
   }
   else{
     $res[]  = array_combine($key,$row);
   }
}

echo "<pre>";
print_r($res);

A: Use build-in function array_combine


text:
Q: WordPress Multisite - (de)activate site action I'm searching the WordPress codex for this but I can't seem to find any article on this issue.
When you have installed WordPress multisite and login as the superadmin you have the ability to archive,(de)activate and delete sites. This is however from the 'network' part of the installation, that only the superadmin can see. I want to place take the (de)activate option in every site's dashboard as well, so a specific (non (super)admin) role can use them to.
I want to know, is there a function I can use to display the (de)activate (depending on if the sites is active/deactive at that moment) links where I want to?
If there is not, where is the information about whether a site is active or not stored ? I was hoping for an option with a boolean in it but I can't seem to find it. This way I will be able to check myself if a site is active or not and depending on that display the correct link?
Sorry if my question is unclear or confusing.
Thanks in advance!

A: Deactivating the site, just adds the deleted attribute on it. And site administrators already can do that by visiting Tools -> Delete site. It is only a little different because it also removes the users from the site if it is clicked from there (it might be made in the future to be the same though).
You can use this function to see if a site with ID 2 for example has the attribute deleted (so it is deactivated):
if ( get_blog_status( 2, 'deleted' ) == 1 ) {
    // The site with ID 2 is marked as deleted (it is deactivated)
}

A: For the specific username rights I used:
//give the right to deactivate sites to 'username' if the user doesn't have it already
$user = new WP_User( 'username' );
if ( ! $user->has_prop( 'can_manage_sites' ) ) {
   $user->add_cap( 'can_manage_sites' );
}
if ( ! $user->has_prop( 'username' ) ) {
   $user->add_cap( 'manage_sites' );
}

//ofcourse replace 'username' with the username you need

In my view (wich loops mu sites) I simply used an if statement to check if the site was active or not to know what link to use (activate/deactivate)
//deactivated, show activate link
if(get_blog_status( $site->blog_id, 'deleted' ) == '1'){
    echo ' Niet actief
';
    echo 'blog_id ), 'activateblog_' . $site->blog_id ) ) . '">' . __( 'Activate' ) . '';
}
//activated, show deactivate link
else {
    echo ' Actief
';
    echo 'blog_id ), 'deactivateblog_' . $site->blog_id ) ) . '">' . __( 'Deactivate' ) . '';
}

This code will get you the link you need to (de)activate the site wich will get you to a confirmationpage.In this confirmationpage the user can see a 'sites'tab in the menu, when they click it they have the options for all the sites in the mu. This didn't matter for me since the people who will be using this functionality are colleages and know they shouldn't go there. But you might want to hide that if it concerns people who shouldn't be able to see that


text:
Q: Flutter TableCalendar . SharedPreferences I want to save the table calendar data.
First of all, I succeeded in creating data for each date, but I don't know how to use sharedPreferences.
I don't know what it is even if I googled it and applied it in various ways.
https://medium.flutterdevs.com/display-dynamic-events-at-calendar-in-flutter-22b69b29daf6
I think the code that's closest to the answer is this person's method
If you apply it and make some changes, you will encounter various bugs.
I spent almost a week on this for three hours. It's so hard that I just want to solve it today.
I have to work out, and I have a lot of other assignments
Because of the desire to keep solving this problem, it doesn't get out of the chair.
My personality is getting dirty after meeting a problem that hasn't been solved for a week.
I beg you.

class DiaryService extends ChangeNotifier {

  DateTime focusedDay = DateTime.now();
  DateTime selectedDay = DateTime.now();

  TextEditingController createFieldController = TextEditingController();
  TextEditingController updateFieldController = TextEditingController();

  List<Diary> diaryList = [];

  Map<DateTime, List<Diary>> diaryMap = {};

  List<Diary> getByDate(DateTime date) {
    return diaryMap[date] ?? [];
  }

  void create(String text, DateTime selectedDate) {
    diaryList.add(Diary(text: text, createdAt: DateTime.now(), selectedDate:
selectedDate));
    diaryMap[selectedDate] = diaryList.where((element) {
      return element.selectedDate == selectedDate;
    }).toList();
    print(selectedDate.day);
    notifyListeners();
  }

  void update(DateTime createdAt, String newContent) {
    int t = diaryList.indexWhere((element) => element.createdAt == createdAt);
    diaryList.removeWhere((element) => element.createdAt == createdAt);
    diaryList.insert(t, Diary(text: newContent, createdAt: createdAt,
selectedDate: selectedDay));
    addListInMap();
    notifyListeners();
  }

  void delete(DateTime createdAt) {
    diaryList.removeWhere((element) => element.createdAt == createdAt);
    addListInMap();
    print(getByDate);
    print(diaryMap);
    notifyListeners();
  }

  void addListInMap() {
    diaryMap[selectedDay] = diaryList.where((element) => element.selectedDate
== selectedDay).toList();
  }

  void encodeData() async {
    String dd = Diary.encode(diaryList);
    SharedPreferences prefs = await SharedPreferences.getInstance();
    prefs.setString("diaryList", dd);
    notifyListeners();
  }

  Future<List<Diary>> decodeData() async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    String getData = prefs.getString("diaryList") ?? "[]";
    print(getData);
    diaryList = Diary.decode(getData);
    notifyListeners();
    return diaryList;
  }
}


text:
Q: curl to python for post request I would like to "translate" my curl request into python using request or urllib.
I try to post a file.
My curl request is :
curl -X POST -H "Content-Type: multipart/form-data" -H "Authorization: Bearer $1" -F "data=@$2;filename=$3" --cert certificateprivate.pem --cacert MyDigiCertSHA2.crt.pem <my_url>

I tried the code below ( doesn't work , response 400)
def upload_file(token,file_path):
    ctx = ssl.create_default_context(ssl.Purpose.CLIENT_AUTH,cafile='MyDigiCertSHA2.crt.pem')
    ctx.load_cert_chain(certfile='certificateprivate.pem')
    url = <my_url>
    hdr = {"Content-Type": "multipart/form-data","Authorization":"Bearer "+token}
    data = '{"filterList":[{}]}'
    with open(file_path, 'rb') as f:
        from urllib import request, parse
        data = parse.urlencode( {'filename':file_path,"data": f.read()}).encode()
        req = request.Request( url, data = data,headers=hdr)
        resp = request.urlopen(req, context=ctx)
        content = resp.read()
        data = json.loads(content.decode('utf-8'))
        print(data)

A: The curl command has "Content-Type: multipart/form-data", but your python code has "Content-Type": "application/json".


text:
Q: Lyx not working with any \cite, or MMD cite I have a slight problem with Lyx and citations that I have not been able to find a solution to anywhere else.
When inserting any citation style, such as the following (notice #1 and #4 are identical, expect that #1 is greyed out as i inserted it manually):

Lyx outputs #2 #3 #4 as text, and #1 as a working citation, despite it being identical to #4.

--
I have tried switching between different bibtex styles (plain, natbib, ect.) under document/settings/bib and I've added \usepackage{cite}, \usepackage{MMD} to my preamble. But to no avail.
Any ideas how to solve this?
FYI, I am running 2.1.2 on a Macbook Pro (Yosemite 10.10.1), and I use Papers3 as my reference manager.
Any input is appreciated!
best,
T

A: I will self answer this one.
Answer was simple. Type your citation inside a ERT box. Press CTRL-L to insert ERT box. It should look like this:


text:
Q: Styling React Component with class How can we define CSS class within react component, not in external style sheet? I know there is a concept call CSS module which solve the issue of global style sheet. Is there any other way to style component by defining classes with in component?

A: it's very simple, just run command "npm run eject" It moves create-react-app's configuration files and dev/build/test scripts into you app directory.
now go to config folder and open 'webPackConfig.js' file and add the following code
          use: getStyleLoaders({
              ....
              ....
            modules:true,
            getLocalIdent:getCSSModuleLocalIdent,
            localIdentName: '[name]_[local]_[hash:base64:5]'
          })

example:
import React from 'xyz';
import Logo from '../../Logo/Logo';

import classes from './Toolbar.css';
import NavigationItems from '../NavigationItems/NavigationItems';
import DrawerToggle from '../SideDrawer/DrawerToggle/DrawerToggle';

const toolbar = (props) => (
    <header className={classes.Toolbar}>
        <DrawerToggle clicked={props.DrawerToggleClicked}/>
        <div className={classes.Logo}>
            <Logo />
        </div>
        <nav className={classes.DesktopOnly}>
            <NavigationItems />
        </nav>
    </header>
);
export default toolbar;

try this and you can definitely solve your issue


text:
Q: how to scaffold complex types in asp.net mvc3? I have a User class that has a property of type Login, which is just another simple class composed of two string properties, Username and Password.
What would be the correct (and best) way to make MVC3 scaffold the Login property too when adding a Scaffolded View for the User class?
I saw this question related to this right here on StackOverflow, but it asked MVC2, and since I've read that MVC3 improved scaffolding a lot, I want to know if there's a better way to do it.
Thanks!

A: EDIT: This article shows how to do what you're looking for exactly (one to many relationship):
http://weblogs.asp.net/scottgu/archive/2011/05/05/ef-code-first-and-data-scaffolding-with-the-asp-net-mvc-3-tools-update.aspx
Steven Sanderson is also crazy good with this kind of stuff.  Check out his MvcScaffolding project with a One to Many relationship scaffolder:
http://blog.stevensanderson.com/2011/01/28/mvcscaffolding-one-to-many-relationships/


text:
Q: AJAC MVC3 Request object and raw Ajax data, where the heck is it? If this was a regular post of a form I could go to Request.Form['somevalue'] and get the value. If this was a get with a query string I could go to Request.QueryString["somevalue"] and get the value.
Where is the raw data when you post an ajax request. I need a value out of the raw data string in a filter method.
Any help will be appreciated!!
Edits below:
public class ValidateAntiForgeryId : FilterAttribute, IAuthorizationFilter {
    public void OnAuthorization(AuthorizationContext filterContext) {
        if (filterContext == null) {
            throw new ArgumentNullException("filterContext");
        }

        Guid filterGuid;
        Guid.TryParse(filterContext.RequestContext.HttpContext.Request.Form["__sessionId"], out filterGuid);

        if (filterGuid == Guid.Empty)
            throw new AuthenticationException("Authentication failure");
        try {
            var cookieGuid = (Guid)filterContext.RequestContext.HttpContext.Items["SessionId"];
        } catch {
            throw new AuthenticationException("Authentication failure");
        }
    }

The posted data looks like this:
{"SsnLastFour":"2222","AccountNumber":"B112233","__sessionId":"dca0a504-3c40-4118-ae19-afefb9bfc8bd"}

I need access to the __sessionId chunk inside the filter.

A: There's nothing magic about AJAX posts.  They're just plain old HTTP.  That means you have plain old HTTP post values, and/or plainold HTTP Get values.
If you're not seeing them, it probably means you're not actually submitting them.
EDIT:
Two issues you did not include in your original question:  1) That this is JSON, and 2) That this is in an AuthorizationFilter (rather than an action method).
Both change the answers.  Since ASP.NET does not natively understand JSON post values, you will have to parse them, via Request.InputStream.  MVC3 by default has a JSON model binder, but AuthorizationFilters execute before model binders do, so you will be accessing things prior to the model binders being executed, and as such FormsCollection won't be populated (Request.Form[] won't work either, because as I said, asp.net doesn't natively understand JSON).
You may find that installing JSON.net via nuget may help with this task.  Or you might just write a simple parse routine, since you know exactly what you're looking for.

A: You can accept the parameter values the same way you accept in normal form post.
Ex :
$.get("User/Get", { userId : "24"} ,function(data){
  alert(data);
});

or
$("#yourDivId").load("User/Get?userId=23");

Your action method should look like
public ActionResult Get(int userId)
{
 // you have value present in userId
  if(Request.IsAjax())
  {
     return View("Partial/MyPartialView");
  }
  return View();
}

One thing you have to remember is, the parameter name of your action method should be same as of what your parameter/querystring name.

A: The fitlerContext has an ActionParameters collection which should have the parsed JSON properties (in case that helps). This may be easier than parsing the InputStream.
var sessionId = filterContext.ActionParameters["__sessionId"];


text:
Q: Retrieving Values from Getters and Setters I'm having an issue retrieving a values from my getters and setters. I'm setting the value in one class and then trying to retrieve it in another so that it can be used in a label. I haven't done any programming in Java in a while so I feel that there is something fundamental that I am not aware of.
I've written this short code to display the problem I'm having in my main project. Any help will be appreciated, I hope you have a good day.
Form1 Class:
public class Form1 extends JFrame implements ActionListener {

    JButton btn1;
    JTextField tf1;

    public Form1() {

        btn1 = new JButton("submit");
        btn1.setBounds(75, 90, 100, 40);
        btn1.setFocusable(false);
        btn1.addActionListener(this);

        tf1 = new JTextField();
        tf1.setBounds(20, 30, 200, 40);
        btn1.addActionListener(this);

        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        this.setSize(250, 180);
        this.setLayout(null);
        this.setResizable(false);
        this.setVisible(true);
        this.add(btn1);
        this.add(tf1);
    }
    public void actionPerformed(ActionEvent e) {

        String b = "";
        String v = "";
        String m = "";
        String r = "";

        Cars car = new Cars(b, v, m, r);

        if(e.getSource()==btn1) {

            b = tf1.getText();
            car.SetBmw(b);

            new Form2();
            System.out.println(car.GetBmw());
            // Side note, for some reason this will be printed twice in the console.
        }
    }
}

Form2 Class:
import javax.swing.JFrame;
import javax.swing.JLabel;

public class Form2 extends JFrame {

    Cars car = new Cars();

    public Form2() {

        JLabel label = new JLabel();
        label.setText(car.GetBmw());
        label.setBounds(10, 10, 50, 50);

        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        this.setSize(250, 180);
        this.setLayout(null);
        this.setResizable(true);
        this.setVisible(true);
        this.add(label);
    }
}

Cars Class:

public class Cars {

    private String bmw;
    private String vw;
    private String mazda;
    private String renault;

        public Cars() {}
        public Cars(String bmw, String vw, String mazda, String renault) {

            this.bmw = bmw;
            this.vw = vw;
            this.mazda = mazda;
            this.renault = renault;
        }

        // Getters and Setters for BMW
        public String GetBmw() {
            return bmw;
        }
        public void SetBmw(String bmw) {
            this.bmw = bmw;
        }

        // Getters and Setters for VW
        public String GetVw() {
            return vw;
        }
        public void SetVw(String vw) {
            this.vw = vw;
        }

        // Getters and Setters for Mazda
        public String GetMazda() {
            return mazda;
        }
        public void SetMazda(String mazda) {
            this.mazda = mazda;
        }

        // Getters and Setters for Renault
        public String GetRenault() {
            return renault;
        }
        public void SetRenault(String renault) {
            this.renault = renault;
        }
}

A: In Form2 you are creating a new Cars instance:
    Cars car = new Cars();

This is a completely different instance to the one created in Form1.actionPerformed, so it will have completely unrelated values. Since you're using the parameterless constructor here, all the fields will be at their default value of null.
It's difficult to tell what your intention is, because this is a meaningless toy example, but my best guess is that you want to pass the created Cars instance into the constructor of Form2.
In Form1.actionPerformed(), pass the created instance (called car) to the constructor:
            new Form2(car);

In Form2, receive the value and assign it to the field:
import javax.swing.JFrame;
import javax.swing.JLabel;

public class Form2 extends JFrame {

    Cars car;

    public Form2(Cars car) {
        this.car = car;

        ...
    }
}

A: You are creating a new instance of Car in Form2 which is empty, and you are using getters on this empty instance.
To retrieve data on instance from Form1, you have to pass it to Form2, through constructor for example:
    public void actionPerformed(ActionEvent e) {

        String b = "";
        String v = "";
        String m = "";
        String r = "";

        Cars car = new Cars(b, v, m, r);

        if(e.getSource()==btn1) {

            b = tf1.getText();
            car.SetBmw(b);

            new Form2(car);
            System.out.println(car.GetBmw());
            // Side note, for some reason this will be printed twice in the console.
        }
    }

public class Form2 extends JFrame {

    public Form2(Car car) {

        JLabel label = new JLabel();
        label.setText(car.GetBmw());
        label.setBounds(10, 10, 50, 50);

        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        this.setSize(250, 180);
        this.setLayout(null);
        this.setResizable(true);
        this.setVisible(true);
        this.add(label);
    }
}


text:
Q: Dynamo DB single table design and query I'm new to Dynamo and scratching my head on how query my table, and I think I might overthink things. I have a simple table with partners with corresponding developers. I would like to query the partner data based on a given developer id. I've created a secondary global index with base table SK as PK (which lets me query with developer#123), but how would I get the partner item (partner#123) by developer id (developer#123) in this scenario in one single query? I'm only querying using the aws console now so now code examples available.
Any pointers would be greatly appreciated!


text:
Q: Server 2012 R2 missing PSReadline cmdlets? Works on Win 10 but on server 2012 R2 its not there.
PS> Get-PSReadlineKeyHandler
Get-PSReadlineKeyHandler : The term 'Get-PSReadlineKeyHandler' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was
included, verify that the path is correct and try again.
At line:1 char:1
+ Get-PSReadlineKeyHandler
+ ~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : ObjectNotFound: (Get-PSReadlineKeyHandler:String) [], CommandNotFoundException
    + FullyQualifiedErrorId : CommandNotFoundException

Can confirm I'm running v5
PS> $PSVersionTable

Name                           Value
----                           -----
PSVersion                      5.0.10586.117
PSCompatibleVersions           {1.0, 2.0, 3.0, 4.0...}
BuildVersion                   10.0.10586.117
CLRVersion                     4.0.30319.42000
WSManStackVersion              3.0
PSRemotingProtocolVersion      2.3
SerializationVersion           1.1.0.1

A: You can install it from the PowerShell gallery. But I believe you are correct that Windows 10 is the only OS that installs the module by default.
Find-Module psreadline | Install-Module


text:
Q: Remove duplicate data from dynamic select option of HTMl form In my website's database, there are a lot of posts inserted with the date. I am making a post shorting system where a user selects a year from the dynamic dropdown and after pressing the submit button only that year's post will be visible on the website. Everything is going good but on the dynamic dropdown, a year is showing multiple time.
For example, There are 3 posts in my database which date is 2/2/2019 , 21/2/2019 , 22/3/2019. In my dynamic dropdown there I find 2019 3 times, but I need to show 2019 only one time.
I have tried some jQuery and JavaScript code but it did not work.
My code :
<?php
    $query = "SELECT year(date) FROM `press_release` WHERE del_status=0";
    $year = $conn->query($query);
?>

<form class="form-inline title" action="press_new.php" method="post">

        Search by year
        <select name="year">
            <option value="0">Please Select</option>

            <?php while($row = mysqli_fetch_array($year)){ ?>
                <option value="<?php echo($row['year(date)'])?>">
                    <?php echo($row['year(date)']) ?>
                </option>
            <?php } ?>
        </select>
        <button type="submit" name="submit" class="btn btn-default" style="background-color:#EB2227">Submit</button>

</form>

A: Select unique/distinct years instead of just year in your sql query.
<?php

        $query = "SELECT distinct year(date) FROM `press_release` WHERE del_status=0";
        $year = $conn->query($query);
        ?>

        <form class="form-inline" class="title" action="press_new.php" method="post">

                Search by year
                <select name="year">
                    <option value="0">Please Select</option>
                    <?php
                        while($row = mysqli_fetch_array($year))
                        {
                    ?>
                    <option value="<?php echo($row['year(date)'])?>">
                        <?php echo($row['year(date)']) ?>
                    </option>
                    <?php
                        }
                    ?>
                </select>
                <button type="submit" name="submit" class="btn btn-default" style="background-color:#EB2227">Submit</button>

        </form>

A: Have you tried DISTINCT ?
$query = "SELECT DISTINCT year(date) FROM `press_release` WHERE del_status=0";


text:
Q: $\tau$ structure of the sixth Painlevé equation I am studying the isomonodromic deformations theory, which leads in the case of a $\mathcal{C}_{0,4}$ Riemann surface to the sixth Painlevé equation.
I read that this equation had a $\tau$-structure, so we can determine a $\tau$ function associated to isomonodromic deformations.
Here is my silly question : what is a $\tau$-structure, why is it important ?

A: A good starting point for learning how $\tau$ functions are defined explicitly is Okamoto's paper: Okamoto, K. (1981). On the $\tau$-function of the Painlevé equations. Physica D: Nonlinear Phenomena, 2(3), 525-535. Okamoto starts from a Hamiltonian viewpoint.
A $\tau$ function associated with a Painlevé equation has (movable) zeroes where the solution of the original equation has (movable) poles. This analytic relationship is explained, e.g., in Hietarinta, J., & Kruskal, M. D. (1992). Hirota forms for the six Painlevé equations from singularity analysis. In Painlevé Transcendents (pp. 175-185). Springer, Boston, MA.
If you are familiar with elliptic functions, it may be useful to know that the same role is played by Weierstrass' sigma function $\sigma(x)$ or Jacobi's theta functions. These associated functions have zeroes where the elliptic function has poles. See for example, Chapter 23 of DLMF, where Weierstrass' sigma function $\sigma(x)$ is defined with zeroes where $\wp(x)$ has poles. Similarly, theta functions associated with Jacobi's elliptic functions are entire functions.
I am not familiar with the term $\tau$-structure, but I am familiar with what is often called a $\tau$-lattice. This is a fascinating lattice of interrelationships between $\tau$ functions corresponding to different values of parameters in a Painlevé equation. These relationships are also related to isomonodromy problems. See for example Section 5 of Jimbo, M., & Miwa, T. (1981). Monodromy perserving deformation of linear ordinary differential equations with rational coefficients. II. Physica D: Nonlinear Phenomena, 2(3), 407-448.
It is impossible to answer your question "why is it important?" in finite terms.  One answer is that $\tau$ functions are functions of several variables and satisfy differential equations, differential-difference equations and partial difference equations with very rich properties. They are special cases of the Hirota's DAGTE equation, which includes almost all the known integrable equations (including the Kadomtsev-Petviashvili equation) and their difference versions. See Hirota, R. (1981). Discrete analogue of a generalized Toda equation. Journal of the Physical Society of Japan, 50(11), 3785-3791.
I hope this helps.


text:
Q: How can I place my scene with a background of the Andromeda galaxy I'm rather new at povray and I've been struggling with just getting a simple background image behind my rendering. I can create spheres and atmospheres and mapping clouds and surfaces, but I can't make an image simply show up behind my planet.
I've tried the sky_sphere, I've tried putting an infinite plane behind the planet but the Andromeda image_map will not just map as it is. It's either distorted, or zoomed in so close a single star is the size of a dime, or the stars are lines radiating out like I'm making the jump to light speed. There's got to be the right combination of map_type, scaling and translate that will get me what I want but I haven't found it yet.
I'm assuming this is a simple thing for anyone with experience.
I'm after something like this:


text:
Q: adding css and js file in view for application based on play framework Adding reverse routing in view file is causing error. Following is the snippet:
@main(title = "index")  {
<head>
    <link rel="stylesheet" type="text/css" href='@routes.Assets.at("/Content/Site.css")' />
    <script  type="text/javascript" src='@routes.Assets.at("Scripts/bootstrap.js")'></script>

</head>
<body>
</body>
}

I have added the css and js file in public folder
  [error] C:\myproject\app\views\index.scala.html:5: value at is not a member of controllers.ReverseAssets
  [error]     <link rel="stylesheet" type="text/css" href='@routes.Assets.at("/Content/Site.css")' />
  [error]                                                                     ^
  [error] C:\myproject\app\views\index1.scala.html:6: value at is not a member of controllers.ReverseAssets
  [error]     <script  type="text/javascript" src='@routes.Assets.at("Scripts/bootstrap.js")'></script>

Any help is appreciated.

A: I have to use following syntax for getting rid of error
 <link rel="stylesheet" type="text/css" href='@routes.Assets.versioned("stylesheets/Content/bootstrap.css")'


text:
Q: MinGW compiler for Qt 5.5 MSVC 2013 version I've installed Qt 5.5 MSVC 2013 version on my Windows 7 64bit PC. The problem is that I don't have Visual Studio 2013 installed on my PC. I've Visual Studio 2012. But my Qt does not detect compilers from Visual Studio 2012. Is it possible to use MinGW as compiler in Qt  5.5 MSVC 2013?

A: No, not possible. Especially on Windows, you have to use any C++ libraries built with the same toolchain you are using to build the application.
So if you want to use MinGW toolchain, you have to use MinGW version of Qt libs (be it with installer or by building it yourself). If you want to use some MSVC version, you need matching version of Qt, etc.
Note that you should be able to use the free "Express" version of MSVC (as long as it is the right "year" and service pack version), if you really want to go with MSVC. However, since Qt installer can install the MinGW toolchain, it's much easier, no special setup needed.


text:
Q: smallest set of curves for constructing any real number and angle If we are limited by what we can construct with compass and straight edge,
then what are the fundamental curves required for constructing any real number?
In other words, what is the smallest collection of geometric objects for constructing a line segment of any length? And does that collection also allow for the construction of any angle?
This question is not limited to tangible tools. Any software tool or theoretical tool that is based on already constructed points, lines and circles is fine.

A: It seems the following.
If on each step of the construction we have a finite number of choices of operations, if we are based on already constructed points, lines and circles, there we can obtain only countably many results. So to construct a segment of each length and an arc of each angle we have to have a $\frak c$ many choices. But in this case we may simply enumerate all angles and real numbers as our tools.
PS. But the question with algebraic numbers instead of real seems not so trivial, so you may ask it as a different question at MSE.


text:
Q: concatenate columns and selecting some columns in Pyspark data frame I have a data frame like below in pyspark
data = [
(1, 'a', '', 'b', '', 'c', '123_abc', 'sam', 'NY'),
(2, 'b', 'abc_123', 'd', '', 'e', '', 'Tim', 'NJ'),
(3, 'c', '', 'f', '', 'g', '', 'Jim', 'SFO')]

df = sc.parallelize(data).toDF(["id", "abc_abled", "abc_serial", "bca_abled", "bca_serial", "cca_abled", "cca_serial", "name", "city"])

df
DataFrame[id: int, abc_abled: string, abc_serial: string, bca_abled: string, bca_serial: string, cca_abled: string, cca_serial: string, name: string, city: string]

df.show()

+---+---------+----------+---------+----------+---------+----------+----+----+
| id|abc_abled|abc_serial|bca_abled|bca_serial|cca_abled|cca_serial|name|city|
+---+---------+----------+---------+----------+---------+----------+----+----+
|  1|        a|      null|        b|      null|        c|   123_abc| sam|  NY|
|  2|        b|   abc_123|        d|      null|        e|      null| Tim|  NJ|
|  3|        c|      null|        f|      null|        g|      null| Jim| SFO|
+---+---------+----------+---------+----------+---------+----------+----+----+

I want to create a new data frame by selecting the following columns and concatenate certain column values.
df1
DataFrame[id:int, serial_number: string, name:string, city:string]

df1.show()

+---+-------------+----------+
| id|serial_number|name| city|
+---+-------------+----------+
|  1|      123_abc| sam|   NY|
|  2|      abc_123| Tim|   NJ|
|  3|             | Jim|  SFO|
+---+-------------+----+-----+

Here serial_number will be all columns that end with _serial concatenated. If the columns have null values ignore the values and concatenate other strings
How can I achieve that?

A: All you have to do is get the array of column names that ends with _serial
serialCols = [x for x in df.columns if str(x).endswith('_serial')]

Then use it with concat_ws inbuilt function to concat the column values in select expression as
from pyspark.sql import functions as f
df.select(
    df['id'],
    f.concat_ws('', *serialCols).alias('serial_number'),
    df['name'],
    df['city']
).show(truncate=False)

Here I have used an empty character to concat the strings
so the above code should give you
+---+-------------+----+----+
|id |serial_number|name|city|
+---+-------------+----+----+
|1  |123_abc      |sam |NY  |
|2  |abc_123      |Tim |NJ  |
|3  |             |Jim |SFO |
+---+-------------+----+----+

Edit: One could also use pyspark.sql.functions.concat() in place of concat_ws().


text:
Q: Audio issue with Samsung NP350E5C I have Ubuntu 18.04.3 LTS at my old laptop Samsung NP350E5C-S05.
A little strange but sometimes I have audio issue.
It happens especially when I turn on the laptop. I try playing music / YouTube video but nothing plays.
When I run audio settings and run through cards like "Input, Output, Sound effects, Programs" sound works (two times, sometimes one).
After that sound works perfect, as long as I don't need to reboot the machine. In the long perspective it is really frustrating.
I have another PC with Debian(gnome) and something like that doesn't happen there at all.
Previously I had Ubuntu 16.04 with the same problem.
lspci:


text:
Q: UWP MVVM Sqlite C# - New items added to listview update after page is reloaded I am trying to implement CRUD functionality to use with a local SQLite database (namespace Microsoft.Data.Sqlite) and following an MVVM pattern (John Shew's Blog).
I encounter an issue where the update functionality does not work on newly added items to the listview. Any new items added to a listview will need to be reloaded before the user can edit their data and have the change update in the database. Items that were previously loaded into the listview can still be edited, and those changes are reflected in the listview and in the database.
I've looked into using async/await, Task Async Programming, switching all List<> to ObservableCollections<>, and still not working. I've looked through a lot of posts and now coming to stackoverflow for help.
I'm not sure what code to post, as I only want to provide what's applicable for diagnosis and not create too much noise/clutter. Please let me know and I will provide.
public static void InitializeDatabase()
        {
            using (SqliteConnection db =
                new SqliteConnection("Filename=TestDB.db"))
            {
                db.Open();
            string tableCommand = "CREATE TABLE IF NOT " +
                "EXISTS Student (Id INTEGER PRIMARY KEY AUTOINCREMENT, " +
                "Name NVARCHAR(2048) NULL," +
                "Email NVARCHAR(2048) NULL)";

            SqliteCommand createTable = new SqliteCommand(tableCommand, db);
            createTable.ExecuteReader();
            db.Close();
        }
    }
public static void Write(Student student)
        {
            using (SqliteConnection db = new SqliteConnection("Filename=TestDB.db"))
            {
                db.Open();
                SqliteCommand insertCommand = new SqliteCommand
                {
                    Connection = db,
                    CommandText = "INSERT INTO Student VALUES (NULL, @Name, @Email)"
                };
                insertCommand.Parameters.AddWithValue("@Name", student.Name = "");
                insertCommand.Parameters.AddWithValue("@Email", student.Email = "");
                insertCommand.ExecuteReader();
                db.Close();
            }
        }

public static void Update(Student student)
        {
            using (SqliteConnection db = new SqliteConnection("Filename=TestDB.db"))
            {
                db.Open();
                SqliteCommand insertCommand = new SqliteCommand
                {
                    Connection = db,
                    CommandText = "UPDATE Student SET Name=@Name, Email=@Email WHERE Id=@Id";
                };
                insertCommand.Parameters.AddWithValue("@Name", ((object)student.Name) ?? DBNull.Value);
                insertCommand.Parameters.AddWithValue("@Email", ((object)student.Email) ?? DBNull.Value);
                insertCommand.Parameters.AddWithValue("@Id", ((object)student.Id) ?? DBNull.Value);
                insertCommand.ExecuteNonQuery();
                db.Close();
            }
        }


text:
Q: Солирование паролей пользователей Есть таблица с пользователями, в колонке хранится зашифрованный пароль. Я хочу, чтобы каждый пользователь имел свою соль, а не общую, для лучшей безопасности. Как это лучше реализовать? Иметь дополнительную колонку для солей, или сделать какую-нибудь функцию для генерации уникальной соли? Я не хочу использовать функцию, т.к. тут трудности что брать за параметр (имя (меняется), дату регистрации (может быть общая), id - слишком простое значение). Подскажите у кого есть опыт.

A: дополнительная колонка для соли.
https://cheatsheetseries.owasp.org/cheatsheets/Password_Storage_Cheat_Sheet.html#salting
Имхо, соль не обязательно должна быть уникальной, т.е. не нужно по ней создавать уникальный констрейнт. Куда важнее ее случайность.
Генерировать соль лучше всего безопасным генератором случайных чисел. Например:
static final SecureRandom PRNG = new SecureRandom();
static final int SALT_SIZE = 16; // length of your salt column

// ...

byte[] salt = new byte[SALT_SIZE];
PRNG.nextBytes(salt);

но это нужно только в том случае, если использовать классические хэш алгоритмы, если же взять к примеру BCrypt то соль будет закодирована в хэш, т.е. дополнительная колонка будет не нужна.


text:
Q: App with UINavigationController and UITabBarController I've been struggling around for some time with this problem. I got it working but not the way it should and I guess its because Im doing it wrong. My goal is to have the following layout.
I have a Main Menu with four buttons. Clicking on each shows a different TableView (I should have a back button in the right corner of the navController, to be able to go back to the main menu, but I don't). Each of these TableViews are inside a UITabBarController (looks like this http://i.stack.imgur.com/GkFwo.jpg)
So how do I have to do this?
This is my current code (definitely wrong at some point(s))
- (IBAction)MyButton:(id)sender
{
self.tabBarController = [[UITabBarController alloc] init];
UIViewController *viewController1, *viewController2, *viewController3, *viewController4;
if ([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPhone) {
    viewController1 = [[[LexikonControllerViewController alloc] initWithNibName:@"LexikonControllerViewController" bundle:nil] setArrays:PflanzenIDs List:ListOfPlants Index:IndexOfPlants dict:DictionaryOfPflantsAndIDs];
}

UINavigationController *navController1 = [[UINavigationController alloc] initWithRootViewController:viewController1];

NSArray* controllers = [NSArray arrayWithObjects:navController1, nil];

self.tabBarController.viewControllers = controllers;

CGRect frame = self.tabBarController.view.frame;
frame.size.height = frame.size.height - 20;
self.tabBarController.view.frame = frame;

[self.view addSubview:self.tabBarController.view];
}

EDIT:
Now I tried this:
    - (void)applicationDidFinishLaunching:(UIApplication *)application
    {
    window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
vc = [[MyViewController alloc] init];
[vc setTitle:@"Home"];
[vc setParent:self];

navController = [[UINavigationController alloc] initWithRootViewController:vc];

UITabBarController *tb = [[UITabBarController alloc] init];
NSArray *controllers = [[NSArray alloc] initWithArray:[NSArray arrayWithObjects:navController, nil]];
tb.viewControllers = controllers;

[window addSubview:[tb view]];
[window makeKeyAndVisible];
}

Problem: on the main view (with the main menu) I can see the tab bar (which shouldnt be there) and using hidesBottomBarWhenPushed hides the tabbar completetely on all other views :(

A: The tab bar controller should be your root view controller.  You could also hook this up within a storyboard.

A: Made it. What I did was set up my Main menu as root view for the navigationcontroller and if I click on one of the buttons I load a new UIViewController which takes care of setting up a TabBarController and load my four different tableviews in each Tab.
All of this without storyboard and XIBs.


text:
Q: Select specific part in file name For example the files come in this format.
JasperReports - 14000369-ITR-2022-ORIGI-Recibo.pdf

JasperReports - 14000369-ITR-2022-ORIGI-Declaracao.pdf

JasperReports - 13079980-ITR-2022-ORIGI-Recibo.pdf

JasperReports - 13079980-ITR-2022-ORIGI-Declaracao.pdf

The part that needs the name is the one that has this 8-digit code "14000369", as it is what identifies each document, when I get that name I need to create a folder and move the files to it and move to the next file, the folder contains more than 400 files, with different codes so I want to automate, that's what I've managed to do, I'm starting in python.
from importlib.resources import path
import os
import os.path
from pathlib import Path
caminho = r"C:\Users\amanda.regina.PROCONT\Desktop\move\itr"
lista_arquivos = os.listdir(caminho)

for arquivo in lista_arquivos:
    print(arquivo)
#lista_arquivos = os.listdir(caminho+"\itr")
path = Path(caminho)
for arquivo_nome in path.glob('*13079980*'):
    print(arquivo_nome)

A: If the file names are always in this format, you can use .split() to extract the number and then create the directory with os.mkdir() and move the files there with shutil.move():
import os
from shutil import move

files = ['JasperReports - 14000369-ITR-2022-ORIGI-Recibo.pdf',
         'JasperReports - 14000369-ITR-2022-ORIGI-Declaracao.pdf',
         'JasperReports - 13079980-ITR-2022-ORIGI-Recibo.pdf',
         'JasperReports - 13079980-ITR-2022-ORIGI-Declaracao.pdf']

for f in files:
    number = f.split('-')[1].strip()
    os.mkdir(number) if not os.path.isdir(number) else None
    move(f, number)

A: import os
from shutil import move

src = "path-to-folder"
for f in os.listdir(src):
    if os.path.isfile(os.path.join(src, f)): # you can check here for .pdf type
        code = f"{f.split('-ITR-')[0].split(' - ')[1]}"
        dir_path = os.path.join(src, code)
        if not os.path.exists(dir_path):
            os.mkdir(dir_path)
        # you can add here extra check to do not move if
        # the file exists in dir_path
        move(f"{os.path.join(src, f)}", f"{dir_path}")


text:
Q: How does a treap help to update this ordered queue? I'm having trouble understanding this solution to a problem on HackerRank. Please see the solution code below, apparently by Kimiyuki Onaka.
The problem is: given a list of unique numbers, and m queries of the type, "move the current ith to jth elements (l,r) to the beginning", return the final arrangement of the numbers.
Onaka suggests that a treap data structure (one that maintains both priority and binary search) can help solve it in O(m log n). Since I'm not versed in C++, I've tried but failed to conceptualize how a treap could be used. My understanding is that to solve the problem you need log time access to the current ith to jth elements and log time update of the current first element/s and overall order. But I can't see how to conceptualize it.
Ideally, I'd like an explanation in words of how it could be done. Alternatively, just an explanation of what Onaka's code is doing.
Thanks!
#include <iostream>
#include <tuple>
#include <random>
#include <memory>
#define repeat(i,n) for (int i = 0; (i) < (n); ++(i))
using namespace std;

template <typename T>
struct treap {
    typedef T value_type;
    typedef double key_type;
    value_type v;
    key_type k;
    shared_ptr<treap> l, r;
    size_t m_size;
    treap(value_type v)
            : v(v)
            , k(generate())
            , l()
            , r()
            , m_size(1) {
    }
    static shared_ptr<treap> update(shared_ptr<treap> const & t) {
        if (t) {
            t->m_size = 1 + size(t->l) + size(t->r);
        }
        return t;
    }
    static key_type generate() {
        static random_device device;
        static default_random_engine engine(device());
        static uniform_real_distribution<double> dist;
        return dist(engine);
    }
    static size_t size(shared_ptr<treap> const & t) {
        return t ? t->m_size : 0;
    }
    static shared_ptr<treap> merge(shared_ptr<treap> const & a, shared_ptr<treap> const & b) { // destructive
        if (not a) return b;
        if (not b) return a;
        if (a->k > b->k) {
            a->r = merge(a->r, b);
            return update(a);
        } else {
            b->l = merge(a, b->l);
            return update(b);
        }
    }
    static pair<shared_ptr<treap>, shared_ptr<treap> > split(shared_ptr<treap> const & t, size_t i) { // [0, i) [i, n), destructive
        if (not t) return { shared_ptr<treap>(), shared_ptr<treap>() };
        if (i <= size(t->l)) {
            shared_ptr<treap> u; tie(u, t->l) = split(t->l, i);
            return { u, update(t) };
        } else {
            shared_ptr<treap> u; tie(t->r, u) = split(t->r, i - size(t->l) - 1);
            return { update(t), u };
        }
    }
    static shared_ptr<treap> insert(shared_ptr<treap> const & t, size_t i, value_type v) { // destructive
        shared_ptr<treap> l, r; tie(l, r) = split(t, i);
        shared_ptr<treap> u = make_shared<treap>(v);
        return merge(merge(l, u), r);
    }
    static pair<shared_ptr<treap>,shared_ptr<treap> > erase(shared_ptr<treap> const & t, size_t i) { // (t \ t_i, t_t), destructive
        shared_ptr<treap> l, u, r;
        tie(l, r) = split(t, i+1);
        tie(l, u) = split(l, i);
        return { merge(l, r), u };
    }
};

typedef treap<int> T;
int main() {
    int n; cin >> n;
    shared_ptr<T> t;
    repeat (i,n) {
        int a; cin >> a;
        t = T::insert(t, i, a);
    }
    int m; cin >> m;
    while (m --) {
        int l, r; cin >> l >> r;
        -- l;
        shared_ptr<T> a, b, c;
        tie(a, c) = T::split(t, r);
        tie(a, b) = T::split(a, l);
        t = T::merge(T::merge(b, a), c);
    }
    repeat (i,n) {
        if (i) cout << ' ';
        shared_ptr<T> u;
        tie(t, u) = T::erase(t, 0);
        cout << u->v;
    }
    cout << endl;
    return 0;
}

A: Perhaps some pictures of the data structure as it processes the sample input would be helpful.
First, the six numbers "1 2 3 4 5 6" are inserted into the treap. Each one is associated with a randomly generated double, which determines if it goes above or below other nodes. The treap is always ordered so that all of a node's left children come before it, and all its right children come after.

Then we start moving intervals to the beginning. The treap is split into three parts—one with the first l-1 nodes, one with the nodes in the interval, and the last nodes. Then they are re-merged in a different order.
First, the interval [4,5] is moved:

Now the treap's order is 4, 5, 1, 2, 3, 6. (The root 4 comes first, because it has no left child; 3 is preceded by its left child 2, which is preceded by its own left child 5; then comes 5's right child 1; then 2, then 3, then 6.) The nodes keep track of the size of each subtree (m_size).
Given [3,4], we first call split(t,4), which should return a pair: one treap with the first 4 elements, and another one with the rest.
The root node (4) does not have 4 things under its left subtree, so it recurses with split(t->r, 3).
This node (3) does have 3 things under its left subtree, so it
calls split(t->l, 3).
Now we are at node (2). It calls split(t->r, 0),
but it does not have a right child, so this returns a pair of null pointers.
Thus from node (2) we return the unchanged subtree from (2), and a nullptr.
Propagating up, node (3) sets its left child to null, and returns
the subtree from (2), and the subtree at (3) itself (which is now just two elements, (3) and (6).)
Finally, at node (4) we set the right subchild to (2), and return the tree at (4) (which now has four elements, as required) and the two-element tree rooted at (3).
Next a call is made to split(a,2), where a is the first, four-element, tree from the last call.
Again, the root (4) has no left child, so we recurse with split(t->r, 1).
The node (2) has a left subtree with size 2, so it calls split(t->l, 1).
The node (5) has no left child, so it calls split(t->r, 0).
At the leaf (1), 0 <= size(t->l) is vacuously true: it gets a pair of null pointers from split(t->l, 0) and returns a pair(null, (1)).
Up at (5), we set the right child to null, and return a pair((5), (1)).
Up at (2), we set the left child to (1), and return a pair((5), (2)->(1)).
Finally, at (4), we set the right child to (5), and return a pair((4)->(5), (2)->(1)).

Finally the interval [2,3] (consisting of the elements 2 and 4) is moved:

Finally the nodes are popped in order, yielding 2, 4, 1, 5, 3, 6.
Perhaps you'd like to see the tree states given different input. I put a copy of the treap code, "instrumented" to produce the pictures, on GitHub. When run, it produces a file trees.tex; then running pdflatex trees produces pictures like those above.
(Or if you like, I'd be happy to make pictures for different input: that would be easier than installing a whole TeX distribution if you don't have it.)


text:
Q: Spring Boot - inject map from application.yml I use spring boot in a J2SE app.
I have some constant data, such as a map, indicating a HandlerClass to process one operation Type.
The map relation is not changed, so I want to config it in application.yml
I try this:
info:
  modify_nodeip: omm.task.impl.ModifyNodeIpHandler

But the map is only can be recognized as Map<String,String>, How can I inject the map as Map<Enum,Class>?
Thank you!
Updated:
I followed @cfrick instruction, but it doen't work.
application.yml
config:
    optHandlerMap:
        modify_oms_nodeip: 'omm.task.opthandler.impl.ModifyOMSNodeIpHandler'

TestConfiguration:
@Configuration
@ConfigurationProperties(prefix = "config")
public class TestConfiguration
{

    Map<OperationType,OptHandler> optHandlerMap; // here we store the handlers, same name in yaml
    TestConfiguration() {}

}

and the main func used the configuration
@Autowired
private TestConfiguration testConfiguration;

what's wrong with that? But it doesn't work, optHandlerMap in testConfiguration is null.

A: You can play a trick like this:
In your TestConfiguration, define a Map<String,String>, and getter.
then provide a Map<Operator,Handler> getXXXX() function, in this function, convert the Map<String,String> to Map<Operator,Handler>.
Maybe you need to use reflect to new a instance.
By the way, you can use Maps.transform() in Guava to perform the conversion.

A: You write your own settings and annotate as @ConfigurationProperties (see 21.6 Typesafe Configuration Properties)
@Component
@ConfigurationProperties(prefix="cfg") // the root in my yaml
class HandlerConfiguration {
    public enum Handler { Handler1, Handler2 } // enum
    Map<Handler,Class> handlers // here we store the handlers, same name in yaml
    HandlerConfiguration() {}
}

Then my application.yaml looks like this:
cfg:
  handlers:
    Handler1: 'app.Handler1'

And accessing it like this:
def ctx = SpringApplication.run(Application, args)
ctx.getBean(HandlerConfiguration).with{
    assert handlers.size()==1 // there is the one
    assert handlers[HandlerConfiguration.Handler.Handler1] // it's key is the enum
    assert handlers[HandlerConfiguration.Handler.Handler1] == Handler1 // its value is the actual class
    handlers[HandlerConfiguration.Handler.Handler1].newInstance().run()
}

(app.Handler1 is just some random class I put there, all this is in the same package (app))

A: just enable config spring.data.rest.enable-enum-translation (Spring document) and Spring will do the trick


text:
Q: IIS7 ASP.NET connection string override I am trying to deploy a ASP .NET website on IIS7.
The dev version has connection string like this:
<appSettings>
<add key="ConnectionString" value="Data Source=localhost,1533;Network Library=dbmssocn;Database=Leads_DB1;Connection Timeout=15;Packet Size=4096; Integrated Security=no;User ID=localdbuser;Password=Pa55w0rd!; Encrypt=no;"/>

<!--DEVELOPMENT DATABASE -->
<add key="ConnectionString" value="Data Source=localhost,1533;Network Library=dbmssocn;Database=Mail_Development;Connection Timeout=15;Packet Size=4096; Integrated Security=no;User ID=localdbuser;Password=Pa55w0rd!; Encrypt=no;"/>
<add key="ConnectionStringCRM" value="Data Source=localhost,1533;Network Library=dbmssocn;Database=CRM_MAIL_QUEUE;Connection Timeout=15;Packet Size=4096; Integrated Security=no;User ID=localdbuser;Password=Pa55w0rd!; Encrypt=no;"/>
</appSettings>

Now when I create a new connection string using IIS manager connection string dialog, I need to provide a name for the connection and it creates something like this:
<connectionStrings>
<add name="Leads_DB1"
connectionString="Data Source=.;Initial Catalog=Leads_DB1;Integrated Security=no;User ID=localdbuser;Password=Pa55w0rd!; Encrypt=no;"/>
 </connectionStrings>

Problem is in both cases I am not getting DB connection from the App.
Is there any way I can make the Dev version work?
I am afraid, if I use the default config IIS generates, then it would require a major code change at every point there is a DB call.
So, is there any simpler way to do these modifications?

A: One standard way of accomplishing this is using web.config transformations. You would set the default connection string in your web.config (that will be used in development) and transform the connection string when you deploy to qa/production (supplying the qa or prod connection string.)
See this for more information.

A: There is a fundamental difference between connectionString and appSettings:
They look for different things. In .NET 2.0 and above:
A connectionString object is an XML node that has specific attributes to set; and semantically it refers to a database connection string.
For instance, a connectionString looks like the following:
<connectionStrings>
  <clear/>
  <add name="LocalSqlServer"
      connectionString="Data Source=(local);Initial Catalog=aspnetdb;Integrated Security=True"
      providerName="System.Data.SqlClient" />

You'll notice it has a few different attributes:

*

*name

*connectionString : This has a specific string inside of it, it needs an Initial Catalog, a security mechanism (in this case Integrated Security

*providerName

Whereas appSettings is just a user-defined Key-value pair that allows you to... well... set application settings. It can be anything:
<appSettings>
  <add key="Mom" value="Your"/>
  <add key="UseCache" value="True"/>
  <add key="MapsKey" value="1234567890-AA"/>
  <add key="SMTPServer" value="smtp.peterkellner.net"/>
</appSettings>

you can fine more infromation at http://peterkellner.net/2008/02/23/webconfigbestpractice/


text:
Q: Create json object from mysql database Hi I am trying to figure out how to create a json object with a very specific format using php and mysql:
My mysql table looks like this (Not the prettiest, I know):
CREATE TABLE IF NOT EXISTS `room120` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `timestamp_start` datetime NOT NULL,
  `timestamp_end` datetime NOT NULL,
  `month` int(2) NOT NULL,
  `day` int(2) NOT NULL,
  `year` int(4) NOT NULL,
  `name` text NOT NULL,
  `email` text NOT NULL,
  `phone` text NOT NULL,
  `title` text NOT NULL,
  `start` varchar(5) NOT NULL,
  `end` varchar(5) NOT NULL,
  `approved` enum('true','false','new') NOT NULL DEFAULT 'new',
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=1;

How I need my JSON object to look:
[
    "10-23-2013": {
        0: {
            id : 1,
            title : "Hello World",
            time : "8:00 am - 10:00 am"
        },
        1: {
            id : 2,
            title : "Hello Universe",
            time : "1:00 pm - 3:00 pm"
        }
    }
]

I have my cuurent php loop that builds the id and title part but I am having an issue building the part that has the date.
Here is my php loop (Yes I know there is no code for building the date part, I am trying to figure it out.):
$return_arr = array();
while ($row = $result->fetch_array(MYSQLI_ASSOC)) {
    $date = str_pad($row[month], 2, "0", STR_PAD_LEFT).'-'.str_pad($row[day], 2, "0", STR_PAD_LEFT).'-'.$row[year];
    $start_time = DATE("g:i a", STRTOTIME($row[start]));
    $end_time = DATE("g:i a", STRTOTIME($row[end]));

    $row_array[id] = $row[id];
    $row_array[title] = $row[title];

    array_push($return_arr, $row_array);
}
echo json_encode(array("event" => $return_arr));

It currently returns something like this:
Object {event: Array[15]}
  event: Array[15]
    0: Object
      id: "1"
      title: "Hello World"

A: You need to store in $return_arr another sub-array row. Look here:
$return_arr = array();
while ( $row = $result->fetch_array(MYSQLI_ASSOC) ) {

    $date = str_pad($row[month], 2, "0", STR_PAD_LEFT).'-'.str_pad($row[day], 2, "0", STR_PAD_LEFT).'-'.$row[year];
    $start_time = DATE("g:i a", STRTOTIME($row[start]));
    $end_time = DATE("g:i a", STRTOTIME($row[end]));

   // create rowArr
    $rowArr = array(
        'id' => $row['id'],
        'title' => $row['title'],
        'time' => $startTime . ' - ' . $endTime
    );

    // store rowArr in $return_arr
    $return_arr[$date][] = $rowArr;

}

// display json encode

echo json_encode(array("event" => $return_arr));

Now your $return_arr is a multi dimensional array and should be echoed well.


text:
Q: Break down a pcap file into individual flows and modify them I have a pcap file and I want to:

*

*separate every flow

*separate responses and requests in each flow

*modify ip and port in some packets

*reply packets
Is there any utility in linux that helps me for do this?


text:
Q: To use thread safe or non thread safe PHP i wonder which is better to use? i read somewhere thread safe is for multithreading and is faster. then shldnt php just release a thread safe php? why release a lousier version of software. so my question is since they release different versions, there must be a difference. so whats it?
from here

This new FastCGI handler from
  Microsoft enables you to configure the
  non thread safe PHP binaries in
  FastCGI mode, which is one massive
  shot in the arm for performance.
  Easiest way to put it is using the non
  thread safe PHP binaries with
  Microsoft's new FastCGI handler is
  like putting twin turbos on your car
  (without the inherent risk of blowing
  up your engine)

so can i say if i use iis, i should use non thread safe php and thread safe for apache?

A:
i read somewhere

I read somewhere that the earth is flat - it must be true. Please cite your sources.

thread safe is for multithreading

This is non-sensical

and is faster

Possibly true depending on a large number of other factors.

shldnt php just release a thread safe php?

PHP has been thread safe for a very long time (approx 10 years now). You may be refering to the issue that Rasmus Lerdorf pointed out some time ago, that adoption of thread-safe code by third-party developers (i.e. extension writers) was expected to lag behind PHP's adoption. It is not known whether this is still the case.

This new FastCGI handler from Microsoft

You seem to be under the impression that this amazing new invention by Microsoft (no, just a new release of software originally designed by someone else) can somehow seperate the threadsafe and non-threadsafe parts of the php installation - this is not the case.

putting twin turbos on your car

I expect it feels like that compared to the alternatives on MSWindows.

so can i say if i use iis, i should use non thread safe php and thread safe for apache?

This sentence does not make any syntactic sense. Certainly for production systems, unless you have reason to believe that the system may be thread safe, then you should not use a threaded PHP module. And for Microsoft NT / Solaris / AIX systems then there is a performance beneift in using a threaded apache. For Linux systems the difference between threaded and pre-fork is significantly less. Not sure about BSD / Apple.


text:
Q: Getting n-th row in a group - SAS / SQL any hints how do I get the n-th element from the group. SAS 4GL is preferred, SQL will do.
From the list of transactions below, I would like to extract a row corresponding to a 2nd (by date) transaction per each customer.
Input:

Output:

Customer C from the example above has just one transaction, hence there is no rows corresponding to him in the output table.
Thank you in advance!

A: There are a couple of ways you can accomplish this using SAS. The easiest being to sort the data set and then use a data step to output the records you want.
proc sort data=have;
by Customer TransactionDate;
run;

data want(drop=counter);
set have;
by Customer TransactionDate;
retain counter;
if first.Customer then counter=1;
else counter+1;
if counter=2 then output;
run;

A: The way to achieve the desired result set is by applying windowing functions. Please, check the query below.
SELECT
    c.TransactionDate
    , c.Customer
    , c.Product
    , c.Quantity
    , c.[Purchase Value]
FROM (
    SELECT
        TransactionDate
        , Customer
        , Product
        , Quantity
        , [Purchase Value]
        , RANK() OVER (PARTITION BY Customer ORDER BY TransactionDate) AS Ranking
    FROM transactions
) AS c
WHERE c.Ranking = 2;

I hope this help you!
EDIT
This query works in case you're working with an engine that supports windows functions how I'm using in the query above (SQL Server in this case).

A: This code will handle the case of multiple items bought on that day. I used Retain Functionality and kept a count of sub-groups.
Data: I added two extra item to A & B on the same day
data have;
 infile datalines dlm=',' dsd;
 informat Transaction_Date yymmdd10.;
 format Transaction_Date yymmdd10.;
 input Transaction_Date Customer $ Product $ Quantity Purchase_Value;
 datalines;
2018-01-15, A , Milk , 1 , 100
2018-01-28, A , Onion , 2 , 140
2018-01-28, A , corn , 2 , 140
2018-02-13, B , Carrot , 1 , 50
2018-03-20, B , Rice , 10 , 40
2018-03-20, B , tomato , 10 , 40
2018-04-14, B , Carrot , 1 , 50
2018-06-02, C , Candy  ,5 , 125
;
run;

Code: The Counter is your Nth row
proc sort data=have; by Customer Transaction_Date; run;
data want;
set have;
by Customer  Transaction_Date ;
retain outter;
retain inner;
retain counter;
if first.Customer then do; outter=1; counter=0; end; else outter+1;
if first.Transaction_Date then do; inner=1; counter+1; end; else inner+1;
if counter=2 then output;
run;

Output:
 Transaction_Date=2018-01-28 Customer=A Product=Onion Quantity=2 Purchase_Value=140 outter=2 inner=1 counter=2
 Transaction_Date=2018-01-28 Customer=A Product=corn Quantity=2 Purchase_Value=140 outter=3 inner=2 counter=2
 Transaction_Date=2018-03-20 Customer=B Product=Rice Quantity=10 Purchase_Value=40 outter=2 inner=1 counter=2
 Transaction_Date=2018-03-20 Customer=B Product=tomato Quantity=10 Purchase_Value=40 outter=3 inner=2 counter=2

A: *

*if you are trying to do in database processing then @alfonsohdez08  is the way to go .
Otherwise @J_Lard  is the way to go.
One another way by using proc sql is shown below
proc sql;
create table want(drop = rnk) as
select a.*,
(select count(transaction_date) from have b
where a.customer=b.customer
and a.transaction_date>=b.transaction_date) as rnk
  from have a
where calculated rnk = 2;


text:
Q: Efficiently fuzzy match every sentence in a collection of documents I am attempting to build a list of similar sentences across a collection of 10 or so documents. I am using the FuzzyWuzzy library in Python to determine similarity, and although my current algorithm works, it is not very efficient and takes forever to run.
for doc in docs:
        for sentence in doc.sentences:
            if len(sentence) > 8:
                for document in docs:
                    if similarity(document,doc)["ratio"] < 100:
                        for sentn in document.sentences:
                            if len(sentn) > 8:
                                simil = similarity(sentence,sentn)
                                if simil["ratio"] > 60:
                                    count+=1
                                    print count
                                    pairs.append([sentence,sentn,simil])

in case you don't feel like reading that mess of code, it takes each document in the list, then iterates over each sentence in it, then it takes that sentence and compares it to every other sentence in every other document, meaning it is processing billions of possible combinations, many of them with similarities of less than 5%, which is terribly inefficient and a waste of processing power, is there a more efficient algorithm or way in which to process the documents?
EDIT:
At Starks suggestion I added this line of code
if abs(len(sentence)-len(sentn))<10:
    simil = similarity(sentence,sentn)
    ...

There is a marked performance increase, but I still can't help but feel the algorithm is inefficient
Note: This is not a duplicate question, the other question asks how to figure out if two sentences are similar, I already can do that, what I need to know is how to do it efficiently, a lot of times

A: There are at least two issues with that loop that are causing major bottlenecks.
First, you are taking the first sentence from your first document and checking it against every sentence of every document, including itself. So instead of
 for doc in docs:
     for sentence in doc.sentences:
         if len(sentence) > 8:
             for document in docs:

try
for doc in docs:
        for document in docs:
                for sentence in doc.sentences:
                     if len(sentence) > 8:

Second,
if similarity(document,doc)["ratio"] < 100:

is not very efficient, you don't need to use fuzzy matching to tell if two documents are identical, you can just use
if document.text == doc.text:


text:
Q: Heroku Godaddy naked domain SSL HTTPS I'm trying to get my naked domain work. Currently, it's showing this
NET::ERR_CERT_COMMON_NAME_INVALID

I read this answer, and the ones in it. The answers are leading me to believe that if I am using GoDaddy and Heroku, I simply cannot use my naked domain. Forwarding from naked domain to full domain only work on HTTP websites. I mean, who still uses HTTP?
What's the easiest way to solve this? Port my domain from GoDaddy to another host that supports ANAME? Is there an option that does not require a large amount of work?


text:
Q: How can I retrieve the package-relevant architecture of a Debian Linux system? I currently try to build a Debian package for the armhf (ARMv7) architecture, but I want the build script to recognize the architecture itself. The problem is, that I can not find the architecture, that APT uses to retrieve the package from a repository.
In my case, APT uses armhf, when it retrieves packages.
When I run uname -m, I get armv7 as a result. A grep -rn armhf /etc does not show any appearance of armhf, relevant for APT to choose from.
So, where can I get (Debian 9 (Stretch) or Armbian next) a reliable source for that information from the system that is independent of the architecture (my script should run also on i686, amd64, armel & arm64)?

A: The answer is
dpkg --print-architecture

This gives you the architecture Debian is selecting for packages. I'm not sure what happens on multi-architecture systems (i686 and amd64), but this can be separated quite easily.


text:
Q: DataTable Bootstrap Collection I am using bootstrap v4.2.1 and datatables v1.10.19 with the buttons extension. I'm trying to group together my "export" buttons (csvHtml5 and excelHtml5) in a collection using the following:
var data = $('#data').DataTable({
  dom: 'Bfrtip',
  buttons: [
    {
      extend: 'collection',
      className: 'btn btn-outline-success dropdown-toggle',
      text: 'Export',
      buttons: [
        {
          extend: 'csvHtml5',
          className: 'dropdown-item'
        },
        {
          extend: 'excelHtml5',
          className: 'dropdown-item'
        }
      ]
    },
    {
      extend: 'print',
      className: 'btn btn-outline-success'
    }
  ]
});

The problem that I'm running into is that the dropdown isn't being displayed correctly. My guess is that because the parent
 that the dropdown items are being displayed in does not have the dropdown-menu class. So to correct this I added the following after initializing the datatable:
$('.dropdown-toggle').on('click', function() {
  $('.dropdown-item').parent().addClass('dropdown-menu');
});

This works, only now the dropdown items are displayed for a second and then they disappear.
My first question is: am I setting this up right?
My second question is: if not, then how do I setup the datatable collection to look like the bootstrap dropdown?
UPDATE
Something that I noticed after making this post is that if I click on my print button before I click on the export button then the dropdown items stay showing up as expected.

A: After embedding you code on stack-snippet with the needed CDN libraries:
1) The first thing I see wrong was a darker background on the buttons. This is because the Datatables integration with Bootstrap adds class btn-secondary to the buttons. Lucky us, they provide and option called ìnit we can use to delete this class, like this:
{
  extend: 'print',
  init: (api, node, config) => $(node).removeClass('btn-secondary'),
  className: 'btn btn-outline-success'
}

2) The second issue I note is that there is no need to add the dropdown particular classes in the className options, if you use the browser inspector you will see that they already have the correct structure and classes of Bootstrap.
Finally, you can check the complete example with the mentioned fixs:

$(document).ready(function()
{
    $('.table').DataTable({
      dom: 'Bfrtip',
      buttons: [
        {
          extend: 'collection',
          init: (api, node, config) => $(node).removeClass('btn-secondary'),
          className: 'btn btn-outline-success',
          text: 'Export',
          buttons: [
            {extend: 'csvHtml5'},
            {extend: 'excelHtml5'}
          ]
        },
        {
          extend: 'print',
          init: (api, node, config) => $(node).removeClass('btn-secondary'),
          className: 'btn btn-outline-success'
        }
      ]
    });
})

<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/css/bootstrap.min.css" integrity="sha384-GJzZqFGwb1QTTN6wy59ffF1BuGJpLSa9DkKMp0DgiMDm4iYMj70gZWKYbI706tWS" crossorigin="anonymous">

<link rel="stylesheet" href="https://cdn.datatables.net/1.10.19/css/dataTables.bootstrap4.min.css">

<link rel="stylesheet" href="https://cdn.datatables.net/buttons/1.5.4/css/buttons.bootstrap4.min.css">

      Name
      Position
      Office
      Age
      Start date
      Salary

      Tiger Nixon
      System Architect
      Edinburgh
      61
      2011/04/25
      $320,800

      Garrett Winters
      Accountant
      Tokyo
      63
      2011/07/25
      $170,750

      Ashton Cox
      Junior Technical Author
      San Francisco
      66
      2009/01/12
      $86,000


text:
Q: SharePoint Navigation Edit Links is not visible I created top navigation using Metadata term set.
I have full control on this site.
Why I can not see the link "Edit links" for quick edit navigation terms?
What permission is responsible for adding this link to the page?
If I choose "Structural Navigation" in Navigation Settings, I see "EDIT LINKS", but with "Managed Navigation" it does not work.
The main problem is that our main site uses the same navigation, but there "Edit links" is visible for all users, even with viewing rights. Now I hid this link with css, but some users can open develop console and disable my css. I have to find a way to prevent it.

A: Edit links has lot of rules. please check below blog for more info.
http://www.sharepointdiary.com/2014/09/edit-links-missing-in-sharepoint-2013-navigation.html

A: I found solution!

*

*Open master-page (How to check master-page filename: {site url}/_api/web?$select=CustomMasterUrl,MasterUrl)

*Find:
                    <asp:ContentPlaceHolder id="PlaceHolderTopNavBar" runat="server">
                    <SharePoint:AspMenu
                        ID="TopNavigationMenu"
                        Runat="server"
                        EnableViewState="false"
                        DataSourceID="topSiteMap"
                        AccessKey="<%$Resources:wss,navigation_accesskey%>"
                        UseSimpleRendering="true"
                        UseSeparateCss="false"
                        Orientation="Horizontal"
                        StaticDisplayLevels="2"
                        AdjustForShowStartingNode="true"
                        MaximumDynamicDisplayLevels="2"
                        SkipLinkText="" />
                </asp:ContentPlaceHolder>

*Add Editable="false" for hidding Edit Links or Editable="true" for showing
                    <asp:ContentPlaceHolder id="PlaceHolderTopNavBar" runat="server">
                    <SharePoint:AspMenu
                        ID="TopNavigationMenu"
                        Runat="server"
                        EnableViewState="false"
                        Editable="false"
                        DataSourceID="topSiteMap"
                        AccessKey="<%$Resources:wss,navigation_accesskey%>"
                        UseSimpleRendering="true"
                        UseSeparateCss="false"
                        Orientation="Horizontal"
                        StaticDisplayLevels="2"
                        AdjustForShowStartingNode="true"
                        MaximumDynamicDisplayLevels="2"
                        SkipLinkText="" />
                </asp:ContentPlaceHolder>

Don't forget to publish your master-page!
So, now you can add/remove "Edit Links" without css(css!)


text:
Q: Conversion from any base to decimal and case sensitivity I am using the following portal to verify the results of my code (again sourced from the web):
RapidTables BaseConverter
My code is as shown below:
// C program to convert a number from any base
// to decimal
#include <stdio.h>
#include <string.h>

// To return value of a char. For example, 2 is
// returned for '2'.  10 is returned for 'A', 11
// for 'B'
int val(char c)
{
    if (c >= '0' && c <= '9')
        return (int)c - '0';
    else
        return (int)c - 'A' + 10;
}

// Function to convert a number from given base 'b'
// to decimal
int toDeci(char *str, int base)
{
    int len = strlen(str);
    int power = 1; // Initialize power of base
    int num = 0;  // Initialize result
    int i;

    // Decimal equivalent is str[len-1]*1 +
    // str[len-1]*base + str[len-1]*(base^2) + ...
    for (i = len - 1; i >= 0; i--)
    {
        // A digit in input number must be
        // less than number's base
        if (val(str[i]) >= base)
        {
           printf("Invalid Number\n");
           return -1;
        }

        num += val(str[i]) * power;
        power = power * base;
    }

    return num;
}

// Driver code
int main()
{
    char str[] = "25a";
    int base = 36;
    printf("Decimal equivalent of %s in base %d is " " %d ", str, base, toDeci(str, base));
    return 0;
}

As shown inside main(), if use the value "25a" for str[], I get the following output:
Invalid Number
Decimal equivalent of 25a in base 36 is  -1

But if I change the value of str[] to "25A", I get the following output:
Decimal equivalent of 25A in base 36 is  2782

Using the portal link that I have provided above for result verification, I get the last result for both values.
So my question is, how can I modify my code to make the corresponding change?
TIA
Vinod

A: Why don't you make use of strtoll() function:
#include <stdio.h>
#include <stdlib.h>

int main()
{
    char str[] = "25a";
    int base = 36;
    unsigned long long todeci;

    todeci = strtoll(str, (char **)NULL, base);
    printf("Decimal equivalent of %s in base %d is %lld\n", str, base, todeci);
    return 0;
}

Output:
Decimal equivalent of 25a in base 36 is 2782

A: If you can't or don't want to change the function signatures or use the proper  library functions to perform the conversion, a simple change to the val function would allow the code to also manage the lower cases.
int val(char c)
{
    if ( '0' <= c  &&  c <= '9')
        return c - '0';
    else if ( 'A' <= c  &&  c <= 'Z' )
        return c - 'A' + 10;
    else if ( 'a' <= c  &&  c <= 'z' )
        return c - 'a' + 10;
    else
        return -1;
}

A little change to the other function (using the Horner method to evaluate the polynomial) and we can also avoid a call to strlen.
int toDeci(char *str, int base)
{
    unsigned long long int num = 0;

    while( *str != '\0' )
    {
        int digit = val(*str);
        if ( digit == -1  ||  digit >= base )
        {
            printf("Invalid digit.\n");
            return -1;
        }
        unsigned long long int n = num * base + digit;
        if ( n < num )
        {
            printf("The number is too big.\n");
            return -1;
        }
        num = n;
        ++str;
    }
    if ( num > INT_MAX )  // You'll have to include <limits.h>
    {
        printf("The number is too big to fit into an int.\n");
        return -1;
    }
    return num;
}

Note that this code still can't process negative numbers or prefixes like 0 for octals and 0x for hexadecimal numbers. The error checking also follows OP's choice (returning -1 when something goes wrong) and needs to be rethinked.


text:
Q: Flot JS turn target into diamond shape I've three series of data: for green bars, red bard and target like
var dataBarsRed = {
    data: [
        [2, 3], ],
    label: 'Bars in Red',
    color: 'red'
};
var dataBarsGreen = {
    data: [
        [1, 2],
        [3, 1],
        [4, 3]
    ],
    label: 'Bars in Green',
    color: 'green'
};
var dataLines = {
    data: [
        [1, 3, 3],
        [2, 3.5, 3.5],
        [3, 1.5, 1.5],
        [4, 2.5, 2.5]
    ],
    label: 'Lines',
    color: 'navy',
    bars: {
        barWidth: 0.5
    }
};

I've attached the fiddle for it.
It is possible to make the target as diamond () using Flot JS?

A: You can customize the point shape by specifying it in the series options (or each individual series). The symbol plugin can be used access more shapes:
var options = {
    series: {
        points: {
            shape: "diamond"
        }
    }
}

This updated JSFiddle uses the symbols plugin to show diamonds as the point marker.


text:
Q: 451 5.7.3 STARTTLS is required to send mail Exchange 2013 Hybrid Certificate from GoDaddy is in place, I have removed esmtp inspection from our Cisco ASA, and hybrid mail is flowing from Office 365 to our on prem Exchange 2013 server. When trying to send mail to a mailbox migrated to Office365 I am receiving the dreaded '451 5.7.3 STARTTLS is required to send mail".
Since our MX is pointing to a 3rd party mail filter I changed the on prem connector created by the hybrid config wizard to relay mail through 'ourdomain-com.mail.protection.outlook.com'
I am also able to telnet directly from our Exchange server to ourdomain-com.mail.protection.outlook.com 25. An ehlo shows the STARTTLS verb IS available.
Kind of hitting a wall here. I would greatly appreciate any insights from the community!

A: In our network we have a router out in front of our ASA.
I had overlooked CBAC smtp inspection. I removed this statement on the router, re-ran the HCW, modified the On Prem connector to 365 to point to domain-com.mail.protection.outlook.com, and now Hybrid is working as intended.


text:
Q: writing Probability Y>X as an integral im working through an example where X and Y are exponential random variables
We are computing $ P(Y>X) $ the first step is
$$ P(Y>X) = \int_{0}^{\infty} f_{X}(x)P(Y>X|X=x) dx $$
How does this step make sense rigorously, I think we are conditioning on each value of X and 'summing over all of values of X' and $f_{X}(x)$ represents the probability of each of those x's?

A: It is the Total Law of Probability for the continuous case. $$\mathbb P(A) = \int_{\Omega} \mathbb P(A|x)f(x)dx $$
To understand this I like to think about it as an extension of the discrete case first:
$$\mathbb P(A) = \sum_{\Omega} \mathbb P(A|x)P(X=x(\omega)) $$
If a probability calculation can be broken into cases, the final answer is the weighted average of the answers for each case, weighing each case by the probability that it holds.


text:
Q: Phonegap - Unable to open asset URL: file:///android_asset/www/cordova_plugins.json I am about to set up a phonegap project and wanted to create a little hello world application to make sure my phonegap app works alright. For this I am printing out some device information. Here is my JavaScript code:
 function onDeviceReady(){
     document.getElementById("name").innerHTML      = device.name; // undefined
     document.getElementById("phonegap").innerHTML  = device.phonegap; // undefined
     document.getElementById("platform").innerHTML  = device.platform; // Android
     document.getElementById("version").innerHTML   = device.version; // 4.4.2
     document.getElementById("uuid").innerHTML      = device.uuid; // 1dafa426...
   }

   /** Called at the bodys onLoad event */
   function init(){
      document.addEventListener("deviceready", onDeviceReady, false);
   }

As soon as I run this code I get the following error message:

Unable to open asset URL:
  file:///android_asset/www/cordova_plugins.json

I have tried commenting out the device.name and device.phonegap lines, but this couldn't fix it.
Any ideas to fix this? I am using Cordova 2.9.0 and have attached both my config.xml file and my full error log.

config.xml:
<?xml version="1.0" encoding="UTF-8"?>
<widget xmlns     = "..."
        id        = "io.cordova.helloCordova"
        version   = "2.0.0">
    <name>Hello Cordova</name>

    <description>
        A sample Apache Cordova application that responds to the deviceready event.
    </description>

    <author href="..." email="dev@cordova.apache.org">
        Apache Cordova Team
    </author>

    <access origin="*"/>

    <!-- <content src="..." /> for external pages -->
    <content src="index.html" />

    <preference name="loglevel" value="DEBUG" />
    <!--
      <preference name="splashscreen" value="resourceName" />
      <preference name="backgroundColor" value="0xFFF" />
      <preference name="loadUrlTimeoutValue" value="20000" />
      <preference name="InAppBrowserStorageEnabled" value="true" />
      <preference name="disallowOverscroll" value="true" />
    -->

    <feature name="App">
      <param name="android-package" value="org.apache.cordova.App"/>
    </feature>
    <feature name="Geolocation">
      <param name="android-package" value="org.apache.cordova.GeoBroker"/>
    </feature>
    <feature name="Device">
      <param name="android-package" value="org.apache.cordova.Device"/>
    </feature>
    <feature name="Accelerometer">
      <param name="android-package" value="org.apache.cordova.AccelListener"/>
    </feature>
    <feature name="Compass">
      <param name="android-package" value="org.apache.cordova.CompassListener"/>
    </feature>
    <feature name="Media">
      <param name="android-package" value="org.apache.cordova.AudioHandler"/>
    </feature>
    <feature name="Camera">
      <param name="android-package" value="org.apache.cordova.CameraLauncher"/>
    </feature>
    <feature name="Contacts">
      <param name="android-package" value="org.apache.cordova.ContactManager"/>
    </feature>
    <feature name="File">
      <param name="android-package" value="org.apache.cordova.FileUtils"/>
    </feature>
    <feature name="NetworkStatus">
      <param name="android-package" value="org.apache.cordova.NetworkManager"/>
    </feature>
    <feature name="Notification">
      <param name="android-package" value="org.apache.cordova.Notification"/>
    </feature>
    <feature name="Storage">
      <param name="android-package" value="org.apache.cordova.Storage"/>
    </feature>
    <feature name="FileTransfer">
      <param name="android-package" value="org.apache.cordova.FileTransfer"/>
    </feature>
    <feature name="Capture">
      <param name="android-package" value="org.apache.cordova.Capture"/>
    </feature>
    <feature name="Battery">
      <param name="android-package" value="org.apache.cordova.BatteryListener"/>
    </feature>
    <feature name="SplashScreen">
      <param name="android-package" value="org.apache.cordova.SplashScreen"/>
    </feature>
    <feature name="Echo">
      <param name="android-package" value="org.apache.cordova.Echo"/>
    </feature>
    <feature name="Globalization">
      <param name="android-package" value="org.apache.cordova.Globalization"/>
    </feature>
    <feature name="InAppBrowser">
      <param name="android-package" value="org.apache.cordova.InAppBrowser"/>
    </feature>
    <!-- Deprecated plugins element. Remove in 3.0 -->
    <plugins>
    </plugins>
</widget>

The CatLog:
D/CordovaWebView(8703): CordovaWebView is running on device made by: LGE
D/JsMessageQueue(8703): Set native->JS mode to 2
D/CordovaActivity(8703): CordovaActivity.init()
D/CordovaWebView(8703): >>> loadUrl(file:///android_asset/www/index.html)
D/PluginManager(8703): init()
D/CordovaWebView(8703): >>> loadUrlNow()
D/Config(8703): Unlimited access to network resources
I/CordovaLog(8703): Found start page location: index.html
I/CordovaLog(8703): Changing log level to DEBUG(3)
D/CordovaActivity(8703): Resuming the App
D/CordovaActivity(8703): CB-3064: The errorUrl is null
D/CordovaActivity(8703): onMessage(onPageStarted,file:///android_asset/www/index.html)
I/ActivityManager(770): Displayed sample/.HelloPhonegap: +254ms
E/AndroidProtocolHandler(8703): Unable to open asset URL: file:///android_asset/www/cordova_plugins.json
D/Cordova(8703): onPageFinished(file:///android_asset/www/index.html)
D/CordovaActivity(8703): onMessage(onPageFinished,file:///android_asset/www/index.html)
E/AndroidProtocolHandler(8703): Unable to open asset URL: file:///android_asset/www/cordova_plugins.js

EDIT (Workaround)
Creating a dummy file cordova_plugins.json helped me to get rid of my error messages. This seems just to be a little workaround and I still have got the problem that I cannot access the variables device.name and device.phonegap (They're undefined).
EDIT (Upgrade to Cordova 3.x)
After upgrading my project to cordova 3.x this error disappeared. Maybe I did just make any mistake in setting up the project. Nevertheless everything works totally fine with Cordova 3.x (I updated to 3.1 and later on to 3.4)