text:
Q: Conversion of strings to integers on arm64? I've got a small chunk of code which I've noticed is behaving differently for arm64 targets. I'm fetching a numeric string from JSON data, and then using integerValue to convert the string to an integer. The string generally has thousands separators, in the form of a comma.
On non-64bit targets, (iPhone 4/s, 5/s, etc), everything works perfectly and I get the correct integer regardless of whether there is a comma separating the thousands. However, on arm64, integerValue only returns the first "chunk" of numbers, before the separator comma. I've included the code and a sample result to show what exactly is happening:
NSInteger value = [BTCValue integerValue];
[UIApplication sharedApplication].applicationIconBadgeNumber = value;

For example, on non-64bit targets:
BTCValue = @"54,321.00" and value = 54321.
On arm64 targets, however:
BTCValue = @"54,321.00" and value = 54.
It doesn't seem to matter whether value is an int or an NSInteger, the same thing happens regardless. Is there something that I'm missing? I don't understand why everything works properly on armv7 but not arm64.

A: It's likely that your ARM64 device has a locale setting that is causing the comma to be treated as a decimal or simply as non-numeric text.
In general, you're better off using NSNumberFormatter.
Apple docs on NSNumberFormatter


text:
Q: AngularJS Error using manifest.appcache Case 1: After event 'cached' comming from  window.applicationCache.addEventListener, i get my mobile using OFFLINE MODE(airplane mode i mean),then i open my webapp from HomeScreen icon and everything works fine, except AngularJS, that doesnt get loaded. None function or variable is recnognized.
Case 2: After event 'cached' comming from  window.applicationCache.addEventListener, i open my webapp from HomeScreen icon using ONLINE MODE, at this moment angular worked fine because its on correct view. BUT if i dont interact with webApp (Login for example), when i get offline mode, AngularJs get a error and not even the correct view is displayed anymore.
EDIT: I realized that if after cached event, i close web app, and then open it again, without interact, it will work fine in offline mode... How is it possible?
All the calls to Angular scripts are getting called from same page that im using <html manifest="manifest.appcache" type="text/cache-manifest">, why it wont work just after i send it to home screen?
I already tried couple workarounds.. none work!
Any help is appreciated
Above my manifest code:
CACHE MANIFEST

# Learn more:
# https://developer.mozilla.org/en-US/docs/Web/HTML/Using_the_application_cache

# -----------------------------------------------------------------------------

# It's necessary to tell web browsers to reconsider this manifest any time the
# website is updated, and you do so by changing *anything* inside the manifest.
# A common way to do this is by simply updating a commented-out string, like a
# date or a version number, or both:

# 2016-09-10:v1.122

# -----------------------------------------------------------------------------

# This is where you define all of the resources to be cached. Add new and/or
# remove old resourses as needed, keeping each one on its own line. Learn more:
# https://developer.mozilla.org/en-US/docs/Web/HTML/Using_the_application_cache#Explicit_entries
CACHE:
assets\js\jquery.min.js
assets\js\main.js
assets\js\skel.min.js
assets\js\util.js
assets\js\ie\html5shiv.js
assets\js\ie\respond.min.js
js\angular.min.js
js\angular-cookies.min.js
js\app\gmApp-controller.js
js\app\gmApp-factory.js
LICENSE.txt
assets\css\ie8.css
assets\css\ie9.css
assets\css\main.css
assets\fonts\FontAwesome.otf
assets\fonts\fontawesome-webfont.eot
assets\fonts\fontawesome-webfont.svg
assets\fonts\fontawesome-webfont.ttf
assets\fonts\fontawesome-webfont.woff
assets\fonts\fontawesome-webfont.woff2
assets\css\font-awesome.min.css
images\02.png
images\avatar.jpg
images\bg_login.jpg
images\favicon.png
images\fundo-bar.jpg
images\fundo-home.jpg
images\hotel-1.png
images\logo.jpg
images\pic01.jpg
images\pic02.jpg
images\pic03.jpg
images\pic04.jpg
images\pic05.jpg
images\pic06.jpg
images\pic07.jpg
images\pic08.jpg
images\pic09.jpg
images\pic10.jpg
images\pic11.jpg
images\pic12.jpg
images\cancun\chichen-tza.jpg
images\cancun\cirque-soleil.jpg
images\cancun\coco-bongo.jpg
images\cancun\haceienta-mortero.jpg
images\cancun\isla-mujeres.jpg
images\cancun\la-isla-shopping.jpg
images\cancun\navio-pirata.jpg
images\cancun\shopong-plaza.jpg
images\cancun\tulum.jpg
images\cancun\xcaret.jpg
images\cancun\xel-ha.jpg
images\dicas\dica1.jpg
images\dicas\dica2.png
images\dicas\dica3.jpg
images\dicas\dica3a.jpg
images\dicas\dica3b.jpg
images\dicas\dica3c.jpg
images\dicas\dica3d.jpg
images\dicas\dica3e.jpg
images\dicas\dica4.jpg
images\dicas\dica5.jpg
images\dicas\dica6.jpg
images\dicas\dica6a.jpg
images\dicas\dica6b.jpg
images\dicas\dica6c.jpg
images\dicas\dica7.jpg
images\dicas\dica7a.jpg
images\dicas\dica7b.jpg
images\dicas\dica7c.jpg
images\dicas\dica9.jpg
images\dicas\rodape.jpg
images\mini-menu\Cancun-42.jpg
images\mini-menu\chichen-tza.jpg
images\mini-menu\cirque-soleil.jpg
images\mini-menu\coco-bongo.jpg
images\mini-menu\haceienta-mortero.jpg
images\mini-menu\isla-mujeres.jpg
images\mini-menu\la-isla-shopping.jpg
images\mini-menu\navio-pirata.jpg
images\mini-menu\shopong-plaza.jpg
images\mini-menu\tulum.jpg
images\mini-menu\xcaret.jpg
images\mini-menu\xel-ha.jpg
index.html

# -----------------------------------------------------------------------------

# Resources that must be retrieved from the network. The wild card ensures any
# resource not listed in the cache above will instead be downloaded from the
# network. Learn more:
# https://developer.mozilla.org/en-US/docs/Web/HTML/Using_the_application_cache#Network_entries

NETWORK:
*

# -----------------------------------------------------------------------------

# Fallbacks. In each row, if the first resource isn't available, the second
# resource is requested. Uncomment and update as needed. Learn more:
# https://developer.mozilla.org/en-US/docs/Web/HTML/Using_the_application_cache#Fallback_entries

FALLBACK:
assets\fonts\FontAwesome.otf assets\fonts\FontAwesome.otf
assets\fonts\fontawesome-webfont.eot assets\fonts\fontawesome-webfont.eot
assets\fonts\fontawesome-webfont.svg assets\fonts\fontawesome-webfont.svg
assets\fonts\fontawesome-webfont.ttf assets\fonts\fontawesome-webfont.ttf
assets\fonts\fontawesome-webfont.woff assets\fonts\fontawesome-webfont.woff
assets\fonts\fontawesome-webfont.woff2 assets\fonts\fontawesome-webfont.woff2
js\angular.min.js js\angular.min.js
js\angular-cookies.min.js js\angular-cookies.min.js

Detail: all these fallback links are already 'work-arounds' im trying to get everything works fine at 'Add to home screen' event

A: After a while i realized that it was a css reference inside .css files. After add that references into manifest everything works like a charm

redpajama_set_name: RedPajamaStackExchange


text:
Q: Asus PH GeForce gtx 1050ti Video Card and Intel UHD Graphics 630 Integrated Card I have searched everywhere but I was not able to find a specific answer to my problem. This is my first post, so please be gentle :) Thanks in advance.
The two video cards mentioned in the title are on my Desktop. I have two LG monitors, one is plugged with Asus 1050ti and the other LG monitor is plugged with Intel UHD 630, and both through their HDMI connections. Once I have installed Ubuntu 18.04, these two monitors were working in parallel (as extended monitor) with the above mentioned connection method. When I installed NVIDIA Driver, things started to get awkward. Now, I can only get one monitor working at a time, while switching between intel and nvidia Prime options.
However, on windows 10, which I installed along with Ubuntu 18.04, there are no issues and both monitor with the above-mentioned connection method are working like a charm.
So the question: How can I get the dual-monitors worked, while they are connected to different video card (mentioned in the title) outputs through HDMIs on both end?
I really need help! Thank you!
  -lshw -c video:
  *-display
       description: VGA compatible controller
       product: GP107 [GeForce GTX 1050 Ti]
       vendor: NVIDIA Corporation
       physical id: 0
       bus info: pci@0000:01:00.0
       version: a1
       width: 64 bits
       clock: 33MHz
       capabilities: pm msi pciexpress vga_controller bus_master cap_list rom
       configuration: driver=nvidia latency=0
       resources: irq:127 memory:a3000000-a3ffffff memory:90000000-9fffffff memory:a0000000-a1ffffff ioport:4000(size=128) memory:a4000000-a407ffff
  *-display
       description: VGA compatible controller
       product: Intel Corporation
       vendor: Intel Corporation
       physical id: 2
       bus info: pci@0000:00:02.0
       version: 00
       width: 64 bits
       clock: 33MHz
       capabilities: pciexpress msi pm vga_controller bus_master cap_list rom
       configuration: driver=i915 latency=0
       resources: irq:124 memory:a2000000-a2ffffff memory:80000000-8fffffff ioport:5000(size=64) memory:c0000-dffff

A: So here is my solution.
Uninstall any manually installed NVIDIA drivers.
Then reboot and reinstall using Software & Updates. But here, there is a very important thing to do.
ONLY CHOOSE and old version of NVIDIA DRIVER. In my case, nvidia-driver-390 did the trick.
Thank you anyways. My first question it was and not it is the first response from myself. But this could really help to many others.


text:
Q: How to set font size, family and colour of listview in ASP.NET (C#) So I have the following ListView1
[asp.net]
 <asp:ListView ID="ListView1" runat="server" DataSourceID="SqlDataSource1"
            onprerender="ListView1_PreRender"
            onselectedindexchanged="ListView1_SelectedIndexChanged">

To which I have tried to set the following properties through CSS
[css]
#ListView1
{
    color: White;
    font-family: Calibri;
}

But that did not work for some reason.

A: You could set the ClientIdMode to static to ensure that the ID of the server control doesn't change when it is rendered as html even if it is in a container or a master page.
 <asp:ListView ID="ListView1" runat="server" DataSourceID="SqlDataSource1"
            onprerender="ListView1_PreRender"
            onselectedindexchanged="ListView1_SelectedIndexChanged" ClientIdMode="Static">

A: you can try the CssClass property
.ListView1
{
    color: White;
    font-family: Calibri;
}

and then use it as
<asp:ListView ID="ListView1" runat="server" DataSourceID="SqlDataSource1"
            onprerender="ListView1_PreRender"  CssClass= "ListView1"
            onselectedindexchanged="ListView1_SelectedIndexChanged">

You can style it more better if you use the ItemTemplate / LayoutTemplate as shown here

A: runat='server' will change element IDs often times, appending the name of the class of the page. You can do two things to fix the issue:
1) Change the name of the ID selector in CSS to match what the ID is altered to be (which you figure out by doing a view source on the rendered page).
2) Apply a class to the element instead of using the ID.
The second one is probably better, as you can reuse that class on other pages without changing any CSS, and it's a bit more straightforward.


text:
Q: jQuery FadeIn Delay Issue I'm having trouble figuring out what is causing my issue. If you go to my site and choose a random plant. Lets say for example you click Vegetables and then Bean Bush Plant there is a 3 second delay and then the grass image fades in. This will only happen if you reload the page and start from the beginning. Once the grass fades in and you hit the back button in the webpage (not the web browser back button) and click any plant there is not delay issue. The 3 second delay only happens after you reload the page. Can anyone tell me why this is occurring? Here's the site:
http://andrewhnovak.com/Botany/index.html#

A: This happens because in your home.js file you have an initial 5 seconds fade in for the grass
$("#grass").fadeTo(5000, 8);
$("#grass1").fadeTo(5000, 8);

So if you move quickly before it has faded in, you have to wait until it completes its fade.


text:
Q: Dragging with inertia in AS3 for dummies I'm trying to create an inertia effect for dragging that's constricted to the x axis. I know this questions was asked before here but I couldn't understand the answer!
I'm currently using startDrag and stopDrag. I'm assuming I should add something to the startDrag function that captures the speed in which the user is moving the mouse, but I'm not sure how this is done. I guess then I'd add something to the stopDrag function that kicks in and makes the object keep moving at that speed and then come to a stop.
Any suggestions?

A: I've found an grat online tutorial that has the answer. I was a matter of tinkering with the code. The writer even has .fla files for download.
http://www.quasiuseful.com/?id=11


text:
Q: For what values of $n$ do more than two thirds of subsets of $[n]$ have size beteen $\frac{n}{3}$ and $\frac{2n}{3}$ My actual problem is slightly different.
For what values of $n$ do we have:
$2\sum_{i=1}^{\lfloor n/3 \rfloor}\binom{n}{i}\geq \sum\limits_{i=\lfloor n/3 \rfloor+1}^{\lceil n/2 \rceil-1} \binom{n}{i}$?
I haven't taken any probability theory yet, so I am not sure, I think we have to do some approximations using the binomial distribution curve. I think that for large values of $n$ say $n>10$ it won't hold, but i'm not sure what tools to use.

Edit: the following c++ program checks for all integers between $1$ and $50$:
#include <cstdio>
long long B[50][50];

int main(){
    for(int i=0;i<50;i++){
        B[i][0]=1;
    }
    for(int i=1;i<50;i++){
        for(int j=1;j<50;j++){
            B[i][j]=B[i-1][j]+B[i-1][j-1];
        }
    }
    for(int i=1;i<50;i++){
        long long sum1=0;
        for(int j=1;j<=i/3;j++){
            sum1+=B[i][j];
        }
        long long sum2=0;
        for(int j=i/3+1;2*j<i;j++){
            sum2+=B[i][j];
        }
        if(2*sum1>=sum2){
            printf("%d\n",i);
        }
    }
}

It appears to work only for $1,2,3,4,5,6,7,8,9,10,12$. So now we need to prove it is never true for $n>50$


text:
Q: How To Change IMG Tag src Based Drop Down Menu and Date? Suppose that i have 20 IMG Tags Which Remain Same But I Wanted to add a funcnalty where a user can select the city and date after selecting the city & date all image src changed according to user input.
Here is my img tags looks like:

I created a form like this:
Form for user input
Here dl is the city code.
-: Select Your City :-

<form action="" method="POST">
<select name="city">
<option value="">Select city...</option>
<option value="dl" selected>Delhi</option>
<option value="mb">Mumbai</option>
<option value="bl">Banglore</option>
<option value="hy">Hyderabad</option>
<option value="ch">Chennai</option>
<option value="ch">Kolkata</option>
</select>

Select Date :-

<input type="date" name="old" value="2023-01-08" min="2015-01-01" max="2023-01-08" required />

<input type="submit" value="Go" />
</form>

The default city should be Delhi & Date should be currnt date.

A: To change imagesource like you want you'll have to use javascript. and make the date dynamic:
const today = new Date();
const year = today.getFullYear();
const month = String(today.getMonth() + 1).padStart(2, '0');
const day = String(today.getDate()).padStart(2, '0');

// Get the form elements
const form = document.querySelector('form');
const citySelect = form.querySelector('select[name="city"]');
const dateInput = document.querySelector('input[type="date"]');
dateInput.value = `${year}-${month}-${day}`;
dateInput.max = `${year}-${month}-${day}`;

// Add an event listener to the form that will run a function
// when the form is submitted
form.addEventListener('submit', (event) => {
    // Prevent the form from submitting and refreshing the page
    event.preventDefault();

    // Get the selected city and date values
    const city = citySelect.value;
    const date = dateInput.value;

    // Get all the img elements
    const images = document.querySelectorAll('img');

    // Update the src attribute of each img element
    images.forEach((image, index) => {
        const imageNumber = String(index + 1).padStart(2, '0');
        image.src = `https://www.example.com/${date}/${city}/${imageNumber}/image.jpg`;
        image.alt = `image nr:${index+1}of ${city} on ${date}`;
    });
});

And the date input should just be changed to this:
<input type="date" name="old" min="2015-01-01" required />

Not sure what you want to achieve with this code but this does what you requested


text:
Q: Wordpress, can't get advanced custom fields plugin to work I tried following the instruction s but can't get the plugin to work, the fields show in admin and i upload images with them but when I publish and view the post no images show. Do I need to add something to template files for this to show?

A: Yes, you need to add:
<?php the_field('field_name'); ?>

Check ACF docs: http://www.advancedcustomfields.com/docs/code-examples/

A: Reading from the producer's page they state that for images/files their API returns a URL.
That might mean that the plug-in is not integrated with the native file handling functions. And you might need to use their template tags like <img src="<?php the_field('name') ?>" />.
file: public_html/wp-content/themes/theme_name/category.php

somewhere after this
<?php if ( have_posts() ) : ?>
    <?php while ( have_posts() ) : the_post(); ?>
        <img src="<?php the_field('name') ?>" />
        ...


text:
Q: Guardar imagen obtenida de una respuesta get Estoy haciendo una peticion GET a un servicio para traer una imagen. Usando la libreria axios desde NodeJS.
axios
  .get("RUTA_DE_LA_IMAGEN")
  .then(res => {
    /*Como guardar la imagen obtenida*/
  })
  .catch(err => {
    console.log("err");
  });

Me pregunto como puedo guargar la imagen obtenida en la respuesta en mi sistema de ficheros, con una ruta indicada y nombre personalizado.
Supongo que tendra algo que ver con el modulo fs de node, pero no logre encontrar nada.

A: ¿La imagen que obtienes con axios la deseas guardar localmente, o deseas mandarla a otro lugar mediante otra api?
Lo imagino de esta forma , ya que es muy poco codigo el que proporcionas.
var path = require('path');

axios
  .get("RUTA_DE_LA_IMAGEN")
  .then(res => {
    var staticBasePath = './RUTA_TUYA'; //images
    var resolvedBase = path.resolve(staticBasePath);
    var fileloc = path.join(resolveBase,res.data.image);
    res.statusCode = 200;
    res.write(fileloc);
    return res.end();

  })
  .catch(err => {
    console.log("err");
  });


text:
Q: PowerMockito With Singleton class with laziLoading I have a singleton class as mentioned below. Need to write down a Junit
class PanCryptoService{

 public PanCryptoService() {
    }

    public static synchronized PanCryptoService getClassInstance() {
        if (panCryptoService != null) return panCryptoService;
        PanCryptoService panCryptoServiceInstance = panCryptoService;
        if (panCryptoService == null) {
            panCryptoServiceInstance = panCryptoService = new PanCryptoService();
            return panCryptoServiceInstance;
        }
        return null;
    }

    }

I am using power Mockito to write Junit. below testcase I have write down but it is not cover the code coverage.
public class PanCryptoServiceTest {
@Before
    public void setup() {
        try {
            panCryptoService = Whitebox.invokeConstructor(PanCryptoService.class);
        } catch (Exception e) {
            fail(e.getMessage());
        }
    }
@Test
    public void shouldCheckTheSingleTonInstanceWorkingProperlyOrNot(){
        PowerMockito.mockStatic(PanCryptoService.class);
        when(PanCryptoService.getClassInstance()).thenReturn(panCryptoService);
        Assert.assertTrue(panCryptoService instanceof PanCryptoService);

    }
    }

The above test case working fine without exception. But it is not cover the code coverage.what should I do so it will come under test coverage
Please let me know


text:
Q: Conservation of energy for a planet I was reading Lectures by Feynman (which are soo good at any qualification!) and he talks about how energy of a particular planet in our solar system is constant at all times $ i.e, KE+PE= constant.$
But what if a rogue planet appears all of a sudden and, let's say, kicks out Mars from it's orbit and from the solar system. $(imagine!)$
Now the total energy of Mars is not the same as it was before. Am I missing out on something? (which I believe I do!)

A: You've added a new planet to the solar system.  You have to add the kinetic and potential energies of that object to the rest of the solar system.  If you consider that enlarged solar system, you would find that KE + PE remains constant.
One troubling word in your question is "all of a sudden".   One interpretation of that is the new planet appeared from nothing.  That it was brought into existence suddenly.  That is unphysical.  Applying physics to unphysical situations leads to "solutions" that are meaningless.


text: Q: Creating an Object in AWS S3 using Go Language i want to create an object (file) in my s3 bucket using Go Language, i've read the API Reference and search it on google but all of them just uploading the file, no one using the method create a new object and fill it body with base64 encoded (for image), if someone can help me with this? i've done it with PHP but now im using Go Language


text:
Q: How to set affinity on multiple cpu cores of a single CPU not on Multiple CPUs? I am currently working in C multi-threading on server having multiple hexa-core cpus. I want to set affinity of some of my threads to respective cores of a single CPU. I have used pthread_setaffinity_np() and also  sched_setaffinity() but i guess the set affinity on the cpus not the cores. am I right?

A: pthread_setaffinity_np() et al operate in terms of logical CPUs (i.e. cores), not physical ones (i.e. CPU sockets).


text:
Q: onLoadFinished is not called properly from ContentProvider I have two different SimpleCursorAdapters and linked ListViews in MainActivity. Initializing them with:
getLoaderManager().initLoader(0, null, this);
getLoaderManager().initLoader(2, null, this);

After initialization, both loaders are created and ran queries on ContentProvider with correctly returned data.
LoaderManager implementations:
@Override
    public Loader<Cursor> onCreateLoader(int id, Bundle args) {
        CursorLoader loader = null;

        switch (id) {
            case 0:
                loader = new CursorLoader(this,
                        DataProvider.CONTENT_URI_PROFILE_Match,
                        new String[]{DataProvider.COL_ID, DataProvider.COL_MATCH_NAME, DataProvider.COL_COUNT, DataProvider.COL_MATCH_PROFILE_IMAGE, DataProvider.COL_MATCH_BIRTH_DATE},
                        null,
                        null,
                        DataProvider.COL_ID + " DESC");
                break;
            case 2:
                loader = new CursorLoader(this,
                        DataProvider.CONTENT_URI_PROFILE_Trash,
                        new String[]{DataProvider.COL_ID, DataProvider.COL_MATCH_NAME, DataProvider.COL_EXPIRATION_STATUS, DataProvider.COL_MATCH_PROFILE_IMAGE, DataProvider.COL_MATCH_BIRTH_DATE},
                        null,
                        null,
                        DataProvider.COL_ID + " DESC");
                break;
        }
        return loader;
    }

    @Override
    public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
        switch (loader.getId()) {
            case 0:
                adapterMatch.swapCursor(data);
                break;
            case 2:
                adapterTrash.swapCursor(data);
                break;
        }
    }

The app works as follow. when receiving a message from server on BroadCastReceiver, below part of code will run on Receiver class and insert a row in db via ContentProvider
ContentValues values = new ContentValues(5);
                    values.put(DataProvider.COL_MATCH_ID, matchedUser);
                    values.put(DataProvider.COL_EXPIRATION_STATUS, expirationStatus);
                    values.put(DataProvider.COL_MATCH_NAME, matchName);
                    values.put(DataProvider.COL_MATCH_BIRTH_DATE, matchBirthDate);
                    values.put(DataProvider.COL_MATCH_PROFILE_IMAGE, matchProfileImage);
                    context.getContentResolver().insert(DataProvider.CONTENT_URI_PROFILE_Match, values);

My problem is after inserting new values received from server to SQLite database, cursor data is not passed to MainActivity, so not updating the UI until next time Activity is created.
Below is the highlighted codes from my ContentProvider :
public static final Uri CONTENT_URI_MESSAGES = Uri.parse("content://com.example.vcc4.mashroom.provider/messages");
    public static final Uri CONTENT_URI_PROFILE = Uri.parse("content://com.example.vcc4.mashroom.provider/profile");
    public static final Uri CONTENT_URI_PROFILE_Match = Uri.parse("content://com.example.vcc4.mashroom.provider/match");
    public static final Uri CONTENT_URI_PROFILE_Trash = Uri.parse("content://com.example.vcc4.mashroom.provider/trash");

private static final UriMatcher uriMatcher;
    static {
        uriMatcher = new UriMatcher(UriMatcher.NO_MATCH);
        uriMatcher.addURI("com.example.vcc4.mashroom.provider", "messages", MESSAGES_ALLROWS);
        uriMatcher.addURI("com.example.vcc4.mashroom.provider", "messages/#", MESSAGES_SINGLE_ROW);
        uriMatcher.addURI("com.example.vcc4.mashroom.provider", "profile", PROFILE_ALLROWS);
        uriMatcher.addURI("com.example.vcc4.mashroom.provider", "profile/#", PROFILE_SINGLE_ROW);
        uriMatcher.addURI("com.example.vcc4.mashroom.provider", "match", PROFILE_AllROWS_MATCH);
        uriMatcher.addURI("com.example.vcc4.mashroom.provider", "match/#", PROFILE_SINGLE_ROWS_MATCH);
        uriMatcher.addURI("com.example.vcc4.mashroom.provider", "trash", PROFILE_ALLROWS_TRASH);
    }

@Override
    public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) {
        SQLiteDatabase db = dbHelper.getReadableDatabase();
        SQLiteQueryBuilder qb = new SQLiteQueryBuilder();

        switch(uriMatcher.match(uri)) {
        case MESSAGES_ALLROWS:
            qb.setTables(TABLE_MESSAGES);
            break;

        case MESSAGES_SINGLE_ROW:
            qb.setTables(TABLE_MESSAGES);
            qb.appendWhere("_id = " + uri.getLastPathSegment());
            break;

        case PROFILE_ALLROWS:
            qb.setTables(TABLE_PROFILE);
            break;

        case PROFILE_SINGLE_ROW:
            qb.setTables(TABLE_PROFILE);
            qb.appendWhere("_id = " + uri.getLastPathSegment());
            break;

        case PROFILE_AllROWS_MATCH:
            qb.setTables(TABLE_PROFILE);
            qb.appendWhere(COL_EXPIRATION_STATUS + " = " + "'wait'" + " OR " + COL_EXPIRATION_STATUS + " = " + "'active'");
            break;

        case PROFILE_ALLROWS_TRASH:
            qb.setTables(TABLE_PROFILE);
            qb.appendWhere(COL_EXPIRATION_STATUS + " = " + "'expired'");
            break;

        default:
            throw new IllegalArgumentException("Unsupported URI: " + uri);
        }

        Cursor c = qb.query(db, projection, selection, selectionArgs, null, null, sortOrder);
        c.setNotificationUri(getContext().getContentResolver(), uri);
        return c;
    }

@Override
    public Uri insert(Uri uri, ContentValues values) {
        SQLiteDatabase db = dbHelper.getWritableDatabase();

        long id;
        switch(uriMatcher.match(uri)) {
        case MESSAGES_ALLROWS:
            id = db.insertOrThrow(TABLE_MESSAGES, null, values);
            if (values.get(COL_TO) == null) {
                db.execSQL("update profile set count = count+1 where email = ?", new Object[]{values.get(COL_FROM)});
                getContext().getContentResolver().notifyChange(CONTENT_URI_PROFILE, null);
            }
            break;

        case PROFILE_ALLROWS:
            id = db.insertOrThrow(TABLE_PROFILE, null, values);
            break;

        case PROFILE_AllROWS_MATCH:
            id = db.insertOrThrow(TABLE_PROFILE, null, values);
            break;

        default:
            throw new IllegalArgumentException("Unsupported URI: " + uri);
        }

        Uri insertUri = ContentUris.withAppendedId(uri, id);
        getContext().getContentResolver().notifyChange(insertUri, null);

        return insertUri;
    }

I've searched many SO questions and android resources, but cannot find any clue to solve this problem. Any solutions please?
Edit: below added the codes for setting up SimpleCursorAdapters:
adapterMatch = new SimpleCursorAdapter(this,
                R.layout.main_list_item,
                null,
                new String[]{DataProvider.COL_MATCH_PROFILE_IMAGE, DataProvider.COL_MATCH_NAME, DataProvider.COL_MATCH_BIRTH_DATE, DataProvider.COL_COUNT, DataProvider.COL_MATCH_ID},
                new int[]{R.id.avatar, R.id.text1, R.id.text2, R.id.text3},
                0);
adapterWatch = new SimpleCursorAdapter(this,
                    R.layout.main_list_item,
                    null,
                    new String[]{DataProvider.COL_MATCH_PROFILE_IMAGE, DataProvider.COL_MATCH_NAME, DataProvider.COL_MATCH_BIRTH_DATE, DataProvider.COL_MUTUAL_ACTION, DataProvider.COL_EXPIRATION_STATUS, DataProvider.COL_MATCH_ID},
                    new int[]{R.id.avatar, R.id.text1, R.id.text2, R.id.text3},
                    0);
adapterTrash = new SimpleCursorAdapter(this,
                    R.layout.main_list_item,
                    null,
                    new String[]{DataProvider.COL_MATCH_PROFILE_IMAGE, DataProvider.COL_MATCH_NAME, DataProvider.COL_MATCH_BIRTH_DATE, DataProvider.COL_EXPIRATION_STATUS},
                    new int[]{R.id.avatar, R.id.text1, R.id.text2, R.id.text3},
                    0);

A: It may be nothing, but would you mind debugging and checking the value of the insertUri variable on the 4th last line of the insert method in your ContentProvider when a match is inserted?


text:
Q: Microstrategy - Ratio from Summary Report fields In a query I have a case statement that gives either of two values for Attend Interview - this is worked out from another field that gives one value for 3 different scenarios that actually mean attend = Y, one value covers not attend = N. So for example I have something like this in my output:
Unique_ID   New/Existing                 Attend_Interview
=========   ========================     ================
12554445    E                            Y
65766879    N                            N
53375654    N                            Y
44323224    E                            N
93656786    E                            Y

What I then do is put this into a summary grid in Microstrategy (MS) to work out the new/existing applications further broken down by Y/N for attend.
But I also want to find out the ratio of New Application Attend to New Application Not Attend, however can't do that in MS since I am using a crosstab summary report and therefore need to try and calculate in SQL if possible.
My summary looks something like this at the moment:
                  N                       E
       ======================  =========================
        **Y**           N         **Y**           N
      =========    ==========   =========     =========
         570           140         89            56

And I would like to work out the ratio of 570/89 but as I said I think I need to do something in SQL so that I can put this in to my summary report as these are not physical columns I can divide.
Many thanks in advance for any suggestions on how to create this ratio field or suggestions for rework what I am doing.
Using : SQL Server 2008 R2 Express and web version of MS

A: You can create two conditional metrics for Attend_Interview = Y and Attend_Interview = N cases, then you can calculate the ratio between these two metrics.
If you want to use these metrics in you in your crosstab report you should replace the Attend_Interview attribute with the metrics.


text:
Q: Spacing and fontsize from caption of longtable I have a problem with the longtables, they are not in the same format as the tables.
I don't fully understand the way it works.
The code is as follows:
\documentclass[
    12pt,               % tamanho da fonte
    a4paper,            % tamanho do papel.
    english,            % idioma adicional para hifenização
    brazil              % o último idioma é o principal do documento
    ]{abntex2}
\usepackage{float}
\usepackage{listings}
\usepackage{longtable}

\begin{document}
\selectlanguage{brazil}
\frenchspacing
\OnehalfSpacing
%%% Longtable
\begin{center}
    \ABNTEXfontereduzida
    \begin{longtable}{ p{.05\textwidth} p{.15\textwidth} p{.70\textwidth} }
    \caption{I want this to go up and have a space from the table and to change this font size}\\
    \toprule
    \textbf{Bit}       &
    \textbf{Nome}         &
    \textbf{Descrição} \\
    \endfirsthead
    \toprule
    \textbf{Bit}       &
    \textbf{Nome}         &
    \textbf{Descrição}
    \\
    \endhead
    \hline
    \multicolumn{3}{l}{Continua...}\\
    \endfoot
    \multicolumn{3}{c}{I want this to go down and have a space from the table}\\
    \endlastfoot
    \\
    15     &
    NACKMOD           &
    The text seems to be different as well. I think the font size is bigger
    \\
     14     &
     FREE           &
     Welcome to the website. If you're here, you're likely looking to find random words. Random Word Generator is the perfect tool to help you do this. While this tool isn't a word creator, it is a word generator that will generate random words for a variety of activities or uses.
    \\
    \\
    \bottomrule
    \end{longtable}
\end{center}

This is format I wanted the longtable to be.
%%%table
\begin{table}[H]
    \ABNTEXfontereduzida
    \caption{This is the font style and size I wanted}
    \begin{center}
    \begin{tabular}{@{}p{1cm}p{2cm}p{12cm}@{}}
        \toprule
        \textbf{Bit}       &
        \textbf{Nome}         &
        \textbf{Descrição}
        \\
        15     &
        NACKMOD           &
        The text seems to be different as well. I think the font size is smaller.
        \\
         14     &
         FREE           &
         Welcome to the website. If you're here, you're likely looking to find random words. Random Word Generator is the perfect tool to help you do this. While this tool isn't a word creator, it is a word generator that will generate random words for a variety of activities or uses.
        \\
        \\
        \bottomrule
    \end{tabular}
    \end{center}
    \fonte{This is the distance I wanted}
\end{table}
\end{document}

The results are:

I didn't find any example that had this spacing after the table and I don't know what to look for in \ABNTEXfontereduzida (which is the format I am looking for).

A: Using the class abntex2 abntex2.cls  (based on memoir)

(\ABNTEXfontereduzida is defined as  \footnotesize)
\documentclass[
12pt,               % tamanho da fonte
a4paper,            % tamanho do papel.
english,            % idioma adicional para hifenização
brazil              % o último idioma é o principal do documento
]{abntex2}
\usepackage{float}
\usepackage{listings}
\usepackage{longtable}

\begin{document}
    \selectlanguage{brazil}
    \frenchspacing
    \OnehalfSpacing
    %%% Longtable

    \begin{center}
        \captionnamefont{\normalfont\normalsize} % added <<<<<<<<<<<<<<<<<<
        \captiontitlefont{\normalfont\normalsize} % added <<<<<<<<<<<<<<<<<<
        \setlength{\belowcaptionskip}{20pt}% added <<<<<<<<<<<<<<<<<<
        \renewcommand{\baselinestretch}{1}\selectfont% added <<<<<<<<<<<<<<<<<<
        \ABNTEXfontereduzida
        \begin{longtable}{@{} p{.05\textwidth} p{.15\textwidth} p{.70\textwidth}@{} }
            \caption{I want this to go up and have a space from the  table}\\
            \toprule
            \textbf{Bit}       &
            \textbf{Nome}         &
            \textbf{Descrição} \\
            \endfirsthead
            \toprule
            \textbf{Bit}       &
            \textbf{Nome}         &
            \textbf{Descrição}
            \\
            \endhead
            \hline
            \multicolumn{3}{l}{Continua...}\\
            \endfoot%
            \multicolumn{3}{c}{I want this to go down and have a space from the table  \rule{0pt}{6ex}}\\% rule added <<<<<<<<<<<<<<<<<<
            \endlastfoot
            15     &
            NACKMOD           &
            The text seems to be different as well. I think the font size is bigger
            \\
            14     &
            FREE           &
            Welcome to the website. If you're here, you're likely looking to find random words. Random Word Generator is the perfect tool to help you do this. While this tool isn't a word creator, it is a word generator that will generate random words for a variety of activities or uses.
            \\ \\
            \bottomrule
        \end{longtable}
    \end{center}

    This is format I wanted the longtable to be.
    %%%table
    \begin{table}[H]
        \ABNTEXfontereduzida
        \caption{This is the font style and size I wanted}
        \begin{center}
            \begin{tabular}{@{}p{1cm}p{2cm}p{12cm}@{}}
                \toprule
                \textbf{Bit}       &
                \textbf{Nome}         &
                \textbf{Descrição}
                \\
                15     &
                NACKMOD           &
                The text seems to be different as well. I think the font size is smaller.
                \\
                14     &
                FREE           &
                Welcome to the website. If you're here, you're likely looking to find random words. Random Word Generator is the perfect tool to help you do this. While this tool isn't a word creator, it is a word generator that will generate random words for a variety of activities or uses.
                \\
                \\
                \bottomrule
            \end{tabular}
        \end{center}
        \fonte{This is the distance I wanted}
    \end{table}
\end{document}

The  \rule{0pt}{6ex} in the \endfoot allows to increase the vertical space.


text:
Q: Why is my macro not working? I want to make a macro that will take \testfunc{1,2,3}{4,5,6} and generate
\begin{bmatrix}
        1 & 2 & 3\\
        4 & 5 & 6
    \end{bmatrix}

Here's the code:
\def\testfunc#1{
    \ExplSyntaxOn
    \NewDocumentCommand \countItems { m } {
        \clist_count:N #1
    }
\ExplSyntaxOff
    \begin{bmatrix}
        \foreach #1 \do {
            \def\length{\countItems{##1}}
            \foreach \col [count=\i] in {##1} {
                \ifx\i\length
                \col
                \else
                \col &
                \fi
                \ifx&##1&  \else \\ \fi
            }
        }
    \end{bmatrix}
}

However, I keep getting Paragraph ended before \pgffor@@vars was complete., though if I add a new line before the \end{document} a lot more errors pop up.

A: It cannot work, because each \foreach cycle is processed in a group.
And you can't use #1 as the variable in \foreach.
It's much simpler: with \clist_use:nn you can insert a list of tokens (here &) between items.
\documentclass{article}
\usepackage{amsmath}

\ExplSyntaxOn

\NewDocumentCommand{\testfunc}{mm}
 {
  \begin{bmatrix}
  \clist_use:nn { #1 } { & } \\
  \clist_use:nn { #2 } { & }
  \end{bmatrix}
 }

\ExplSyntaxOff

\begin{document}

\[
\testfunc{1,2,3}{4,5,6}
\]

\end{document}

More generally
\documentclass{article}
\usepackage{amsmath}

\ExplSyntaxOn

\NewDocumentCommand{\testfunc}{m}
 {
  \begin{bmatrix}
  \tl_map_function:nN { #1 } \drownedsuccess_row:n
  \end{bmatrix}
 }

\cs_new:Nn \drownedsuccess_row:n
 {
  \clist_use:nn { #1 } { & } \\
 }

\ExplSyntaxOff

\begin{document}

\[
\testfunc{{1,2,3}{4,5,6}{7,8,9}}
\]

\end{document}

With a different syntax, you can use as many rows as you want.
\documentclass{article}
\usepackage{amsmath}

\ExplSyntaxOn

\NewDocumentCommand{\testfunc}{m}
 {
  \begin{bmatrix}
  \seq_set_split:Nnn \l_tmpa_seq { ; } { #1 }
  \seq_map_function:NN \l_tmpa_seq \drownedsuccess_row:n
  \end{bmatrix}
 }

\cs_new:Nn \drownedsuccess_row:n
 {
  \clist_use:nn { #1 } { & } \\
 }

\ExplSyntaxOff

\begin{document}

\[
\testfunc{1,2,3;4,5,6;7,8,9}
\]

\end{document}


text:
Q: How do you find this limit $\lim_{n\to +\infty} \int _{\frac{1}{n}}^{n} \frac{|\sin x|^n}{x^{\alpha}}\,dx $ I don't know how to solve the limit
$$\lim_{n\to +\infty} \int _{\frac{1}{n}}^{n} \frac{|\sin x|^n}{x^{\alpha}}\,dx $$
for each $\alpha>1$.
My attempt:
$\displaystyle f_n(x)=\frac{\chi_{[\frac{1}{n},n]}(x) |\sin x|^n}{x^{\alpha}}$
If $x>0$ : $0<|f_n(x)|<\frac{1}{x^\alpha}$ and $f_n \to 0 $ pointwise
$\lim_{n\to +\infty} \int _{\frac{1}{n}}^{n} \frac{|\sin x|^n}{x^{\alpha}}\,dx =\lim_{n\to +\infty} \int _{0}^{+\infty} \frac{|\sin x|^n}{x^{\alpha}}\,dx < \lim_{n\to +\infty} \int _{0}^{+\infty} \frac{1}{x^{\alpha}}\,dx $ but $\alpha>1$ !
Any help is appreciated :)

A: I think it should converge to zero if $\alpha>1/2$.
Very roughly, the $\sin^nx$ factor becomes $n/\pi$ spikes of width $1/\sqrt{n}$.  So the integral turns into $\frac1{\sqrt{n}}\sum_{k=1}^n k^{-\alpha}=O(n^{1/2-\alpha})$

A: Let be: $$f_n(x)=\chi_{[\frac{1}{n},1]}\frac{|sin(x)|^n}{x^\alpha}+\chi_{[1,n]}\frac{|sin(x)|^n}{x^\alpha}$$ and let be$$\chi_{[\frac{1}{n},1]}\frac{|sin(x)|^n}{x^\alpha}=g_n(x)$$ $$\chi_{[1,n]}\frac{|sin(x)|^n}{x^\alpha}=h_n(x)$$
so we have:
$$g_n(x)<\chi_{[0,1]}sin(1)^nn^\alpha\to0$$$$\int{\chi_{[0,1]}sin(1)^nn^\alpha}=sin(1)^nn^\alpha\to0=\int 0$$
and
$$h_n(x)<\frac{1}{x^\alpha}\chi_{[1,\infty]}$$
so for the first and second theorem of dominated convergence$$\lim\int{f_n}=\lim\int{g_n+h_n}=\lim(\int{g_n}+\int{h_n})=\int{\lim h_n}+\int{\lim g_n}=\int{\lim f_n}$$ so $$\lim \int{f_n}=0$$

A: Observe that
$$\lim_{n\to\infty}\frac{|\sin x|^n}{x^\alpha}=0$$
for almost every $x>0$. Indeed, the above limit is zero for every $x>0$ where $|\sin x|<1$, which is true except on $\{n+\frac\pi2\,:\,n\in\mathbb{N}\}$ which has measure zero. Our aim is then to use the dominated convergence theorem to show that
$$\lim_{n\to\infty}\int_{1/n}^n\frac{|\sin x|^n}{x^\alpha}\ dx=0.$$
It suffices now to find a suitable dominating function. If $x\in(0,1]$, then for all $n>\alpha$, $\frac{|\sin x|^n}{x^\alpha}\leq\frac{|\sin x|^\alpha}{x^\alpha}$. For $x>1$, note that $\frac{|\sin x|^n}{x^\alpha}\leq\frac1{x^\alpha}$. So if we set
$$g(x):=\begin{cases}
\frac{|\sin x|^\alpha}{x^\alpha}&\text{if }0<x\le1,\\
\frac1{x^\alpha}&\text{if }x>1
\end{cases}$$
we find that $\frac{|\sin x|^n}{x^\alpha}\le g(x)$ for all $x>0$ and $n>\alpha$ (note that it is acceptable for the dominating function to dominate all but finitely many of the functions). Note that $g$ is continuous on $(0,1)$ and $\lim_{x\to0^+}g(x)=1$, so there exists $M>0$ such that $g(x)\le M$ for all $x\in(0,1]$. Hence
$$\int_0^\infty g(x)\ dx=\int_0^1g(x)\ dx+\int_1^\infty\frac1{x^\alpha}\ dx\leq M+\frac1{\alpha-1}<\infty$$
and so the dominated convergence theorem applies, completing the proof.


text:
Q: What other possible issues could there be to getting my spring project running? I am trying to start my spring project and am getting the following error:
Error starting Tomcat context. Exception:
org.springframework.beans.factory.UnsatisfiedDependencyException. Message: Error creating
bean with name 'jwtRequestFilter': Unsatisfied dependency expressed through field
'userService'; nested exception is
org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with
name 'userService': Unsatisfied dependency expressed through field 'userRepository'; nested
exception is org.springframework.beans.factory.BeanCreationException: Error creating bean
with name 'userRepository': Cannot create inner bean '(inner bean)#cf199f9' of type
[org.springframework.orm.jpa.SharedEntityManagerCreator] while setting bean property
'entityManager'; nested exception is
org.springframework.beans.factory.BeanCreationException: Error creating bean with name
'(inner bean)#cf199f9': Cannot resolve reference to bean 'entityManagerFactory' while
setting constructor argument; nested exception is
org.springframework.beans.factory.BeanCreationException: Error creating bean with name
'entityManagerFactory' defined in class path resource
[org/springframework/boot/autoconfigure/orm/jpa/HibernateJpaConfiguration.class]: Invocation
of init method failed; nested exception is org.hibernate.service.spi.ServiceException:
Unable to create requested service [org.hibernate.engine.jdbc.env.spi.JdbcEnvironment]

userRepository:
package com.plearnit.website.config;

import java.io.IOException;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import com.plearnit.website.services.UserService;

import io.jsonwebtoken.ExpiredJwtException;

@Component
public class JwtRequestFilter extends OncePerRequestFilter {

@Autowired
private UserService userService;

@Autowired
private JwtTokenUtil jwtTokenUtil;

@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response,
FilterChain chain)
        throws ServletException, IOException {

    final String requestTokenHeader = request.getHeader("Authorization");

    String username = null;
    String jwtToken = null;
    // JWT Token is in the form "Bearer token". Remove Bearer word and get
    // only the Token
    if (requestTokenHeader != null && requestTokenHeader.startsWith("Bearer ")) {
        jwtToken = requestTokenHeader.substring(7);
        try {
            username = jwtTokenUtil.getUsernameFromToken(jwtToken);
        } catch (IllegalArgumentException e) {
            System.out.println("Unable to get JWT Token");
        } catch (ExpiredJwtException e) {
            System.out.println("JWT Token has expired");
        }
    } else {
        logger.warn("JWT Token does not begin with Bearer String");
    }

    // Once we get the token validate it.
    if (username != null && SecurityContextHolder.getContext().getAuthentication() == null)
{

        UserDetails userDetails = userService.loadUserByUsername(username);

        // if token is valid configure Spring Security to manually set
        // authentication
        if (jwtTokenUtil.validateToken(jwtToken, userDetails)) {

            UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken = new
UsernamePasswordAuthenticationToken(
                    userDetails, null, userDetails.getAuthorities());
            usernamePasswordAuthenticationToken
                    .setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
            // After setting the Authentication in the context, we specify
            // that the current user is authenticated. So it passes the
            // Spring Security Configurations successfully.

SecurityContextHolder.getContext().setAuthentication(usernamePasswordAuthenticationToken);
        }
    }
    chain.doFilter(request, response);
}

}

UserService:
package com.plearnit.website.services;

import java.util.ArrayList;
import java.util.Optional;

import javax.servlet.http.HttpServletRequest;

import com.plearnit.website.models.User;
import com.plearnit.website.config.JwtTokenUtil;
import com.plearnit.website.repositories.UserRepository;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

@Service
public class UserService implements UserDetailsService {

@Autowired
private UserRepository userRepository;
@Autowired
private PasswordEncoder bcryptEncoder;
@Autowired
private JwtTokenUtil jwtTokenUtil;
@Autowired
private HttpServletRequest request;

@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

    User user = userRepository.findByUsername(username);
    if (user == null) {
        throw new UsernameNotFoundException("User not found with username: " + username);
    }
    return new org.springframework.security.core.userdetails.User(user.getUsername(),
user.getPassword(),
            new ArrayList<>());
}

public User save(User user) {
    user.setPassword(bcryptEncoder.encode(user.getPassword()));
    return userRepository.save(user);
}

public User loadCurrentUser(){
    String token = request.getHeader("Authorization").replace("Bearer ", "");
    return userRepository.findByUsername(jwtTokenUtil.getUsernameFromToken(token));
}

public Optional<User> findById (Integer id) {
    return userRepository.findById(id);
}
}

UserRepository:
package com.plearnit.website.repositories;

import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;

import com.plearnit.website.models.User;

@Repository
public interface UserRepository extends CrudRepository<User, Integer> {
    User findByUsername(String username);
}

User:
package com.plearnit.website.models;

import com.fasterxml.jackson.annotation.JsonIgnore;

import lombok.Data;

import java.util.Date;

import javax.persistence.*;

@Entity
@Table(name = "user")
@Data
public class User {

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
@Column
private String username;
@Column
@JsonIgnore
private String password;
@Column(updatable=false)
private Date createdAt;
private Date updatedAt;

@PrePersist
protected void onCreate(){
    this.createdAt = new Date();
}
@PreUpdate
protected void onUpdate(){
    this.updatedAt = new Date();
}
}

Related dependencies:
<dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-jpa</artifactId>
    </dependency>

Things I've tried:

*

*Make sure MySQL is running

*Confirmed MySQL Credentials

*Compared my files against my Github repository (no changes)

*Made sure dependencies were included in pom.xml

*Added Lombok @NoArgsConstructor to user model

*Searched SO for 2 hours

Seems it might be something outside my project, but I cannot figure out what else could be the issue.
Where else can I look for a source to this error beyond where I've looked so far?
Update -
Turns out I wasn't scrolling up enough on the errors to see there was a complaint related to the timezone on the DB. Not sure why, but all of a sudden, after months of working, that the timezone needed to be specified in the DB initialization  string.

A: If I am not mistaken, Entity should have a separate empty constructor. And one more constructor with data, which comes from request.


text:
Q: What is this statement mean "It is connected but not path-connected." What is this statement mean "It is connected but not path-connected."
For example. topologist's sine curve is one of the example.

A: Let $X$ be a topological space.  To say that $X$ is connected is to say that there are no (non-empty) open sets $U,V\subset X$ such that $U\cap V=\emptyset$ and $U\cup V=X$.
To say that $X$ is path-connected is to say that for every pair of points $x,y\in X$, there exists a continuous map $\varphi: [0,1]\rightarrow X$ such that $\varphi(0)=x$ and $\varphi(1)=y$.
As you point out, the topologists' sine curve is one of the typical examples to exhibit that being connected need not imply path-connectedness, though the converse does hold: path-connectedness always implies connectedness.


text:
Q: Issue with Object.keys() I am having issue with Object.keys(arrayOfFigures[i]) returning empty array. Despite I am seeing in the debbuger that arrayOfFigures[i] is an instance of a class and has all properties and values for the specific class.
Basically I have a classes for Geometric figures that store the properties and functions for each figure type.
I also have class for reading user input and rendering the Geometric figures on canvas. The issue is with a function in the rendering class where I need all properties of a rendered instance of Geometric Figure to be displayed in a separate div on the index.html page.
I also tried to use (for in) loop but with no result. Also I suspected the issue might be I am using WeakMaps to hide the properties, so I decided to try to implement a function not in the class that is rendering the Geometry, but in the Geometric Figure class itself - same result. I feel I am missing something very basic for JS behavior of classes and enumerables and need to solve it before moving on to the next chapter...
Below are the classes for Geometric Figures (I have many more but all are descendants of class Shape and have the same functions(although functions have different implementation))
Classes for geometric figures:
pastebin.com/vsV4KbmR
This is the class for Geometry rendering:
https://pastebin.com/nkj60uyx
This is the function I have issues with
initializeAllFigures(){
    let infoDiv=document.getElementById('information')
    infoDiv.innerHTML=''
    infoDiv.innerText='Figures drawn:'
    for (let i in this.arrayOfFigures){
        let logParagraph = document.createElement('p');
        logParagraph.setAttribute("id", i);
        let arrayOfKeys=Object.keys(this.arrayOfFigures[i]);
        for (let j in arrayOfKeys){
            logParagraph.innerText+=`${arrayOfKeys[j]}: `
        }

        infoDiv.appendChild(logParagraph)
    }
    if (this.selectedFigure>=0){
        let domElement=document.getElementById(this.selectedFigure);
        domElement.style.color = '#ff0000'
    }

}

https://pastebin.com/NiV4EcbB
This is the repository with the whole API
https://github.com/nikolaydimov83/Javascript_OOP_Homeworks


text:
Q: Swift - is lazy var thread-safe? Maybe this question requires a bit of context.
I've been working on my persistence layer using Core Data and found out that Core Data isn't thread-safe and thus requires NSManagedObjectContext to be confined to each one thread only.
So my approach is to create custom background thread NSManagedObjectContext which executes fetching, saving etc, while also to create main thread NSManagedObjectContext which will be used to get NSManagedObject from fetched NSManagedObjectId and pass it to caller method.
By default, Xcode generates template code related to Core Data using lazy var for all NSManagedObjectContext, NSManagedObjectModel etc.
So my question is whether to
use the lazy var instantiation approach for creating NSManagedObjectContext, provided that lazy var initiates an object for each thread trying to access (not thread-safe?)
or
declare separate variables for NSManagedObjectContext in each thread and make all thread-related methods to reference two different NSManagedObjectContext provided that lazy var is thread-safe(?) and created only once when it is accessed regardless of thread.
Thank you in advance!
edit: Anyone who is struggling with Core Data concurrency issue, this article lays out a very nice design pattern to work with as pointed out by Aaron in the comment below!

A: From The Swift Programming Language: Properties:

If a property marked with the lazy modifier is accessed by multiple threads simultaneously and the property has not yet been initialized, there is no guarantee that the property will be initialized only once.

lazy var is not thread safe. You can use

*

*dispatch_once (runs once per lifetime of the app)

*a constant (let)

*the nested struct pattern (typically used for singletons)

for thread safety. (See this question for some examples.)
You could also employ your own locking using NSRecursiveLock but that's probably not as efficient as dispatch_once.


text:
Q: Using a fluent security custom policy with castle windsor I have Fluent Security setup (and working) to secure my controller actions and have used castle windsor to resolve everything (pretty much as shown in the castlewindsor-fluentsecurity project you can download). What I want to do now is create a custom policy that runs a query on our Active Directory. I've created a test policy that implements ISecurityPolicy but it doesn't have a default constructor since I need to inject the interface to access the AD. Here's the policy:-
 public class TestPolicy : ISecurityPolicy
{
    private readonly IQueryHandler<GetUserQuery, User> userQueryHandler;

    public TestPolicy(IQueryHandler<GetUserQuery, User> userQueryHandler)
    {
        this.userQueryHandler = userQueryHandler;
    }
    public PolicyResult Enforce(ISecurityContext context)
    {
        var adUser = userQueryHandler.Handle(new GetUserQuery());

        if (adUser.HasManager())
        {
            return PolicyResult.CreateSuccessResult(this);
        }
        return PolicyResult.CreateFailureResult(this, "Access denied!");
    }
}

The IQueryHandler is used elsewhere and resolves correctly.
I added the policy to the controller:-
configuration.For<Areas.People.Controllers.InfoController>().AddPolicy<TestPolicy>();

but when called this fails with:-
TestPolicy could not be loaded! Make sure the policy has an empty constructor or is registered in your IoC-container.
Now looking through the documentation it seems I'm missing the step where I tell the SecurityConfigurator that I'm using an IoC. The docs don't show a specific Castle Windsor example but I 'came up with':-
SecurityConfigurator.Configure(configuration => configuration.ResolveServicesUsing(type => _container.ResolveAll(type).Cast<object>()));

Well it doesn't work and it seems strange that the SecurityConfigurator requires the Castle Windsor container when by the time SecurityConfig.RegisterSecurityRules() is called I've pretty much finished with Castle Windsor.
Can anyone show me how I should be configuring Fluent Security in this instance?

A: OK - well I finally got it working:
In the SecurityConfigurator I have
configuration.ResolveServicesUsing(
                    type => container.ResolveAll(type).Cast<object>(),
                    type => container.Kernel.HasComponent(type) ? container.Resolve(type) : null
                    );
I changed the Controller policy to add an interface, rather than an actual policy:
configuration.For<Areas.People.Controllers.InfoController>().AddPolicy<ITestPolicy>();

The interface implements ISecurityPolicy:
    public interface ITestPolicy : ISecurityPolicy
{
}

And then the Interface can be wired up with Castle:
container.Register(Component.For<ITestPolicy>().ImplementedBy<TestPolicy>());

I think the custom policy examples at Fluent Docs could do with saying that you need to use a policy interface so that it can be resolved by CastleWindsor... (Unless I'm using it wrong!)


text:
Q: Javascript change CSS page with javascript buttons and save based on cookie All right, folks! Here is the basic gist of this question:
I wish to create a cookie on the user's computer called cursor with the value of yes by default. Then, I want to create two buttons on the home page. One of them will say "Change the cursor to default" and the other will say "Change cursor to new."
They would both modify the cursor cookie. If the cookie's value is set to yes, it will load the main CSS page. Otherwise, it will load an alternate CSS page.
Here is what I have attempted that doesn't seem to work:
In the head tags:
<link type="text/css" rel="stylesheet" href="http://example.com/main.css" />

In the body tags:

Another note is that I am using GoDaddy if that means anything.
I hope this is information is good enough. If not, please tell me so.
Thank you!
Update:
Thank you for all of your help, Akshay!
Using what you said and what I knew, here is the final code that worked for me.
document.getElementsByTagName("head")[0].setAttribute("id", "linkcss");
Hellocookie();

function Hellocookie() {
   var curcookie = getCookie("cursor");
   if (curcookie === null) {
      curcookie = "";
   }
   if (curcookie === "no") {
      changecss2();
   }
   else {
      changecss1();
   }
}

function getCookie(cname) {
   var name = cname + "=";
   var ca = document.cookie.split(';');
   for(var i=0; i<ca.length; i++) {
      var c = ca[i];
      while (c.charAt(0)==' ') c = c.substring(1);
      if (c.indexOf(name) === 0) return c.substring(name.length,c.length);
   }
   return "";
}

function changecss1() {
   document.getElementById("linkcss").innerHTML += ('<link rel="stylesheet" type="text/css" href="http://example.com/firstcss.css">');
}

function changecss2() {
   document.getElementById("linkcss").innerHTML += ('<link rel="stylesheet" type="text/css" href="http://example.com/secondcss.css">');
}

As for the buttons:

A: Your javascript code is badly formatted.
You are not closing your brackets, and you are writing onload twice. That's why your code won't work. And your are using double qutoes in place of single quotes here.
onclick=\"document.cookie = \"cursor=no\"\""

But you should use.
onclick=\'document.cookie=\"cursor=no\"'

Here's the proper code.
<link type="text/css" rel="stylesheet" href="http://example.com/main.css" />

For the body tag:

Working fiddle


text:
Q: Optional spaces between multiple layout renderers? I think I must be missing something extremely obvious here but furious doc reading and googling has failed me. I have the following layout for a file name:
<target name="asyncLogFile" xsi:type="AsyncWrapper" queueLimit="5000" overflowAction="Discard" >
      <target name="mainLogFile" xsi:type="File" fileName="logs/${mdlc:item=GameServer:whenEmpty=Main} ${mdlc:item=Controller}.log"
              layout="${longdate} ${level:uppercase=true} | ${logger} | ${message} ${exception:format=toString,Data:maxInnerExceptionLevel=3}" />
    </target>

The MDLC items can both be null, in the games of the GameServer it gets replaced with "Main" and the Controller doesn't matter (If the GameServer is null then the Controller will be null).
However this means that if GameServer is null I end up with
Main .log Because of the space I have between the two mdlc entries. How can I make that space optional as part of the GameServer mldc entry!? I have looked at :pad to add a space after the  but that doesn't seem to work. I have tried concatenating the mdlc's but that doesn't work.
I was expecting something simple you could add as an ambient property like :suffix but nothing like that exists.
Again I think I must be missing something basic here but it eludes me.

A: Ugly but this works
<target name="mainLogFile" xsi:type="File" fileName="logs/${when:when=length('${mdlc:item=GameServer}') > 0:inner=${mdlc:item=GameServer} ${mdlc:item=Controller}:else=Main}.log"

A: Same ugly, but faster because of less allocation:
    <variable name="GameServerLogFile" value="${when:when='${mdlc:item=GameServer}'=='':inner=Main:else=${mdlc:item=GameServer} ${mdlc:item=Controller}}" />

    <targets>
       <target name="mainLogFile" xsi:type="File" fileName="logs/${GameServerLogFile}.log" />
    </targets>

Better to compare against empty-string '', than to call length()-method.


text:
Q: How to display text on GTK label using two different fonts? I have a GTK label and I am displaying text on it in Arial Rounded Mt Bold by using following code:
PangoFontDescription *df;
df = pango_font_description_new ();
pango_font_description_set_family(df,"Arial Rounded Mt Bold");
pango_font_description_set_size(df,fontsize*PANGO_SCALE);
gtk_widget_modify_font(Message_Label, df);
gtk_label_set_text(GTK_LABEL(Label), "Hello World");
pango_font_description_free (df);

Now this Hello World is displayed in Arial Rounded Mt Bold. But what if I want to display Hello in Arial Rounded Mt Bold and World in some other font for example Arial. Is this possible in GTK label. I am doing it in C. Any advice or any useful links. Thanks.

A: gtk_widget_modify_font() is deprecated and won't let you do what you want.
You can use a PangoAttrList, which combines attributes (including the individual components of a PangoFontDescriptor) over ranges of text. For instance:
PangoAttrList *attrlist;
PangoAttribute *attr;
PangoFontDescription *df;

attrlist = pango_attr_list_new();

// First, let's set up the base attributes.
// This part is copied from your code (and slightly bugfixed and reformatted):
df = pango_font_description_new();
pango_font_description_set_family(df, "Arial Rounded MT");
pango_font_description_set_size(df, fontsize * PANGO_SCALE);
pango_font_description_set_weight(df, PANGO_WEIGHT_BOLD);
// You can also use pango_font_description_new_from_string() and pass in a string like "Arial Rounded MT Bold (whatever fontsize is)".
// But here's where things change:
attr = pango_attr_font_desc_new(df);
// This is not documented, but pango_attr_font_desc_new() makes a copy of df, so let's release ours:
pango_font_description_free(df);
// Pango and GTK+ use UTF-8, so our string is indexed between 0 and 11.
// Note that the end_index is exclusive!
attr->start_index = 0;
attr->end_index = 11;
pango_attr_list_insert(attrlist, attr);
// And pango_attr_list_insert() takes ownership of attr, so we don't free it ourselves.
// As an alternative to all that, you can have each component of the PangoFontDescriptor be its own attribute; see the PangoAttribute documentation page.

// And now the attribute for the word "World".
attr = pango_attr_family_new("Arial");
// "World" starts at 6 and ends at 11.
attr->start_index = 6;
attr->end_index = 11;
pango_attr_list_insert(attrlist, attr);

// And finally, give the GtkLabel our attribute list.
gtk_label_set_attributes(GTK_LABEL(Label), attrlist);
// And (IIRC this is not documented either) gtk_label_set_attributes() takes a reference on the attribute list, so we can remove ours.
pango_attr_list_unref(attrlist);

You can also use gtk_label_set_markup() to use an HTML-like markup language to set both text and styles in one go:
gtk_label_set_markup(GTK_LABEL(Label),
    "Hello World");
// Or even...
gtk_label_set_markup(GTK_LABEL(Label),
    "Hello World");


text:
Q: php validation for a beginner I've used html, css, javascript, and jQuery validation and I think I'm ready to load variables in php. My webpage has about 300 elements (20 text(area)s, 40 radio, and 250 check-boxes with only a few that are required.
I found this code for php validation and have 3 newbie questions:
<?php
// define variables and set to empty values
$name = $email = $gender = $comment = $website = "";

if ($_SERVER["REQUEST_METHOD"] == "POST") {
  $name = test_input($_POST["name"]);
  $email = test_input($_POST["email"]);
  $website = test_input($_POST["website"]);
  $comment = test_input($_POST["comment"]);
  $gender = test_input($_POST["gender"]);
}

function test_input($data) {
  $data = trim($data);
  $data = stripslashes($data);
  $data = htmlspecialchars($data);
  return $data;
}
?>

1-   Have I left out any important steps?
2-   Do only text(area)s need this kind of server validation or do I need to do this for the radio and checkboxes?
3-   Can null elements go through this cleaning process or do I have to test for and exclude null elements first?
Thanks, Dan

A: I'll start by stating this: You can never trust any user input. Never trust any user input. You should program with the view that each user accessing your form is doing so with malicious intent.(i.e. they want to hack your site)
1 Yes, you're leaving out important steps. You aren't preventing SQL Injection. (If you're saving the details to a database.). If you are saving it to a database, you're best to use libraries that are designed to protect you through proper use, like PDO or MySQLi Prepared Statements. It's actually rather simple to do:
try {
    $dbh = new PDO('mysql:host=localhost;dbname=test', $user, $pass);
    $dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

    $statement = $link->prepare("INSERT INTO testtable(`name`, `lastname`, `age`)
    VALUES(:fname, :sname, :age)");
    $statement->execute(array(
    "fname" => "Bob",
    "sname" => "Desaunois",
    "age" => "18"
));
} catch (PDOException $e) {
    print "Error!: " . $e->getMessage() . "<br/>";
    die();
}

Source
2 Yes you should make sure all, and I mean all user input is validated.

As you can see in the image above, it's not hard at all to change the checkbox values to what you want.
3 Why would you want to do it for null elements? Do you mean empty elements? It's always good to clean any and all user input, but if it's null theoretically you aren't going to use it, right?

A: I have made some changes based on some assumptions to address your concerns and questions. I am assuming that the "name" field is required so we will do a check to see if it is set. Also I am assuming you will be storing this data into a database. If so I have included some MYSQL to help with cleaning for storage into a MYSQL database.
<?php
// define variables and set to empty values
$name = $email = $gender = $comment = $website = "";

if (isset($_POST["name"])) {
  $name = test_input($_POST["name"]);
  $email = test_input($_POST["email"]);
  $website = test_input($_POST["website"]);
  $comment = test_input($_POST["comment"]);
  $gender = test_input($_POST["gender"]);
}
else
{
   // tell the user they missed something.
}

function test_input($data) {
  $data = trim($data);
  $data = stripslashes($data);
  $data = htmlspecialchars($data);
  $data = mysql_real_escape_string($data);
  return $data;
}
?>

To address your other questions, no you don't need to validate fields like check boxes and radio buttons, however, be aware that the user can post their own values to your form with Javascript turned off and thereby circumvent your Javascript checks for form validation. So anything you think the user might supply information for like a selection menu should be cleaned before storing into the database. You don't need to check for NULL values.


text:
Q: anchor link in Svelte app using page.js routing I have an anchor tag on a page in my Svelte app. The link to the anchor works on the page itself, but I can't link to the anchor from another page. And when I enter the URL with the anchor, the page doesn't scroll down. I need to be able to give people a link and have them go to a specific part of the page.
Here's the relevant code:

      go to anchor

        ... lots of lorem ipsum ...

anchor

And I have a REPL here: https://svelte.dev/repl/e651218bdb47455d9cafe8bff27c8d7b?version=3.24.0
I'm using page.js for my routing to components -- I haven't found anything specific about targeting anchor tags in the documentation.
Any help would be greatly appreciated.

A: You don't need JS for smooth scrolling, just add some CSS:
/* :global if in component */
:global(html) {
    scroll-behavior: smooth;
}

REPL
As for scroll on page load, that is an issue of client-side rendering. For SSR the CSS alone takes care of everything but if the element that should be scrolled to is added after the page is loaded, the scroll will not happen.
One way of dealing with that would be to add an onMount, ideally high up in the component hierarchy so it triggers after everything is mounted, which manually performs the scroll:
onMount(() => {
  const { hash } = document.location;
  const scrollTo = hash && document.getElementById(hash.slice(1));
  if (scrollTo)
    scrollTo.scrollIntoView();
});

(Some of that logic is from SvelteKit which does all that automatically.)


text:
Q: Velocity: "Lexical error" with JavaScript I'm developing a web application using Apache Velocity and encountered a lexical error that said "Lexical error, Encountered: "(" (40), after : "".
The error was brought about by codes that included "JavaScript" like the following.
<script>
  function getHelloWorld() {
    return "Hello World!";
  }
  $var = window;
  $var.alert(getHelloWorld());
</script>

Avoiding that error, I tried the code below and got a result as expected.
<script>
  $var = window;
  helloworld = "Hello World!";
  $var.alert(helloworld);
</script>

I wondered if you could tell me the reason as in detail as possible.
Thank you.
Takahiro,


text:
Q: Sample Java class to decrypt AES128 encryption Looking for some sample Java code that decrypts AES encrypted string. I'm trying to encrypt using Apex's Crypto class and decrypt using Java.

A: apex crypto uses AES(128/192/256)/CBC/PCKS5Padding. Any standard Cipher example from a java tutorial should do the job. Create the Cipher with the IV, create the SecretKey from your key and the AES strength and doFinal() on the encryption. Thats it.
Sorry abt the formatting. total n00b on these forums...
byte [] encBytes = ...; /* your enc string */
SecretKeySpec keySpec = new SecretKeySpec(key, "AES");
byte[] iv = ...; /* your IV */;
IvParameterSpec ivSpec = new IvParameterSpec(iv);
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
cipher.init(Cipher.DECRYPT_MODE, keySpec, ivSpec);
byte[] decBytes = cipher.doFinal(encBytes);
String decStr = new String(decBytes);

A: The easiest way is to use the Managed IV methods in crypto which will place the Initialization Vector on the front of your cipherText
So, for this Apex:
String clearText = 'the quick brown fox jumps over the lazy dog';
Blob key = EncodingUtil.base64Decode('mRMjHmlC1C+1L/Dkz8EJuw==');
Blob cipherText = Crypto.encryptWithManagedIV('AES128', key, Blob.valueOf(clearText));
String encodedCipherText = EncodingUtil.base64Encode(cipherText);
System.debug(encodedCipherText);

Here's the corresponding Java
import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import org.apache.commons.codec.binary.Base64;
import java.util.Arrays;

public class AESDecrypt {

    private static final String characterEncoding = "UTF-8";
    private static final String cipherTransformation = "AES/CBC/PKCS5Padding";
    private static final String aesEncryptionAlgorithm = "AES";

    public static byte[] decryptBase64EncodedWithManagedIV(String encryptedText, String key) throws Exception {
        byte[] cipherText = Base64.decodeBase64(encryptedText.getBytes());
        byte[] keyBytes = Base64.decodeBase64(key.getBytes());
        return decryptWithManagedIV(cipherText, keyBytes);
    }

    public static byte[] decryptWithManagedIV(byte[] cipherText, byte[] key) throws Exception{
        byte[] initialVector = Arrays.copyOfRange(cipherText,0,16);
        byte[] trimmedCipherText = Arrays.copyOfRange(cipherText,16,cipherText.length);
        return decrypt(trimmedCipherText, key, initialVector);
    }

    public static byte[] decrypt(byte[] cipherText, byte[] key, byte[] initialVector) throws Exception{
        Cipher cipher = Cipher.getInstance(cipherTransformation);
        SecretKeySpec secretKeySpecy = new SecretKeySpec(key, aesEncryptionAlgorithm);
        IvParameterSpec ivParameterSpec = new IvParameterSpec(initialVector);
        cipher.init(Cipher.DECRYPT_MODE, secretKeySpecy, ivParameterSpec);
        cipherText = cipher.doFinal(cipherText);
        return cipherText;
    }

    public static void main(String args[]) throws Exception{
        byte[] clearText = decryptBase64EncodedWithManagedIV("CERcUfcNbCAkVxklXVpMqko2FqhE12iU6eldQ9jpFPUl+uVQXKDCXxtfPQ1hwt9A5fIbt60kdVgyFhb2V40z7w==", "mRMjHmlC1C+1L/Dkz8EJuw==");
        System.out.println("ClearText:" + new String(clearText,characterEncoding));
    }

}


text:
Q: Scraping an element as it is stored in the database I'm in the process of scraping a website using python with scrapy for a univeristy assignment.
I came across an element on the website taht's supposed to hold a rating. The rating is shown as an integer, but I think it's stored as a decimal in the database.
Is there a way to get the rating as it's stored in the database? if so, what are the tools and concepts I need to learn to do it?
An example for a page I'm trying to scrape: https://www.old-games.org/games/bond (written in Hebrew).
That's the element I'm talking about:
rating element
and that's the html code:
7/10

The desired result is to get the actual value of "7" as it stored in the database, for example "7.32".
The website doesn't have an API for getting the information out of it.
I've tried to search on my own, but since I'm new to the field of web development/scraping I couldn't find any solution (probably because I don't know the terminology).

A: If you're scraping a website, you can't even know if there is a database, let alone what's in the database. For all you (or your code) can tell, there is someone sitting there typing out those ratings manually, or a function that generates them at random each time you access the page.
Another way of looking at it is if I asked you to tell me what the "real" rating was, where would you look? You can look on the displayed page; you can look in the HTML source, and in any JS, AJAX calls, etc. If you can find it in any of those, you can write a scraper for it; if you can't, you can't.
Imagine for a second that there was a special trick to read the database of any website in the world. Now you could go to Amazon and apply that trick to find the personal details of the people who left reviews, or of the suppliers who are selling marketplace items!
The owner of any website can choose what information to give you, and what to keep private. There's no way to force the website to tell you the private bits unless the person operating the site has accidentally left something available publicly that they intended to be private (and looking too hard for those mistakes may well be breaking the law).


text:
Q: SwiftUI @AppStorage doesn't refresh in a function I am trying to reload the data every .onAppear, but if I change the @AppStorage nearMeter's value in the SettingsView, it isn't updating the value in the reloadNearStops func and using the previous @AppStorage value.
    struct SettingsView: View {
        @AppStorage("nearMeter") var nearMeter: Int = 1
        @State var meters = ["100 m","200 m","400 m","500 m","750 m","1 km"]

    var body: some View {

    ………

                            Picker(selection: $nearMeter, label: HStack {
                                    Text(NSLocalizedString("near_stops_distance", comment: ""))
                            }) {
                                ForEach(0 ..< meters.count, id: \.self) {
                                        Text(meters[$0])
                                }
                            }}}

    struct FavouritesView: View {
 @AppStorage("nearMeter") var nearMeter: Int = 1

            func reloadNearStops(nearMeter: Int) {

                print(nearMeter)
                readNearStopsTimeTable.fetchTimeTable(nearMeter:        getLonLatSpan(nearMeter: nearMeter), lat: (locationManager.lastLocation?.coordinate.latitude)!, lon: (locationManager.lastLocation?.coordinate.longitude)!)
            }

            func getLonLatSpan(nearMeter: Int) -> Double {
                let meters = [100,200,400,500,750,1000]

                if nearMeter < meters.count {
                    return Double(meters[nearMeter]) * 0.00001
                }
                else {
                    return 0.001
                }
            }
        var body: some View {

    .....

        ……….
        .onAppear() {

                    if locationManager.lastLocation?.coordinate.longitude != nil {
                            if hasInternetConnection {
                                reloadNearStops(nearMeter: nearMeter)
                            }
                    }

        }}

A: AppStorage won't call a function but onChange can call a function when AppStorage has changed.
struct StorageFunctionView: View {
    @AppStorage("nearMeter") var nearMeter: Int = 1
    @State var text: String = ""
    var body: some View {
        VStack{
            Text(text)
            Button("change-storage", action: {
                nearMeter = Int.random(in: 0...100)
            })
        }
        //This will listed for changes in AppStorage
        .onChange(of: nearMeter, perform: { newNearMeter in
            //Then call the function and if you need to pass the new value do it like this
            fetchSomething(value: newNearMeter)
        })
    }
    func fetchSomething(value: Int)  {
        text = "I'm fetching \(value)"
    }
}


text:
Q: Naming pandas columns with variables I have a list of tuples, which has all possible combinations of a dataframe's columns. I'd like to create new dataframe columns by combining these columns' values.
Example dataframe
d = {'c1':['a', 'b', 'c'], 'c2':['Low', 'Low', 'High'], 'c3':['True', 'True', 'False']}
dd = pd.DataFrame(data=d)

All possible columns combinations with length 2
from itertools import combinations
com = list(combinations(dd.columns, 2))

It returns[('c1', 'c2'), ('c1', 'c3'), ('c2', 'c3')]
I'd like to create new columns with the above combinations
For example, creating a combined column
dd['c1 + c2'] = dd['c1'] + '+' + dd['c2']
    c1  c2      c1 + c2
0   a   Low     a+Low
1   b   Low     b+Low
2   c   High    c+High

The real dataframe has many columns so I would like to automate the process by looping through the tuple list and use variables as dataframe's new column names.
Something like this:
[dd[f'dd[i[0]] + dd[i[1]]'] = dd[i[0]] + '+' + dd[i[1]] for i in com]

where dd[i[0]] = 'c1' and dd[i[1]] = 'c2'
I'm pretty sure I cannot use f-strings in dataframe columns but don't know how to make it work.

A: Just do
for i in com:
    dd[f'{i[0]} + {i[1]}']= dd[i[0]] + '+' + dd[i[1]]


text:
Q: How to mock aws timestream for unit test on python? I found on the net an example to test the aws timestream service; when I try to launch the test I get a NoRegionError
#test_timestream.py

import logging
from datetime import datetime
import pandas as pd
import awswrangler as wr
import logging
from datetime import datetime
import pandas as pd
import awswrangler as wr

logging.getLogger("awswrangler").setLevel(logging.DEBUG)

def test_basic_scenario(timestream_database_and_table):
    name = timestream_database_and_table
    df = pd.DataFrame(
       {
        "time": [datetime.now(), datetime.now(), datetime.now()],
        "dim0": ["foo", "boo", "bar"],
        "dim1": [1, 2, 3],
        "measure": [1.0, 1.1, 1.2],
       }
   )
   rejected_records = wr.timestream.write(
        df=df,
        database=name,
        table=name,
        time_col="time",
        measure_col="measure",
        dimensions_cols=["dim0", "dim1"],
   )
   assert len(rejected_records) == 0
   df = wr.timestream.query(
        f"""
          SELECT
             1 as col_int,
             try_cast(now() as time) as col_time,
             TRUE as col_bool,
             current_date as col_date,
             'foo' as col_str,
             measure_value::double,
             measure_name,
             time
             FROM "{name}"."{name}"
             ORDER BY time
             DESC LIMIT 10
        """
   )
   assert df.shape == (3, 8)

ERROR
enter image description here
how can the problem be solved? Since even the "moto" library does not offer the mock of the aws service ?

A: If you look at the AWS DataWrangler example for Timestream:
https://aws-data-wrangler.readthedocs.io/en/stable/stubs/awswrangler.timestream.write.html
When you call the constructor, you can pass the boto3_session or it will use the default session:
boto3_session (boto3.Session(), optional) – Boto3 Session. The default boto3 Session will be used if boto3_session receive None.

You boto3 configs need to specify a default region or you need to declare in the boto3 session.
https://boto3.amazonaws.com/v1/documentation/api/latest/guide/configuration.html
import boto3
from botocore.config import Config

my_config = Config(
    region_name = 'us-west-2',
    signature_version = 'v4',
    retries = {
        'max_attempts': 10,
        'mode': 'standard'
    }
)

client = boto3.client('kinesis', config=my_config)


text:
Q: Designing layout, reuse views. Best practice Im going to have several same fields in Activity
eg
Fragment A
Age
Height

Fragment B
Age
Weight

Fragment C
Weight
Height

Should I create layout for each fragment or is way to "dynamicaly" show fields I need

A: You can use the include tag. It's a very easy way to achieve what you are looking for.


text:
Q: MSMQ and multiple wcf-services on different servers reading from the very same queue I'm aware of that there are a couple of posts here on SO that discusses this issue, but I can't figure out a straight answer to my scenario.
Lets say i have:

*

*One queue on Server-A with alot of messages coming in

*One WCF service with NetMsmq binding on Server-B reading from Server-A's queue

*The very same WCF Service deployed to another Server-C with the same binding reading from Server-A's queue

Am I guaranteed that the services on Server-B and Server-C will never process the same message?
Are there any other problems with this setup that needs to be taken care of?
The purpose of this setup with multiple wcf services reading from the same queue is to increase processing speed, and I do not want to use a hardware loadbalancer.
Thanks for your time!

A: You will need to make your queue transactional and then set the exactlyOnce property on the binding to true.
Reference:
http://msdn.microsoft.com/en-us/library/system.servicemodel.msmqbindingbase.exactlyonce(v=vs.110).aspx
This should take care of it.  You can have multiple readers (WCF Services) reading from the same queue.  That's basically a load-levelling concept and is the intent of queue-based messaging.  Here is some background documentation on WCF and MSMQ.
http://msdn.microsoft.com/en-us/library/ms789048(v=vs.110).aspx


text:
Q: Pairing new device in Lock Task Mode (Android P/10) I have an issue when I use the Lock Task Mode (Kiosk mode) on Android.
In "normal" mode, when I try to pair a device, a pop-up message appears :
"Are you sure you want to pair the Bluetooth Device?" Yes/No
But in Lock Task Mode, the message doesn't appear.
I added in my code to authorize notifications but pop-up are not displayed :
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
            int test = dmp.getLockTaskFeatures(adminComponentName);
            dmp.setLockTaskFeatures(adminComponentName, DevicePolicyManager.LOCK_TASK_FEATURE_SYSTEM_INFO |
                                                                                DevicePolicyManager.LOCK_TASK_FEATURE_NOTIFICATIONS |
                                                                                DevicePolicyManager.LOCK_TASK_FEATURE_HOME);
        }

Is there a way in Lock Task Mode to authorize such pop-ups?
Thanks

A: public class Bluetooth extends AppCompatActivity {
    ArrayList<String> listItems=new ArrayList<String>();
    //DEFINING A STRING ADAPTER WHICH WILL HANDLE THE DATA OF THE LISTVIEW
    ArrayAdapter<String> adapter;
    BroadcastReceiver mReceiver;
    DevicePolicyManager dpm;
    ComponentName deviceAdmin;
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_bluetooth);

         dpm = (DevicePolicyManager) Bluetooth.this.getSystemService(Context.DEVICE_POLICY_SERVICE);
         deviceAdmin = new ComponentName(Bluetooth.this, MyDeviceAdminReceiver.class);
        dpm.setLockTaskPackages(deviceAdmin, new String[]{
                Bluetooth.this.getPackageName()
                "com.android.settings"
        });
        ListView lista=findViewById(R.id.devices);
        adapter=new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, listItems);
        lista.setAdapter(adapter);

        BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();

        //setdevicevisible();
        boolean hasBluetooth = getPackageManager().hasSystemFeature(PackageManager.FEATURE_BLUETOOTH);
        if(!hasBluetooth) {
            AlertDialog dialog = new AlertDialog.Builder(Bluetooth.this).create();
            dialog.setTitle("Bluetooth nem elérhető");
            dialog.setMessage("Bluetooth ki van kapcsolva!");
            dialog.setButton(AlertDialog.BUTTON_NEUTRAL, "OK",
                    new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int which) {
                            // Closes the dialog and terminates the activity.
                            dialog.dismiss();
                            Bluetooth.this.finish();
                        }
                    });
            dialog.setCancelable(false);
            dialog.show();
        }

        if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION)
                != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions((Activity) this,
                    new String[]{Manifest.permission.ACCESS_COARSE_LOCATION},
                    1);
        }

        if (mBluetoothAdapter.isDiscovering()) {
            mBluetoothAdapter.cancelDiscovery();
        }

        mBluetoothAdapter.startDiscovery();
        mReceiver = new BroadcastReceiver() {
            public void onReceive(Context context, Intent intent) {
                String action = intent.getAction();

                //Finding devices
                if (BluetoothDevice.ACTION_FOUND.equals(action))
                {
                    // Get the BluetoothDevice object from the Intent
                    BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
                    // Add the name and address to an array adapter to show in a ListView
                    //device.setPairingConfirmation(true);

                    if (device.getName() != null) {
                        adapter.add(device.getName() + "\n" + device.getAddress());
                        device.createBond();

                    }

                    //adapter.add(device.getAddress());
                }
            }
        };

        IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
        registerReceiver(mReceiver, filter);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        try{
            unregisterReceiver(mReceiver);
            dpm.setLockTaskPackages(deviceAdmin, new String[]{
                    Bluetooth.this.getPackageName()
            });
        }catch (Exception e){
            // already unregistered
        }
    }
}


text:
Q: Cut the content after 10 words
Possible Duplicate:
How to select first 10 words of a sentence?

I want to show 10 words of the content words not characters
$string = 'Lorem ipsum dolor sit amet,consectetur adipiscing elit. Mauris ornare luctus diam sit amet mollis.';

should the result to be "Lorem ipsum dolor sit amet,consectetur adipiscing elit. Mauris ornare"

A: This version will work no matter what kind of "space" you use between words and can be easily extended to handle other characters... it currently supports any white space character plus , . ; ? !
function getSnippet( $str, $wordCount = 10 ) {
  return implode(
    '',
    array_slice(
      preg_split(
        '/([\s,\.;\?\!]+)/',
        $str,
        $wordCount*2+1,
        PREG_SPLIT_DELIM_CAPTURE
      ),
      0,
      $wordCount*2-1
    )
  );
}

For those who should might prefer the original formatting :)
function getSnippet( $str, $wordCount = 10 ) {
  return implode( '', array_slice( preg_split('/([\s,\.;\?\!]+)/', $str, $wordCount*2+1, PREG_SPLIT_DELIM_CAPTURE), 0, $wordCount*2-1 ) );
}

A: Try:
$str = 'Lorem ipsum dolor sit amet,consectetur adipiscing elit. Mauris ornare luctus diam sit amet mollis.';
$arr = explode(" ", str_replace(",", ", ", $str));
for ($index = 0; $index < 10; $index++) {
    echo $arr[$index]. " ";
}

Output:
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Mauris ornare

A: We can retrieve the words in a string using str_word_count function .
For more description about the function please refer the below link
http://php.net/manual/en/function.str-word-count.php
For displaying only 10 words in the string please refer the below code snippet
    $str='Lorem ipsum dolor sit amet,consectetur adipiscing elit. Mauris ornare luctus diam sit amet mollis.';
    $words=str_word_count($str,true);
    $a=array_slice($words,10);
    $s=join('',$a);
    echo $s;

A: Try this function:
function shorten_string($string, $wordsreturned)
{
  $retval = $string;
  $string = preg_replace('/(?<=\S,)(?=\S)/', ' ', $string);
  $string = str_replace("\n", " ", $string);
  $array = explode(" ", $string);
  if (count($array)<=$wordsreturned)
  {
    $retval = $string;
  }
  else
  {
    array_splice($array, $wordsreturned);
    $retval = implode(" ", $array)." ...";
  }
  return $retval;
}

On your text, so like this:
$string = 'Lorem ipsum dolor sit amet,consectetur adipiscing elit. Mauris ornare luctus diam sit amet mollis.';
$firsttenwords = shorten_string($string, 10);

From here.
UPDATE: Now it's space-compliant, and also new-line compliant.

A: Try like this
$str = 'Lorem ipsum dolor sit amet,consectetur adipiscing elit. Mauris ornare luctus diam sit amet mollis.';
$arr = explode(" ", str_replace(",",", ",$str), 10);
echo implode(" ", $arr);


text:
Q: ++v2 output to stop before my first variable I'm trying a very basic C++ exercise:
Write a program that prompts the user for two integers. Print each number in the range specified by those two integers.
This is my program:
#include <iostream>

int main()
{
    std::cout << "Write two numbers: " << std::endl;
    int v1 = 0, v2 = 0;
    std::cin >> v1 >> v2;
    std::cout << "The numbers between " << v1 << " and " << v2 << " are: " << std::endl;

    while (v1 > v2)
    {
        std::cout << ++v2 << std::endl;
    }

}

My output shows like this:
Write two numbers:
10
5
The numbers between 10 and 5 are:
6
7
8
9
10

And my questions is, how do I output just from 6 to 9, without the 10?
I'm with the basics, so I don't need for or loops or other things more advanced, just a while and ++v2.

A: while(v1 != v2 - 1)
{
    std::cout << ++v1 << std::endl;
}

A: I finally added this code in order to work and to read both cases as a comment suggested before:
#include <iostream>

int main()
{
    std::cout << "Write two numbers: " << std::endl;
    int v1 = 0, v2 = 0;
    std::cin >> v1 >> v2;
    std::cout << "The numbers between " << v1 << " and " << v2 << " are: " << std::endl;

    while (v2 < v1 && ++v2 < v1)
    {
        std::cout << v2 << std::endl;
    }

    while (v1 < v2 && ++v1 < v2)
    {
        std::cout << v1 << std::endl;
    }

}

If it is too newbie, let me know, maybe there is another way to make it look simpler (just with while).


text:
Q: IComparable IgnoreCase I'm writing a function to compare 2 values of IComparable type, and throwing if not equal. Basically, re-making assert. Yes, I'm aware I'm reinventing the wheel.
    public static void IsEqual<T>(T Value1, T Value2) where T : IComparable<T>
    {
        if (0 != Value1.CompareTo(Value2))
        {
            throw new ApplicationException("Fail");
        }
    }

Works fine except for strings, I was hoping for the option of ignoring case. "AA" vs "aa"
I'd like to override this method specifically when T is a String, so I could use String.Compare and ignore case. It would also be cool to have another param so the user could specify if string should be ignored (though, this is useless for other types like int so seems kind of like a confusing/bad design. I'm open to suggestions here).
Is there a good way to do this? I'm also open to changing to a different type than IComparable, initially thought this was the best interface for the job but now realize I could have been wrong.
where T : IComparable<T>

A: You could create another function, specially for strings.
public static void IsEqual(string value1, string value2)
{
  if (string.Compare(value1, value2, true) != 0)
    throw new ApplicationException("Fail for strings");
}

Then if you would call IsEqual(1, 1) your generic overload will be called, but if you call IsEqual("A", "a") the string overload will be called. Then you can simply add another optional parameter for the string overload, if desired.

A: You can try:
public static void IsEqual<T>(T Value1, T Value2) where T : IComparable<T>
    {
        if (typeof(T) == typeof(String))
        {
            if (String.Compare(Value1.ToString(), Value2.ToString(), true) != 0)
            {
                throw new ApplicationException("Fail");
            }
        }
        else if (0 != Value1.CompareTo(Value2))
        {
            throw new ApplicationException("Fail");
        }
    }


text:
Q: Why am I not able to print to a LaserJet 4250, but others can? We've got an HP LaserJet 4250 network enabled printer on our network.  I normally can print to it, as can anyone else in our office.  For some reason I can't print to it now.  It appears, to my PC, to be offline, but it doesn't appear that way to others.
Why?

A: Since you say you're using Windows 7 and the others are using Windows XP, I've actually seen a printer that does this before (a Xerox Workcentre M20i to be exact).  It was incorrectly reporting the online status of the device, so Windows refused to print, but only in Windows 7 (it's ancient so the driver is...questionable).  Try this -

*

*In Devices and Printers, right-click the printer and select Printer
properties.

*Under the Ports tab, select the port that's currently in
use (presumably standard TCP/IP of some sort) and click Configure
Port...

*Uncheck SNMP Status enabled.

This should, in theory, get it to always assume that printer is online.  If this is your only problem, it should print properly like this.  (The downside is if it ever DOES go offline for realsies, you have no way of knowing.)

A: Sometimes Windows Updates can bollix up the drivers.  You may need to reinstall the drivers for this printer.
Go to Control Panel->Devices and Printers and select the printer and remove and re-add the device, or try Troubleshoot and see if this allows you to fix it.

A: Click the "Start" button and select "Printers" or "Printers and Faxes" from the menu. A window opens up showing all the printers you can access.
Double-click the printer that is having the issue A new window opens with a list of current print jobs.
Click printer in the menu bar and make sure that "use printer offline" is not checkmarked.
Also, make sure that you can ping the i.p. address of the network printer.

A: Verify the network connection. Print out the printers network information (OR connect to the printers http web interface from a working computer), and compare the info to your computers ipconfig. Check the ip range and subnet. And make sure you are pinging the correct ip.