text:
Q: spring data jpa isolation I use spring boot with spring data jpa with hibernate and oracle
I need to take data of a datable with a couple of millions of record and write data in a file. After data it's wrote, I need to remove the row.
I thing using stream to get data.
During theses process, some of other data can be inserted in the table (by another program).
Don't know if when we stream database, new insertion are added to the query.
I was thinking doing somehting like
public void processData(){

  //create file

  Stream<Billing> billingStream = billingRepository.getAll();

  billingStream.forEach( billing-> {

    //write billing row to file

    //delete billing row; //should be remove in memory
    entityManager.remove(billing);

  });

}

If inserted, is there a way to avoid to take it?


text:
Q: Why the login_user function not logiging me in? I'm new to flask and all that backend thing, so i decided to start with flask. I found Miguel Grinberg's tutorial most beginner-friendly, so I started to follow it. But when tried to login the user with login_user it still didn't logged me in. The usernmame and the password are correct. I have a page protected with @login_required and when I pass the credentials, I still see the "Please log in to" access this page" message. Also the login_user function returns True and that's really strange. After that I copy-pasted the route function from the tutorial and it still didn't worked. Can you, guys, say what I'm doing wrong?

Here's the route functions:

from app import app, db
from flask import render_template, flash, redirect, url_for, render_template, request
from app.forms import LoginForm, RegisterForm
from flask_login import login_user, current_user, logout_user, login_required
from app.models import User
from werkzeug.urls import url_parse

@app.route('/')
@app.route('/index')
@login_required
def index():
    posts = [
        {
            'author': {'username': 'Susan'},
            'body': 'Beautiful day in Portland'
        },
        {
            'author': {'username': 'Andy'},
            'body': 'The Avengers film was awesome!'
        }
    ]
    return render_template('index.html',title='Home',posts=posts)

@app.route('/login', methods=['GET','POST'])
def login():
    if current_user.is_authenticated:
        return redirect(url_for('index'))
    form = LoginForm()
    if form.validate_on_submit():
        user = User.query.filter_by(username=form.username.data).first()
        if user is None or not user.check_pwd(form.password.data):
            flash('Invalid username or password')
            return redirect(url_for('login'))
        login_user(user,remember=form.remember_me.data)
        next_page = request.args.get('next')
        if not next_page or url_parse(next_page).netloc != '':
            next_page = url_for('index')
        return redirect(next_page)
    return render_template('login.html', title='Sign In', form=form)

@app.route('/logout')
def logout():
    logout_user()
    return redirect(url_for('index'))

@app.route('/register',methods=['GET','POST'])
def register():
    if current_user.is_authenticated:
        return redirect(url_for('index'))
    form = RegisterForm()
    if form.validate_on_submit():
        user = User(username=form.username.data,email=form.email.data)
        user.set_pwd(form.password.data)
        db.session.add(user)
        db.session.commit()
        flash('Congratulations, you\'re now a registered user!')
        login_user(user)
        return redirect(url_for('index'))
    return render_template('register.html', title='Register', form=form)

Don't pay attention to the posts list

Here's the User model:

from app import db
from werkzeug.security import generate_password_hash, check_password_hash
from flask_login import UserMixin
from app import login

class User(UserMixin,db.Model):
    id = db.Column(db.Integer,primary_key=True)
    username = db.Column(db.String(64),index=True,unique=True)
    email = db.Column(db.String(120),index=True,unique=True)
    password_hash = db.Column(db.String(128))
    posts = db.relationship('Post',backref='author',lazy='dynamic')
    def __repr__(self):
        return '<User {}>'.format(self.username)

    def set_pwd(self,pwd):
        self.password_hash = generate_password_hash(pwd,'pbkdf2:sha1:10',60)

    def check_pwd(self,pwd):
        return check_password_hash(self.password_hash,pwd)

if I need to add something here for you to understand, write in the comments

A: This is happening because, on login, the User must have the is_active attribute and its value should be True.
To force login, you can pass argument force=True, like this   login_user(user,remember=form.remember_me.data, force=True).
Or, you can add the is_active attribute on your User's model is_active = db.Column(db.Boolean(), default=True).
Or, you can inherit from class flask_login.UserMixin, which provides default implementations for all of the properties and methods expected from flask login. I recommend it this way.
from flask_login import UserMixin

class User(UserMixin):
    ...

You can look at the documentation here or here to see how it works.

redpajama_set_name: RedPajamaStackExchange


text:
Q: NoMethodError at before_save callback I'm getting this error message when submitting a form that creates an object and nested objects:
NoMethodError (undefined method `ratio' for nil:NilClass):

app/models/sale.rb:57:in `set_total_valuation'
app/controllers/api/v1/sales_controller.rb:19:in `create'

Here's my model
class Sale < ApplicationRecord
    belongs_to :user
    has_many :distribution_entries, dependent: :destroy

    accepts_nested_attributes_for :distribution_entries, reject_if: :all_blank, allow_destroy: true

    validates :name, presence: true, uniqueness: true

  before_save :set_total_valuation

  private

  def set_total_valuation
    main_ratio = self.distribution_entries.find { |object| object["item"] == "Main" }.ratio / 100
    self.total_valuation = self.target / main_ratio
  end
end

I think I'm getting nil because distribution_entries doesn't exist at this stage of the creation cycle but when seeding it works fine.

A: In this case if it's plausible and likely there will be scenarios where there won't be distribution entries yet on a sale then you can add a conditional to your call back and check distribution_entries.present? with another method or a proc (http://guides.rubyonrails.org/active_record_callbacks.html#using-if-and-unless-with-a-proc):
before_save :set_total_valuation if: Proc.new { |sale| sale.distribution_entries.present? }


text:
Q: Geolocation Issue - Ionic 2 I'm trying to get the user's position ( Latitude and Longitude) But for some reason it doesn't work. It works in browser but not in phone or emulator. Here is my code.
constructor(public navCtrl: NavController, public _http:Http, public alertCtrl:AlertController, public zone:NgZone, public platform:Platform, public loadingCtrl:LoadingController){
  this.platform.ready().then(() => {
    if(navigator.geolocation){
        console.log('Condition is true');
        Geolocation.getCurrentPosition().then((position) => {
          console.log(position);
          }, (err) => {
            console.error(err);
          });
    }else{
      console.error("Navigator is unavailable");
    }
});}

In console I get Condition is true but that's the only console log I'm getting nothing else.
Version and Plugin
Cordova version 6.4.0
Ionic version 2.1.4
cordova-plugin-geolocation 2.4.0 "Geolocation"
Below is the code from www/index.html
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
  <meta charset="UTF-8">

  <title>Ionic App</title>
    <meta http-equiv="Content-Security-Policy" content="">

  <meta name="viewport" content="width=device-width, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, user-scalable=no">
  <meta name="format-detection" content="telephone=no">
  <meta name="msapplication-tap-highlight" content="no">

  <link rel="icon" type="image/x-icon" href="assets/icon/favicon.ico">
  <link rel="manifest" href="manifest.json">
  <meta name="theme-color" content="#4e8ef7">
   <script src="https://maps.google.com/maps/api/js?key=AIzaSyDRu7tdUdnsl1-BbA-l-Qcctwa66LBt8Ww"></script>

  <!-- cordova.js required for cordova apps -->
  <script src="cordova.js"></script>

  <!-- un-comment this code to enable service worker
  <script>
    if ('serviceWorker' in navigator) {
      navigator.serviceWorker.register('service-worker.js')
        .then(() => console.log('service worker installed'))
        .catch(err => console.log('Error', err));
    }
  </script>-->
  <link href="build/main.css" rel="stylesheet">

</head>
<body>

  <!-- Ionic's root component and where the app will load -->
  <ion-app></ion-app>

  <!-- The polyfills js is generated during the build process -->
  <script src="build/polyfills.js"></script>

  <!-- The bundle js is generated during the build process -->
  <script src="build/main.js"></script>

</body>
</html>

Below code is from config.xml
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<widget id="com.ionicframework.miyabiairapp257144" version="0.0.1" xmlns="http://www.w3.org/ns/widgets" xmlns:cdv="http://cordova.apache.org/ns/1.0">
  <name>MiyabiAir</name>
  <description>An awesome Ionic/Cordova app.</description>
  <author email="hi@ionicframework" href="http://ionicframework.com/">Ionic Framework Team</author>
  <content src="index.html"/>
  <access origin="*"/>
  <access origin="*"/>
  <access origin="tel:*" launch-external="yes"/>
  <access origin="*"/>
  <allow-navigation href="http://localhost:8000*"/>
  <allow-navigation href="*"/>
  <allow-navigation href="http://*/*"/>
  <allow-navigation href="https://*/*"/>
  <allow-navigation href="data:*"/>
  <allow-intent href="http://*/*"/>
  <allow-intent href="https://*/*"/>
  <allow-intent href="tel:*"/>
  <allow-intent href="sms:*"/>
  <allow-intent href="mailto:*"/>
  <allow-intent href="geo:*"/>
  <allow-intent href="*"/>
  <platform name="android">
    <allow-intent href="market:*"/>
    <icon src="resources\android\icon\drawable-ldpi-icon.png" density="ldpi"/>
    <icon src="resources\android\icon\drawable-mdpi-icon.png" density="mdpi"/>
    <icon src="resources\android\icon\drawable-hdpi-icon.png" density="hdpi"/>
    <icon src="resources\android\icon\drawable-xhdpi-icon.png" density="xhdpi"/>
    <icon src="resources\android\icon\drawable-xxhdpi-icon.png" density="xxhdpi"/>
    <icon src="resources\android\icon\drawable-xxxhdpi-icon.png" density="xxxhdpi"/>
    <splash src="resources\android\splash\drawable-land-ldpi-screen.png" density="land-ldpi"/>
    <splash src="resources\android\splash\drawable-land-mdpi-screen.png" density="land-mdpi"/>
    <splash src="resources\android\splash\drawable-land-hdpi-screen.png" density="land-hdpi"/>
    <splash src="resources\android\splash\drawable-land-xhdpi-screen.png" density="land-xhdpi"/>
    <splash src="resources\android\splash\drawable-land-xxhdpi-screen.png" density="land-xxhdpi"/>
    <splash src="resources\android\splash\drawable-land-xxxhdpi-screen.png" density="land-xxxhdpi"/>
    <splash src="resources\android\splash\drawable-port-ldpi-screen.png" density="port-ldpi"/>
    <splash src="resources\android\splash\drawable-port-mdpi-screen.png" density="port-mdpi"/>
    <splash src="resources\android\splash\drawable-port-hdpi-screen.png" density="port-hdpi"/>
    <splash src="resources\android\splash\drawable-port-xhdpi-screen.png" density="port-xhdpi"/>
    <splash src="resources\android\splash\drawable-port-xxhdpi-screen.png" density="port-xxhdpi"/>
    <splash src="resources\android\splash\drawable-port-xxxhdpi-screen.png" density="port-xxxhdpi"/>
  </platform>
  <platform name="ios">
    <allow-intent href="itms:*"/>
    <allow-intent href="itms-apps:*"/>
  </platform>
  <preference name="webviewbounce" value="false"/>
  <preference name="UIWebViewBounce" value="false"/>
  <preference name="DisallowOverscroll" value="true"/>
  <preference name="android-minSdkVersion" value="16"/>
  <preference name="BackupWebStorage" value="none"/>
  <preference name="SplashMaintainAspectRatio" value="true"/>
  <preference name="FadeSplashScreenDuration" value="300"/>
  <preference name="SplashScreen" value="screen"/>
  <preference name="SplashScreenDelay" value="3000"/>
  <feature name="StatusBar">
    <param name="ios-package" onload="true" value="CDVStatusBar"/>
  </feature>
  <plugin name="cordova-plugin-device" spec="~1.1.3"/>
  <plugin name="cordova-plugin-console" spec="~1.0.4"/>
  <plugin name="cordova-plugin-whitelist" spec="~1.3.0"/>
  <plugin name="cordova-plugin-splashscreen" spec="~4.0.0"/>
  <plugin name="cordova-plugin-statusbar" spec="~2.2.0"/>
  <plugin name="ionic-plugin-keyboard" spec="~2.2.1"/>
  <icon src="resources\android\icon\drawable-xhdpi-icon.png"/>
</widget>

Thanks in advance.

A: Follow steps:

*

*ionic run android

*Close GPS

*Open GPS

*Close App

*Open App

This happens because the app is in debug mode and its related to the permissions of the app to use the GPS

A: try this code it works for me.
var posOptions = {timeout: 5000, enableHighAccuracy: true};
$cordovaGeolocation.getCurrentPosition(posOptions).then(function (position) {
  var fromlat = position.coords.latitude;
  var fromlng = position.coords.longitude;
  var latlng = new google.maps.LatLng(fromlat, fromlng);
  var geocoder = new google.maps.Geocoder();
  geocoder.geocode({'latLng': latlng}, function (results, status) {
    if (status == google.maps.GeocoderStatus.OK) {
      console.log(results);
    }
  });
}, function (err) {
});

A: This is what I use.
import {Geolocation} from 'ionic-native';

export class someThing {
   data: any;

constructor(public navCtrl: NavController, public alertCtrl: AlertController) {
    Geolocation.getCurrentPosition().then((resp) => {
        let lat = resp.coords.latitude;
        let lng = resp.coords.longitude;
        this.data.lat = lat;
        this.data.lng = lng;
    });
}

}
Would you be able to post your index.html file and your config.xml

A: I did the code belowed, you can find an example in my github https://github.com/prolland006/ionic2-geoloc/blob/master/src/services/background-geolocation-service.ts
 Geolocation.getCurrentPosition(this.foreGroundOptions)
        .then((position: Geoposition) => {
            this.trace.info(`Foregrnd current ${position.coords.latitude},${position.coords.longitude}`);
        }).catch((error)=>{
            if ((error.code == undefined) || (error.code != 3)) { //3=timeout
                this.trace.error('BackgroundGeolocationService', 'refreshLocations', `error Foregrnd.getCurrentPos:${error.toString()}`);
            }
        });

maybe you forgot the options
  // Foreground Tracking
foreGroundOptions = {
    frequency: 2000,
    enableHighAccuracy: true,
    maximumAge: Infinity,
    timeout: 2000
};


text:
Q: CurrentCulture incorrectly defaulting to en-US in ASP.net I have just migrated around 100 ASP.net sites from IIS 6 on Windows Sever 2003 to IIS 7 on Windows 2008. I've just noticed that various pieces of code that use things like DateTime.Parse have started kicking up errors "String was not recognized as a valid DateTime". I've tracked this down to the fact that the CurrentCulture of the sites is defaulting to 'en-US' and so my UK users are inputting dates in an unexpected format.
Question is, where are they getting en-US from? Starting from the top, if I look in 'Control Panel > Region and Language' everything is set to English (United Kingdom). The web.configs of the sites either don't have a <globalization> section or have it set as <globalization culture="auto" uiCulture="auto" />. In 'IIS7 - .Net Globalization' all of the sites have their culture set to 'Invariant Language (Invariant Country)'.
I can't find anywhere that's settings the culture to 'en-US'... but something is.
Thread.CurrentThread.CurrentCulture.Name is outputting 'en-US'
Thread.CurrentThread.CurrentCulture.NumberFormat.CurrencySymbol is outputting '$'

I can fix the issue by adding <globalization culture="en-GB" uiCulture="en-GB" /> to every web.config BUT I really don't want to have to hand edit about 100 web.configs! I wan't it to inherit the culture from the server OS settings, which are set to en-GB.
Am I missing something?

A: I had the same problem and after many hours I found out that even though the regional settings were correct, I also needed to change the original culture for all the reserved accounts (e.g. ASP.NET).
This is done through the button "Copy Settings..." under the Administrative tab in Regional Settings. The settings are copied if you enable the checkbox "Welcome screen and system accounts".

A: If I add a globalization section in the root web.config ( windir\Microsoft.NET\Framework\ver\Config\Web.config), set to en-GB, it does solve my problem and propagates down to the other sites. Which kinda solves my problem. Still doesn't explain where its getting en-US from by default though but it should do the trick. Thanks.

A: .Net web application is picking up your browser's default culture. For e.g. in FF, default language is set as shown in below image.
So, if you want your site's culture other than the one from browser, in page's InitializeCulture method (Create a BasePage and keep below code here and inherit existing pages from this BasePage).
protected override void InitializeCulture()
    {
            System.Threading.Thread.CurrentThread.CurrentUICulture = System.Globalization.CultureInfo.GetCultureInfo("en-GB");
        System.Threading.Thread.CurrentThread.CurrentCulture = System.Threading.Thread.CurrentThread.CurrentUICulture;

            base.InitializeCulture();
        }
    }

A: These are alternative places where you could search:

I can't find anywhere that's settings the culture to 'en-US'... but something is.
Thread.CurrentThread.CurrentCulture.Name is outputting 'en-US'
Thread.CurrentThread.CurrentCulture.NumberFormat.CurrencySymbol is outputting '$'

Try looking for the InitializeCulture method, this method is overridden in ASP.Net pages to set the Culture like:
protected override void InitializeCulture()
{
    var hidden = this.Request.Form["hidden"];
    var culture = this.Request.Form[hidden];
    if (!string.IsNullOrWhiteSpace(culture))
    {
        this.Culture = culture;
        this.UICulture = culture;
    }

    base.InitializeCulture();
}

Try to look for the following assembly attributes:
    [assembly: AssemblyCulture("en-US")]
    [assembly: NeutralResourcesLanguage("en-US", UltimateResourceFallbackLocation.MainAssembly)]

Try to look for the following page directive attributes:
    <%@ Page Culture="en-US" UICulture="en-US" Title="" Language="C#" MasterPageFile="~/MasterPage.master" AutoEventWireup="true" CodeFile="Default2.aspx.cs" Inherits="Default2" %>

Try to look in web.configs:
<globalization uiCulture="en-US" culture="en-US" enableClientBasedCulture="false" />

Edit 1
Try to look for HttpHandlers or HttpModules trying to set the language
Try to look in the web.config hierarchy (at the server, <wwwroot> means the root folder of your IIS Web Site)

*

*Global machine. <windir>\Microsoft.NET\Framework\<ver>\Config\Machine.config

*Root Web config. <windir>\Microsoft.NET\Framework\<ver>\Config\Web.config

*Website. <wwwroot>\Web.config

*Web application. <wwwroot>\<webapp>\Web.config

*Folder. <wwwroot>\<webapp>\<dir>\Web.config
If you have multiple servers (web farm), check you are being redirected to the correct server (the one you are checking the configuration), in order to do it you can use the ip of the desired server or configure your host files in your client computer

A: It can come from the culture of a system account used to run the Application Pool or Web Application.
Check this link:
different culture settings between IIS and ASP.NET

A: In my case, my application pool was running as my domain user, which had the current culture set to en-GB, and the application worked fine with en-GB date format.
I changed the app pool to be run under Network Service instead and suddenly the DateTime.Parse calls were breaking as the app was now using en-US culture. I saw some SO posts (e.g) about how IIS cultures are user-specific which explains that.
Opening the .NET Globalization of the root element in IIS Manager and setting both Culture and UI Culture to English UK (en-GB) fixed it for me.

A: Just to help someone gets the same problem....
After tried change IIS Culture, set globalization and so far unsecessfully, i did it in Global.asax:
void Application_BeginRequest(Object sender, EventArgs e)
{
    System.Globalization.CultureInfo newCulture = (System.Globalization.CultureInfo)System.Threading.Thread.CurrentThread.CurrentCulture.Clone();

    newCulture.DateTimeFormat.ShortDatePattern = "dd/MM/yyyy";
    newCulture.DateTimeFormat.DateSeparator = "/";

    System.Threading.Thread.CurrentThread.CurrentCulture = newCulture;
}

A: I've spent hours trying to find a solution for my case. I am working under Win10 (English version), but with Russian regional settings. Nevertheless, I got "en-US" culture in my app, hosted on IIS with ApplicationPoolIdentity. That solved the problem:
IIS -> Application Pools -> Advanced Settings -> Change "Load User Profile" to False

A: I had this problem too, but I solved it.
You must set the following values:
CultureInfo.DefaultThreadCurrentCulture = "en-GB";
CultureInfo.DefaultThreadCurrentUICulture = "en-GB";

A: I had this issue with a Windows Server Core 2022 installation so there's no simple UI solution like "Copy Settings" from the Regional Settings tab.
I wanted a Powershell or CLI solution and like you say it can be applied for the user but not copied across to all users.
For that I found help from an article by Lewis Roberts on his blog
https://www.lewisroberts.com/2017/03/01/set-language-culture-timezone-using-powershell/
You need to use control.exe to import a regional settings XML file.
The following will be for en-GB UK region so adjust it to fit your requirements.
Save the following XML to a file called UKRegion.xml or whatever you want.
<gs:GlobalizationServices xmlns:gs="urn:longhornGlobalizationUnattend">
<!--User List-->
<gs:UserList>
    <gs:User UserID="Current" CopySettingsToDefaultUserAcct="true" CopySettingsToSystemAcct="true"/>
</gs:UserList>
<!-- user locale -->
<gs:UserLocale>
    <gs:Locale Name="en-GB" SetAsCurrent="true"/>
</gs:UserLocale>
<!-- system locale -->
<gs:SystemLocale Name="en-GB"/>
<!-- GeoID -->
<gs:LocationPreferences>
    <gs:GeoID Value="242"/>
</gs:LocationPreferences>
<gs:MUILanguagePreferences>
    <gs:MUILanguage Value="en-GB"/>
    <gs:MUIFallback Value="en-US"/>
</gs:MUILanguagePreferences>
<!-- input preferences -->
<gs:InputPreferences>
    <!--en-GB-->
    <gs:InputLanguageID Action="add" ID="0809:00000809" Default="true"/>
</gs:InputPreferences>
</gs:GlobalizationServices>

Then import it using the following command (Powershell formatted):
& $env:SystemRoot\System32\control.exe "intl.cpl,,/f:`"UKRegion.xml`""

You still need a reboot but this worked for me and set the ASP.NET workers to use en-GB locale by default without having to set it in code or in the web.config.
This was particularly useful for me as I am using it to set up EC2 instances using launch templates so many of these
other solutions don't work.


text:
Q: Reactjs passing different properties to the same function with similar buttons? [Noob to react]: I'm trying to do something that I think is simple, I have two number counters that have buttons to add one number to them. I want the buttons to use the same math function but pass in the property assigned to them. What ends up happening is that it seems like it's adding a string value to the prop value instead of doing a math operation and I don't fully understand why.
The simple math function:
  addOne = (event) => {
    var { target: { name, value } } = event

    this.setState({
        [name] : value + 1
    });

    console.log("name: " + name + "\nvalue: " + value)

  }

One of the buttons:
<button type="button" name="count2" value={this.state.count2} onClick={this.addOne} >Add One</button>

Example output:
name: count2
value: 0
name: count2
value: 01
name: count2
value: 011
name: count2
value: 0111

JS fiddle: https://jsfiddle.net/Vallamost/pf7kys5e/2/
React code:
class ButtonReuse extends React.Component {
  constructor(props) {
    super(props)
    this.state = {
      count1: 0,
      count2: 0,
    }
  }

  addOne = (event) => {
    var { target: { name, value } } = event

    this.setState({
        [name] : value + 1
    });

    console.log("name: " + name + "\nvalue: " + value)

  }

  render() {
    return (
      <form onSubmit={this.handleSubmit}>

          Counter 1:
{this.state.count1}

        <button type="button" name="count1" value={this.state.count1} onClick={this.addOne} >Add One</button>

          Counter 2:
{this.state.count2}

        <button type="button" name="count2" value={this.state.count2} onClick={this.addOne} >Add One</button>

      </form>
    );
  }
}

ReactDOM.render(<ButtonReuse />, document.querySelector("#app"))

A: It's because of JavaScript's type coersion. The value that you have in your buttons is in fact a string. So when you try to execute value + 1, JavaScript tries to resolve this by first identifying a common data-type (string) before running the calculation. To work around this, simply don't use the value stored in the button and just use the state itself.
class ButtonReuse extends React.Component {
  constructor(props) {
    super(props)
    this.state = {
      count1: 0,
      count2: 0,
    }
  }

  addOne = (event) => {
    var { target: { name, value } } = event

    this.setState({
        [name] : this.state[name] + 1
    });

    console.log("name: " + name + "\nvalue: " + value)

  }

  render() {
    return (
      <form onSubmit={this.handleSubmit}>

          Counter 1:
{this.state.count1}

        <button type="button" name="count1" value={this.state.count1} onClick={this.addOne} >Add One</button>

          Counter 2:
{this.state.count2}

        <button type="button" name="count2" value={this.state.count2} onClick={this.addOne} >Add One</button>

      </form>

A: Looks like a buttons value is always a string. You should not be giving the button a value like this anyways, this is very roundabout. Why not just access the state directly:
 addOne = (event) => {
    var { target: { name } } = event

    this.setState({
        [name] : this.state[name] + 1
    });

    console.log("name: " + name + "\nvalue: " + this.state[name])

  }

Then you can just remove the value from the buttons. No string conversion necessary.

A: Your addOne method is not counting correct. Try this:
addOne = (event) => {
    var { target: { name, value } } = event

    this.setState({
        [name] : ++value
    });

    console.log("name: " + name + "\nvalue: " + value)
}

A: wrap the value with parseInt() as it is being received as string from event.
this.setState({
        [name] : parseInt(value) + 1
    });

if you'd console.log(typeof value), you'd see that it's type is string.


text:
Q: Getting the probability density kernel estimator with R I am working on a density estimation project and I need to get an estimation of the density as well as an equation for the density estimator (and not the estimate).
I am working with kernel estimators, and for that, I am using the density function, which gives me an estimation of the density given the data I have inputted.
I am new to non-parametric statistics and kernel estimation, therefore I am not fully comfortable with kernels, so maybe my question might be a bit dull.
As I explained, I need both an estimation of the density (which I can then plot; this I have been able to do it with density) as well as the density estimator (i.e. the equation, the formula), but I have been unable to achieve this with density function. Do you know how can I get the formula, i.e. the value of the parameters that determine it ?
On the other side, I might not need R to infer the equation. Indeed, if I am not mistaken, given I am working with a Gaussian kernel, I have the following estimator for the density :
$\hat f(x) = \frac{1}{nh} \sum\limits_{i=1}^n K(\frac{x-x_i}{h}) = \frac{1}{nh\sqrt {2\pi}} \sum\limits_{i=1}^n e^{-\frac{1}{2}(\frac{x-x_i}{h})^2}$
I think I have all I need there without requiring R's help any further, haven't I? I know $n$ as well as my sample $(x_1,...,x_n)$; $h$ has been computed by R or equivalently determined by some optimal rule. Thus, to get an estimation for some $x$ which does not belong to $(x_1,...,x_n)$ I just have to input it into $\hat f(.)$, isn't it? Or am I missing something?
Thank you for your help.


text:
Q: How do you launch a C# Console App from a USB device? I would like to run a console app from a USB drive. I have the project, the installation files, the deployable folder, and the starting .bat files all on the USB drive. The machine has the proper version of .NET to run the project but when the console app gets called the cmd window says "You must install .NET to run this application". Could I be getting this error because the working directory of the batch is on the USB Drive so the search for .NET fails?
Ideally when I click the start .bat (contained on the USB) it calls the executable in the deployable folder (USB) and passes it args which then installs the software (.exe or .msi contained on the USB but INSTALLING to the machine).

A: Gunr2171 suggested making the console app self contained. Using the docs found here https://learn.microsoft.com/en-us/dotnet/core/deploying/single-file/overview?tabs=vs we successfully published into a single file and it worked wonderfully!


text:
Q: Why doesn't __qualname__ work the same way in @classmethod than in metaclass I have implemented a minimalistic enum by writing
class SymbolClass(type):
    def __repr__(cls): return cls.__qualname__
class Symbol(metaclass=SymbolClass): pass

class Animal:
    class Dog(Symbol): pass
    class Cat(Symbol): pass
    class Cow(Symbol): pass

It works perfectly well
>>> {Animal.Dog: 'Wan Wan', Animal.Cat: 'Nyaa', Animal.Cow: 'Moooh'}
{Animal.Dog: 'Wan Wan', Animal.Cat: 'Nyaa', Animal.Cow: 'Moooh'}

However, I wondered, if I could get rid of the metaclass by using a class method instead
class Symbol:
    @classmethod
    def __repr__(cls): return cls.__qualname__

class Animal:
    class Dog(Symbol): pass
    class Cat(Symbol): pass
    class Cow(Symbol): pass

But it doesn't work as well :
>>> {Animal.Dog: 'Wan Wan', Animal.Cat: 'Nyaa', Animal.Cow: 'Moooh'}
{<class '__main__.Animal.Dog'>: 'Wan Wan', <class '__main__.Animal.Cat'>: 'Nyaa', <class '__main__.Animal.Cow'>: 'Moooh'}

Then I wrote a little piece of test code
class SymbolClass(type):
    def __repr__(cls): return cls.__qualname__
    def __str__(cls): return cls.__name__

class SymbolA(metaclass=SymbolClass): pass

class SymbolB:
    @classmethod
    def __repr__(cls): return cls.__qualname__

class SymbolC:
    def __repr__(cls): return cls.__qualname__

class Animal:
    class Dog(SymbolA): pass
    class Cat(SymbolB): pass
    class Cow(SymbolC): pass

import sys
def printcompare(n1, l1n, l1v, n2, l2n):
    v1 = eval(n1)
    v2 = eval(n2)
    file = sys.stdout if v2==v1 else sys.stderr
    print(f'{n1:>{l1n}} = {v1+",":<{l1v+2}} {n2:>{l2n}} = {v2}', file=file, flush=True)

for name in "SymbolClass", "SymbolA", "SymbolB", "SymbolC", "Animal", "Animal.Dog", "Animal.Cat", "Animal.Cow":
    printcompare(f"{name}.__qualname__", 24, 11, f"repr({name})", 16)

Which provided me with the following result:

and I can't figure what make this difference. It looks like the @classmethod works as if it was a normal method...

A: You can trace through what happens in the two cases to understand the differences.
A dict prints the __repr__ of its keys and values. Since __repr__ is a magic method, python does not look it up on the instance. It is critical to understand this. When calling repr(obj), the binding goes like this:
type(obj).__repr__(obj)     # No binding happening, just calling function

Not
obj.__repr__.__get__(obj)()  # Binding of non-data function descriptor

You are getting the former but expecting the latter.
Metaclass
type(Animal.Dog).__repr__(Animal.Dog) is exactly equivalent to SymbolClass.__repr__(Animal.Dog), which just returns the exact string Animal.Dog.__qualname__. There is very little ambiguity here as such. However, some confusion arises because if you ignored the fact that __repr__ is optimized to bind on the class, you would get the same result. That is, Animal.Dog.__repr__() would follow MRO to the type of Animal.Dog and call __repr__ with an implicit self of Animal.Dog. You would not see a difference.
classmethod
When you use a classmethod, however, you are attempting to bypass Python's optimized binding for magic methods. This is because classmethod relies on being bound as a descriptor first, but instead is called as a simple function.
Here is what actually happens for the first key:
type(Animal.Dog).__repr__(Animal.Dog)

This boils down to type.__repr__(Animal.Dog). Notice that without the metaclass, you are now calling the default __repr__, not your custom one. The output should be pretty clear at this point.
If the magic method mechanism had worked as you expected, you would instead be doing Animal.Dog.__repr__(), which would work as expected because it would now bind __repr__ correctly to the class through classmethod, and pass Animal.Dog as cls. You can try calling it this way to see what happens. In fact, even this calling convention works because the classmethod decorator does not blindly pass in type(self) to the wrapped method, but rather checks if it's the parent class object first.


text:
Q: Delete a key from JSON (python) I tried to delete the key ts in every machine but always I have the same error keyerror 0.
My JSON:
{
  "timestamp": "2023-01-03 10:30:39",
  "Essais": {
    "machine": {
      "temperature": [{ "ts": 1671781231183, "value": "100" }],
      "humidity": [{ "ts": 1671781231183, "value": "40" }]
    },
    "machine2": {
      "temperature": [{ "ts": 1671781231183, "value": "100" }],
      "humidity": [{ "ts": 1671781231183, "value": "40" }]
    }
  }
}

How can I delete the key ts and its value in all the JSON file?

A: Here is one way you can delete the ts keys and their values from the JSON object:
import json

json_data = {"timestamp": "2023-01-03 10:30:39",
  "Essais": {
   "machine": {
    "temperature": [
     {
      "ts": 1671781231183,
      "value": "100"
     }],
     "humidity": [
     {
      "ts": 1671781231183,
      "value": "40"
     }]},
    "machine2":{
    "temperature": [
     {
      "ts": 1671781231183,
      "value": "100"
     }],
     "humidity": [
     {
      "ts": 1671781231183,
      "value": "40"
     }]}}}

def delete_ts(obj):
    if isinstance(obj, list):
        for i in obj:
            delete_ts(i)
    elif isinstance(obj, dict):
        if 'ts' in obj:
            del obj['ts']
        for key in obj:
            delete_ts(obj[key])

delete_ts(json_data)

print(json.dumps(json_data))

This will output the following JSON object:
{
"timestamp": "2023-01-03 10:30:39",
"Essais": {
    "machine": {
    "temperature": [
        {
        "value": "100"
        }
    ],
    "humidity": [
        {
        "value": "40"
        }
    ]
    },
    "machine2": {
    "temperature": [
        {
        "value": "100"
        }
    ],
    "humidity": [
        {
        "value": "40"
        }
    ]
    }
}
}


text:
Q: 'NoneType' is made when I create a list and error in randrange when I haven't used it import random
foundwords = []
wordsDict = {}

with open("text", "r") as file:
    contents = file.read().replace('\n',' ')
words = contents.split(' ')

def findwords(word):
    for i in range(len(words) - 1):
        if words[i] == word:
            if not words[i + 1] == '':
                foundwords.append(words[i + 1])
    return foundwords

for word in words:
    wordsDict.setdefault(word, findwords(word))

# for i in range(len(words) - 1):
#     findwords(words[i])
#     wordsDict.setdefault(words[i], foundwords)
#     del foundwords[:]

def nextword(word):
    wordList = wordsDict.get(word.lower())
    new = wordList[random.randint(0, len(wordList) - 1)]
    return new

def assemble():
    final = [words[random.randint(0, len(words))].capitalize()]
    final.append(nextword(final[-1]))
    print(final)

assemble()

I have tried to create a markov-chain project, however, I get the following error:
Traceback (most recent call last):
  File "main.py", line 32, in <module>
    assemble()
  File "main.py", line 28, in assemble
    final.append(nextword(final[0]))
  File "main.py", line 23, in nextword
    new = wordList[random.randint(0, len(wordList) - 1)]
  File "/usr/local/lib/python3.6/random.py", line 220, in randint
    return self.randrange(a, b+1)
  File "/usr/local/lib/python3.6/random.py", line 198, in randrange
    raise ValueError("empty range for randrange() (%d,%d, %d)" % (istart, istop, width))
ValueError: empty range for randrange() (0,0, 0)
exited with non-zero status

And sometimes this error:
Traceback (most recent call last):
  File "main.py", line 31, in <module>
    assemble()
  File "main.py", line 28, in assemble
    final.append(nextword(final[0]))
  File "main.py", line 23, in nextword
    new = wordList[random.randint(0, len(wordList) - 1)]
TypeError: object of type 'NoneType' has no len()

I have no idea how to start fixing this problem. I'm only a beginner programmer, so if my code is inefficient or anything, I apologize. Also, I'm not sure if this ok to post as a question, sorry.


text:
Q: Como guardar a sessão do usuário em um site armazenado na AWS - S3? Na AWS podemos usar o serviço S3 para disponibilizar web sites estáticos. Seundo a documentação entende-se por estático a não utilização de back-end como php, asp.net, etc.
Porém posso carregar conteúdo dinamicamente através de requisições javascript get, consumindo end-points de APIs que podem ser carrgadas assincronamente. POsso carregar imagens, graficos, videos textos e etc.
O unico problema que estou encontrando é como guardar a sessão do usuário.
Existe alguma maneira de fazer isso?

A: Então cara, vou responder por aqui porque não posso comentar.
Você não vai conseguir armazenar sessão através de API (requisições ajax, etc). Isso porque essas requisições são completamente independentes umas das outras e geralmente o backend trata cada uma delas como sessões independentes.
Existem algumas formas de você contornar isso. O que eu costumo fazer é utilizar um JWT (Json Web Token). Com ele você consegue armazenar informações sobre o usuário dentro do mesmo e recuperar elas dentro do seu backend. Estes tokens são muitas vezes utilizados em forma de sessão, você pode enviar uma data de expiração dentro dele e renovar essa expiração a cada chamada ao backend, por exemplo, fazendo com que, caso o usuário fique mais de 20min sem chamar o backend, o token se torne inválido e ele precise logar novamente. Você pode armazenar esse token no sessionStorage, localStorage ou até mesmo utilizar cookies.
Através do S3, pelo fato de ser estático, você não irá conseguir trabalhar com sessões, já que sessões geralmente funcionam bem em sites que são renderizados pelo proprio backend (Django, Pyramid, entre outros frameworks) fazem isso, mas, você não conseguirá usar o S3 para publicar este tipo de site.
Resumindo, eu sugiro você utilizar o JWT para trabalhar com sessões (simular elas, no caso)


text:
Q: How to link continuous integration to my latest sprint trunk? Using a continuous integration on my project, I need to checkout the code from latest sprint from BAZAAR as bzr://path/to/myproject/sprint/123
As this path is changing repeatedly (for each sprint), I'm currently using externals to create a bzr://path/to/myproject/current pointing to bzr://path/to/myproject/sprint/123.
So, I just need to change the externals to redirect the continuous integration tool to the latest project.
Is there another way to do this ?
What I don't want is to change the configuration of my project inside the continuous integration tool (CruiseControl.NET).

A: One option (might not be suitable for your teams' processes) would be to stop using a separate "sprint" location in bzr for each iteration's changes.  Instead, just use a "trunk" (or perhaps your "current" above).  If you are usually in a situation where you have multiple sprints having changes at the same time, then this would probably not be appropriate.

A: I suppose you can use a lightweight checkout.
bzr checkout --lightweight bzr://path/to/myproject/iterations/123 bzr://path/to/myproject/current

You can then use bzr switch to switch to the next branch (I'm not sure if it will work over the network):
bzr switch -d bzr://path/to/myproject/current bzr://path/to/myproject/iterations/124

A: After searching the web, I've found some articles about this question.
There are two solutions so far:

*

*Automatically detect newly finished branch and build them. There is an example here using CC.NET. It is so applicable to my iterations.

*Another way is to provide scripts to developer that execute most of the CI tool. This is not perfect, but this may detect issues before merging in the trunk.

Other references:
Best branching strategy when doing continuous integration?


text:
Q: Mockito ArgumentCaptor with lambda (Chronicle Queue) I have implemented following Chronicle Queue and for this I want to write unit test case. How do I capture ArgumentCaptor arguments while using lambda. I want to get writeBuffer in test case to verify the data.
public class Persister  {

public Persister(SingleChronicleQueue chronicle) {
    this.chronicle = chronicle;
}
public void write(int outBufferOffset) throws IOException {
       ExcerptAppender appender = chronicle.acquireAppender();
       appender.writeBytes(b -> {
               b.writeInt(outBufferOffset);
               b.write(writeBuffer, 0 , outBufferOffset);
       });}
}

Test case:
@Mock
SingleChronicleQueue chronicle;
@Mock
ExcerptAppender appender;
@Captor
ArgumentCaptor<WriteBytesMarshallable> argumentCaptorLambda;

Persister persister = new Persister();
@Test
public void shouldPersistByteMessage() throws IOException {
    persister.write(MESSAGEBYTES);

    verify(appender).writeBytes(argumentCaptorLambda.capture());
    WriteBytesMarshallable lastValue =  argumentCaptorLambda.getValue();

    //final byte[] persistedBytes = ?? how to get writeBuffer here ??
    //assertThat(readPersistedMessage(persistedBytes), is(MESSAGE));
}

Thanks

A: I have used the doAnswer for this implementation
@Captor
ArgumentCaptor<WriteBytesMarshallable> argumentCaptorLambda;
@Mock private BytesOut bytesOut;

public void shouldPersistReliableMessage() throws IOException {
        doAnswer(invocationOnMock -> {
            WriteBytesMarshallable marshallable = (WriteBytesMarshallable) invocationOnMock.getArguments()[0];
            marshallable.writeMarshallable(bytesOut);
            return null;
        }).when(appender).writeBytes((WriteBytesMarshallable)any());

        persister.persist(MESSAGEBYTES);

        verify(bytesOut).writeInt(84);
        verify(bytesOut).write(argumentCaptor.capture(), eq(0), eq(84));

        assertThat(readPersistedMessage(argumentCaptor.getValue()), is(MESSAGE));

    }


text:
Q: Join entity in many to many not being persisted after applying "@Transient" to the corresponding entities and the join entity the main idea of my setup is to manage the many to many relationship via repositories. That is why, in the following setup, all the relations are annotated as @Transient, since those sets should only be populated "manually", instead of letting Hibernate do that.
@Entity
@Table(name = "house")
public class House {
    @Column(name = "id")
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Id
    private long id;

    @Transient
    private Set<Owner> owners;
}

@Entity
@Table(name = "owner")
public class Owner {
    @Column(name = "id")
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Id
    private long id;

    @Transient
    private Set<House> houses;
}

public class HouseIdOwnerId implements Serializable {
    private long houseId;
    private long ownerId;

    public HouseIdOwnerId(final long houseId, final long ownerId) { /* ... */ }

    @Override
    public boolean equals(final Object other) { /* ... */ }

    @Override
    public int hashCode() { /* ... */ }
}

@Entity
@IdClass(HouseIdOwnerId.class)
@Table(name = "house_owner")
public class HouseOwner{
    @Column(name = "house_id")
    @Id
    private long houseId;

    @Column(name = "owner_id")
    @Id
    private long ownerId;

    @Transient
    private House house;

    @Transient
    private Owner owner;

    @CreatedTimestamp
    private LocalDateTime createdAt;

    public HouseOwner(final House house, final Owner owner) {
        this.houseId = house.getId();
        this.house = house;

        this.ownerId = owner.getId();
        this.owner = owner;
    }

    // ...

    @Override
    public boolean equals(final Object other) { /* ... */ }

    @Override
    public int hashCode() { /* ... */ }
}

As one would expect, when trying to persist the join entity, since its properties are marked as @Transient, nothing happens:
@Test
void testInsertRelated() {
    // ...
    this.entityManager.persist(house);
    this.entityManager.persist(owner);
    this.entityManager.persist(owner2);

    final HouseOwner ho = new HouseOwner(house, owner);
    final HouseOwner ho2 = new HouseOwner(house, owner2);

    this.entityManager.persist(ho);
    this.entityManager.persist(ho2);
}

The reason I didn't do @OneToMany relationships in the dependent entities is because they would end up with ugly Set<HouseOwner> houses and Set<HouseOwner> owners properties, that of course would get ignored when persisting the main entities.
So, imagine that a request comes which creates a new house that is going to get associated with multiple owners. You would need to, somehow, map the incoming owner IDs to multiple HouseOwner objects, so these need some way of being created without the House part, because it is not yet created. Therefore, you end up with an ugly HouseOwner object.

Summarizing, I think I am mixing up concepts here. However, is it possible to do what I am trying above? Thank you in advance.

A: I'm not sure if I understood the question correctly. Why don't you use many-to-many relationships? Is it a design choice? Let me try to answer in both flavors.
PART I - Using many-to-many relationships
When using the 'many-to-many' relationships, you shouldn't create entity classes for join tables. In your example, the class "HouseOwner" shouldn't be coded. Your model contains two entities: House and Owner. The way they interact with each other is through a many-to-many relationship. Once you define this relationship in your mappings, the JPA engine will derive the join table automatically (you can use @JoinTable mapping if the defaults doesn't fit you). The code would look like this:
@Entity
@Table(name = "house")
public class House {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private long id;

    @ManyToMany
    @JoinTable(name = "house_owner", joinColumns = {
        @JoinColumn(name = "house_id")},
            inverseJoinColumns = @JoinColumn(name = "owner_id"))
    private Set<Owner> owners;
}

@Entity
@Table(name = "owner")
public class Owner {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private long id;

    @ManyToMany(mappedBy = "owners") /* you must elect a relationship owner */
    private Set<House> houses;
}

And that's all you need to define your entities and their relationships. You can see the JPA is expecting the existence of a third table by enabling the jakarta.persistence.schema-generation.scripts.action property in your persistence.xml. Sniffing the created script, you would see something like this:
create table house (id bigint generated by default as identity, primary key (id));
create table house_owner (house_id bigint not null, owner_id bigint not null, primary key (house_id, owner_id));
create table owner (id bigint generated by default as identity, primary key (id));
alter table if exists house_owner add constraint FK96rb7vss0wg6qgwkbfmt4iw9w foreign key (owner_id) references owner;
alter table if exists house_owner add constraint FKcb77jw3le78e333bx246ln3ap foreign key (house_id) references house;

PART II - Using @Transient
If yet you want to use @Transient in your modeling, I can only imagine that you don't want the JPA engine doing the hard work for you. But, if you must, you can do the following:
@Entity
@Table(name = "house")
public class House {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private long id;

    @Transient
    private Set<Owner> owners;
}

@Entity
@Table(name = "owner")
public class Owner {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private long id;

    @Transient
    private Set<House> houses;
}

@Entity
@Table(name = "house_owner")
public class HouseOwner {

    @Id
    @Column(name = "house_id")
    private long houseId;
    @Id
    @Column(name = "owner_id")
    private long ownerId;

    @Transient
    private House house;
    @Transient
    private Owner owner;
}

Again, sniffing the created script by enabling jakarta.persistence.schema-generation.scripts.action property, you would see something like this:
create table house (id bigint generated by default as identity, primary key (id));
create table house_owner (owner_id bigint not null, house_id bigint not null, primary key (house_id, owner_id));
create table owner (id bigint generated by default as identity, primary key (id));

As you can see, the same three tables - but this time without the foreign keys. This means that JPA will ignore any relationship between your entities.


text:
Q: How to handle code migration when working with Snowflake? I am trying to understand the best way to migrate code when working with Snowflake. There are two scenarios, one where we have only one snowflake account and that houses all environments (dev, test, prod). And the other has two accounts (non-prod, prod). With the second option, I was planning to create a separate script that will set up the correct database name which is based on environment (dev_ent_dw, prod_ent_dw) and then I will refer these as variables when creating objects. Example -
set env = 'dev';
set db = $env || '_ent_dw.';

Right now we're running everything manually so the devops team will run these upfront before running ddl scripts. We may do something similar with the former scenario but I am wondering if folks can share best practices of dealing with this as I am sure it would be common topic at large enterprises.

A: We have different accounts for each environment (dev, qa, prod).  We use Azure DevOps for change management within our team, including the Git repos and Azure Pipelines for deploying scripts via schemachange.
We do NOT append an environment to objects, as that is handled by the account.
Developers write migration scripts and check them into source control.  We then create Version folders and move/rename the migration scripts for deployment, and run a pipeline to execute the changes.  The only thing we need to change is the URL to deploy against, and that is handled within the pipeline itself.  The nice thing here is that we do not need to tweak anything going from different branches in source control.
We have not been doing much with creating clones for development work, as we usually only have one developer working on changes to a set of objects at a time.  We are exploring ways to improve our process, but what we have works fairly well for our current needs.


text:
Q: How do I tell if my Apple hardware is covered by AppleCare? My iPhone's lock screen button isn't behaving well and I'd like to take it to the Apple Store to get it replaced. I'm fairly certain I bought AppleCare on it, but the receipt and anything that might indicate I made that purchase are locked away in a storage locker and far from convenient to find.
Is there a way to determine if any piece of Apple hardware is currently under warranty or covered by an AppleCare plan without having the original purchase receipt?

A: Apple's self-solve web portal can tell you whether any Apple product is currently under warranty or covered by an AppleCare plan. It can also tell you when the coverage ends and help you setup an appointment to get your problem looked in to.
You'll need to know the serial number for your Apple product to look up the coverage. There's an Apple support article on how to find this identifier for all the different bits of hardware Apple makes.


text:
Q: If I have a url is there a way to figure out how many reddit votes it has? When I say url it doesn't necessarily have to be a url on the reddit.com domain but simply just one submitted to the site.  Any help is appreciated!

A: http://code.reddit.com/wiki/API
Official Reddit API :)


text:
Q: Any working Javascript Auto Completion or Content Assist for Eclipse? I am using Eclipse to develop some JavaScript codes where I need auto-completion ( Code Content Assist) available. Is there anyway to activate such a thing for JavaScript codes in Eclipse?

A: Once you have the JavaScript Development Tools installed, you have to be working with a file in a JavaScript Source Folder.  To do that, you can create a JavaScript project or enable an existing project from its Configure context menu (right-click->Configure->something JavaScript). Once that's done, if it wasn't opened automatically, bring up the project's JavaScript Include Path property page and create or mark an existing folder as a Source Folder.  That should enable it for both JS files and web pages--assuming you have the web page support from the Web Tools Platform installed as well.  To get the entire thing installed, you can follow the instructions at http://wiki.eclipse.org/WTP_FAQ#How_do_I_install_WTP.3F .
The defaults during conversion should set it up to deal with JavaScript that's aware of browser objects.

A: You need to have the Javascript Development Tools component of Eclipse installed. You can install this in Help > Install New Software.

A: Eclipse is best suited for Java and related technologies. Although it has a very basic support for Javascript, like you can use ctrl + O to view all the variables and functions. There is no auto complete support for Javascript.


text:
Q: Equivalent of dynamic type "automatically adjusts font" setting for UIButton in Interface Builder? A UILabel has a Dynamic Type: Automatically Adjusts Font check-box in the Attributes Inspector in Interface Builder.
Is there an equivalent in Interface Builder for automatically adjusting the font size of a UIButton, or does this have to be handled in code?
I'm using Xcode 9.0 beta 6, targeting iOS 11.

A: Apparently there isn't, but it's not very hard to fix. You can make an extension on UIButton with an @IBInspectable property:
extension UIButton {

    @IBInspectable
    var adjustsFontForContentSizeCategory: Bool {
        set {
            self.titleLabel?.adjustsFontForContentSizeCategory = newValue
        }
        get {
            return self.titleLabel?.adjustsFontForContentSizeCategory ?? false
        }
    }
}

Now you can simply turn it on for every UIButton (or any of its subclasses).

A: Well there seems to be a way to do it in the Interface Builder only. I use Xcode version 11.5.
1. First set as usual a dynamic font type:

I choose Subhead because according to this link it will be 15 pt height which was the font size I had previously set for the button.
2. Instead of setting the titleLabel.adjustsFontForContentSizeCategory in code, you can set it in the "User Defined Runtime Attributes" section in Xcode.

A: There is a simple solution directly on IB without having so much pain of extension on button and all that.
In Interface Builder

*

*Set Button Type from System to Custom

*Set as usual Font to Text Style.

Optional

*You can set auto layout constrains on .leading & .trailing so that when Large accessibility text is set, button should not be out of visible area.


text:
Q: asp.net linq to aadata datatable Hello I have been trying to use dataTable for one project in ASP.net yet I have come into a wall in which I want to pass from sql database to aadata string format, I have managed to get the LINQ query which is the following:
     var querytable4 = from table1 in db.ScrapClassifications
                      join table2 in db.ScrapGroups on table1.idGroup equals table2.idGroup
                      join table3 in db.ProdAreas on table1.idArea equals table3.idArea
                      join table4 in db.ScrapSubGroups on table1.idSubGroup equals table4.idSubGroup
                      select new {ActiveBool = table1.Active,
                                   idScrap= table1.idScrapClassification,
                                   Area= table3.Area,
                                   groupDesc= table2.Description,
                                   subgroupdesc=table4.Description,
                                   description=table1.Description
                                    };

and it does seem to work correctly displaying all the values, then using Newtonsoft serializer I try to do the following:
        var json = JsonConvert.SerializeObject(querytable4);

and it throws me the following output:
  [{\"ActiveBool\":true,\"idScrap\":1,\"Area\":\"Controllers\",\"groupDesc\":...

yet my ajaxhandler which is the following:
    return Json(new
    {
        sEcho = param.sEcho,
        iTotalRecords = 100,
        iTotalDisplayRecords = 100,
        aaData = json

    },JsonRequestBehavior.AllowGet);

only accepts the following format:
public class HomeController : Controller
{
    public ActionResult AjaxHandler(jQueryDataTableParamModel param)
    {
        return Json(new{
                sEcho = param.sEcho,
                iTotalRecords = 97,
                iTotalDisplayRecords = 3,
                aaData = new List<string[]>() {
                    new string[] {"1", "Microsoft", "Redmond", "USA"},
                    new string[] {"2", "Google", "Mountain View", "USA"},
                    new string[] {"3", "Gowi", "Pancevo", "Serbia"}
                    }
            },
        JsonRequestBehavior.AllowGet);
    }
}

anyway to do this conversion? I have been stuck for a week just trying to figure this out, also my database contains booleans and other numeric value, I have also tried to create a list of strings, but when I try to make the conversion it tells me that some values aren't strings in my query..

A: I was able to solve the issue by doing the following changes in the query:
        var querytable = (from table1 in db.ScrapClassifications
                          join table2 in db.ScrapGroups on table1.idGroup equals table2.idGroup
                          join table3 in db.ProdAreas on table1.idArea equals table3.idArea
                          join table4 in db.ScrapSubGroups on table1.idSubGroup equals table4.idSubGroup
                          select new{Active=table1.Active,
                                       Classification=table1.idScrapClassification,
                                       Area=table3.Area,
                                       Group=table2.Description,
                                       SubGroup=table4.Description,
                                       Description=table1.Description
                                        }).ToArray();

then I changed the json input file to the following:
        var data = displayquery.Select(d => (new string[] { d.Active.ToString(), d.Classification.ToString(),d.Area.ToString(),d.Group,d.SubGroup,d.Description  }));

my Json ended looking like the following:
        return Json(new
        {
            sEcho = param.sEcho,
            iTotalRecords = querytable.Count(),
            iTotalDisplayRecords = filteredquery.Count(),
            aaData = data
        },
       "application/json", Encoding.UTF8, JsonRequestBehavior.AllowGet);


text:
Q: makeValidWord(std::string word) not working properly I'm programming a hash table thing in C++, but this specific piece of code will not run properly. It should return a string of alpha characters and ' and -, but I get cases like "t" instead of "art" when I try to input "'aRT-*".

*

*isWordChar() return a bool value depending on whether the input is a valid word character or not using isAlpha()

 // Words cannot contain any digits, or special characters EXCEPT for
 // hyphens (-) and apostrophes (') that occur in the middle of a
 // valid word (the first and last characters of a word must be an alpha
 // character). All upper case characters in the word should be convertd
 // to lower case.
 // For example, "can't" and "good-hearted" are considered valid words.
 // "12mOnkEYs-$" will be converted to "monkeys".
 // "Pa55ive" will be stripped "paive".

std::string WordCount::makeValidWord(std::string word) {
    if (word.size() == 0) {
        return word;
    }
    string r = "";
    string in = "";
    size_t incr = 0;
    size_t decr = word.size() - 1;
    while (incr < word.size() && !isWordChar(word.at(incr))) {
        incr++;
    }
    while (0 < decr && !isWordChar(word.at(decr))) {
        decr--;
    }
    if (incr > decr) {
        return r;
    }
    while (incr <= decr) {
        if (isWordChar(word.at(incr)) || word.at(incr) == '-' || word.at(incr) == '\'') {
            in =+ word.at(incr);
        }
        incr++;
    }
    for (size_t i = 0; i < in.size(); i++) {
        r += tolower(in.at(i));
    }
    return r;
}

A: Assuming you can use standard algorithms its better to rewrite your function using them. This achieves 2 goals:

*

*code is more readable, since using algorithms shows intent along with code itself

*there is less chance to make error

So it should be something like this:
std::string WordCount::makeValidWord(std::string word) {
    auto first = std::find_if(word.cbegin(), word.cend(), isWordChar);
    auto last = std::find_if(word.crbegin(), word.crend(), isWordChar);
    std::string i;
    std::copy_if(first, std::next(last), std::back_inserter(i), [](char c) {
        return isWordChar(c) || c == '-' || c == '\'';
    });
    std::string r;
    std::transform(i.cbegin(), i.cend(), std::back_inserter(r), std::tolower);
    return r;
}

A: I am going to echo @Someprogrammerdude and say: Learn to use a debugger!
I pasted your code into Visual Studio (changed isWordChar() to isalpha()), and stepped it through with the debugger. Then it was pretty trivial to notice this happening:
First loop of while (incr <= decr) {:

Second loop:

Ooh, look at that; the variable in does not update correctly - instead of collecting a string of the correct characters it only holds the last one. How can that be?
in =+ word.at(incr); Hey, that is not right, that operator should be +=.
Many errors are that easy and effortless to find and correct if you use a debugger. Pick one up today. :)


text:
Q: Binary string comparison/sort vs Dictionary string comparison/sort what is other difference than performance ?
cheers,
/Marcin

A: Well it depends on the sorting technique and how big the strings are. The other different other than performance would be the memory usage. Dictionary one will use more memory depending on the size of the string.


text:
Q: minify es2017 with gulp Hey guys I'm currently using uglify-gulp with babel to minify my js. And it works great with es2015 and es2016. But it breaks if I try to do es2017.
Does anyone know any workarounds to minify js that is using the new experimental features in es2017?
gulp.src('build/js/bundled/bundle.js')
.pipe(babel({
    compact: false,
    presets: ["es2017", "react"],
    plugins: ["transform-decorators-legacy"],
}))
.pipe(uglify())
.pipe(gulp.dest('build/js/bundled'));

which generates this error
GulpUglifyError: unable to minify JavaScript

If I change es2017 to es2015/es2016 it will minify my bundles that don't have es2017 features just fine. But I want to be able to use those experimental features and be able to minify my code

A: I think that Uglify can't parse some ES2015 features, so you need to transpile those down to ES5 (es2017 targets Node 5+).
With these webpack instructions, specifically the presets and plugins, you should be able to get it working (at least it did for me, as I could replicate similar Uglify issues by just using es2017):
presets: ['es2015', 'es2017', 'react'],
plugins: ['transform-runtime', 'transform-decorators-legacy', 'transform-class-properties']


text:
Q: Angular 4 adding an image before each new line using renderer I am trying to add an image before each new line
So I am able to achieve this
Apple
Ball
Cat
Dog

but I want to add image before in every new line
(img) Apple
(img) Ball
(img) Cat
(img) Dog

The code
this.tooltipTitle = "Apple,Ball,Cat,Dog,Elephant"

create() {
  this.tooltip = this.renderer.createElement('div');
  this.tooltipTitle.split(',').forEach((text) => {
  this.renderer.appendChild(this.tooltip, this.renderer.createText(text));
  this.renderer.appendChild(this.tooltip, this.renderer.createElement('br'));
  this.renderer.appendChild(document.body, this.tooltip);
 });
}

this.renderer.addClass(this.tooltip,'classA')

 .classA{
   positon:absolute;
   max-width: 150px;
   font-size: 14px;
   color: black;
   padding: 3px 8px;
   background: grey;
   border-radius: 4px;
   z-index: 100;
   opacity: 0;
 }

So the addClass is adding styles to the whole tooltip.That is good and working what I am further trying is to add an image at beginning of new line as well
Edit
After trying a lot I am able to add the image "but" it is only getting added to the last value not to the previous values(whereas I want to add image on every new line).
this.tooltip = this.renderer.createElement('div');
this.imgforres = this.renderer.createElement('img');
this.imgsrc =
this.renderer.setAttribute(this.imgforres,"src",
"assets/images/restriction.png")

this.tooltipTitle.split(',').forEach((text) => {
this.renderer.appendChild(this.tooltip,this.imgforres);
this.renderer.appendChild(this.tooltip, this.renderer.createText(text));
this.renderer.appendChild(this.tooltip, this.renderer.createElement('br'));
this.renderer.appendChild(document.body, this.tooltip);
});

Latest
Now I have achieved I get the image before every new line of text, Thanks to Yuri for his response
One last glitch is if the text is long it surely wraps up but the indentation is not with the above line text, it starts below the image
<img> Apple
<img> Ball
<img> So this a long text
and it starts from below
the image
<img> Cat

Expected
<img> Apple
<img> Ball
<img> So this a long text
      and it starts from
      below the image
<img> Cat

I have tried word-break, justify , it's not helping , maybe I'll have to embed this text in a div or p tag and then give styling to those.

A:       this.tooltip = this.renderer.createElement('div');
      this.tooltipTitle.split(',').forEach((text) => {
      this.renderer.appendChild(this.tooltip, this.renderer.createText(text));
      this.renderer.appendChild(this.tooltip, this.renderer.createElement('br'));

      var img2 = document.createElement('img'); // Use DOM HTMLImageElement
      img2.src = 'image2.jpg';
      img2.alt = 'alt text';
      this.renderer.appendChild(this.tooltip,img2);
      this.renderer.appendChild(this.tooltip, this.renderer.createElement('br'));

      this.renderer.appendChild(document.body, this.tooltip);
    });

Another layout

A: You can try something like this -
create(){
  this.tooltip = this.renderer.createElement('div');

    this.tooltipTitle.split(',').forEach((text) => {
      let container = this.renderer.createElement('div');
      let img = this.renderer.createElement('img');
      this.renderer.setAttribute(img, "src", "assets/images/restriction.png");
      this.renderer.appendChild(container, img);

      let textSpan = this.renderer.createElement('span');
      this.renderer.appendChild(textSpan, this.renderer.createText(text));
      this.renderer.appendChild(container, textSpan);

      this.renderer.appendChild(this.tooltip, container);
    });

    this.renderer.appendChild(document.body, this.tooltip);
}

In html, I kept an inline css which you can have in separate file and load it by calling this.renderer.addClass()
<style>
  span {
    margin-left: 10px;
    display:inline-flex;
    width:150px;
    word-wrap:break-word;
}
</style>

Here's my test tooltipTitles -
tooltipTitle = "Apple,Ball,Cat,Dog,Elephant Elephant  Elephant  Elephant  Elephant  Elephant  Elephant  Elephant  Elephant  Elephant  Elephant ";
And here's the output screenshot
Test Output


text:
Q: How to update all the elements of repeated array (fields) of bigquery My Table has the schema:
name: String - Nullable
Email: String - Nullable
Contact-number : String - Repeated
age: int64 Nullable
eg:

Name
Email
Contact-number
Age

John
row
1256545, 1309045
30

I want to update both the numbers of the user John.

A: update mytable
set Contact-number = ['0000','1111']
where name = 'John'


text:
Q: Calculate base and coefficient for power curve through 3 non-linear points I have a formula that takes a 0-based bounded single dimensional input and transforms it to a specific power curve.
EDIT
This is single dimensional. There is no $y$. In the image, I'm showing how the $x$ input is transformed. The only way to show this is to simulate it in the $y$ dimension. Technically, the graph should be shown stepped, but this is inconsequential to what I need.
If this isn't clear, then simply consider the curve to be a straight line with 3 points.
Looking at the image within the context of the input:
$k$ represents the number of buckets; this is logarithmic bucketing & I'm dividing A-C into $k$ logarithmic buckets; $k$ is predefined.
$A$ is always $0$ and is the lower bound.
$B$ maps to an output of 1, meaning the second bucket (0 is first); it is the beginning point of the second bucket; $B$ is predefined.
$C$ is the upper bound target, always +; $C$ is predefined.

The output $z$ is calculated as: $$z=\lfloor log_b(xR+1) \rfloor$$ where $$R=\frac{b^k-1}{C}$$
I need to determine $b$ based on $C$, $k$, and $B$. I worked out a recursive approximation algorithm, but I would prefer a formulaic solution.
EXAMPLE
$C=17987547480$
$k=128$
$B=0.000001$
$b=1.3280368123342627$
$R=328036.81233426905$
The difficulty is that $b$ and $R$ need to be simultaneously solved.

A: The curve $z=\log_b(xR+1)$ has $z(0)=0$ and $z(C)=k$ provided $R$ is defined as
$$R=\frac{b^k-1}{C}.\tag{1}$$
From a comment it appears you want $B$ to denote the value of $x$ at which $z(x)=1$, and since $z$ is defined as a log base $b$ this means that at $x=B$ the input of the log should be $b$ [since $\log_b(b)=1$]. This gives $BR+1=b$ or
$$R=\frac{b-1}{B}.\tag{2}$$
Now from your example and the post, $k$ is known (there are $k$ or $k+1$ buckets, depending on whether bucket $0$ counts). It also appears you want to set the value $B$ yourself, as the $x$ value at which the curve $z$ first reaches $1$, and that the value $C$ is also regarded as known. With $B,C$ taken as known, either formula determines $R$ provided only we can find $b.$ Equating the right sides of $(1)$ and $(2)$ and rearranging, we have
$$\frac{b^k-1}{b-1}=\frac{C}{B}.\tag{3}$$
For even moderately large $k$ this is really a polynomial equation for $b$ of large degree, so there seems little hope for a closed form solution giving $b$ as a formula in terms of $C,B.$ One could carry out the division on the left of $(3)$ and get the polynomial
$$1+b+b^2+\cdots +b^{k-1},$$
or perhaps save some notation by rewriting $(3)$ as
$$b^k -(C/B)b+(1-C/B)=0.$$
Either way it remains a problem of solving a large degree polynomial equation.


text:
Q: Javascript looping problem and converting nested objects into an array In the below array I am trying to convert "reporting" object into an array of objects.
Below is how I am trying:
  const data = [{
    m_id: '61',
    reporting: {
     0: {
      report_cd: 'L',
      report_category: 'Light Vehicles'
     },
     1: {
      report_cd: 'M',
      report_category: 'Motorcycles'
     }
    }
   },
   {
    m_id: '62',
    reporting: {
     0: {
      report_cd: 'L',
      report_category: ' Extra Light Vehicles'
     },
     1: {
      report_cd: 'M',
      report_category: 'Bike'
     },
     2: {
      report_cd: 'H',
      report_category: 'Extra Heavy'
     }
    }
   }
  ];

  var arr = [];
  for (let j = 0; j < data.length; j++) {
   let keys = Object.keys(data[j].reporting);

   for (var i = 0, n = keys.length; i < n; i++) {
    var key = keys[i];
    arr[key] = data[j].reporting[key];
   }
   data[j].reporting = arr;
  }
  console.log(data);

I am able to convert it into an array in the current output but there's some problem in my loop due to which for both the objects I am getting back 3 arrays for reporting:
Current Output :
[{
 "m_id": "61",
 "reporting": [{
  "report_cd": "L",
  "report_category": " Extra Light Vehicles"
 }, {
  "report_cd": "M",
  "report_category": "Bike"
 }, {
  "report_cd": "H",
  "report_category": "Extra Heavy"
 }]
}, {
 "m_id": "62",
 "reporting": [{
  "report_cd": "L",
  "report_category": " Extra Light Vehicles"
 }, {
  "report_cd": "M",
  "report_category": "Bike"
 }, {
  "report_cd": "H",
  "report_category": "Extra Heavy"
 }]
}]

Expected Output:
[{
 "m_id": "61",
 "reporting": [{
  "report_cd": "L",
  "report_category": "Light Vehicles"
 }, {
  "report_cd": "M",
  "report_category": "Motorcycles"
 }]
}, {
 "m_id": "62",
 "reporting": [{
  "report_cd": "L",
  "report_category": " Extra Light Vehicles"
 }, {
  "report_cd": "M",
  "report_category": "Bike"
 }, {
  "report_cd": "H",
  "report_category": "Extra Heavy"
 }]
}]

A: The problem with your code is that since arrays are reference types using the same array(var arr) for the second iteration will also modify the reporting array of the first object.
An alternative using map and Object.values:

const data = [{
    m_id: '61',
    reporting: {
      0: {
        report_cd: 'L',
        report_category: 'Light Vehicles'
      },
      1: {
        report_cd: 'M',
        report_category: 'Motorcycles'
      }
    }
  },
  {
    m_id: '62',
    reporting: {
      0: {
        report_cd: 'L',
        report_category: ' Extra Light Vehicles'
      },
      1: {
        report_cd: 'M',
        report_category: 'Bike'
      },
      2: {
        report_cd: 'H',
        report_category: 'Extra Heavy'
      }
    }
  }
];

const result = data.map(el => ({...el, reporting: Object.values(el.reporting)}))

console.log(result)

Object.values is just like Object.keys but instead of returning an array of keys, it'll return an array of values.

A: You can use Object.keys to create your array for reports inside data object

const data = [{
    m_id: '61',
    reporting: {
      0: {
        report_cd: 'L',
        report_category: 'Light Vehicles'
      },
      1: {
        report_cd: 'M',
        report_category: 'Motorcycles'
      }
    }
  },
  {
    m_id: '62',
    reporting: {
      0: {
        report_cd: 'L',
        report_category: ' Extra Light Vehicles'
      },
      1: {
        report_cd: 'M',
        report_category: 'Bike'
      },
      2: {
        report_cd: 'H',
        report_category: 'Extra Heavy'
      }
    }
  }
];

const result = data.map(x => ({
  ...x,
  reporting: Object.keys(x.reporting).map(key => x.reporting[key])
}))

console.log(result)


text:
Q: Which is the best method to redirect users from an existing website to an existing WP blog? I have a website with around 500 HTML pages. I have now posted all these HTML pages into my blog as blog posts. I now want to now redirect users from the page to the blog. I could do that using mod_rewrite or JavaScript?
Since Google will re-index these posts, which of the these two methods would be a better option for SEO?
Kindly also suggest any other techniques you know.

A: Search engines generally don't interpret JavaScript. You should better do a proper HTTP redirect. And that can be done with either the mod_alias or mod_rewrite. Here's a simple example that you can use in your .htaccess file:
# mod_alias
RedirectMatch 301 ^/page/(.*) /blog/$1

# mod_rewrite
RewriteEngine on
RewriteRule ^page/(.*) /blog/$1 [L,R=301]

That will redirect requests of the URL path that starts with /page/ to /blog/. So /page/foo/bar.html would be redirected to /blog/foo/bar.html. Also note the 301 for the proper permanent redirect status code.

A: Don't know if it might be easier, but Redirection is a WP plugin that handles 301s and logs them.

A: pop a redirect in your htaccess for the site.


text: Q: ValidateAntiForgeryToken Equivalent for ASMX Web Method We have an MVC web application that has multiple web technologies including a portion with numerous extJs Post requests that call into an asmx web service. The web service methods are decorated with the [WebMethod] attribute. In MVC we are able to use the [ValidateAntiForgeryToken] attribute and append the csrf token the client side .ajax post. Is there a similar attribute that we could append to the Web Service(asmx) methods to get HP Fortify to stop complaining?


text:
Q: Getting windows caption from process ID I have a process ID, what I want to do is return the class.  If it is the desired class then return the caption, how do I do that?
C Visual Studio 2008, XP SP3

A: Use EnumWindows with GetWindowThreadProcessID to find the HWND with the matching process ID that you're looking for.
Once you have the HWND you can use GetClassName to get the class name.
Once you have the HWND with the class you want you can use either:

*

*SendMessage to send a WM_GETTEXT.

*Or GetWindowText
Read Raymond Chen's post here on the differences.


text:
Q: The equivalence principle and the existence first quantization? So imagine we are doing Einstein's famous thought experiment where we are locked in an elevator so narrow we are unable to detect tidal forces. The equivalence principle suggests that we should be unable to distinguish if we are accelerating due to gravity or a potential.
Let us assume it is a potential then I would expect the notion of first quantization to make sense for say system $X$. But we could also be instead near the surface of a black hole and travelling with non-relativistic velocities.
Does the equivalence principle suggest the notion of first quantization should make sense here for $X$? Because if it didn't I have a method of violating the equivalence principle since I can locally distinguish if gravity is causing the acceleration or not?
I've never seen this argument in the literature but it seems correct to me. Can someone shed some light on its validity?


text:
Q: pull specific data using scrapy in python (jupyter notebook)? I am trying to run a spider using jupyter notebook to grab specific data - in this case, the result should grab "21 Servings" from the drop-down in the link.
I have the following code:
import scrapy
from scrapy.crawler import CrawlerProcess

class DCspider( scrapy.Spider ):
    name = "dcspider"

    def start_requests( self ):
        urls = [ 'https://www.bodybuilding.com/store/alpha-lion/superhuman-pre-workout.html' ]
        for url in urls:
                yield scrapy.Request( url = url, callback = self.parse )
    def parse( self, response ):
        links = response.css('#skugroup-select > div > div.bb-dropdown > div.bb-dropdown__label.bb-dropdown__label--custom > bb-dropdown-label > div:nth-child(2) > div.sku-chooser__label-value').extract()
        filepath = '/path/as.csv'
        with open( '/path/as.csv', 'w' ) as f:
            f.writelines( [link + '/n' for link in links] )

process = CrawlerProcess()
process.crawl(DCspider)
process.start()

It runs fine but it doesn't grab anything so I am not sure if the mistake comes from the selector path or I am doing something else wrong? (When I tried any path had the same 0 outcome)
Here is part of the message after running the spider.
2019-12-31 13:03:10 [scrapy.middleware] INFO: Enabled item pipelines:
[]
2019-12-31 13:03:10 [scrapy.core.engine] INFO: Spider opened
2019-12-31 13:03:10 [scrapy.extensions.logstats] INFO: Crawled 0 pages (at 0 pages/min), scraped 0 items (at 0 items/min)
2019-12-31 13:03:10 [scrapy.extensions.telnet] INFO: Telnet console listening on 127.0.0.1:6023
2019-12-31 13:03:11 [scrapy.core.engine] DEBUG: Crawled (200) <GET https://www.bodybuilding.com/store/alpha-lion/superhuman-pre-workout.html> (referer: None)
2019-12-31 13:03:11 [scrapy.core.engine] INFO: Closing spider (finished)

I hope anyone can find the issue.

A: There is a problem with your selector:
it should be:
links = response.css('div.bb-dropdown__label.bb-dropdown__label--custom > bb-dropdown-label > div > div.sku-chooser__label-value').extract()

because #skugroup-select does not contain desired thing.
With this selector I get:

21 Servings
/n
Hulk Juice
/n%

in the file. and if you change '/n' to '\n' you will get what you are looking for:

21 Servings

Hulk Juice

I recommend printing links, and advancing the selector step by step for debugging.


text:
Q: Force apps to be opened everytime in a new desktop Is it possible to force an app that is being opened to be actually opened every time in a different desktop, so that the current desktop is not polluted with layered or stacked windows?

A: You can set any app to launch in a specific Space.
It will open in the same one every time after that.
To get it there the first time

*

*Switch to that Space then launch it,

or if it's already running

*

*Right click it in the Dock > Options.
Set to 'All Desktops'.
Switch to your preferred Space - it will move with you.

Right click it in the Dock > Options. Set the Option to 'This Desktop'.

This method, of course, is not an automatic process & requires setting up by hand. One advantage is that you quickly learn which Space belongs to which app & can then use shortcut keys -  Ctrl ⌃   [number]  by default.
Setting System Prefs > Mission Control to disable 'Automatically rearrange Spaces based on most recent use' will make the assigned Space numbers stick.

This method will only work correctly if you don't manually move any app window to a different Space. Spaces cannot correctly handle apps split over more than one Space.

A: It should remember your choice if you change it to fullscreen before quitting. Another option is to use the Single Application Mode:
defaults write com.apple.dock single-app -bool true
killall Dock

Which may not be exactly what you want. I just tried on macOS Sierra and it's a little clunky- but still works.


text:
Q: How to difine variables as to avoid "Property must be initialized or be abstract" error in Kotlin I use Kotlin on Android Studio.
If you code as below, the "Property must be initialized or be abstract" error occurred. In the other hand, you cannot write public val ButtonA = binding.ButtonA inside onCreate method. In this case, as  Learn the Kotlin programming language says, is it the only way to rewrite the comment place as val ButtonA:String? = null and write ButtonA = binding.ButtonA in the onCreate method?
I would not like to write as val ButtonA = binding.ButtonA in other method such as onClickedButtonA, so I asked. If you have other solution, I'd like to know.
class MainActivity : AppCompatActivity() {
    private lateinit var binding: ActivityMainBinding
    private val ButtonA:Button // THE ERROR OCCURED IF YOU CODE LIKE THIS.

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = ActivityMainBinding.inflate(layoutInflater)
        setContentView(binding.root)

        ButtonA = binding.ButtonA
    }

    fun onClickedButtonA(view:View){
        ButtonA.text = "Hoge"
    }
}

Thank you for your help.


text:
Q: How do I use "tied" against a subroutine? I seem to have a small issue with my script where I need to call "tied" against a sub routine that is earlier in the the script so that I can access the functions that are related to the object that the hash is tied to. The problem is when I go to run the script it return the error "Can't call method "SetWriteMode" on unblessed reference at cbc_encrypt_test.pl line 30." At first I had no idea what it was talking about, I think the problem is due to me using a reference to point back at the subroutine which return the hash reference in the first place. Because as far I understand "config_file = \%cfg" in this case. After looking at perldoc about perlref's I am still lost. I read over the document pretty well and did not see anything about referencing subroutines in the way I need to.
Here the entire script so far.
#!/usr/bin/perl

use strict;

use warnings;

use Term::ANSIColor;

use Config::IniFiles;

use Crypt::CBC;

start_script();

sub start_script {

    system ("clear");

    encrypt_password();

} # end start_script

sub config_file {

    my $cfg_file = 'settings.ini';

    my %cfg;

    tie %cfg, 'Config::IniFiles', ( -file => "$cfg_file" );

    return \%cfg;

} # end config_file

sub encrypt_password {
    my $password = config_file()->{ESX}{password};
    my $cipher = Crypt::CBC->new( -key => 'EF1FAD9B87F8365B242669E624FEB36CDBCCFEE0096CC45DDDCF6F5995E83F61',
                    -cipher => 'Rijndael'
                    );
    my $encrypted_password = $cipher->encrypt_hex("$password");
    chomp $encrypted_password;
    config_file()->{ESX}{password} = $encrypted_password;
    tied config_file()->SetWriteMode(0666);
    tied config_file()->RewriteConfig();
    return $encrypted_password;
} # end encrypt_password

A: tied needs to be used on a tied variable.  If you have a reference to such a variable, you can do this:
tied( %{ config_file() } )

but in your code as it stands, each call to config_file will create a new tied hash, and methods you had called on the previous hash's tied object will have done no good, so you need to ensure that config_file() is only called once (or have it internally memoize its result).

A: Looks like a precedence issue. Running the construct through B::Deparse shows the problem:
$ perl -MO=Deparse,-p -e 'tied config_file()->method()'
tied(config_file()->method);
-e syntax OK

So Perl first tries to call the method on the reference returned by config_file(), and fails because that reference is not a blessed object (like tied would return).
Instead try:
tied(%{config_file()})->SetWriteMode(0666);
tied(%{config_file()})->RewriteConfig();

or better yet:
my $cfg = tied %{config_file()};
$cfg->SetWriteMode(0666);
$cfg->RewriteConfig();

or
for (tied %{config_file()}) {
    $_->SetWriteMode(0666);
    $_->RewriteConfig();
}

Also, depending on how Config::IniFiles is written, you may run into problems where each call to config_file() returns a new object, so the aggregate calls you make don't apply to each other properly.  You should cache the object as shown in my answer to your previous question.
Edit:  I didn't catch the missing dereference that ysth pointed out which would have been the second problem.  Fixed above.


text:
Q: Spring Security form login is not taking to custom user details service when I add a pattern to  tag I am facing problem while logging in the user using spring security. I'm using spring security 3.1. I want to use a separate authentication manager for the users accessing pattern "/brand/**". so I specified pattern and authentication-manager-ref in "http" tag. I wrote a custom user details service.
Below is my spring-security.xml configuration. If I remove pattern="/brand/**" login form submission is taking to my custom user details service. But when I keep pattern="/brand/**" in "http" tag, it's not working.

   <http auto-config="true" pattern="/brand/**" use-expressions="true" authentication-manager-ref="brandAuthenticationManager">
    <intercept-url pattern="/brandLogin" access="permitAll" />
    <intercept-url pattern="/brand/activity/**" access="hasRole('BRAND_USER')" />
    <form-login login-page="/brandLogin" authentication-failure-url="/brand/login/failure"
        default-target-url="/" />

    <access-denied-handler error-page="/brand/denied" />

    <logout invalidate-session="true" logout-success-url="/brand/logout/success"
        logout-url="/brand/logout" />
</http>

   <authentication-manager alias="brandAuthenticationManager">
    <authentication-provider user-service-ref="customBrandUserDetailsService">
        <password-encoder ref="passEncoder">
            <salt-source user-property="salt" />
        </password-encoder>

    </authentication-provider>
</authentication-manager>

<beans:bean id="customBrandUserDetailsService" class="com.myproj.service.CustomBrandUserDetailsService"></beans:bean>

Any ideas on why is it happening like this? Please help ...


text:
Q: Error 500: Filter [Spring OpenEntityManagerInViewFilter]: could not be loaded I am trying to deploy a Spring application on WAS 6.0 (JDK 1.4.2). Day back I was getting tons of (Unsupported major.minor version 49.0) errors. I replaced most of the jar files and now I am left with only one error on:
org/springframework/orm/jpa/support/OpenEntityManagerInViewFilter (Unsupported major.minor version 49.0)
what jar file do I need to replace for this? Also when I am running my URL in the browser I am getting the error:
Error 500: Filter [Spring OpenEntityManagerInViewFilter]: could not be loaded
Can you please guide me ,where exactly I am doing wrong. Attached is my Web.xml.
Your help is highly appreciated.
enter code here

http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
    analytics
    Roo generated analytics application
<context-param>
    <param-name>webAppRootKey</param-name>
    <param-value>analytics.root</param-value>
</context-param>

<context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>classpath:applicationContext.xml</param-value>
</context-param>

<context-param>

log4jConfigLocation
classpath:log4j.properties

org.springframework.web.util.Log4jConfigListener

        org.springframework.web.context.ContextLoaderListener

<servlet>
    <servlet-name>analytics</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <load-on-startup>2</load-on-startup>
</servlet>

<!-- Serves static resource content from .jar files such as spring-js.jar -->
<servlet>
    <servlet-name>Resource Servlet</servlet-name>
    <servlet-class>org.springframework.js.resource.ResourceServlet</servlet-class>
</servlet>

<servlet-mapping>
    <servlet-name>analytics</servlet-name>
    <url-pattern>/*.html</url-pattern>
</servlet-mapping>

<!-- Map all /resources requests to the Resource Servlet for handling -->
<servlet-mapping>
    <servlet-name>Resource Servlet</servlet-name>
    <url-pattern>/resources/*</url-pattern>
</servlet-mapping>

<filter>
    <filter-name>httpMethodFilter</filter-name>
    <filter-class>org.springframework.web.filter.HiddenHttpMethodFilter</filter-class>
</filter>

<filter-mapping>
    <filter-name>httpMethodFilter</filter-name>
    <servlet-name>analytics</servlet-name>
</filter-mapping>

<filter>
    <filter-name>Spring OpenEntityManagerInViewFilter</filter-name>
    <filter-class>org.springframework.orm.jpa.support.OpenEntityManagerInViewFilter</filter-class>
</filter>

        Spring OpenEntityManagerInViewFilter
        /*

<session-config>
    <session-timeout>10</session-timeout>
</session-config>

<welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
</welcome-file-list>

<error-page>
    <exception-type>java.lang.Exception</exception-type>
    <location>/WEB-INF/jsp/uncaughtException.jsp</location>
</error-page>

A: The "Unsupported major.minor version" errors are caused by your using JAR files compiled for a higher version of java than you're running.
I think class file version 49.0 is Java 5, and you're running 1.4. That means you must be using a library that's Java 5 only, and the only version of Spring thats java 5 only is Spring 3.0. If that's the case, then downgrade your Spring to 2.5.6.


text:
Q: Create bins on groupby in pandas my data frame got a column department and rank
name  dept  Rank
"A"  "ENG"  1
"A"  "MGMT"  1
"B"  "ENG"  2
"C"  "MGMT"  2
"D"  "MGMT"  3
"E"  "ENG"  3

I want to create bins in each dept.
name  dept  Rank  Comment
"A"  "ENG"  1  Good
"A"  "MGMT"  1  Good
"B"  "ENG"  2  Avg
"C"  "MGMT"  2  Avg
"D"  "MGMT"  3  Poor
"E"  "ENG"  3  Poor

I'm able to do this by below code
 df['Comment'] = pd.qcut(df[df['dept'] == "ENG"]['Rank'], q=[0.0, .25, .5, 1.0], labels=['Good', 'Avg', 'Poor'])
 df['Comment'] = pd.qcut(df[df['dept'] == "MGMT"]['Rank'], q=[0.0, .25, .5, 1.0], labels=['Good', 'Avg', 'Poor'])

I'm very sure, there must be some way using groupby, but can't figure it out.

A: wouldn't it be simpler to create a dictionary and map the values? Since you would need to do it anyways while creating the labels and mapping to the bins
d={1:'Good',
   2:'Avg',
   3:'Poor'}

df['comments']=df['Rank'].map(d)
df

    name    dept    Rank    comments
0   "A"     "ENG"     1     Good
1   "A"     "MGMT"    1     Good
2   "B"     "ENG"     2     Avg
3   "C"     "MGMT"    2     Avg
4   "D"     "MGMT"    3     Poor
5   "E"     "ENG"     3     Poor

A: You can use groupby.transform/groupby.apply:
df['Comment'] = (df
 .groupby('dept')['Rank']
 .transform(lambda g:
     pd.qcut(g,
             q=[0, 1/3, 2/3, 3/3],   # changed
             labels=['Good', 'Avg', 'Poor']))
 )

NB. quantiles are in the range [0, 1], I changed the example.
Output:
  name  dept  Rank Comment
0    A   ENG     1    Good
1    A  MGMT     1    Good
2    B   ENG     2     Avg
3    C  MGMT     2     Avg
4    D  MGMT     3    Poor
5    E   ENG     3    Poor