text:
Q: Filling Zillow Searchbox using VBA (Zillow is react-based website) I am trying to identify the element for the search box, so that I can change the value of the search box to an address.  I was able to do this with redfin and pellago, but zillow is written with react, and I am having trouble.
I have already tried just about every element in "" I can see when I inspect element, but there is no real "name" or "id" like I am used to.
Sub WebscrapeZillow()

    Dim IE As New SHDocVw.InternetExplorer
    Set IE = New SHDocVw.InternetExplorer

    IE.Visible = True
    IE.navigate "https://zillow.com./"

    Do While IE.readyState <> READYSTATE_COMPLETE

    Loop

    IE.document.getElementById("__next").Value = "hello world"

End Sub

I get a debug message every time.  I would like to enter an address in the search box.  I'm not sure I am "getting" the correct type of element or the correct item in "".  I have tried about 25 different element names, so "__next" is just the last I tried.  I have searched stackoverflow, and could not find what I thought was the answer (although I may not know exactly what I am looking for).  Thank you for any help!

A: To see which class or id to go after in your DOM you'll need to pull up zillow in a browser. In chrome and newer versions of IE, you can hit F12 and it will bring up a developer panel where you can select elements on the page and see all of their attributes.

There are 3 classes for that search box that you can use react-autosuggest__input, Input-sc-7nzn9k-0, and dIKGyt so:
IE.document.getElementsByClassName("Input-sc-7nzn9k-0")(0).Value = "hello world"

I put that (0) after value because getElementsByClassName returns an array of elements that match that class. Here we just want "The first element that has this class", so (0) which works out here as there is only one element on that page that has that particular class.


text:
Q: Custom Javascript doesn't work in Safari? I am working on a woocommerce site and I have purchased 2 plugins to give the ability to customize the item in my product page.
The plugin demo can be found here:
In this demo there are 2 plugins, one called Multistep Product Configurator (MSPC) which is the tabs at the top of the page and a second one called Fancy Product Designer (FPD) which is the product display panel underneath it.
I wanted to use these two plugins to display them one next to each other in order to avoid scrolling down the page to see the changes made with MSPC plugin.
So I have been trying to customise the css code for hours with no success.
You can see my page here:
I ended up using a custom javascript code in my theme's custom js section which basically repositions the wrapper a few seconds after the page loads.
My issue is that with the js code I achieved what I wanted in all browsers except safari!
Here is the code I used:
document.onreadystatechange = function(){
 if(document.readyState === 'complete'){
     setTimeout(function () {
         var x = document.getElementsByClassName("mspc-wrapper");
         x[0].style.float = "none";
     }, 3000);
 }

}
Any idea why it doesn't work in Safari browser?
Feel free to try fixing this with CSS but I am pretty sure it doesn't work...
Any feedback much appreciated.

A: It seems to me that your code for changing the styles is wrong:
 x[0].style.styleFloat //returns undefined

You'll be wanting to use
x[0].style.float = 'none';

If this doesn't work make sure the js is even running :)

A: Safari doesn't seem to support the state 'complete'. Try using 'loaded' instead (if it doesn't matter whether the document has been fully loaded or just loaded) since it seems to be supported by all browsers.
Reference
Just to make sure, try debugging it or throwing in a console.log to see if the if-statement ever returns true.

A: Ok guys,
Thanks a lot for taking a time to respond to this. What I had to do was to add a hook inside the content-single-product.php and then I could fix it with the CSS code.
I didn't need to add the javascript in the end.
Thanks for replying though!

redpajama_set_name: RedPajamaStackExchange


text:
Q: Mess with data inside class w/ databinding Im trying to edit some data within a class which is linked to with databinding. Here is my class:
public class Line
{
    public string Equation { get; set; }
    public int PreviousLine { get; set; }
    public int LineNumber { get; private set; }

    public Line()
    {
        this.LineNumber = (this.PreviousLine + 5);
    }
}

however the line number always returns 5, even if previous line is set to 6...
here is how I link to it within my viewmodel:
this.Lines.Add(new Line { Equation = "5*2", PreviousLine = 6 });

thanks

A: try declaring it as static.
public static int PreviousLine { get; set; }

A:  private int _previousLine;
    public int PreviousLine
    {
        get { return _previousLine; }
        set { _previousLine = value;
            Line = _previousLine + 5;
        }
    }
    public int Line { get; private set; }


text:
Q: How to FLATTEN a test statement in Pig? Using Pig .12.
I want to use a FOREACH with a block statement; the result, via GENERATE depends on some value. I know that i can use Flatten with a statement in it. I.e.:
grunt> d = foreach j2 {
       ord = order j1 by A::a1 desc;
       l = limit ord 1;
       generate flatten((IsEmpty(l)?'f':'g')); };

This works.
But what i want to do:
grunt> d = foreach j2 {
  ord = order j1 by A::a1 desc;
  l = limit ord 1;
  generate flatten((l.$0=='2') ?'f':'g'); };

2014-05-07 22:28:08,750 [main] ERROR org.apache.pig.tools.grunt.Grunt
  - ERROR 1200:   mismatched input '?' expecting RIGHT_PAREN

Why does it say this?
I tried:
grunt> d = foreach j2 {
ord = order j1 by A::a1 desc;
l = limit ord 1;
generate flatten(((l.$0=='2') ?'f':'g')); };

2014-05-07 22:40:44,895 [main] ERROR
  org.apache.pig.tools.grunt.Grunt - ERROR 1039:
       (Name: Equal Type: null Uid: null)incompatible types in Equal Operator left hand side:bag :tuple(A::a1:chararray)  right hand side:chararray

And i dont know how to resolve this.
I just want to generate my results in a test case, but first need to flatten the test condition.
Help ?
thanks,
Matt


text:
Q: How to add sign in with google to a simple android application? I am trying to implement a simple android application using android studio where users can sign in with google. I followed the guide at https://developers.google.com/identity/sign-in/android/start-integrating, although I'm not sure if I got the part of "Create an OAuth 2.0 client ID" correctly. However, I need in my application that a user can login either by entering a random email and password, or by a real google account. After following the guide, I proceeded to this one https://developers.google.com/identity/sign-in/android/sign-in. However, after creating a new login activity and adding the part
mGoogleApiClient = new GoogleApiClient.Builder(this)
        .enableAutoManage(this /* FragmentActivity */, this /* OnConnectionFailedListener */)
        .addApi(Auth.GOOGLE_SIGN_IN_API, gso)
        .build();

I have an error that says cannot resolve symbol mGoogleApiClient, and the second this in .enableAutoManage().
I tried to change mGoogleApiClient to GoogleApiClient mGoogleApiClient but the this problem persisted. Am I doing something wrong mentioned in the guide or is there something extra I should do?
I should also mention that the same problem happened when I added the code to an empty activity, not the predefined loginActivity template, with no success.
Update:
Here is my project level build.gradle
// Top-level build file where you can add configuration options common to all sub-projects/modules.

buildscript {
    repositories {
        jcenter()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:1.3.0'
        classpath 'com.google.gms:google-services:1.5.0-beta2'
        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}

allprojects {
    repositories {
        jcenter()
    }
}

task clean(type: Delete) {
    delete rootProject.buildDir
}

And my app level build.gradle
apply plugin: 'com.android.application'
apply plugin: 'com.google.gms.google-services'

android {
    compileSdkVersion 23
    buildToolsVersion "23.0.2"

    defaultConfig {
        applicationId "com.karim.tvme"
        minSdkVersion 15
        targetSdkVersion 23
        versionCode 1
        versionName "1.0"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    testCompile 'junit:junit:4.12'
    compile 'com.android.support:appcompat-v7:23.1.1'
    compile 'com.google.android.gms:play-services-auth:8.3.0'
    compile 'com.android.support:design:23.1.1'
    compile 'com.google.android.gms:play-services:8.3.0'
}

A: I found using BNK's code that I had to implement GoogleApiClient.OnConnectionFailedListener and thus the method public void onConnectionFailed(ConnectionResult connectionResult) although this was not mentioned in the guide. Also the guide didn't mention that we had to declare an attribute private GoogleApiClient mGoogleApiClient; .
Hope this helps.


text:
Q: Getting error while creating two object from one object using loop in javascript I am new to Javascript as I am trying to do something in that I am creating two object from one object.
my Parent object is
payload = { docType: 'ProduceRateAsset',
  PRODUCE: 'Banana',
  STATE: 'MH',
  COUNTRY: 'IN',
  BASE_UNIT: 'KG',
  SELECTED_UNIT: { NAME: 'LB', WEIGHT: 40 },
  RATES:
   [ { VARIETY: 'ABC',
       MinRate: { UNIT: 'LB', CURRENCY: 'INR', VALUE: 0.49 },
       MarketRate: { UNIT: 'LB', CURRENCY: 'INR', VALUE: 0.53 } },
     { VARIETY: 'XYZ',
       MinRate: { UNIT: 'LB', CURRENCY: 'INR', VALUE: 0.31 },
       MarketRate: { UNIT: 'LB', CURRENCY: 'INR', VALUE: 0.33 } } ] }

from that I am trying two object like below
   A =  {
     PRODUCE: 'Banana',
    STATE: 'MH',
    COUNTRY: 'IN',
    BASE_UNIT: 'KG',
    VARIETY: 'ABC',
    MinRate: 0.49,
    MarketRate: 0.53,
    timeStamp: 2021-01-09T15:45:20.000Z };

   B =  {
     PRODUCE: 'Banana',
    STATE: 'MH',
    COUNTRY: 'IN',
    BASE_UNIT: 'KG',
    VARIETY: 'XYZ',
    MinRate: 0.31,
    MarketRate: 0.33,
    timeStamp: 2021-01-09T15:45:20.000Z }

I tried below code which give me error as TypeError: Cannot read property 'VARIETY' of undefined
 var Data = {}
    var mylist = []
   let currentDate = new Date();
    for (let i = 0; i <3; i++) {

        Data.PRODUCE = payload.PRODUCE
        Data.STATE = payload.STATE
        Data.COUNTRY = payload.COUNTRY
        Data.BASE_UNIT = payload.BASE_UNIT

        Data.VARIETY = payload.RATES[i].VARIETY
        Data.MinRate = payload.RATES[i].MinRate.VALUE
        Data.MarketRate = payload.RATES[i].MarketRate.VALUE;
        Data.timeStamp = new Date(currentDate.toLocaleString());
        mylist.push(GRNData);

      };

A: The problem is because payload.RATE has two elements.
But you are trying to get third elements.

payload = {
  docType: 'ProduceRateAsset',
  PRODUCE: 'Banana',
  STATE: 'MH',
  COUNTRY: 'IN',
  BASE_UNIT: 'KG',
  SELECTED_UNIT: { NAME: 'LB', WEIGHT: 40 },
  RATES: [
    {
      VARIETY: 'ABC',
      MinRate: { UNIT: 'LB', CURRENCY: 'INR', VALUE: 0.49 },
      MarketRate: { UNIT: 'LB', CURRENCY: 'INR', VALUE: 0.53 },
    },
    {
      VARIETY: 'XYZ',
      MinRate: { UNIT: 'LB', CURRENCY: 'INR', VALUE: 0.31 },
      MarketRate: { UNIT: 'LB', CURRENCY: 'INR', VALUE: 0.33 },
    },
  ],
};

let currentDate = new Date();

const res = payload.RATES.map((rate) => ({
  PRODUCE: payload.PRODUCE,
  STATE: payload.STATE,
  COUNTRY: payload.COUNTRY,
  BASE_UNIT: payload.BASE_UNIT,

  VARIETY: rate.VARIETY,
  MinRate: rate.MinRate.VALUE,
  MarketRate: rate.MarketRate.VALUE,
  timeStamp: new Date(currentDate.toLocaleString()),
}));

console.log(res)

A: If the data you're using is the data you provided, the answer is simple: you only have 2 rates, but you're trying to perform this operation on 3 rates. You loop condition means that the loop will be executed 3 times, looking for 3 rates. You can fix this (and make it more modular) by changing your loop condition to
for (let i = 0; i < payload.RATES.length; i++) {...}


text:
Q: Can't get HTML select form to display selected home_state that the user saved to a database previously When an user select any state and save it then on reload, it only returns first state which is Alabama. I checked the database via rails console to confirm that it saved correctly and it did but the HTML select isn't just getting the correct field.  Other fields are receiving correct values.
Here's _contact_info.html.erb

 <%= f.select :home_state, options_for_select(us_states), id: "home_state",
  prompt: "State", class: "form-control" %>

Application_controller.rb

      <%= f.select :home_state, options_for_select(us_states), id: "home_state",
      prompt: "State", class: "form-control" %>
    </div

us_states.helper
module UsStatesHelper
    def us_states
        [
          ['Alabama', 'AL'],
          ['Alaska', 'AK'],
          ['Arizona', 'AZ'],
          ['Arkansas', 'AR'],
          ['California', 'CA'],
          ['Colorado', 'CO'],
          ['Connecticut', 'CT'],
          ['Delaware', 'DE'],
          ['District of Columbia', 'DC'],
          ['Florida', 'FL'],
          ['Georgia', 'GA'],
          ['Hawaii', 'HI'],
          ['Idaho', 'ID'],
          ['Illinois', 'IL'],
          ['Indiana', 'IN'],
          ['Iowa', 'IA'],
          ['Kansas', 'KS'],
          ['Kentucky', 'KY'],
          ['Louisiana', 'LA'],
          ['Maine', 'ME'],
          ['Maryland', 'MD'],
          ['Massachusetts', 'MA'],
          ['Michigan', 'MI'],
          ['Minnesota', 'MN'],
          ['Mississippi', 'MS'],
          ['Missouri', 'MO'],
          ['Montana', 'MT'],
          ['Nebraska', 'NE'],
          ['Nevada', 'NV'],
          ['New Hampshire', 'NH'],
          ['New Jersey', 'NJ'],
          ['New Mexico', 'NM'],
          ['New York', 'NY'],
          ['North Carolina', 'NC'],
          ['North Dakota', 'ND'],
          ['Ohio', 'OH'],
          ['Oklahoma', 'OK'],
          ['Oregon', 'OR'],
          ['Pennsylvania', 'PA'],
          ['Puerto Rico', 'PR'],
          ['Rhode Island', 'RI'],
          ['South Carolina', 'SC'],
          ['South Dakota', 'SD'],
      ['Tennessee', 'TN'],
      ['Texas', 'TX'],
      ['Utah', 'UT'],
      ['Vermont', 'VT'],
      ['Virginia', 'VA'],
      ['Washington', 'WA'],
      ['West Virginia', 'WV'],
      ['Wisconsin', 'WI'],
      ['Wyoming', 'WY']
    ]   end

end

A: You need to pass in the value of the element you want to start selected. Something like

 <%= f.select :home_state, options_for_select(us_states, selected_state.abbreviation), id: "home_state",
  prompt: "State", class: "form-control" %>

see https://guides.rubyonrails.org/form_helpers.html#the-select-and-option-tags for more details


text:
Q: Using dictionary keys as coordinates when writing to csv I have a dictionary which has cell coordinates as the keys and the desired cell content as the value, eg:
dict1 = {'AN32': '2', 'AZ17': '47', ect...}

The cell range is D4: AZ52
I want to write this into a csv file.
The problem I am encountering when it comes to design is that the dictionary isn't necessarily ordered alphabetically or numberically as can be seen in the example above.
I know how to write to a .csv file with
with open('example.csv', 'w') as f:

    for i in dict1:

        f.write(str(dict1[i]) + ',')

this would write the values out in order, which would mean they wouldn't be in the correct cell, I need them to be in the cell which is specified by their key.

A: This code uses a list comprehension to build each row.
First we create a list of the column labels, using the uppercase string from the string module, and we build a list of all the column labels using a simple list comprehension.
Then we use a slightly more complicated list comprehension that makes a key by combining each column label with the current row number (converted to a string). That key is passed to dict1's .get() method to get the value associated with that key. We use an empty string '' as the 2nd arg to .get() so that if a key doesn't exist in the dict we get an empty string.
Then we use the .join() method to join all those strings, separated by commas.
from string import uppercase

#Make a list of the column letters
cols = list(uppercase[3:]) + ['A' + c for c in uppercase]
#print(cols)

with open('example.csv', 'w') as f:
    for r in range(4, 53):
        row = ','.join([dict1.get(c + str(r), '') for c in cols])
        f.write(row + '\n')

If the values in dict1 are actually int rather than strings, then you need to convert them to strings before attempting to join them. Change the list comprehension to
row = ','.join([str(dict1.get(c + str(r), '')) for c in cols])

That will cope even if some values are strings and some are numbers.


text:
Q: Uncaught TypeError: Cannot read properties of undefined (reading '$$') `I set up TypeScript in Svelte. After building the project, I get this error:
Uncaught TypeError: Cannot read properties of undefined (reading '$$')
There is a Panel component.

button

I connect it like this:

<Panel/>

import App from './App.svelte';

const app = new App({
    target: document.body,
});

export default app;

After building, I get this error:
Uncaught TypeError: Cannot read properties of undefined (reading '$$')


text:
Q: How To Bind Google Visualization Data source Date values with Google Charts DateRangeFilter I use REST services to fetch data into google charts.To create a chart supported json i used google visualization data source API to generate valid json obj.But the problem was that i can not create DateRangeFilter on my front view.Below is my sample code snippet.
REST Service Code
final DataTable data = new DataTable();
ArrayList<ColumnDescription> cl = new ArrayList<ColumnDescription>();
cl.add(new ColumnDescription("Time Stamp", ValueType.DATETIME, "Time Stamp"));

timeStamp = tr.getTimestamp().toString().trim();
dateTime = timeStamp.substring(0,timeStamp.indexOf(".")).replaceAll("-", "/");

for each(...){
data.addRowFromValues(dateTime );
}

Js Code
var dateSlider = new google.visualization.ControlWrapper({
          'controlType': 'DateRangeFilter',
          'containerId': 'control_dateSlider',
          'options': {
            'filterColumnLabel': 'Time Stamp',
               'ui': {'labelStacking': 'vertical', 'label': 'Timeline :'}
          }
        });

Sample Date Time value from DB
12/5/2014 10:48:25 AM

Seems like the problem was on  data.addRowFromValues(dateTime );.Please can someone tell me that how can i pass valid date time value to google chart DateRangeFilter


text:
Q: Accessing variables using a for loop in HTML (python flask) class fruit(flaskform):
fruit1 = "apple"
fruit2 = "orange"
fruit3 = "grapes"

I am trying to access the variables in a for loop in my html page.
{% for index in range(3) %}
    {{"fruit" + index}}
{%endfor%}

Is this possible? I would like to avoid writing 100 lines of code to access the variables if I have 100 fruits. I am new to flask and html. My question could be unclear and feel free to ask me if more info is needed.

A: You can store your fruits in a list like this:
fruits = ['apple', 'orange', 'grapes']

Then, you can use a for loop in Jinja2 to iterate through your list and display each individual item.
{% for fruit in fruits %}
    {{ fruit }}
{% endfor %}


text:
Q: Are elements returned by Linq-to-Entities query streamed from the DB one at the time or are they retrieved all at once? Are elements returned by Linq-to-Entities query streamed from the database one at the time ( as they are requested ) or are they retrieved all at once:
    SampleContext context = new SampleContext(); // SampleContext derives from ObjectContext
    var search = context.Contacts;

    foreach (var contact in search)
    {
       Console.WriteLine(contact.ContactID); // is each Contact retrieved from the DB
                                             // only when foreach requests it?
    }

thank you in advance

A: They are retrieved using one query. Your example does simple select for all rows of Contacts table.
Streaming would be highly ineffective.
But this is only for query itself. There might be lazy loading involved for navigation entities stored in properties or collection of entities. Those are loaded on-demand as you access them. This might result in in-famous N+1 problem.


text:
Q: How to rotate a LaTeX ylabel in gnuplot? I would like the ylabel on a gnuplot to be the same as $\omega_2(R_{3,n})$ appears in LaTeX.  But if I use the following, it overlaps with the plot itself.
set ylabel "\\omega_2(R_{3,n})"

One way to get around this problem is to rotate the ylabel by 90 degrees.  How can that be done?

A: You could try the following (source):
gnuplot> set lmargin 20
gnuplot> set label 1 '\omega_2(R_{3,n})' at graph -0.2, graph 0.5

Somewhat unrelated here, but don't you need to use write $\omega_2(R_{3,n})$ when trying to produce LaTeX-output with gnuplot?


text:
Q: Authentication authorization ASP/NET MVC 3 using membership I am looking for a good tutorial for securing an MVC 3 application the right way.
Please help.

A: Membership is not a new thing for MVC It is same like in asp.net. I can recommend this old and good tutorial Examining ASP.NET's Membership, Roles, and Profile and this book Professional ASP.NET 3.5 Security, Membership, and Role Management with C# and VB.


text:
Q: Angular 9 Ivy and Wishtack ReactiveComponentLoader :4200/vendor.js:39633 ERROR Error: Component '<app-shared-hero-image>' not found.
    at componentNotFoundError (:4200/vendor.js:113712)
    at ReactiveComponentLoader._tryGetComponentType (:4200/vendor.js:113803)
    at ReactiveComponentLoader.<anonymous> (:4200/vendor.js:113769)
    at Generator.next (<anonymous>)
    at fulfilled (:4200/vendor.js:280350)
    at ZoneDelegate.invoke (:4200/polyfills.js:377)
    at Object.onInvoke (:4200/vendor.js:71213)
    at ZoneDelegate.invoke (:4200/polyfills.js:376)
    at Zone.run (:4200/polyfills.js:136)
    at :4200/polyfills.js:870

I am having trouble to render my components with wishtack reactive component loader, it says that doesn't found my component but i really exist.


text:
Q: InnoDB locking a different index while using a where clause on a foreign key I'm trying these queries in two different transactions:
START TRANSACTION;
DELETE FROM `StopHistory` WHERE `deviceId` = 34;

START TRANSACTION;
SELECT id FROM `StopHistory` WHERE deviceId = 33 AND endAt > '2018-06-18 17:01:32.473';

the second query waits, since the first query is creating a lock on the endAt field.
MySQL [(none)]> select * from INFORMATION_SCHEMA.INNODB_LOCKS;
+-----------------------+-------------+-----------+-----------+--------------------------+------------+------------+-----------+----------+--------------------------+
| lock_id               | lock_trx_id | lock_mode | lock_type | lock_table               | lock_index | lock_space | lock_page | lock_rec | lock_data                |
+-----------------------+-------------+-----------+-----------+--------------------------+------------+------------+-----------+----------+--------------------------+
| 104222007:699:1035:16 | 104222007   | S         | RECORD    | `db`.`StopHistory`       | endAt      |        641 |      1035 |       16 | 0x99A026D21307DA, 115347 |
| 104221958:699:1035:16 | 104221958   | X         | RECORD    | `db`.`StopHistory`       | endAt      |        641 |      1035 |       16 | 0x99A026D21307DA, 115347 |
+-----------------------+-------------+-----------+-----------+--------------------------+------------+------------+-----------+----------+--------------------------+

    ---TRANSACTION 104231466, ACTIVE 3 sec fetching rows
mysql tables in use 1, locked 1
LOCK WAIT 4 lock struct(s), heap size 376, 3 row lock(s)
MySQL thread id 59556, OS thread handle 0x2b1375f03700, query id 20584248 172.31.2.181 db Sending data
SELECT id FROM `StopHistory` WHERE deviceId = 33 AND endAt > '2018-06-18 17:01:32.473'
------- TRX HAS BEEN WAITING 3 SEC FOR THIS LOCK TO BE GRANTED:
RECORD LOCKS space id 641 page no 1035 n bits 16 index `endAt` of table `db`.`StopHistory` trx id 104231466 lock mode S waiting
Record lock, heap no 16 PHYSICAL RECORD: n_fields 2; compact format; info bits 32
 0: len=7; bufptr=0x2b134db1c16c; hex= 99a026d21307da; asc   &    ;;
 1: len=4; bufptr=0x2b134db1c173; hex= 8001c293; asc     ;;

------------------
---TRANSACTION 104231429, ACTIVE 11 sec
44 lock struct(s), heap size 376, 3103 row lock(s), undo log entries 1549
MySQL thread id 59555, OS thread handle 0x2b1375f03700, query id 20584210 172.31.2.181 db delayed send ok done

the StopHistory table has a foreign key on deviceId and an index on endAt
CREATE TABLE `StopHistory` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `endAt` datetime(3) DEFAULT NULL,
  `deviceId` int(11) DEFAULT NULL,
  `beginAt` datetime(3) DEFAULT NULL,
  PRIMARY KEY (`id`),
  KEY `fk_StopHystory_2_idx` (`deviceId`),
  KEY `beginAt` (`beginAt`),
  KEY `endAt` (`endAt`),
  KEY `device_beginAt` (`deviceId`,`beginAt`),
  CONSTRAINT `fk_StopHystory_2` FOREIGN KEY (`deviceId`) REFERENCES `Devices` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB AUTO_INCREMENT=115351 DEFAULT CHARSET=utf8;

output of the explain:
MySQL [db]> explain DELETE FROM `StopHistory` WHERE `deviceId` = 34 \G
*************************** 1. row ***************************
           id: 1
  select_type: SIMPLE
        table: StopHistory
         type: range
possible_keys: PRIMARY,fk_StopHystory_1_idx,fk_StopHystory_2_idx,fk_StopHistory_1_idx,beginAt,endAt,device_beginAt
          key: fk_StopHystory_2_idx
      key_len: 5
          ref: NULL
         rows: 1548
        Extra: Using where

Why the endAt field is locked?

A: To help with that SELECT, and possibly cut down the chance of lock, change
KEY `fk_StopHystory_2_idx` (`deviceId`),

To
KEY(deviceId, endAt)

Also, note that 34 comes right after 33.  So deleting all the 34s is touching the "gap" after the 33s.  This may be an unavoidable cause for lock contention.
Also note that the DELETE needs to remove items from 3 BTrees -- the main one, plus both indexes starting with deviceId.  Presumably the latter two will go through the "Change Buffer" and not be too critical.


text:
Q: Changing paragraphs text based on their id

for(var i = 0; i<3; i++) {

var msg = "hello" + i;
$('ul li p').text(msg);
}

I want to create a variable that will shift its value by the id of the paragraph. Meaning, that first p will say hello1, second hello2 etc. I know it`s possible in a click function by doing $(this).attr('id'), but is there someway do do it outside that function, since i need it to run on page load

A: Use this code:

$(document).ready(function(){
  $('ul li p').each(function(index) {
     var msg = "hello" + $(this).attr('id');
     $(this).text(msg);
  });
});

A: try this
$(function(){
for(var i = 0; i<3; i++) {

var msg = "hello" + i;
$('ul li p').text(msg);
}
})


text:
Q: Cannot group fields in Pivot Tables Software: MS Excel 2016
Excel File: GitHub Repository

I am unable to group fields in pivot table of Excel file.
Graffiti table is linked with Calendar table via Date (in PowerPivot > Data Model), so why is there difficulty in grouping the following.
However if I unlink the tables (which is what I DO NOT want to do), then it works

A: In his online course, Building BI with Pivot Tables, Ken Puls, Microsoft Excel MVP explains that if you build your pivot table from the data model, grouping won't work. He also explains that the only exception to this is that for Excel 2016 they fixed the ability to group dates. He says other grouping still doesn't work in Excel 2016. If you make your Pivot Table from your "Table1" in your "DSNY_Graffiti_Information" tab in your Workbook instead of from the Power Pivot data model, you can group:

For the Pivot Table above, I just clicked in "Table1" in your "DSNY_Graffiti_Information" tab, then used Insert -> Pivot Table, and I used your "RESOLUTION_ACTION" column for both the "Rows" and "Values". It defaulted the values to count (i.e., "Count of RESOLUTION_ACTION").

Then I selected all of the "10-..." entries in the Pivot Table, right-clicked, and clicked "Group".
I hope this helps some.


text:
Q: Conditional generic Where equals clause in Entity Framework I'm trying to create a where clause that I can pass in a func and a property then compare them. I have a long list of different properties I need to compare so I want an extension method to wrap it.
Here's how I want to use it:
string transactionNumber = "12345";
Queryable<TranCard> transactions = _context.TranCard
    .WhereEquals(t => t.TransactionNumber, transactionNumber)
    .ToList();

Here's the extension method I currently have that's causing me problems:
public static IQueryable<T> WhereEquals<T>(this IQueryable<T> source, Func<T, string> expression, string queryParam)
    {
        return source.Where(t => string.IsNullOrWhiteSpace(queryParam)
                                 || expression != null
                                 && string.Equals(queryParam.Trim(), expression.Invoke(t).Trim(), StringComparison.OrdinalIgnoreCase));
    }

When I try to run this it's throwing the following runtime error message:
"Incorrect number of arguments supplied for call to method 'Boolean Equals(System.String, System.String, System.StringComparison)'"

A: I was able to get it to work by separating out the calls. This also made it more easy to read!
public static IQueryable<T> WhereEquals<T>(this IQueryable<T> source, Func<T, string> expression, string queryParam)
    {
        if (string.IsNullOrWhiteSpace(queryParam))
        {
            return source;
        }

        return source.Where(x => expression(x).Trim().ToLower() == queryParam.Trim().ToLower());
    }

Thanks to everyone for your help!


text:
Q: Submit a Post to symfony FosRestBundle As I try to use a REST API, I setted up a simple controller which should only return my POST Vars as a xml response.
Unfortunately, it won't return it. I guess I have some probs by getting the data from the request.
This is my Action inside the Controller. GET works fine, but POST won't do.
 public function postAuthAction (Request $request)
 {
   #$request      = $this->get('request');
   $username = $request->request->get('Username');
   $password = $request->request->get('Password');
   $data=array("user"=>$username,"password"=>$password);
   return $data;
 }

It only returns me:
 <result>
   <entry>
     <entry xsi:nil="true"/>
     <entry xsi:nil="true"/>
   </entry>
 </result>

Which isn't that bad for the reason that it returns anything at all ;)
I extpected something like
 <result>
    <user>POST Username</user>
    <password>POST Password</password>
 </result>

What am I doing wrong? IO don't get it.
EDIT: my POST
 <?xml version="1.0" encoding="UTF-8" standalone="yes"?>
  <Login>
       <Username>abc</Username>
       <Password>pass12</Password>
 </Login>


text:
Q: After installing latest version of MySQL then I get error : #1366 - Incorrect integer value: '' for column 'group_id' at row 1 After installing the latest version of MySQL I get the following error when inserting data into the database. My application was running old version of mysql but after update new version all application was breakdown.
mysql query like this :
INSERT INTO tablename SET group_id=''   etc..............

Error :
1366 - Incorrect integer value: '' for column 'name' at row 1

also I have try to set --
sql-mode="STRICT_TRANS_TABLES,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION"

but not resolved problems
So Please help!

A: Find STRICT_ALL_TABLES in sql mode and try removing it in my.ini configuration file.


text:
Q: In PySpark, how can I populate a new column based on a lookup in another DataFrame? New to Spark and PySpark, I am trying to add a field / column in a DataFrame by looking up information in another DataFrame.  I have spent the past several hours trying to read up on RDDs, DataFrames, DataSets, maps, joins, etc. but the concepts are all still new to me and I am still having a hard time making heads or tails of it all.
So for example, given the following input DataFrame with IDs and roles:
+----+-------------+
| ID | Role        |
+----+-------------+
|  1 | Author      |
|  1 | Editor      |
|  2 | Author      |
|  2 | Publisher   |
|  3 | Editor      |
|  3 | Assistant   |
+----+-------------+

And another input DataFrame with a unique mapping of IDs and names:
+----+-------------+
| ID | Name        |
+----+-------------+
|  1 | John Smith  |
|  2 | John Doe    |
|  3 | Bob Jim Bob |
+----+-------------+

I need to somehow merge this data into a single output DataFrame with the Name column added like so:
+----+-------------+-------------+
| ID | Name        | Role        |
+----+-------------+-------------+
|  1 | John Smith  | Author      |
|  1 | John Smith  | Editor      |
|  2 | John Doe    | Author      |
|  2 | John Doe    | Publisher   |
|  3 | Bob Jim Bob | Editor      |
|  3 | Bob Jim Bob | Assistant   |
+----+-------------+-------------+

The actual volume of the data is on the order of 200k+ rows for both input tables.
My initial thoughts were to add a new Name column to the ID + Role table, then iterate through each row and manually look up the Name from the ID + Name table but that is really slow and I am sure fails to capitalize on the strengths of Spark.
Again, still really new to all this so please forgive me if this is a really obvious question.
Thank you!

A: You can merge both dataframeS as below in pySpark:
>>> df1.show()
+---+---------+
| ID|     Role|
+---+---------+
|  1|   Author|
|  1|   Editor|
|  2|   Author|
|  2|Publisher|
|  3|   Editor|
|  3|Assistant|
+---+---------+

>>> df2.show()
+---+-----------+
| ID|       Name|
+---+-----------+
|  1| John Smith|
|  2|   John Doe|
|  3|Bob Jim Bob|
+---+-----------+

>>> df3 = df2.join(df1,"ID")
>>> df3.show()
+---+-----------+---------+
| ID|       Name|     Role|
+---+-----------+---------+
|  1| John Smith|   Author|
|  1| John Smith|   Editor|
|  2|   John Doe|   Author|
|  2|   John Doe|Publisher|
|  3|Bob Jim Bob|   Editor|
|  3|Bob Jim Bob|Assistant|
+---+-----------+---------+

Note: I am assuming "ID" as foreign Key, Please let comment out in case
  any concerns.


text:
Q: Is it safe to use split().body() when the exchange may or may not contain an iterable in the body? So, say we have the follwing (simplified) route setup:
RouteDefination routeDef = from("seda:somewhereIrrelevant")
                               .process(someProcessor1); // normal message.

if ( typeOfRoute.equals("requiresList"){
    routeDef.process(addsAListToBody); // creates list out of normal message.
}

routeDef.split().body()
        .process(oneMessageAtATime) // this is regardless of whether it was originally a part of a list.
        .end();

The thing is, I can see that this works with or without "addsAListToBody" Processor. It we pass a normal object of type Foo it passes on the exchange to "oneMessageAtATime" Processor. If the route contains "addsAListToBody" Processor that returns a List<Foo> then it splits the list into Foo elements that get processed one by one.
The thing is, this seems like a very simple thing that solves what I want to do but for some reason it feels like it's wrong.
Is this "conditional" useage of splitter correct? Or am I doing something wrong here?

A: This is totally OK, nothing wrong here (as your findings confirm).

*

*if the body contains something "splittable" (iterable), it is splitted

*if not, the whole body is passed on (it is treated like a single element list)

This is very convenient since you do not need to create pseudo lists from single objects before passing them to the splitter.


text:
Q: How to pre-fetch data using prefetchQuery with React-Query I am trying to pre-fetch data using react-query prefetchQuery. When I am inspecting browser DevTools network tab I can see that data that was requested for prefetchQuery is coming from the back-end but for some reason when I look into react-query DevTools it does generate the key in the cache but for some reason the Data is not there. Let me know what I am doing wrong.

import { useState, useEffect } from 'react';
import { useQuery, useQueryClient } from 'react-query';
import axios from 'axios';

const baseURL = process.env.api;

async function getSubCategoryListByCategoryId(id) {
  // await new Promise((resolve) => setTimeout(resolve, 300));
  console.log(`${baseURL}/category/subcategories/${id}`);
  try {
    const { data } = await axios.request({
      baseURL,
      url: `/category/subcategories/${id}`,
      method: 'get',
    });
    console.log('data getSubCategoryListByCategoryId index: ', data);
    return data;
  } catch (error) {
    console.log('getSubCategoryListByCategoryId error:', error);
  }
}

// const initialState = {

// };

const ProductCreate = () => {
  const [values, setValues] = useState(initialState);

  const queryClient = useQueryClient();

  const { data, isLoading, isError, error, isFetching } = useQuery(
    'categoryList',
    getPosts
  );

  const dataList = JSON.parse(data);

  useEffect(() => {
    setValues({ ...values, categories: dataList });

    dataList.map((item) => {
      console.log('useEffect values.categories item.id: ', item._id);
      queryClient.prefetchQuery(
        ['subCategoryListByCategoryId', item._id],
        getSubCategoryListByCategoryId(item._id)
      );
    });
  }, []);

  return
Hello
;
};

export default ProductCreate;

A: The second parameter to prefetchQuery expects a function that will fetch the data, similar to the queryFn passed to useQuery.
But here, you are invoking the function, thus passing the result of it into prefetchQuery:
getSubCategoryListByCategoryId(item._id)

if you want to do that, you can manually prime the query via queryClient.setQueryData, which accepts a key and the data for that key passed to it.
otherwise, the fix is probably just:
() => getSubCategoryListByCategoryId(item._id)


text:
Q: Trouble when to use $C(n+k-1,k)$ vs $C(n + (k-1),k-1)$ In my lecture notes I had the exact same problem: we have 6 different apples and 4 identical oranges to distribute them into 5 distinct boxes and I need to place a question: If the boxes are distinct , I am not sure if we should take into consideration when we  distribute the same oranges , that $(b1,b2,b3,b4,b5)=(1,0,1,2,0,0) \neq (0,1,1,2,0,0)$(?).  In both cases the partitions are identical but they are different in terms of boxes. And I am confused whether I should use ${n+k-1} \choose {k}$ (where n stands for boxes and k for objects) or ${n + k-1} \choose {k-1}$. I am particularly confused since my teacher gave us this question (We have $n$ identical objects, and we want to distribute them to $3$ different children $A$, $B$, $C$.) .
I can't see to be able to recognize anymore, in any problem that we distribute identical objects, which formula is needed

As for the second question : I get the method mentioned  by summing up all the inclusive facts but what is wrong with $\frac{10!}{4! (2!)^5}$ and if the boxes are the same ( so we dont consider $(b1,b2,b3,b4,b5)=(1,0,1,2,0,0) \neq (0,1,1,2,0,0)$) shouldn't we also divide by $5! \rightarrow \frac{10!}{4! (2!)^5* 5!}$

A: Distributing distinct objects to distinct boxes:  What matters is which objects are placed in which box.  Therefore, placing a Granny Smith and a MacIntosh in the leftmost of three boxes, a Fuji and a Gala in the middle box, and an Ambrosia and a Honeycrisp in the rightmost box is different from placing an Ambrosia and a Honeycrisp in the leftmost box, a Fuji and a Gala in the middle box, and a Granny Smith and a MacIntosh in the rightmost box.
Distributing indistinguishable objects to distinct boxes:  What matters is how many objects are placed in each box.  Therefore, if we have five indistinguishable oranges, placing two apiece in the leftmost and middle of three boxes and one orange in the rightmost box is different from placing two apiece in the leftmost and rightmost boxes and one in the middle box.  Using your vector notation, that is, $(2, 2, 1) \neq (2, 1, 2)$.
Counting distributions of indistinguishable objects to distinct boxes:  Since the problem you cited has $n$ indistinguishable objects, let's suppose we wish to place $n$ indistinguishable objects in $k$ distinct boxes.  If $x_j$ is the number of objects placed in the $j$th box, where $1 \leq j \leq k$, then
$$x_1 + x_2 + x_3 + \cdots + x_k = n \tag{1}$$
is an equation in the nonnegative integers (unless it is specified that no box is to be left empty).  A particular solution of the equation corresponds to the placement of $k - 1$ addition signs in a row of $n$ ones.
To illustrate, suppose $n = 12$ and $k = 6$, so we wish to find the number of solutions of the equation
$$x_1 + x_2 + x_3 + x_4 + x_5 + x_6 = 12 \tag{2}$$
in the nonnegative integers.  Then
$$1 1 1 + 1 + + 1 1 + 1 1 1 1 + 1 1$$
corresponds to the solution $x_1 = 3, x_2 = 1, x_3 = 0, x_4 = 2, x_5 = 4, x_6 = 2$.  The number of solutions of equation 2 in the nonnegative integers is
$$\binom{12 + 6 - 1}{6 - 1} = \binom{17}{5}$$
since we must choose which $6 - 1 = 5$ of the $12 + 6 - 1 = 17$ positions required for $12$ ones and $6 - 1 = 5$ addition signs will be filled with addition signs.  Equivalently, the number of solutions of equation 2 in the nonnegative integers is
$$\binom{12 + 6 - 1}{12} = \binom{17}{12}$$
since we must choose which $12$ of the $12 + 6 - 1 = 17$ positions required for $12$ ones and $6 - 1 = 5$ addition signs will be filled with ones.
In the general case, we must choose which $k - 1$ of the $n + k - 1$ positions required for $n$ ones and $k - 1$ addition signs will be filled with addition signs or which $n$ of those $n + k - 1$ positions will be filled with ones, so equation 1 has
$$\binom{n + k - 1}{k - 1} = \binom{n + k - 1}{n}$$
solutions.
Selecting $n$ objects from $k$ types of objects:  The related question of selecting $n$ objects from $k$ types of objects also reduces to solving equation 1 in the nonnegative integers.  This is called a combination with repetition problem and yields the same formula as above.
Caveat:  However, in the link, you will notice that the problem is phrased as selection $k$ objects from $n$ types of objects, which reduces to solving the equation
$$x_1 + x_2 + x_3 + \cdots + x_n = k \tag{3}$$
in the nonnegative integers.  Reasoning as above, we interchange the roles of $n$ and $k$, which yields the formula
$$\binom{k + n - 1}{n - 1} = \binom{k + n - 1}{k}$$
Therefore, you have to pay attention to whether $n$ is the number of objects and $k$ is the number of boxes, as in your example, or whether $k$ is the number of objects and $n$ is the number of boxes, as in the linked formula.  If you understand the derivation, you can derive the correct formula regardless of whether $n$ stands for the number of objects and $k$ stands for the number of boxes or vice versa.
Distributing distinct objects to indistinguishable boxes:  The number of ways of placing $n$ objects into $k$ indistinguishable boxes if no box is left empty is the Stirling number of the second kind $S(n, k)$.  If you wish to count all partitions into nonempty sets, you add the Stirling numbers of the second kind to obtain the Bell number $B_n$.
Distributing indistinguishable objects to indistinguishable boxes:  This is an integer partition problem.


text:
Q: k2 loop through all the rows in List View and pass data to another view we have requirement to loop through the rows in List View, and then based on some condition we need to  pass the data to another view
if(impact=yes)
{

//increment a variable
}

pass the variable to another view and set as the control value
any help would be appreciated

A: you can use "For Each Looping" condition on a ListView and then create a condition based on the columns (or in K2 terminology SmartObject properties)


text:
Q: Is it a bug of opencv RotatedRect? I wrote the following code:
#include<iostream>
#include<opencv2/core/core.hpp>
using namespace std;
using namespace cv;

int main()
{
    Point2f p[4];
    RotatedRect rr(Point2f(),Size2f(1,2),0);
    rr.points(p);
    for(int i = 0;i < 4;i++) cout<<p[i]<<endl;
    Rect r = rr.boundingRect();
    cout<< r.x << " " << r.y << " " << r.br().x << " " << r.br().y <<endl;
    return 0;
}

The top-left corner of RotatedRect rr is (-0.5,-1),and the bottom-right corner of RotatedRect rr is (0.5,1).So the minminimal up-right rectangle containing the rotated rectangle is [(-1,-1),(1,1)],(-1,-1) is the top-left corner,(1,1) is the bottom-right corner.But the result rect's bottom-right corner is (2,2).
And I read the source:
Rect RotatedRect::boundingRect() const
{
    Point2f pt[4];
    points(pt);
    Rect r(cvFloor(std::min(std::min(std::min(pt[0].x, pt[1].x), pt[2].x), pt[3].x)),
           cvFloor(std::min(std::min(std::min(pt[0].y, pt[1].y), pt[2].y), pt[3].y)),
           cvCeil(std::max(std::max(std::max(pt[0].x, pt[1].x), pt[2].x), pt[3].x)),
           cvCeil(std::max(std::max(std::max(pt[0].y, pt[1].y), pt[2].y), pt[3].y)));
    r.width -= r.x - 1;
    r.height -= r.y - 1;
    return r;
}

I wonder the code r.width -= r.x - 1; and r.height -= r.y - 1;
And I think it should be  r.width -= r.x; and r.height -= r.y;
Who can tell me is it the source wrong?

A: Looks like cv::boundingRect and RotatedRect::boundingRect are not consistent. I used this little test application
int main(int argc, char* argv[])
{
    cv::Mat input = cv::imread("C:/StackOverflow/Input/Lenna.png");

    //cv::RotatedRect rr = cv::RotatedRect(cv::Point2f(), cv::Size2f(1, 2), 0);

    cv::RotatedRect rr = cv::RotatedRect(cv::Point2f(256,256), cv::Size2f(150, 100), 45);

    cv::Rect rect1 = rr.boundingRect();

    cv::Point2f pt[4];
    rr.points(pt);

    std::vector<cv::Point> pts;
    pts.push_back(pt[0]);
    pts.push_back(pt[1]);
    pts.push_back(pt[2]);
    pts.push_back(pt[3]);

    cv::Rect rect2 = cv::boundingRect(pts);

    std::cout << "RotatedRect::boundingRect: " << rect1 << std::endl;
    std::cout << "cv::boundingRect: " << rect2 << std::endl;

    cv::line(input, pt[0], pt[1], cv::Scalar(0, 0, 255));
    cv::line(input, pt[1], pt[2], cv::Scalar(0, 0, 255));
    cv::line(input, pt[2], pt[3], cv::Scalar(0, 0, 255));
    cv::line(input, pt[3], pt[0], cv::Scalar(0, 0, 255));

    cv::rectangle(input, rect1, cv::Scalar(255, 0, 0));
    cv::rectangle(input, rect2, cv::Scalar(0, 255, 0));

    cv::imshow("input", input);
    cv::waitKey(0);
    return 0;
}

The result gives slightly different bounding rects (RotatedRect::boundingRect surrounds the points while cv::boundingRect is placed ON the points). This might really be a bug, maybe initially cv::RotatedRect::boundingRect was an optimized copy of cv::boundingRect, and a bugfix in cv::boundingRect didn't update the member function. Not sure... I would recommend to use the general purpose cv::boundingRect all the time (didn't measure speed though).


text:
Q: why the space between my html buttons github and facebook or facebook and linkden are operating as links

  <button id="writings">Writings</button>
  <button id="track">Track</button>

    <button id="github">Github</button>

    <button id="twitter">facebook</button>

  <button id="linkden" onclick="linkden()">Linkden</button>
  <button id="email" onclick="email()">Email</button>

i was expecting the space between them to be just a blank space but whenever i click the cursor on the space between buttons the buttons it acts as a link

A: This is because the space is inside the button or part of it. This will happen if you have set padding on your links or buttons. If you want to have space outside the buttons you will need to use margin. Or better, you can make your links container a flexbox and use gap property to create space between them.


text:
Q: Firefox add-ons: 1) Linking Python script to add-on main code | 2) win32 api in JPM / NPM | 3) set file attributes in Windows with OS.file I would like to use the win32 API to create an hidden file on Windows OS.
It seems impossible using JS / Node.js.
With Python, importing the API, it is possible (using SetFileAttributes routine and FILE_ATTRIBUTE_HIDDEN parameter).
So how can I link a Python script to the main JS code for my Firefox add-on? Can you please give me some reference about this matter? I've found nothing on the web.

A: XPCOM is going to be deprecated. While this can be accomplished with nsIFile I don't show it here because the performance is worse for the main thread. The recommended way for file system access right now is `OS.File.
https://developer.mozilla.org/en-US/docs/JavaScript_OS.File/OS.File_for_the_main_thread
Hidden files/directories on windows
This is how you do it with OS.File:
OS.File.setPermissions(
        OS.Path.join(OS.Constants.Path.desktopDir, 'my hidden file.txt'),
          {
            winAttributes: {
                hidden: true
            }
        }
)
.then(x => console.log('success:', x), y => console.error('failure:', y));

This will set the file on the deskto named my hidden file.txt to be hidden. Here are the other winAttributes:
https://dxr.mozilla.org/mozilla-central/source/toolkit/components/osfile/modules/osfile_win_front.jsm#1204-1227
Hidden files/directories on *nix/Mac
Rename or create the file to have a . as the first chracter in its name and it is hidden. Using OS.File this is done with the OS.File.move function as rename is just a move on the file system:
OS.File.move(
        OS.Path.join(OS.Constants.Path.desktopDir, 'my hidden file.txt'),
        OS.Path.join(OS.Constants.Path.desktopDir, '.my hidden file.txt')
)
.then(x => console.log('success:', x), y => console.error('failure:', y));

This will rename, and thus making it hidden, the file on the desktop from my hidden file.txt to .my hidden file.txt.
Platform APIs
If you need to tap into the platform APIs, no need for python. We have js-ctypes:
Here are some docs on js-ctypes:
https://developer.mozilla.org/en-US/docs/Mozilla/js-ctypes/Standard_OS_Libraries
And here is a library/collection of type and function declarations:
https://github.com/Noitidart/ostypes/issues/1#issuecomment-199492249


text:
Q: Firebase iOS push notification custom sound not playing? I'm using firebase push notification service in my iOS app which is developed using swift 3. Currently im getting notification. But i have configured custom sound for notification alert. What happen is when app is closed im getting a default sound not the cutmized sound. But i want to play the custom sound. How can i do this ?
Here is what i have done:
    import UIKit
import UserNotifications
import Firebase
import FirebaseInstanceID
import FirebaseMessaging
import GoogleMaps
import GooglePlaces
import GooglePlacePicker

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate, UNUserNotificationCenterDelegate, MessagingDelegate {

var window: UIWindow?

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {

    //For FireBase Configs
    let settings: UIUserNotificationSettings =
        UIUserNotificationSettings(types: [.alert, .badge, .sound], categories: nil)
    application.registerUserNotificationSettings(settings)
    application.registerForRemoteNotifications()
    FirebaseApp.configure()
    //FireBase Configs

    return true
}

func application(_ application: UIApplication,open url: URL,sourceApplication: String?, annotation: Any) -> Bool {
    return FBSDKApplicationDelegate.sharedInstance().application(application,open: url as URL!,sourceApplication: sourceApplication,annotation: annotation)
}

//FireBase Notifications Begins
func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any],
                 fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {

    //play alert sound
    utilityHelper.playAudio(fileName: "udio", fileExtenstion: "mp3")
    let json = JSON(userInfo)
    NSLog("Received a Notificat`ion: \(json)")
    completionHandler(UIBackgroundFetchResult.newData)
}

func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {

    NSLog("show notification")
    completionHandler(UNNotificationPresentationOptions.alert)
}

func application(received remoteMessage: MessagingRemoteMessage) {

}
func messaging(_ messaging: Messaging, didRefreshRegistrationToken fcmToken: String) {
    NSLog("Refreshed Firebase registration token: \(fcmToken)")

}

func application(_ application: UIApplication,
                         didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
    Messaging.messaging().apnsToken = deviceToken as Data

        NSLog("Register FireBase Token.")

}
//FireBase Notifications End

}

How can i do this, any help would appreciate?

A: What I recently discovered is that on target under ios9 custom sound doesnt play as well as on device with ios 10.0.*.
So just set your build target either >= 9 or use device with iOS >= 10.1


text:
Q: Openfire Java Out of Memory Error - Any solutions? I have huge problem with openfire crashing every now and then because of the lack of memory. In java log i have following error log. however problems are

*

*Openfire is 32 bit and i cant run it as 64 bit.

*Because its only 32 bit max memory i can give to the openfire is 4GB.

*My system is very powerful with 32 GB RAM so i cant increase any more

*Only max 100 users are using the openfire but still cant seems to handle it

*I have run a cron jobs every 5 min to monitor this service and restart every now and then

any solutions on how to optimize open-fire for memory usage and stop it crashing ?
error log as below
#
# There is insufficient memory for the Java Runtime Environment to continue.
# Native memory allocation (malloc) failed to allocate 140 bytes for CHeapObj-new
# Possible reasons:
#   The system is out of physical RAM or swap space
#   In 32 bit mode, the process size limit was hit
# Possible solutions:
#   Reduce memory load on the system
#   Increase physical memory or swap space
#   Check if swap backing store is full
#   Use 64 bit Java on a 64 bit OS
#   Decrease Java heap size (-Xmx/-Xms)
#   Decrease number of Java threads
#   Decrease Java thread stack sizes (-Xss)
#   Set larger code cache with -XX:ReservedCodeCacheSize=
# This output file may be truncated or incomplete.
#
#  Out of Memory Error (allocation.inline.hpp:44), pid=31239, tid=2735213424
#
# JRE version: 6.0_41-b02
# Java VM: Java HotSpot(TM) Server VM (20.14-b01 mixed mode linux-x86 )

---------------  T H R E A D  ---------------

Current thread (0xad2c7000):  JavaThread "Jetty-QTP-AdminConsole-16012" [_thread_in_vm, id=21077, stack(0xa3030000,0xa3081000)]

Stack: [0xa3030000,0xa3081000],  sp=0xa307f3d4,  free space=316k
Native frames: (J=compiled Java code, j=interpreted, Vv=VM code, C=native code)
V  [libjvm.so+0x727990]

A: Openfire is written in java and is not 32-bit specific. If you use a 64bit jvm, it will run in 64 bit mode and you can give it as much ram as you have.  Try installing a 64bit jvm/jre


text:
Q: GET and POST Function App Function/Host Keys Using Python (Azure Government) I am attempting to retrieve and add function/host keys for an Azure Government function app via Python. I am currently working with the information from this question and the corresponding API page. While these are not specific to Azure Government, I would think the process would be similar after updating the URLs to the Azure Government versions. However, I am receiving the error "No route registered for '/api/functions/admin/token'" when running the jwt part of the given code. Is this approach feasible for what I am trying to do?
I also found somewhere that I instead might want to try a GET request like this:
resp = requests.get("https://management.usgovcloudapi.net/subscriptions/<subscription-id>/resourceGroups/<resource-group-name>/providers/Microsoft.Web/sites/<function-app-name>/functions/admin/masterkey?api-version=20XX-XX-XX", headers={"Authorization": f"Bearer {something}"})

This gives me the error "{"error":{"code":"InvalidAuthenticationToken","message":"The access token is invalid."}}", though. If this is indeed the correct approach, then what format should the Bearer token take?

A: Bit late answering but it may be useful for someone else in the future, it took me a while to find out how to do this.
If you want to retrieve the keys of a specific function within a function app then you can use list_function_keys() function from the Python SDK
Working with the Az management API directly may be a bit annoying and since the Azure CLI is written in Python whatever operation you do with the CLI you can do it directly in a Python script.
Here's an example of how you can retrieve the keys
from azure.identity import DefaultAzureCredential
from azure.mgmt.web import WebSiteManagementClient

# Your subscription ID
SUB_ID = "00000000-0000-0000-0000-000000000000"

fn_name = "some_function"  # Name of your function
app_name = "some_app"  # Name of your site/function app
rg_name = "some_rg"  # Resource group name to which the function belongs

web_client = WebSiteManagementClient(subscription_id=SUB_ID, credential=DefaultAzureCredential())
keys = web_client.web_apps.list_function_keys(rg_name, app_name, fn_name)

# Your keys will be accessible in the additional_properties param
print(keys.additional_properties)

Hope it helps! I'm new on Azure so if I'm doing something wrong, please don't hesitate to point out my mistake and share your correction


text:
Q: Show tooltip and keep it visible Whenever the user "mouse out" my chart, I would like a tooltip to automatically appear above one point and stay visible until the mouse returns above the chart.
series: {
  events: {
    mouseOut: function() {
      chart.series[0].data.refresh(0);
  }
}

The code above works, but the tooltip disappear after a second or two.  I want it to stay visible.
Thanks!

A: This reassigning of the reset function should help to achieve wanted result.
Demo: https://jsfiddle.net/BlackLabel/pu9g2dft/
  Highcharts.Pointer.prototype.reset = function() {
    return undefined;
  };


text:
Q: Minimum Methods for Ordering with Duck Typing in Python 3.1 In the manual is says:

in general, __lt__() and __eq__() are sufficient, if you want the
  conventional meanings of the comparison operators

But I see the error:
>       assert 2 < three
E       TypeError: unorderable types: int() < IntVar()

when I run this test:
from unittest import TestCase

class IntVar(object):

    def __init__(self, value=None):
        if value is not None: value = int(value)
        self.value = value

    def __int__(self):
        return self.value

    def __lt__(self, other):
        return self.value < other

    def __eq__(self, other):
        return self.value == other

    def __hash__(self):
        return hash(self.value)

class DynamicTest(TestCase):

    def test_lt(self):
        three = IntVar(3)
        assert three < 4
        assert 2 < three
        assert 3 == three

I am surprised that when IntVar() is on the right, __int__() is not being called.  What am I doing wrong?
Adding __gt__() fixes this, but means I don't understand what the minimal requirements are for ordering...
Thanks,
Andrew

A: Python 3.x will never do any type coercions for operators, so __int__() is not used in this context.  The comparison
a < b

will first try to call type(a).__lt__(a, b), and if this returns NotImplemented, it will call type(b).__gt__(b, a).
The quote from the documentation is about making comparisons work for a single type, and the above explanation shows why this would be enough for a single type.
To make your type interact correctly with int, you should either implement all the comparison operator, or use the total_ordering decorator available in Python 2.7 or 3.2.


text:
Q: Tensorflow hub: Extracting features from the topmost convolutional layer of a Resnet50 I am using Tensorflow Hub to extract features from an image. Namely, I am using the module hub.Module("https://tfhub.dev/google/imagenet/resnet_v2_50/feature_vector/3").
Because I want to extract features from the last convolutional layer, I am a bit confused which dictonary output should I use from the Resnet50. For example:
image = ...
embedding_module = hub.Module("https://tfhub.dev/google/imagenet/resnet_v2_50/feature_vector/3")
output = embedding_module(image, signature="image_feature_vector",
                          as_dict=True)

Now, if we print out the keys from this dictionary there are 3 different keys which I don't know the difference between.

*

*resnet_v2_50/block4/unit_3/bottleneck_v2

*resnet_v2_50/block4/unit_3/bottleneck_v2/conv3

*resnet_v2_50/block4
What I find confusing is that all them have an output that has the same shape (7, 7, 2048), yet the values of resnet_v2_50/block4/unit_3/bottleneck_v2 and resnet_v2_50/block4 are different from resnet_v2_50/block4/unit_3/bottleneck_v2/conv3. Can someone point me to which key should be used for feature extraction from the last convolutional layer of the Resnet50 as well as what is the difference between each of the keys I listed?
Thanks!

A: In Tensorflow2, we can do as below.
For more docs: link
from tensorflow.keras.preprocessing.image import img_to_array
from tensorflow.keras.preprocessing.image import load_img

# as per updated docs
model = hub.KerasLayer("https://tfhub.dev/google/imagenet/resnet_v2_50/feature_vector/5")

imagePath = "......."
image = load_img(imagePath, target_size=(224, 224))
image = img_to_array(image)
image = np.expand_dims(image, axis=0)

embeddings = model(image)

A: according the official manual we can directly use module(xxx) to get result.
it works fine for me
module = hub.Module("https://tfhub.dev/google/imagenet/resnet_v2_50/feature_vector/3")
features = module(images)

Actually I'm also trying to figure out how to get the right last layer by name instead some pre-provided API which lacks flexibility.


text:
Q: Silverlight 4: Binding ChildControl to ParentControl Within a TabItem Style I have a Button. That Button has a command, which I would like to send the (Parent) TabItem to. In Silverlight we don't have RelativeSource. But I can't simply use Elementname neither. because my TabItem has no name within the style.
<Style TargetType="sdk:TabItem">
                        <Setter Property="HeaderTemplate">
                            <Setter.Value>
                                <DataTemplate>
                                    <StackPanel Orientation="Horizontal">
                                        <TextBlock Text="{Binding TabCaption}"/>
                                        <Button Margin="8,0,0,0"
                                                Command="local:Commands.CloseTabItem"
                                                CommandParameter="{Binding RelativeSource={RelativeSource Mode=FindAncestor,AncestorType={x:Type sdk:TabItem}}}"
                                                HorizontalContentAlignment="Center"
                                                VerticalContentAlignment="Center">
                                        </Button>
                                    </StackPanel>
                                </DataTemplate>
                            </Setter.Value>
                        </Setter>
                    </Style>

This would be the code within the Command's method:
private void OnCloseTabItemExecute(object sender, ExecutedRoutedEventArgs e)
{
    TabItem parent = e.Parameter as TabItem;

    if (parent != null)
    {
        FrameworkElement view = (parent as TabItem).Content as FrameworkElement;
        string regionName = RegionManager.GetRegionName(view);

        _regionManager.Regions[regionName].Remove(view);
    }
}

How could I pass in the parent Control (TabItem) as the child control's command Parameter in Silverlight 4?
highly Appreciated.

A: You could use RelativeSource Mode Self or TemplatedParent in the Binding and then walk up the visual tree in the Command method to find the TabItem
Xaml
<Button Margin="8,0,0,0"
        Command="local:Commands.CloseTabItem"
        CommandParameter="{Binding RelativeSource={RelativeSource Mode=TemplatedParent}}"
        HorizontalContentAlignment="Center"
        VerticalContentAlignment="Center">
</Button>

Command method and an implementation of GetVisualParent
private void OnCloseTabItemExecute(object sender, ExecutedRoutedEventArgs e)
{
    DependencyObject element = e.Parameter as DependencyObject;
    TabItem tabItem = GetVisualParent<TabItem>(element);
    //...
}
public static T GetVisualParent<T>(object childObject) where T : FrameworkElement
{
    DependencyObject child = childObject as DependencyObject;
    while ((child != null) && !(child is T))
    {
        child = VisualTreeHelper.GetParent(child);
    }
    return child as T;
}

A: You could use {RelativeSource Self} then in your command handler code use the Parent property to look upward for the control you want.


text:
Q: Ensure space between Cards on colapse to small screen in react Am trying to make sure that when I view my react website on a small screen my cards have space in between them. Right now when I view on a large screen the cards are spaced evenly, however, on a small screen, they are not spaces. Has anyone encountered that issue?
Here is my code
<Row gutter={16} justify="space-between" align="middle">
    {this.state.news.slice(0,4).map((item, key) => (
        <Col span={12} md={{span:6}} lg={{span:6}} style={{paddingTop:15,marginTop:10}}>
            <Card
                hoverable
                style={{ width: 230 }}
                cover={}
                actions={[
                     Read News,
                ]}>

                    <Meta  title={item.title} description={item.categories} />

            </Card>
        </Col>
    ))}
</Row>

cards on a big screen
cards on a small screen

A: You have style={{ width: 100 }},This will keep the width fixed for all screen. take it out and try.
 <Card
                 hoverable
                //  style={{ width: 100 }}
                 cover={}
                 actions={[
                      Read News,
                 ]}>

             </Card>


text:
Q: Xamarin app exit, but still in Task Manager I need to implement an app exit when the user hits the device's back button.
My code makes the app to quit, but when opening the task manager by hitting the menu button twice, my app is still in there. When I click on it, it restarts from the splashscreen...
I've tried :
Finish()
Or
FinishAffinity();
followed by :
Android.OS.Process.KillProcess(Android.OS.Process.MyPid());

Or
Java.Lang.JavaSystem.Exit(0);

It doesnt remove my app from the task manager.
PS: By task manager I mean the page where you can see all opened apps, and you can quit them by swipping your finger.


text:
Q: Нужно получить число из элемента вставленного через innerHTML Я получаю число путем вычитания value двух input. Есть такой код:

const differenceResult = document.querySelector("#difference-result");
const calculateBtn = document.querySelector("#calculate-btn");
const price = document.querySelector("#total-price");

differenceResult.innerHTML = "
" + parseFloat(currentInput.value - lastInput.value).toFixed(2) + "
";

calculateBtn.addEventListener("click", function () {
  price.innerHTML = differenceResult * 2;
});

Как я могу обратиться к числу, которое я получаю при parseFloat(currentInput.value - lastInput.value).toFixed(2), чтобы при клике на calculateBtn добавить его в div price.
Буду благодарен за помощь

A: Правильно будет при клике вычислять по формуле, вставлять результат вычисления в переменную (любую), а потом уже ниже по коду, в этой же функции, оперировать этой переменной, в том числе и вставить в differenceResult.innerHTML и в price.innerHTML

если нужно получить значение до клика и во время клика - то надо создать отдельную функцию, которая будет делать вычисления и делать return этого значения. И уже результатом этой функции оперировать как при клике на кнопку, так и до (вот тут: differenceResult.innerHTML = ...)


text:
Q: Android app crashes when starting a new Intent I'm writing a program where after clicking this button another program will be started.
However, the program force closed when I click the corresponding button.
here's the code.
package com.example.pc.multi_functionapp;

import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Button button1 = (Button)findViewById(R.id.button_1);
        Button button2 = (Button)findViewById(R.id.button_2);

        button1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent int1 = new Intent(MainActivity.this, Accelerometer.class);
                startActivity(int1);
            }
        });
        button2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent int2 = new Intent(MainActivity.this, Locator.class);
                startActivity(int2);
            }
        });
    }
}

Here's the XML code
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout

    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:padding="16dp"
    android:layout_gravity="center_horizontal"

    tools:context=".MainActivity">

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"
        android:id="@+id/button_1"
        android:text="Android Accelerometer"
        />
    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"
        android:id="@+id/button_2"
        android:text="Android Current Location"
        />
    </LinearLayout>

Here's the android manifest code
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.pc.multi_functionapp">

    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".Locator"></activity>
        <activity android:name=".Accelerometer" />
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</man

For the program itself, Accelerometer and Locator work properly if I running it one by one.
I'm creating this program in purpose, these two programs can be run in one app, no need to open it in a different app.
I'm expecting after I click the first button, the accelerometer program will be started and when I click the second button, the Locator program will be started.
what happened is, when I click it the program just force closed.
please help me so the button works properly when clicked.
Edit :
Accelerometer Code
package com.example.pc.multi_functionapp;

import android.content.Context;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;

import androidx.appcompat.app.AppCompatActivity;

public class Accelerometer extends AppCompatActivity implements SensorEventListener {
    private static final String TAG = "MainActivity";
    private SensorManager sensorManager;
    Sensor accelerometer;

    TextView xValue, yValue, zValue;

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

        xValue = (TextView) findViewById(R.id.xValue);
        yValue = (TextView) findViewById(R.id.yValue);
        zValue = (TextView) findViewById(R.id.zValue);
        Log.d(TAG, "onCreate: initializing Sensor Services");
        sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);

        accelerometer = sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
        sensorManager.registerListener(Accelerometer.this, accelerometer, SensorManager.SENSOR_DELAY_NORMAL);
        Log.d(TAG, "onCreate: Registered accelerometer listener");
    }

    @Override
    public void onAccuracyChanged(Sensor sensor, int accuracy) {

    }

    @Override
    public void onSensorChanged(SensorEvent sensorEvent) {
        Log.d(TAG, "onSensorChanged: X: " + sensorEvent.values[0] + "Y: " + sensorEvent.values[1] + "Z: " + sensorEvent.values[2]);

        xValue.setText("xValue: " + sensorEvent.values[0]);
        yValue.setText("yValue: " + sensorEvent.values[1]);
        zValue.setText("xValue: " + sensorEvent.values[2]);
    }
}

Locator Code
package com.example.pc.multi_functionapp;

import android.Manifest;
import android.content.pm.PackageManager;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.os.Bundle;
import android.text.Html;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;

import com.google.android.gms.location.FusedLocationProviderClient;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;

import java.io.IOException;
import java.util.List;
import java.util.Locale;

public class Locator extends AppCompatActivity {
    TextView textView1, textView2, textView3, textView4, textView5;
    FusedLocationProviderClient fusedLocationProviderClient;
    Button btLocation;
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        btLocation = findViewById(R.id.bt_location);
        textView1 = findViewById(R.id.text_view1);
        textView2 = findViewById(R.id.text_view2);
        textView3 = findViewById(R.id.text_view3);
        textView4 = findViewById(R.id.text_view4);
        textView5 = findViewById(R.id.text_view5);

        fusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(this);

        btLocation.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (ActivityCompat.checkSelfPermission(Locator.this
                        , Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED){
                    getLocation();
                }
                else {
                    ActivityCompat.requestPermissions(Locator.this
                            , new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, 44);
                }
            }
        });
    }
    private void getLocation() {
        fusedLocationProviderClient.getLastLocation().addOnCompleteListener(new OnCompleteListener<Location>() {
            @Override
            public void onComplete(@NonNull Task<Location> task) {
                Location location = task.getResult();
                if (location != null){
                    try {
                        Geocoder geocoder = new Geocoder(Locator.this, Locale.getDefault());
                        List<Address> addresses = geocoder.getFromLocation(location.getLatitude(), location.getLongitude(), 1 );
                        textView1.setText(Html.fromHtml("Latitude :
" + addresses.get(0).getLatitude()));
                        textView2.setText(Html.fromHtml("Longitude :
" + addresses.get(0).getLongitude()));
                        textView3.setText(Html.fromHtml("Country Name :
" + addresses.get(0).getCountryName()));
                        textView4.setText(Html.fromHtml("Locality :
" + addresses.get(0).getLocality()));
                        textView5.setText(Html.fromHtml("Address :
" + addresses.get(0).getAddressLine(0)));
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        });
    }
}

Before CLicked
After Clicked

A: Oh, your error is simple.
I think you have copied the Activities and you have forgotten to change the layout in the setContentView() of all of your Activities. all of them are R.layout.activity_main so the app is starting the activity_main.xml but the view are getting findViewById() from their real resources.

A: Crash maybe because of the two reasons.
Make sure you have separate layout for all your activities.
Make sure your activities added in the AndroidManifest.xml file.


text:
Q: Round an int to the nearest in 5X Table? In my iPhone app I need to round an integer to the nearest multiple of 5.
E.g. Round 6 to = 10 and round 23 to = 25 etc
Edit
I forgot to say, I only want to round up! In all situations, so 22 would round up to 25 for example.

A: If you want to always round up, you can use the following:
int a = 22;
int b = (a + 4) / 5 * 5; // b = 25;

If a can be a float, you should add a cast to int as follows:
int b = ((int)a + 4) / 5 * 5; // b = 25;

Note that you can use the function ceil to accomplish the same result:
int a = 22;
int b = ceil((float)a / 5) * 5; // b = 25;

Old Answer:
To round to the nearest multiple of 5, you can do the following:
int a = 23;
int b = (int)(a + 2.5) / 5 * 5;

A: Use :
int rounded = (i%5==0) ? i : i+5-(i%5);

Example :
    for (int i=1; i<25; i++)
    {
        int k= (i%5==0) ? i : i+5-(i%5);

        printf("i  : %d => rounded : %d\n",i,k);
    }

Output :
i  : 1 => rounded : 5
i  : 2 => rounded : 5
i  : 3 => rounded : 5
i  : 4 => rounded : 5
i  : 5 => rounded : 5
i  : 6 => rounded : 10
i  : 7 => rounded : 10
i  : 8 => rounded : 10
i  : 9 => rounded : 10
i  : 10 => rounded : 10
i  : 11 => rounded : 15
i  : 12 => rounded : 15
i  : 13 => rounded : 15
i  : 14 => rounded : 15
i  : 15 => rounded : 15
i  : 16 => rounded : 20
i  : 17 => rounded : 20
i  : 18 => rounded : 20
i  : 19 => rounded : 20
i  : 20 => rounded : 20
i  : 21 => rounded : 25
i  : 22 => rounded : 25
i  : 23 => rounded : 25
i  : 24 => rounded : 25

A: Swift 3
extension Int {
    func nearestFive() -> Int {
        return (self + 4) / 5 * 5
    }
}

use
let a = 23.nearestFive()
print(a) // 25

A: For an integer solution use mod 5 biased by 4 for the rounding:
int i;
int i5;

i = 6;
i5 = i + 4 - ((i+4) % 5);
NSLog(@"i: %i, i5: %i", i, i5);

i = 22;
i5 = i + 4 - ((i+4) % 5);
NSLog(@"i: %i, i5: %i", i, i5);
NSLog output:

i: 6, i5: 10
  i: 22, i5: 25

A: For rounding up to the next multiple of 5, e.g., the following can be used:
(int) (5.0 * ceil((number/5.0)))

A: You probably don't need another answer to this question, but I personally think this is neater:
int ans = ceil(input / 5.0) * 5.0;

A: Since you only need integers to be round off, num+5-(num%5) should be sufficient.
Old Answer
I do not know much about objective-c but shouldn't this be sufficient.
r = num%5
r > 2 ? num+5-r : n-r


text:
Q: Como consigo o tamanho de uma String em Java?
Estou criando um Banco falso em java mas não sei como verificar se a senha tem 8 caracteres.

public void criarSenha(){
 String senhacriada = (JOptionPane.showInputDialog("Qual a senha ?"));
       if(tamanhodasenhacriada >= 8) {       //! O problema está aqui !
   System.out.println("Senha criada com sucesso !");
 }else {
   System.err.println("senha >= 8 !");
 }
}

Como eu faço para descobrir o tamanho da String ?

Em javascript eu faço :
if(lenght(senha) >= 8){
// Codigo
}

Mas em Java eu não sei pois estou começando a aprender !

A: Use o método length(), pois este irá retornar o tamanho de uma string em caracteres.
Seu código ficará:
if(senhacriada.length() >= 8) {       //! A solução está aqui !
   System.out.println("Senha criada com sucesso !");
 }else {
   System.err.println("senha >= 8 !");
 }

Recomendo a leitura:
Por que em Java o tamanho de um array é um atributo e de uma String e um método?


text:
Q: Not able to require the jqueryui I try to require the jquery UI library but If I try to use the functions they are undefined.
here is the code
RequireJS 2.1.11
    <script data-main="/js/lpapi/v3/qfapi.js" src="/vendor/requirejs/require.min.js"></script>

qfapi.js
(function() {
  require.config({
    paths: {
      jquery: '/jquery/jquery-1.11.0.min',
      jqueryui: '/vendor/jqueryui/jquery-ui-1.10.4.custom.min',
      backbone: '/vendor/backbone/backbone-min',
      underscore: '/vendor/underscore/underscore-min'
    },
    shim: {
      "jqueryui": {
        deps: ['jquery'],
        exports: '$'
      },
      "underscore": {
        exports: "_"
      },
      "backbone": {
        exports: 'Backbone',
        deps: ['underscore', "jquery"]
      }
    }
  });

  define(["jquery", "jqueryui", "backbone", "underscore"], function($, _, Backbone) {
    console.log("jquery is loaded");
    console.log("jqueryui is loaded");
    console.log("underscore is loaded");
    console.log("backbone is loaded");
    $("#accordion").accordion();
    return true;
  });

}).call(this);

the "accordion" is not a function.
any idea?

A: There are some problems with the code you are showing. Your define call should be a require call. And your list of arguments is not correct:
require(["jquery", "backbone", "underscore", "jqueryui"], function($, _, Backbone) {

The way you have it in your question _ would get an undefined value and Backbone would be bound to the underscore module.
Your data-main should not include the .js extension. The value of data-main is a module name. RequireJS' module names should generally not contain an extension.


text:
Q: Append (html) delete? I have a div that is created by Ajax with .append(html) function,  I'm trying to select that div and delete it, but I can't select it. How to select that div that is created dynamically by the .append() function?
I created like this,
 $("#loadplace"+Id).append(html);

And I trying to delete like this;
 $('#load_comment'+id).slideUp('slow', function() {$(this).remove();});

A: $('#load_comment'+id).slideUp('slow', function() {$(this).find("#myDiv").remove();});

A: Try first with a variable:
var $myDiv = $(html);

then:
$("#loadplace"+Id).append($myDiv);

then:
$myDiv.remove();


text:
Q: Adam optimizer with exponential decay In most Tensorflow code I have seen Adam Optimizer is used with a constant Learning Rate of 1e-4 (i.e. 0.0001). The code usually looks the following:
...build the model...
# Add the optimizer
train_op = tf.train.AdamOptimizer(1e-4).minimize(cross_entropy)
# Add the ops to initialize variables.  These will include
# the optimizer slots added by AdamOptimizer().
init_op = tf.initialize_all_variables()

# launch the graph in a session
sess = tf.Session()
# Actually intialize the variables
sess.run(init_op)
# now train your model
for ...:
  sess.run(train_op)

I am wondering, whether it is useful to use exponential decay when using adam optimizer, i.e. use the following Code:
...build the model...
# Add the optimizer
step = tf.Variable(0, trainable=False)
rate = tf.train.exponential_decay(0.15, step, 1, 0.9999)
optimizer = tf.train.AdamOptimizer(rate).minimize(cross_entropy, global_step=step)
# Add the ops to initialize variables.  These will include
# the optimizer slots added by AdamOptimizer().
init_op = tf.initialize_all_variables()

# launch the graph in a session
sess = tf.Session()
# Actually intialize the variables
sess.run(init_op)
# now train your model
for ...:
  sess.run(train_op)

Usually, people use some kind of learning rate decay, for Adam it seems uncommon. Is there any theoretical reason for this? Can it be useful to combine Adam optimizer with decay?

A: The reason why most people don't use learning rate decay with Adam is that the algorithm itself does a learning rate decay in the following way:
t <- t + 1
lr_t <- learning_rate * sqrt(1 - beta2^t) / (1 - beta1^t)

where t0 is the initial timestep, and lr_t is the new learning rate used.

A: Empirically speaking: definitely try it out, you may find some very useful training heuristics, in which case, please do share!

Usually people use some kind of decay, for Adam it seems uncommon. Is there any theoretical reason for this? Can it be useful to combine Adam optimizer with decay?

I haven't seen enough people's code using ADAM optimizer to say if this is true or not. If it is true, perhaps it's because ADAM is relatively new and learning rate decay "best practices" haven't been established yet.
I do want to note however that learning rate decay is actually part of the theoretical guarantee for ADAM. Specifically in Theorem 4.1 of their ICLR article, one of their hypotheses is that the learning rate has a square root decay, $\alpha_t = \alpha/\sqrt{t}$. Furthermore, for their logistic regression experiments they use the square root decay as well.
Simply put: I don't think anything in the theory discourages using learning rate decay rules with ADAM. I have seen people report some good results using ADAM and finding some good training heuristics would be incredibly valuable.

A: I agree with @Indie AI's opinion, here I supply some other information:
From CS231n:

... Many of these methods may still require other hyperparameter settings, but the argument is that they are well-behaved for a broader range of hyperparameter values than the raw learning rate. ...

And Also from the Paper Rethinking the Inception Architecture for Computer Vision  Section 8:

... while our best models were achieved using RMSProp [21] with de- cay of 0.9 and ε = 1.0. We used a learning rate of 0.045, decayed every two epoch using an exponential rate of 0.94. ...

A: I trained a dataset with real easy data, if a person is considered fat or not, height and weight - creating data calculating bmi, and if over 27, the person is fat. So very easy basic data. When using Adam as optimizer, and learning rate at 0.001, the accuracy will only get me around 85% for 5 epocs, topping at max 90% with over 100 epocs tested.
But when loading again at maybe 85%, and doing 0.0001 learning rate, the accuracy will over 3 epocs goto 95%, and 10 more epocs it's around 98-99%. Not sure if the learning rate can go below 4 digits 0.0001, but when loading the model again and using 0.00001, the accucary will hover around 99.20 - 100% and wont go below. Again, not sure if the learning rate would be considered 0, but anyway, that's what I've got...
All this using categorical_crossentropy, but mean_square gets it to 99-100% too doing this method. AdaDelta, AdaGrad, Nesterov couldn't get above 65% accuracy, just for a note.

A: Adam uses the initial learning rate, or step size according to the original paper's terminology, while adaptively computing updates. Step size also gives an approximate bound for updates. In this regard, I think it is a good idea to reduce step size towards the end of training. This is also supported by a recent work from NIPS 2017: The Marginal Value of Adaptive Gradient Methods
in Machine Learning.
The last line in Section 4: Deep Learning Experiments says

Though conventional wisdom suggests that Adam does not require tuning, we find that tuning the initial learning rate and decay scheme for Adam yields significant improvements over its default settings in all cases.

Last but not least, the paper suggests that we use SGD anyways.

A: The learning rate decay in the Adam is the same as that in RSMProp(as you can see from this answer), and that is kind of mostly based on the magnitude of the previous gradients to dump out the oscillations. So the exponential decay(for a decreasing learning rate along the training process) can be adopted at the same time. They all decay the learning rate but for different purposes.


text:
Q: Dns hostname debian etch guest not working vmware server 1.x I am running Etch on vmware server 1x on windows, I can only access the guest via ip and not hostname, I have no trouble with Debian Lenny, both installed 1 after each other with autp network config via local dhcp server, virtual network card is in bridged network mode, any ideas as to what may be the problem? im on a larger company lan which has either windows 2003 or bind server, not too sure which one is used as they both perform different functions...

A: Installing SAMBA and disabling WINS in smb.conf automagically made it work...


text:
Q: Gigabyte GA-X58A-UD3R Does Not Boot Into Ubuntu I have a Gigabyte GA-X58A-UD3R (Rev 2) with BIOS FA that I want to install Ubuntu on. I have a 3.5" SATA drive from another machine with that version of Ubuntu on it, but instead of booting after I select Ubuntu from grub, it briefly display the Ubuntu logo, then turns off. The same thing happens when I try to install from an 8 GB USB pen drive.
It can boot from FreeDOS on a USB-HDD no problem.
BIOS Screen Shots


text:
Q: Why is Visual Studio saying my file doesn't exist when it evidently does? Also, does it matter that it's adding a forward slash? I have verified multiple times that the file exists, and when I copy-and-paste the path to the file from the code into Windows explorer, it works. It takes me to the file. So please help, what is going on? The exception message, for your reference says

System.IO.FileNotFoundException: Could not find file "/C:\Users\Daniel\Desktop\Couryah\products_export.csv

Why is this forward slash in front of it? Is it the culprit? How do I fix it?
public void PopulateList()
{
    string line;
    System.IO.StreamReader file = new System.IO.StreamReader("C:\\Users\\Daniel\\Desktop\\Couryah\\products_export.csv");

    while ((line = file.ReadLine()) != null)
    {
        Product newProduct = new Product();
        newProduct.setAll(line.Split(',')[1], line.Split(',')[3], Convert.ToDouble(line.Split(',')[19].Replace("$", "")), line.Split(',')[24]);
        productList.Add(newProduct);
    }
}

A: I would pre-check to make sure the file exists.  Put into a variable just to be sure no false/bogus value with bad forward slash.  Then, check to see if the file exists or not to confirm BEFORE opening.
Next, instead of stream, I just changed to a File.ReadAllLines() which reads each line at a time into an array.
public void PopulateList()
{
    var whatFile = "C:\\Users\\Daniel\\Desktop\\Couryah\\products_export.csv";
    if ( ! System.IO.File.Exists( whatFile ))
    {
        MessageBox.Show("No such file: " + whatFile);
        return;
    }

    foreach( var line in System.IO.File.ReadAllLines( whatFile ))
    {
        Product newProduct = new Product();
        newProduct.setAll(line.Split(',')[1], line.Split(',')[3], Convert.ToDouble(line.Split(',')[19].Replace("$", "")), line.Split(',')[24]);
        productList.Add(newProduct);
    }
}

Now, this does not necessarily answer why a file does not exist, but here is one thing I specifically ran into and was scratching the heck out of my head.  I had a similar for a client.  I had a file on the desktop that was a csv, but no matter what, had same issue.
What I actually had found is the file "MyFile.csv" was ACTUALLY a "MyFile.csv.txt".  Wondering what the... Ended up going to a DOS command prompt, changed to folder and did a DIR of that folder to see it.
Come to find, Windows likes to default HIDING FILE NAME SUFFIX of common file extensions.  So, even though the desktop had .csv, because the .txt was hidden was causing the not found file.  To confirm, I changed the file manager to NOT HIDE file name suffix.  Sure enough, stripped the .txt and everything worked.
Not saying this is what you have, but sometimes the obvious isn't.
One more note.  I would put a breakpoint in your debugger to stop at the point of checking the file.  Then use your watch window and see what variables are and also check/change as needed to confirm its doing what you thought it should.
One additional option...
Try using what WINDOWS thinks is your desktop.
var whatFile2 = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), "Couryah\\products_export.csv")

How does THIS "SpecialFolder.Desktop" compare with your C:\users...


text:
Q: BottomNavigationView setOnNavigationItemReselectedListener is deprecated in Material Component version 1.4.0. What to use now? BottomNavigationView setOnNavigationItemReselectedListener is deprecated with Material Component version 1.4.0.
What to use now?

A: As per the deprecation message:

Use NavigationBarView#setOnItemReselectedListener(OnItemReselectedListener) instead.

So just replace setOnNavigationItemReselectedListener with setOnItemReselectedListener and change your listener to a NavigationBarView.OnItemReselectedListener.

A: Based on the documentation, it seems like you can call the listener interface directly and it will set the listeners internally since it's supported by both bottom navigation and navigation rail now.
https://github.com/material-components/material-components-android/blob/95a769c373792d2fce70d7ee21f3857f65e9d74e/docs/components/NavigationRail.md
NavigationBarView.OnItemSelectedListener { item ->
    when(item.itemId) {
        R.id.item1 -> {
            // Respond to navigation item 1 click
            true
        }
        R.id.item2 -> {
            // Respond to navigation item 2 click
            true
        }
        else -> false
    }
}


text:
Q: Automatically Add Self Reference To Properties Of Object In Visual Studio 2019, when writing .net (C# or VB.net), is there a way to automatically prefix members/ properties of an object with their respective "self" reference?
Eg in c#, automatically prepending "this." when referencing members of a class from within the class.
Eg in VB.net, automatically prepending "me." when referencing members of a class from within the class.
Using an extension to do this is fine, if one exists.

A: Look for Tools/Options/Text Editor/C#/Code Style
You will see a preference like;

Qualify property access with 'this' |  Do not prefer 'this'

Change the option above and voila!
P.S: You still need to run code cleanup(ctrl+K+E) or set the severity to "Error", in which case VS itself will prompt to "fix" it as @stuartd mentions it in the comments


text:
Q: racket to-string function for integer and string Need to write a to-string function that accepts integer and string.
(to-string 3) ; -> "3"
(to-string "hello") ; -> "\"hello\""
(to-string "hel\"lo") ; -> "\"hel\\\"lo\""

I managed to do so with:
(define (to-string x)
  (define o (open-output-string))
  (write x o)
  (define str (get-output-string o))
  (get-output-bytes o #t)
  str
  )
(to-string 3)
(to-string "hello")
(to-string "hel\"lo")

However, the get-output-bytes reseting is not very readable. What's the idiomatic Racket way of doing it?

A: Does the ~v function or the ~s function from racket/format work for you?
> (~v 3)
"3"
> (~v "hello")
"\"hello\""
> (~v "hel\"lo")
"\"hel\\\"lo\""

A: I'm not sure if ~v and ~s functions still require racket/format library for the #lang racket, but you can use format function (see more details) that works even for the racket/base
#lang racket/base
(format "~v" 3)
(format "~v" "hello")
(format "~v" "hel\"lo")

That gives you exactly what you need:
"3"
"\"hello\""
"\"hel\\\"lo\""

A: Using format works, but there are problems. there's no guarantee that what you've been passed is actually a string or an integer. It could be a list or a hash or whatever.
Here's a function to convert an integer or string to a string and raise a contract violation if you tried to do something unexpected like pass in a hash.
You could easily extend this to allow any number by changing the integer? to number? in the contract.
#lang racket

(define/contract (int-or-string->string var)
  (-> (or/c string? integer?) string?)
  (if (string? var)
      var
      (number->string var))

  )


text:
Q: Core data crash when fetching over 1000 objects When I try to fetch more than 1000 NSManagedObjects from Core Data, my app crashes with this message:
error: (1) I/O error for database at .../Documents/Stores/Model.sqlite.
SQLite error code:1, 'Expression tree is too large (maximum depth 1000)'
CoreData: error: (1) I/O error for database at .../Documents/Stores/Model.sqlite.
SQLite error code:1, 'Expression tree is too large (maximum depth 1000)'

The code I use to fetch the objects selected by the user is this:
NSManagedObjectContext *context = cdh.context;
NSFetchRequest *request = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription entityForName:@"Spot" inManagedObjectContext:context];
NSError *error = nil;
[request setEntity:entity];
request.includesPropertyValues = NO;

NSMutableArray *subPredicatesArray = [NSMutableArray array];

for (NSString *string in uuidStrings)
{
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"%K like %@", @"sID", string];
    [subPredicatesArray addObject:predicate];
}

NSCompoundPredicate *compoundPredicate = [NSCompoundPredicate orPredicateWithSubpredicates:subPredicatesArray];
[request setPredicate:compoundPredicate];

NSArray *fetchedObjects = [context executeFetchRequest:request error:&error];

Is there a better way to fetch 1000+ objects that won't cause my app to crash?

A: Assuming the uuidStrings contain exact matches for the sID attribute, you should be able to replace the code with this (untested):
// remove subPredicatesArray, the loop and compoundPredicate

NSPredicate *predicate = [NSPredicate predicateWithFormat:@"sID IN %@", uuidStrings];
[request setPredicate:predicate];