text:
Q: UITableViewCell objectForKey I am loading data into an NSArray to help populate my table view.
(void)viewDidLoad
{
[super viewDidLoad];

PFQuery *query = [PFQuery queryWithClassName:@"UserPhoto"];
[query findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {
    if (!error) {
        NSLog(@"Successfully retrieved %d videos.", objects.count);
        for (PFObject *object in objects) {
            NSArray *videos = [NSArray arrayWithObjects:object, nil];
            NSLog(@"Video Details: %@", videos);
        }
    } else {
        // Log details of the failure
        NSLog(@"Error: %@ %@", error, [error userInfo]);
    }
}];

[self.tableView reloadData];

Details for an individual video looks something like this:
"<UserPhoto:ifb0vYa8x6:(null)> {\n    ACL = \"<PFACL: 0xb3645a0>\";\n    imageFile = \"<PFFile: 0xb2d8ef0>\";\n    title = \"\";\n    user = \"<PFUser:zEwPBaCg7x>\";\n}"

I am then trying to grab the objectForKey of @"title" and load it into my UITableViewCell label but it doesn't seem to work:
pragma mark - Table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
// Return the number of sections.
return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
// Return the number of rows in the section.
return [recipes count];
}

- (UITableViewCell *)tableView:(UITableView *)tableViews cellForRowAtIndexPath:(NSIndexPath *)indexPath object:(PFObject *)object {
static NSString *CellIdentifier = @"Cell";
UITableViewCell *cell = [tableViews dequeueReusableCellWithIdentifier:CellIdentifier];

// Configure the cell...
if (cell == nil) {
    cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}

UILabel *recipeNameLabel = (UILabel *)[cell viewWithTag:101];
recipeNameLabel.text = [[recipes objectAtIndex:indexPath.row ] objectForKey:@"title"];

return cell;
}

My label "recipeNameLabel" is not holding any data for the title. Does anyone know what is wrong?

A: You don't say what is wrong / observed, but findObjectsInBackgroundWithBlock: is an asynchronous call so you should be calling [self.tableView reloadData]; is the callback block, not after the method call (which will actually run before the callback completes).
At the moment you reload the table before you have any data to display.
Also, looking at your object log, title = \"\"; means that the title is an empty string...


text:
Q: HTML table wrap td I've two tables like below:

          One
          Two
          Three
          Four
          Five
          Six
          Seven
          Eight
          Nine
          Ten

When I run this my internal table is exceeding parent table width (100px) because it is having more TDs. How can restrict this?
All values are coming in the same row and it is going out of reserved area (100px). Is there any way to display values in multiple rows with the above code?

A: You cannot do this with
 layout. Even adding the following CSS will not fix it, instead the cells are just rendered over each other.
table {
    table-layout:fixed;
    overflow:hidden;
}

The HTML table column element <col> element will also not really help since it will only apply to the first .
One approach would be to use a non-
 layout instead, for example:
HTML

One

Two

Three

Four

Five

Six

Seven

Eight

Nine

Ten

CSS
table {
    width:100px;
}

#container div {
    display:inline-block;
}

See demo of how <col> does not work and how the
 layout wraps at 100px.

A: U can't fit 10 words like this in 100px with normal size font.
I think you might want to use

(row) tags for each word instead of td(cell)
Or you really want the 100px row to be split in 10 cells and to contain those words? (I think if might be somehow possible but u won't see the words :D or maybe if you used little font and somehow made the words to be rotated about 90 degrees...)
This Q/A Word-wrap in an HTML table might help u in that case.

A: It will help you:
Fixed Table Cell Width
Use style attr 'table-layout:fixed' with table
or try this:

// div css

                        One
                        Two
                        Three
                        Four
                        Five
                        Six
                        Seven
                        Eight
                        Nine
                        Ten

A: add a class to table and set this css code
table.restrict { table-layout:fixed; }
table.restrict td { overflow: hidden; }

redpajama_set_name: RedPajamaStackExchange


text:
Q: 401 Error with AWS Cognito and correct access token I'm using AWS Cognito in my Spring boot application. I can successfuly register, verify and login with the user credentials, however when I try to access an endpoint that a user needs to be authenticated for, with the Bearer token from Cognito, I get a 401 error.
Security Config:
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.csrf().disable().authorizeRequests()
                .antMatchers("/v1/api/auth/login").permitAll()
                .antMatchers("/v1/api/auth/register").permitAll()
                .antMatchers("/v1/api/auth/verify-email").permitAll()
                .antMatchers("/v1/api/auth/verify-email/resend").permitAll()
                .anyRequest().authenticated().and().oauth2ResourceServer().jwt();
    }
}

Application.properties
spring.cloud.aws.security.cognito.app-client-id=XXX
spring.cloud.aws.security.cognito.region=eu-west-2
spring.cloud.aws.security.cognito.user-pool-id=eu-west-XXX

spring.security.oauth2.client.registration.cognito.client-id=XXX
#spring.security.oauth2.client.provider.cognito.issuer-uri=https://cognito-idp.eu-west-2.amazonaws.com/eu-west-XXX
spring.security.oauth2.resourceserver.jwt.issuer-uri=https://cognito-idp.eu-west-2.amazonaws.com/eu-west-XXXX

pom.xml
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-security</artifactId>
</dependency>
    <dependency>
        <groupId>org.springframework.security</groupId>
        <artifactId>spring-security-oauth2-resource-server</artifactId>
        <version>5.7.1</version>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-security</artifactId>
    </dependency>

A: Have you checked the configuration on the API methods and the token validity and scopes?


text:
Q: Express MongoDB - insert a document but before customize data through another query My requirement is pretty straightforward -
I want to insert a document in MongoDB database. But before I have to check if the slug already exists in database. Then perform an operation to rename the slug if the slug is already exists.
What I have been trying is to perform an async await callback to check the slug is already exists then insert the document.
mongoClient.connect(function (err, mongoClient) {
    let db = mongoClient.db("articles");

    let category_information = async (db, category_info) => {
        let slug_information = await db.collection('categories').find({slug: category_info.slug});

        slug_information.count((err, count) => {
            if (count > 0) {
                let new_slug = `${category_info.slug}_${new Date().getTime()}`;
                console.log(new_slug);
                return new_slug;
            }
            else
                return category_info.slug;
        })
    };

    let category_promise = category_information(db, category_info);

    category_promise.then(value => {
        console.log(value);
        category_info.slug = value;
    });

    db.collection('categories')
        .insertOne(category_info, (err, data) => {
            assert.equal(null, err);
            res.status(200);
            res.json('success');
        });

    mongoClient.close();
});

In console I get undefined value from Promise. Can you please figure out my code?
I am new in MongoDB. So also, do you have the solution of the problem in MongoDB way? I mean, can I perform these two queries within a single query?
Thanks!

A: *

*You don't need to await find() since it's actually the command coming after, in this case count() that is executing the query.

*Next I wonder where and how category_info is defined. It's missing in the code above. But I'll assume you have set it properly in your code.

*You must return something from your async function (a promise preferably). Right now you only return from the count-callback.
With async/await you should be able to:
const count = await slug_information.count();
if (count > 0) {
    let new_slug = `${category_info.slug}_${new Date().getTime()}`;
    console.log(new_slug);
    return new_slug;
} else {
    return category_info.slug;
}

Basically, if you use a callback like (err, count)=>{..} then you say "I won't be using promises here!", no promise will come and you have nothing to wait for.

*

*Next: category_promise.then(... this bit is async, so you cannot know that it'll resolve before you start your insertOne( query. Actually you can be almost sure it hasn't.

So you either chain another then:
category_promise.then(value => {
    console.log(value);
    return category_info.slug = value;
}).then( ()=>{
    db.collection('categories')
        .insertOne( ...
});

or just async the whole thing:
const MongoClient = require("mongodb").MongoClient;
const category_info = { slug: "abc" };

async function run(req, res, next) {
  const mongoClient = await MongoClient.connect("mongodb://localhost:27017");
  let db = mongoClient.db("categories");

  // With async/await this is almost superfluous, but lets roll with it.
  let category_information = async (db, category_info) => {
    const count = await db.collection("articles")
      .find({ slug: category_info.slug })
      .count();

    if (count > 0) {
      let new_slug = `${category_info.slug}_${new Date().getTime()}`;
      console.log(new_slug);
      return new_slug;
    } else {
      return category_info.slug;
    }
  };

  category_info.slug = await category_information(db, category_info);
  // note that insertOne() does not return the inserted document.
  let data = await db.collection("categories").insertOne(category_info);

  res.status(200).json(data);

  mongoClient.close();
}

run(); // or app.get("/some-route", run);

This code runs, but I haven' tested every case (count and so on), so grain of salt and all that.


text:
Q: Redirect Yii2 to a page when there is no connection Yii2 shows

SQLSTATE[HY000] [2002] A socket operation was attempted to an unreachable host.

when there is no internet access, how can I make it redirect to a page, says ./index.php?r=site/neterror? I tried to do this in web/index.php by using this code
<?php
use yii\db\Exception;
defined('YII_DEBUG') or define('YII_DEBUG', true);
defined('YII_ENV') or define('YII_ENV', 'dev');
require(__DIR__ . '/../vendor/autoload.php');
require(__DIR__ . '/../vendor/yiisoft/yii2/Yii.php');
$config = require(__DIR__ . '/../config/web.php');
try
{
    (new yii\web\Application($config))->run();
}
catch(Exception $e) {
    header("Location: ./index.php?r=site/error"); /* Redirect browser */
    exit();
}

but all I get back is The page isn't redirecting properly.

A: Following Database Exception View With different msg shown only when YII_DEBUG is true in Entry Script..
As Defined in Yii ErrorHandler Class to use Own View On UserException you have to false YII_DEBUG
class ErrorHandler extends \yii\base\ErrorHandler{
....
  protected function renderException($exception){
  ..
   $useErrorView = $response->format === Response::FORMAT_HTML && (!YII_DEBUG || $exception instanceof UserException);

    if ($useErrorView && $this->errorAction !== null) {
        $result = Yii::$app->runAction($this->errorAction);
        if ($result instanceof Response) {
            $response = $result;
        } else {
            $response->data = $result;
        }
    }
  }

}


text:
Q: Outlook vba error I am not very experienced in Outlook VBA. I am using Outlook 2007 and i am trying to write a VBA code that will run when i receive any email. This code will read the subject line and save the email details in an excel file those are having the word "Update***" in subject. The code worked for the first time only, when i receive another email with the subject Update*** the code shows error 462. I check all the functions and pointed them to the objects. Then the code shows error 13 when running for the second time. I corrected the error 13 but now when i receive emails the VBA neither update the excel file nor shows any error message. My Outlook macro is enabled and I made sure that it isn't in design mode.
Code pasted in Outlook session :
    'Option Explicit

    Private WithEvents myOlItems  As Outlook.Items

Private Sub Application_Startup()
Dim olApp As Outlook.Application
Dim objNS As Outlook.NameSpace
  Set olApp = Outlook.Application
  Set objNS = olApp.GetNamespace("MAPI")
  Set myOlItems = objNS.GetDefaultFolder(olFolderInbox).Items
End Sub

Private Sub myOlItems_ItemAdd(ByVal Item As Object)

On Error GoTo ErrorHandler

Dim Msg As Outlook.MailItem
Dim appExcel As Excel.Application
Dim wkb As Excel.Workbook
Dim wks As Excel.Worksheet
Dim rng As Excel.Range
Dim strSheet As String
Dim strPath As String
Dim intRowCounter As Integer
Dim intColumnCounter As Integer

strSheet = "AppData.xls"
strPath = "C:\Email\"
strSheet = strPath & strSheet

If TypeName(Item) = "MailItem" Then
Set Msg = Item
If InStr(Msg.Subject, "Update***") <> 0 Then

Set appExcel = CreateObject("Excel.Application")
appExcel.Workbooks.Open (strSheet)
Set wkb = appExcel.ActiveWorkbook
Set wks = wkb.Sheets(1)
wks.Activate

intRowCounter = CInt(wks.Cells.Find("*", wks.Range("A1"), , , xlByRows,     xlPrevious).Row) 'substitute of this line of code :intRowCounter = wks.UsedRange.Rows.Count

appExcel.Application.Visible = True

intColumnCounter = 1
intRowCounter = intRowCounter + 1
Set rng = wks.Cells(intRowCounter, intColumnCounter)
rng.Value = Msg.To
intColumnCounter = intColumnCounter + 1
Set rng = wks.Cells(intRowCounter, intColumnCounter)
rng.Value = Msg.SenderEmailAddress
intColumnCounter = intColumnCounter + 1
Set rng = wks.Cells(intRowCounter, intColumnCounter)
rng.Value = Msg.Subject
intColumnCounter = intColumnCounter + 1
Set rng = wks.Cells(intRowCounter, intColumnCounter)
rng.Value = Msg.SentOn
intColumnCounter = intColumnCounter + 1
Set rng = wks.Cells(intRowCounter, intColumnCounter)
rng.Value = Msg.ReceivedTime

End If
End If
ProgramExit:
Exit Sub
ErrorHandler:
MsgBox Err.Number & " - " & Err.Description
Resume ProgramExit
appExcel.Quit

wkb.Save
appExcel.Quit
Set appExcel = Nothing
Set wkb = Nothing
Set wks = Nothing
Set rng = Nothing
Set Msg = Nothing
Set Item = Nothing

End Sub'

A: Change your error handling to this
'
'~~> Rest of the code
'

wkb.Save

End If
End If

ProgramExit:
    On Error Resume Next
    wkb.Close (False)

    appExcel.Quit

    Set Rng = Nothing
    Set wks = Nothing
    Set wkb = Nothing
    Set appExcel = Nothing
    On Error GoTo 0

    Set Msg = Nothing
    Set Item = Nothing

    Exit Sub
ErrorHandler:
    MsgBox Err.Number & " - " & Err.Description
    Resume ProgramExit


text:
Q: bootstrap 5 grid Grid with half fluid / half container I have a problem with my html code and bootstrap 5. I want to add pictures in a row with the description. Now it looks:

and I want to have this:

Can you help me with my code? I can't find the answer.


text:
Q: Randomize the ranking of a string array I'm new to Android and I'm looking for the best and quickest way to randomize the ranking of a string[] array while tracking one of the strings therein.
The array is typically just 5 strings long e.g.
         a) input
          String[] All = {"apple", "fish", "cat, "dog", "mouse"}

         b) output (one of many)
          String[] All = {"fish", "dog", "cat, "apple", "mouse"}

The thing is that the target string would be 'apple' that needs to be tracked after its randomized. In other words, I want to know where the apple is (in the case of output above, apple is All[3])
How do I go about doing this?

A: You can use the Collections.shuffle() and then convert your array of String to List<String> so you can use the shuffle method of the Collections class. After, you then iterate the List of string to find the index of apple.
sample:
String[] All = {"apple", "fish", "cat","dog", "mouse"};
List<String> list = Arrays.asList(All);
Collections.shuffle(list);
System.out.println(list.toString());
for(int i = 0; i < list.size(); i++)
{
    if(list.get(i).equals("apple"))
    {
        System.out.println("Apple at index: " + i);
        break;
    }
}

result:
[fish, apple, dog, cat, mouse]
Apple at index: 1


text:
Q: Reset Tensorflow adam optimizer I am performing K-fold cross validation on a neural network model with Tensorflow, so I need to train the model k times.
I would like to know how to reset the state of the tf.train.AdamOptimizer so I can perform a new training after each fold.
Someone suggested:
 sess.run(tf.variables_initializer(optimizer.variables()))

But this throws the following error:
'Operation' object has no attribute 'variables'


text:
Q: TinyMCE - How can I turn off Visual Aids for printing? I recently added TinyMCE 4.0b2 to a web application I've been developing.
I needed to have visual aids turned on for editing, however turned off when printing and spent a fair amount of time looking for a solution through their forums, StackOverflow and google to no avail!

A: So... I decided to investigate the issue myself!
To get this to work I had to manually 'adjust' the print command of the print plugin.
The following fix applies to TinyMCE v.4.0b2, the version available at time of writing; it may or may not work with previous and future versions of TinyMCE.
The print plugin file can be found in the js/tinymce/plugin/print/ directory.
Open the plugin.min.js file in your favourite editor and you'll see something like this:
tinymce.PluginManager.add("print",function(e){e.addCommand("mcePrint",function(){e.getWin().print();}),e.addButton("print",{title:"Print",cmd:"mcePrint"}),e.addMenuItem("print",{text:"Print",cmd:"mcePrint",icon:"print",shortcut:"Ctrl+P",context:"file"})});

After poking around the tinymce source code I found the hasVisual editor property and mceToggleVisualAid command. I then added these two to the printing plugin as
if(e.hasVisual){e.execCommand("mceToggleVisualAid");}

just prior to the code calling
e.getWin().print();
The finished product looks like so:
tinymce.PluginManager.add("print",function(e){e.addCommand("mcePrint",function(){if(e.hasVisual){e.execCommand("mceToggleVisualAid");} e.getWin().print();}),e.addButton("print",{title:"Print",cmd:"mcePrint"}),e.addMenuItem("print",{text:"Print",cmd:"mcePrint",icon:"print",shortcut:"Ctrl+P",context:"file"})});

I hope this helps someone struggling with this issue in future.


text:
Q: Can't remove .php from website using htaccess. Dreamhost server I am trying to remove the ".php" on my website. I have changed the .htaccess file based on the documentation provided in the dreamhost wiki to the following:
Options +FollowSymlinks
RewriteEngine On
RewriteBase /
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME}.php -f
RewriteRule ^(.+)$ /$1.php [L,QSA]

However, this does not work on the site. For example this code does not work:
link

It shows the following error:
Not Found
The requested URL /jimmyvosler.com/public/about.php was not found on this server.
Additionally, a 404 Not Found error was encountered while trying to use an ErrorDocument to handle the request.
This works (but still displays the .php at the end, which is what im trying to fix):
link

I don't understand what is causing this, especially since the error even points to the correct place. Is there a setting I need to check on my admin tool?

A: Try this:
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^([^\.]+)$ $1.php [NC,L]

A: Here is the solution for anyone else that has the same trouble. I added this to my .htaccess file. This solution came from dreamhost support and was linked from this website:  http://eisabainyo.net/weblog/2007/08/19/removing-file-extension-via-htaccess/
RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME}\.php -f
RewriteRule ^(.*)$ $1.php

A: Try this:
Options All -Indexes
RewriteEngine On

RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME}\.php -f
RewriteRule ^(.+)$ $1.php [L]


text:
Q: I am trying to mount a dvd, but it does not work I type in:
mount /dev/sda2 /mnt/dvd
But this comes out:
mount: you must specify the filesystem type
The output of lsblk is:
sda      8:0    0 149.1G  0 disk
├─sda1   8:1    0 145.1G  0 part /
├─sda2   8:2    0     1K  0 part
└─sda5   8:5    0     4G  0 part [SWAP]
sr0     11:0    1   2.2G  0 rom

A: I can only assume that your DVD is a internal one with Master/slave jumpers set right in
Bios so the hardware is readable for Kernel or the system to be able to access its contents. Hard-disk usually master and other peripheral-devices like cd/dvd usually are slaves.
One way to find where your Cd/Dvd is listed mounted is to insert a cd/dvd in and open up your files in a file reader like nautilus or nemo or what ever is currently installed in your system or just click icon for Files.
Hoover over your Devices currently showing with your mouse pointer. If nothing shows up for your CD/Dvd when hoovering over your mouse over Devices when you have a cd/dvd disk in. If it did show up and your mouse is over the listed device will show you the path ex. Media / (computer or user name ) / Current label of the cd/dvd name.
You can go in to that folder and read what drive letter is assigned for your cd/dvd drive. Ex.cdrom0 or a other number for it so you can mount it permanently to the system.
Another way to do it is simply browse through the subfolders in /media (or could even be /mnt on older systems) until you find the one that shows your disc (you'll need to have one in the drive, of course).
Or if you want to do it via the terminal, you can use
mount|grep ^'/dev'
which will display info as follows: This is just a Ex.
/dev/sda2 on / type ext3 (rw,relatime,errors=remount-ro)
/dev/sda1 on /media/Windows-XP-x64 type fuseblk (rw,nosuid,nodev,allow_other,blksize=4096)
/dev/sr0 on /media/cdrom0 type iso9660 (ro,nosuid,nodev,user=ozzman)
As you see your Cd/dvd listed in that folder you can open that folder by owning root privligies for your file reader so you can modify it in your file system to make it be visible every time you boot up by modifying the mount point or do the following in terminal.
[Ubuntu] Mount/Unmount CD/DVD
in command line
To mount your CD/DVD:
Open a terminal ctrl+alt+t and type
sudo mount /media/cdrom0/ -o unhide
To unmount your CD/DVD:
Open a terminal and type:
sudo umount /media/cdrom0/ -l
Assuming that media/cdrom0 is the location of your CD/DVD rom.
That should mount your cd/dvd player to be part of your system when booting up.
If not can you repost here again.

A: How to mount cdrom in Linux

*

*Detecting CD/DVD-ROM drives

*Creating mount point

*Mount CDROM

*Mounting Audio CD's

*Allowing users to mount CDROM

*Umount and eject CDROM

*Troubleshooting
7.1. Testing for ISO9660 support
CD's and DVDs are using ISO9660 filesystem. The aim of ISO9660 is to provide a data exchange standard between various operating systems. As a result any Linux operating system is capable of handling the ISO9660 file system. This guide describes a way on how to mount / umount ISO9660 file-system in Linux and thus enabling user to read data from CD or DVD media.*

If you still have some questions after reading this article please try our new LinuxCareer Forum.

*

*Detecting CD/DVD-ROM drives
At first we need to find usable devices capable reading ISO9660 data. In other words we need to find CD/DVD drives available on our Linux system. In order to do that, we can use "wodim" command and its --devices option. wodim will scan and output symbolic device names found in /dev/* directory:

wodim --devices
If a wodim command is not available on your system make sure cdrecord package is installed on your system.
Debian and Ubuntu:

Sudo apt-get install cdrecord

RedHat, Fedora, CentOS:
yum install cdrecord
Once you execute wodim command and you have some CD/DVD device hardware available in your system you should see an output similar to the one below:

$ wodim --devices
>wodim: Overview of accessible drives (1 found) :

 0  dev='/dev/scd0'     rwrw-- : 'TSSTcorp' 'CD/DVDW SH-S183L'
From the above output we can determine that our CDROM / DVDROM drive can be accessed at the symbolic location /dev/scd0.
Furthermore, it needs to be mentioned that different systems may behave differently. For example in Debian Linux a user running wodim command must belong to cdrom group, otherwise the wodim command will fail with an error message similar to the one below:
wodim: No such file or directory.
Cannot open SCSI driver!
For possible targets try 'wodim --devices'
or 'wodim -scanbus'.
For possible transport specifiers try 'wodim
dev=help'.
For IDE/ATAPI devices configuration,
see the file README.ATAPI.setup from
the wodim documentation.
2. Creating mount point
Your Linux system may already have created a mount point for you, it is usually something like  /cdrom, /media/cdrom, /media/cdrom0 or /mnt/cdrom . If this is not your case, feel free to create your own mount point. To have mount point available is a absolute must! Mount point will represent a place from where data located on CD or DVD will be made accessible to the user.

sudo mkdir /media/cdrom

*

*Mount CDROM
If you do not belong into cd-rom group and thus do not posses permissions to mount CD-ROM, switch to root user #sudo -i and execute a command below:

sudo mount -t iso9660 /dev/scd0 /media/cdrom
mount: block device /dev/sr0 is write-protected, mounting read-only
your CDROM is now mounted and accessible from /media/cdrom directory. At this point simply navigate to this directory to access your data.

*

*Mounting Audio CD's
Sometimes you would like to listen to your favorite music and when you try mount music cd with a command above you can get problems like:

linuxcareer.com
mount -t iso9660 /dev/hdc /media/cdrom0/
mount: block device /dev/hdc is write-protected, mounting read-only
mount: wrong fs type, bad option, bad superblock on /dev/hdc,
       missing codepage or other error
       In some cases useful info is found in syslog - try
       dmesg | tail  or so
linuxcareer.com#
This is because music CD's does not contain standard iso9660 filesystem as such. In fact the story with music CD-ROMs is easier as it is with data CD-ROMs using iso9660 filesystem.
In order to listen to a music CD all what needs to be done is to insert music CD ( Compact Dics ) into CD-ROM/DVD-ROM drive and fire up you favorite music CD player. The only thing you may need to be concerned about is whether  "kdemultimedia-kio-plugins" package for KDE or "gnome-media" package for gnome window manager are installed. Those packages allow you to listen to music CD content.
In case you would like to see a content of your music CD or perhaps convert some music trakcs to MP3 / OGG format just start "KONQUEROR" and enter location:
audiocd:/
into Konqueror's navigation bar.

*

*Allowing users to mount CD-ROM
You can also allow users on the system mount CD's or DVD's. To do that edit your /etc/fstab file and add line similar to the one below:

/dev/sdc0        /media/cdrom0   iso9660 ro,user,noauto  0       0

*

*Umount and eject CDROM
There are couple ways how to remove/unmount CDROM.

unmount /dev/hdc
eject
or you can simply run:
eject
If you are unable to unmount your previously mounted CD-ROM, make sure that you are not in the directory where your CD-ROM is mounted or that some other application is not using it.
If you are still having problems to unmount your CD-ROM medium you can use fuser command to kill all related processes using your device.
fuser -mk /dev/hdc
eject

NOTE: Never use the above command on devices mounted read/write unless you are sure what you are doing.

*

*Troubleshooting

7.1. Testing for ISO9660 support
Although it is highly unlikely that your system does not support this specific filesystem here are some tips on how to test for ISO9660 presence in your Linux system.
In case you face some troubles try to search for loaded kernel modules with lsmod command or by reading a content of /proc/filesystem file:
cat /proc/filesystems | grep iso9660
or
lsmode | grep iso9660
The actual module is be a part of libiso9660 package. Both commands should report available ISO9660 filesystem.

A: You can't mount a blank dvd, you can only mount things that have filesystems on them.  You don't have to mount it to burn something on it.
You either have to burn something on it (like, an iso9660 image using cdrecord, wodim, or similar), or if it is a dvd+rw, you can format it using things in the udftools package or media with the dvd+rw-tools package.
Also, I don't know why you think /dev/sda2 is a dvd, that looks like a hard drive partition.  Your dvd drive is probably /dev/sr0.


text: Q: Python tornado - How to use Post method to same page I am following the github demo from the repo located at https://github.com/tornadoweb/tornado/tree/master/demos/chat but I cannot figure out how to Post in the index.html without redirect or render in a different html page. Is the redirection controlled by the python script or the js dile?


text:
Q: GitLab LDAP integration with JumpCloud not working I am trying to configure GitLab server to use JumpCloud LDAP as a service, but couldn't make it work. GitLab rake command shows that connectivity to LDAP server is successful but when I try to login, an error Could not authenticate you from Ldapmain because "Invalid Credentials". is shown
ldapsearch command produces output correctly:
ldapsearch -H ldap://ldap.jumpcloud.com:389 -D "uid=username,ou=Users,o=org12345,dc=jumpcloud,dc=com" -w "password"  -b "ou=Users,o=org12345,dc=jumpcloud,dc=com" "(objectClass=inetOrgPerson)" sAMAccountName

# extended LDIF
#
# LDAPv3
# base <ou=Users,o=org12345,dc=jumpcloud,dc=com> with scope subtree
# filter: (objectClass=inetOrgPerson)
# requesting: sAMAccountName
#

# username, Users, org12345, jumpcloud.com
dn: uid=username,ou=Users,o=org12345,dc=jumpcloud,dc=com

# user1, Users, org12345, jumpcloud.com
dn: uid=user1,ou=Users,o=org12345,dc=jumpcloud,dc=com

# search result
search: 2
result: 0 Success

# numResponses: 3
# numEntries: 2

Gitlab rake check
sudo gitlab-rake gitlab:ldap:check

Checking LDAP ...

Server: ldapmain
LDAP authentication... Success
LDAP users with access to your GitLab server (only showing the first 100 results)

Checking LDAP ... Finished

Error in unicorn_stdout.log
I, [2016-12-29T05:52:50.947393 #7067]  INFO -- omniauth: (ldapmain) Callback phase initiated.
E, [2016-12-29T05:52:51.834803 #7067] ERROR -- omniauth: (ldapmain) Authentication failure! invalid_credentials encountered.

Error shown to user

GitLab LDAP configuration
gitlab_rails['ldap_enabled'] = true
gitlab_rails['ldap_servers'] = YAML.load <<-'EOS' # remember to close this block with 'EOS' below
 main:
  label: 'LDAP'
  host: 'ldap.jumpcloud.com'
  port: 389 #Change to 636 if using LDAPS
  method: 'plain' # Change to "tls" if using LDAPS
  uid: 'sAMAccountName' # Don't change this
  bind_dn: 'uid=username,ou=Users,o=org12345,dc=jumpcloud,dc=com'
  password: 'password'
  active_directory: true
  allow_username_or_email_login: false
  block_auto_created_users: false
  base: 'ou=Users,o=org12345,dc=jumpcloud,dc=com'
  user_filter: '(objectClass=inetOrgPerson)'
EOS

I am certain that provided username and password are correct. Can someone please check and let me know if I am making a mistake in the configuration or is there something else I could check to solve this problem?
Thank you very much for your help
Reponse I received from JumpCloud support on 29/Dec:
After reviewing your configuration in addition to gitlab's it looks like it is necessitating that the uid field = sAMAccountName. This is a samba attribute, that we currently do not support. While in JumpCloud, the uid = uid . If you are able to change that field, it looks like it should connect but it appears that gitlab requires samba schema to authenticate via LDAP.

A: The bind_dn should be the domain\username used to connect to the ldap server. The bind_dn and password are used to authenticate GitLab with the LDAP service.
Here is what mine looks like:

bind_dn: 'gintra\gitlab-registrar'

A: Changing uid: 'sAMAccountName' to uid: 'uid' in your config should work:
gitlab_rails['ldap_enabled'] = true
gitlab_rails['prevent_ldap_sign_in'] = false

##! **remember to close this block with 'EOS' below**
gitlab_rails['ldap_servers'] = YAML.load <<-'EOS'
 main: # 'main' is the GitLab 'provider ID' of this LDAP server
 label: 'Gitlab LDAP'
 host: 'ldap.jumpcloud.com'
 port: 636
 uid: 'uid'
 bind_dn: 'uid=xxx,ou=Users,o=xxx,dc=jumpcloud,dc=com'
 password: 'xxx'
 encryption: 'simple_tls' # "start_tls" or "simple_tls" or "plain"
 #     verify_certificates: true
 smartcard_auth: false
 active_directory: true
 allow_username_or_email_login: false
 lowercase_usernames: false
 block_auto_created_users: false
 base: 'ou=Users,o=xxx,dc=jumpcloud,dc=com'
 user_filter: '(objectClass=inetOrgPerson)'
 EOS


text:
Q: Oracle Explain Plan via Sqlplus but for Multiple Queries from One Execution? I'm curious how would a structure look like from SQL Plus perspective mixed with bash magic, so the idea is to be able to parse x amount of .sql files with queries in them, how would this look like, for a single file it would be :
-- generate the explain plan
EXPLAIN PLAN SET statement_id = 'example_plan1'
FOR
  select * from dbms.database1_1 where numberline like '%4214%';

-- actually display the results
select plan_table_output
  from table(dbms_xplan.display('plan_table',null,'typical'));

But I'm unsure how it would look like from perspective of multi parse:
Example I upload 10-13 SQL's and I want all of them parsed via xplain and return the info either in one file or one for each, I guess one total result is more simple and easier to create.


text:
Q: Can I create a Hangout "client" program? (kind of Google TalkAbout) As stated in the Google Talk for Developers site, you can use the provided APIs to build a client that connects to the Google Talk service.
I would like to know if it's possible (or it will be in the near future) to build a similar client to the google hangouts.
What we pretend is to build something similar to cloud print, that provides printing services to the cloud, but for audio/video streaming: a camera and microphone would replace the
printer.
Thanks a lot.

A: Talk and all the XMPP stuff is going to be put down soon.
The new Hangouts infrastructure is proprietary. It only has API to integrate Hangouts into web pages and applications, but no API or protocol to create an alternative Hangouts client software.

A: https://github.com/tdryer/hangups is a library that does exactly that, with a command-line client for Linux.
https://github.com/xmikos/qhangups is a PyQt-based cross-platform app that aims to provide an open-source alternative to the Chrome-based official desktop app. Unfortunately it's not working at the time of posting, but the author is investigating the issue.


text:
Q: Python dictionary to variable assignments based on key value to variable name Basically, I want to take a
Dictionary like { "a":"bar", "b":"blah", "c":"abc", "d":"nada" }
and use it to set variables (in an Object) which have the same name as a key in the dictionary.
class Foo(object)
{
    self.a = ""
    self.b = ""
    self.c = ""
}

So in the the end self.a = "bar", self.b = "blah", etc... (and key "d" is ignored)
Any ideas?

A: Translating your class statement to Python,
class Foo(object):
  def __init__(self):
    self.a = self.b = self.c = ''
  def fromdict(self, d):
    for k in d:
      if hasattr(self, k):
        setattr(self, k, d[k])

the fromdict method seems to have the functionality you request.

A: class Foo(object):
    a, b, c = "", "", ""

foo = Foo()

_dict = { "a":"bar", "b":"blah", "c":"abc", "d":"nada" }
for k,v in _dict.iteritems():
    if hasattr(foo, k):
        setattr(foo, k, v)

A: Another option is to use argument unpacking:
class Foo(object):
     def __init__(self, a='', b='', c='', **kwargs)
         self.a = a
         self.b = b
         self.c = c

d = { "a":"bar", "b":"blah", "c":"abc", "d":"nada" }

f = Foo(**d)


text:
Q: Solve the classic third degree equation Find $x$ such that
$$x^3-6x^2-3x+2=0.$$
Solution: Classical cubic resolution gives three real solutions
$\boxed{2+\sqrt{20}\cos\frac{2k\pi+\arccos\sqrt\frac 45}3,k=0,1,2}$
(write $x=2+\sqrt{20}\cos t$)
I have heard that this was a method that came from Abel or Galois. Is it true or I have made a mistake?

A: This has nothing to do with either Abel or Galois. The trigonometric way of solving cubic equations, when they have three real roots, is due to Viète.

A: Wikipedia identifies François Viète (or Vieta) as having originally derived the trigonometric formula for cubic equations with three real roots.
The solution itself is correct.

A: First use Depressed cubic
$$y=x-2\iff x=y+2$$
$$0=(y+2)^3-6(y+2)^2-3(y+2)+2=y^3-15y-20$$
Use How would you find the roots of $x^3-3x-1 = 0$


text:
Q: How some objects are created before main event loop? While debugging, I came up with strange for me thing. In the main function, I commented out creation of window as follows:
#include <QApplication>
#include <QMetaType>
#include <QDebug>

//#include "mainwindow.h"

int main(int argc, char *argv[])
{
    qDebug() << "Creating QApplication";
    QApplication a(argc, argv);
    qDebug() << "QAplication has been created successfully";

    qDebug() << "Creating application window";
    // MainWindow w;
    qDebug() << "Displaying application window";
    // w.show();
    qDebug() << "Application window has been displayed successfully";

    return a.exec();
}

I thought I am just creating an event loop and lunching it. But output surprised me:
"17:28:32.793" ButtonControl: contructor.
"17:28:32.807" GestureControl: contructor
Creating QApplication
QAplication has been created successfully
Creating application window
Displaying application window
Application window has been displayed successfully

I have ButtonControl and GestureControl classes and first 2 lines of output are from their constructors. I create their objects inside of other class, which I use in MainWindow class. The strange thing for me is they are created before/without MainWindow and event loop. Their messages are printed even if I don't create QApplication object and call its exec() method. I tried cleaning and running qmake, and rebuilding, but no success. What's going on here? What is wrong with ButtonControl and GestureControl classes?
Env: win7, Qt 5.10, MSVC 2015.

Edit
Here is my Control class:
class Control : public QObject
{
    Q_OBJECT
public:
    explicit Control(QObject *parent = nullptr);
    static ButtonControl *getButtonController() {
        return &buttonController;
    }
    static GestureControl *getGestureController() {
        return &gestureController;
    }

private:
    static ButtonControl buttonController;
    static GestureControl gestureController;
};

I call this class inside my MainWindow. (As I understand from comments this code snippet is enough)

A: Following comments, I did a small research and found this answer:

Static members are initialized before main(), and they are destroyed in reverse order of creation after the return in main().
Static members are statically allocated, and their lifetime begins and ends with the program.

Thank you everyone who commented out.


text:
Q: How to access Wordpress authentication token We are trying to link our website to Wordpresses API using OAuth 2.0. Hoping that a client can authenticate and post to WordPress from our site. We need to receive an access token to do this.
We have successfully connected with Wordpress to receive our access code. We've followed the Wordpress api, and have it working for a single user (with secret key not with OAuth). Things we have tried are adding a headers, changing data to different names examples: params, body
This is a simplified version of the code we have been using
const axios = require('axios');
axios({
   method: "POST",
   data: {
       grant_type: 'authorization_code',
       client_id: '12345',
       client_secret: 'ABCABC1235412345',
       code: 'Abc123',
       redirect_uri: 'https://localhost:5000/wordpress/callback_wordpress'
   },
   url: 'https://public-api.wordpress.com/oauth2/token'
}).then( (response) => {
   console.log(response);
}).catch( (error) => {
   console.log(error);
});

We expect to receive a jwt access token, but instead are getting this 400 error:
data:
    { error: 'invalid_client',
      error_description: 'The required "client_id" parameter is missing.' } } }

It seems clear that we are missing the client_id, however we have it included in our request. Is there somewhere else we need to include it?

A:  var authOptions = {
        url: 'https://public-api.wordpress.com/oauth2/token',

        form:
        {
          grant_type: 'authorization_code',
          code: code,
          client_id: client_id,
          client_secret: client_secret,
          redirect_uri: redirect_uri,
        },
        headers: {
          'Authorization': 'Basic ' + (Buffer.from(client_id + ':' + client_secret).toString('base64'))
      },

        json: true
      };

We needed to include a header with that information, and we needed to use the variable 'form' instead of 'data'.


text:
Q: How can I convert regexp to like? I came across this question and apparently regexp are much slower than like.
MySQL regexp much slow than like
How can I convert the following regexp to like?
WHERE category REGEXP  '[[:<:]](5|50|51|52|53|54|55|56|57|58|59|60|61|62|63|64|65|66|67|68|69|70|71|72|73|74|75|76|77|78|79|80|81|82|83|84|85|86|87|88|89|90|91|92|93|94|95|96|97|98|99|100|101|102|103|104|105|106|107|108|109|110|111|112|113|114|115|116|117|118|119|120|121|122|123|124|125|126|127|128|129|130|131|132|133|134|135|136|137|138|139|140|141|142|143|144|145|146|147|148|149|150|151|152|153|154|155|156|157|158|159|160|161|162|163|164|165|166|167|168|169|170|171|172|173|174|175|176|177|178|179|180|181|182|183|184|185|186|187|188|189|190|191|192|193|194|195|196|197|198|199|200|201|202|203|204|205|206|207|208|209|210|211|212|213|214|215|216|217|218|219|220|221|222|223|224|225|226|227|228|229|230|231|232|233|234|235|236|237)[[:>:]]'

categories stored the following way per post:
15,19,66,12

A: This is not a direct answer to your question.  Instead, it is a brief explanation of how data structures should be stored in SQL.
You are storing a comma delimited list of categories on each row.  You then want to see if one of a large set of categories are in the list.  The appropriate data structure is an association table between the two.  It would be defined as something like:
create table ItemCategory (
    ItemCategoryId int auto_increment not null,
    ItemId int not null,
    CategoryId int not null
);

Then, when you want a comma delimited list, you would do:
select ic.ItemId, group_concat(ic.CategoryId) as categories
from ItemCategory ic
group by ic.ItemId;

When you wanted to find items that have one of a large set of categories:
select distinct ItemId
from ItemCategory ic
where ic.CategoryId in (<long list here>);

Then if you have an index on CategoryId, this will use the index and perform well.


text:
Q: extracting data through regexps is returning nil I'm trying to extract a pair of string from a parsed PDF and I have this extract:
Number:731    /         13/06/2016                 1823750212                                   10/06/2016\n\n\n\n Articolo

http://rubular.com/r/GRI6j4Byz3
My goal is to get out the 731 and 1823750212 values.
I tried something like text[/Number:(.*)Articolo/] for the first steps but it's returning nil while on rubular it somewhat matches.
Any tips?

A: Whether the format of the string is fixed (dates and the long number,) this will do the trick:
text.scan /\ANumber:(\d+).*?(\d{5,})/
#⇒ [[ "731", "1823750212" ]]

A: I have assumed that we do not know the length of either string (representations of non-negative integers) to be extracted, only that the first follows "Number:", which is at the beginning of the string, and the second is preceded and followed by at least one space.
r = /
    (?<=\A\Number:) # match beginning of string followed by 'Number:' in a
                    # positive lookbehind
    \d+             # match one or more digits
    |               # or
    (?<=\s)         # match a whitespace char in a positive lookbehind
    \d+             # match one or more digits
    (?=\s)          # match a whitespace char in a positive lookbehind
    /x              # free-spacing regex definition mode

str = "Number:731  /  13/06/2016  1823750212  10/06/2016\n\n\n\n Articolo"
str.scan(r)
  #=> ["731", "1823750212"]

If there could be intervening spaces between the colon and "731", you could do modify the regex as follows.
r = /
    \A      # match beginning of string followed by 'Number:' in a
            # positive lookbehind
    Number: # match string 'Number:'
    \s*     # match zero or more spaces
    \K      # forget everything matched so far
    \d+     # match one or more digits
    |       # or
    (?<=\s) # match a whitespace char in a positive lookbehind
    \d+     # match one or more digits
    (?=\s)  # match a whitespace char in a positive lookbehind
    /x      # free-spacing regex definition mode

str = "Number:  731  /  13/06/2016  1823750212  10/06/2016\n\n\n\n Articolo"
str.scan(r)
  #=> ["731", "1823750212"]

Here \K must be used because Ruby does not support variable-length positive lookbehinds.


text:
Q: delete uploaded file I have a function wp_handle_upload() for uploads files.
$file = $_FILES['attachment_icon-' . $i];
$upload = wp_handle_upload($file, array('test_form' => false));

what is a function for delete a uploaded file?

A: You can use unlink() to delete a file.
unlink('/path/to/file');


text:
Q: Cannot access Kubernetes exposed services by NodePort - The requests reaches timeout - What am I doing wrong? I know there are many questions concerning this aspect... but until now I could not find any answers. I tried two images (Apache Solr and Neo4J). Tried different namespaces, clusterIP, edit /etc/hosts, ingress, tunnel, minikube ip and all my requests got no response.
I tried these images standalone in Docker and they answer properly... with localhost, 127.0.0.1 and my ethernet IP - in case 192.168.0.15. I guessed that could be an internal configuration (from Sol, Neo4J) to allow requests only from localhost... but as they replied the calling from IP address and through a custom domain I set in /etc/hosts, I turned to kubernetes configuration.
Below are the following steps and environment:
1) MacOS 10.15 Catalina
2) minikube version: v1.24.0 - commit: 76b94fb3c4e8ac5062daf70d60cf03ddcc0a741b
3) Kubectl:
Client Version: version.Info{Major:"1", Minor:"23", GitVersion:"v1.23.1", GitCommit:"86ec240af8cbd1b60bcc4c03c20da9b98005b92e", GitTreeState:"clean", BuildDate:"2021-12-16T11:33:37Z", GoVersion:"go1.17.5", Compiler:"gc", Platform:"darwin/amd64"}
Server Version: version.Info{Major:"1", Minor:"22", GitVersion:"v1.22.3", GitCommit:"c92036820499fedefec0f847e2054d824aea6cd1", GitTreeState:"clean", BuildDate:"2021-10-27T18:35:25Z", GoVersion:"go1.16.9", Compiler:"gc", Platform:"linux/amd64"}
4) Docker:
Client:
 Cloud integration: v1.0.22
 Version:           20.10.11
 API version:       1.41
 Go version:        go1.16.10
 Git commit:        dea9396
 Built:             Thu Nov 18 00:36:09 2021
 OS/Arch:           darwin/amd64
 Context:           default
 Experimental:      true

Server: Docker Engine - Community
 Engine:
  Version:          20.10.11
  API version:      1.41 (minimum version 1.12)
  Go version:       go1.16.9
  Git commit:       847da18
  Built:            Thu Nov 18 00:35:39 2021
  OS/Arch:          linux/amd64
  Experimental:     false
 containerd:
  Version:          1.4.12
  GitCommit:        7b11cfaabd73bb80907dd23182b9347b4245eb5d
 runc:
  Version:          1.0.2
  GitCommit:        v1.0.2-0-g52b36a2
 docker-init:
  Version:          0.19.0
  GitCommit:        de40ad0

minikube start --mount --mount-string="/my/local/path:/analytics" --driver='docker'
kubectl apply -f neo4j-configmap.yaml
kubectl apply -f neo4j-secret.yaml
kubectl apply -f neo4j-volume.yaml
kubectl apply -f neo4j-volume-claim.yaml
kubectl apply -f neo4j.yaml
kubectl apply -f neo4j-service.yaml

apiVersion: v1
kind: ConfigMap
metadata:
    name: neo4j-configmap
data:
     neo4j-url: neo4j-service
---
apiVersion: v1
kind: Secret
metadata:
  name: neo4j-secret
type: Opaque
data:
    neo4j-user: bmVvNGoK
    neo4j-password: bmVvNGoK
---
apiVersion: v1
kind: PersistentVolume
metadata:
  name: neo4j-volume
spec:
  storageClassName: hostpath
  capacity:
    storage: 101Mi
  volumeMode: Filesystem
  accessModes:
    - ReadWriteOnce
  persistentVolumeReclaimPolicy: Retain
  hostPath:
      path: "/analytics/neo4j"
---
apiVersion: v1
kind: PersistentVolumeClaim
metadata:
  name: neo4j-volume-claim
  labels:
    app: neo4j
spec:
  storageClassName: hostpath
  volumeMode: Filesystem
  volumeName: neo4j-volume
  accessModes:
    - ReadWriteOnce
  resources:
    requests:
      storage: 101Mi
---
apiVersion: apps/v1
kind: Deployment
metadata:
  name: neo4j-application
  labels:
    app: neo4j
spec:
  replicas: 1
  selector:
    matchLabels:
      app: neo4j
  template:
    metadata:
      labels:
        app: neo4j
    spec:
      volumes:
        - name: neo4j-storage
          persistentVolumeClaim:
            claimName: neo4j-volume-claim
      containers:
        - name: neo4j
          image: neo4j:4.1.4
          ports:
          - containerPort: 7474
            name: neo4j-7474
          - containerPort: 7687
            name: neo4j-7687
          volumeMounts:
          - name: neo4j-storage
            mountPath: "/data"
---
apiVersion: v1
kind: Service
metadata:
  name: neo4j-service
spec:
  type: NodePort
  selector:
    app: neo4j
  ports:
    - protocol: TCP
      port: 7474
      targetPort: neo4j-7474
      nodePort: 30001
      name: neo4j-port-7474
    - protocol: TCP
      port: 7687
      targetPort: neo4j-7687
      nodePort: 30002
      name: neo4j-port-7687

The bash steps where executed in that order. I have each yaml configuration in a separated file. I joined they here as just one yaml just to expose then.
What part or parts of the setup process or configuration process am I missing?
Below follows the kubectl describe all with only neo4j. I tried http, https request from all possibles IP... Connected to each pod and perform a curl inside the pod... and got successfully responses.
Name:         neo4j-application-7757948b98-2pxr2
Namespace:    default
Priority:     0
Node:         minikube/192.168.49.2
Start Time:   Sun, 09 Jan 2022 14:19:32 -0300
Labels:       app=neo4j
              pod-template-hash=7757948b98
Annotations:  <none>
Status:       Running
IP:           172.17.0.4
IPs:
  IP:           172.17.0.4
Controlled By:  ReplicaSet/neo4j-application-7757948b98
Containers:
  neo4j:
    Container ID:   docker://2deda46b3bb15712ff6dde5d2f3493c07b616c2eef3433dec6fe6f0cd6439c5f
    Image:          neo4j:4.1.4
    Image ID:       docker-pullable://neo4j@sha256:b1bc8a5c5136f4797dc553c114c0269537c85d3580e610a8e711faacb48eb774
    Ports:          7474/TCP, 7687/TCP
    Host Ports:     0/TCP, 0/TCP
    State:          Running
      Started:      Sun, 09 Jan 2022 14:19:43 -0300
    Ready:          True
    Restart Count:  0
    Environment:    <none>
    Mounts:
      /data from neo4j-storage (rw)
      /var/run/secrets/kubernetes.io/serviceaccount from kube-api-access-z5hq9 (ro)
Conditions:
  Type              Status
  Initialized       True
  Ready             True
  ContainersReady   True
  PodScheduled      True
Volumes:
  neo4j-storage:
    Type:       PersistentVolumeClaim (a reference to a PersistentVolumeClaim in the same namespace)
    ClaimName:  neo4j-volume-claim
    ReadOnly:   false
  kube-api-access-z5hq9:
    Type:                    Projected (a volume that contains injected data from multiple sources)
    TokenExpirationSeconds:  3607
    ConfigMapName:           kube-root-ca.crt
    ConfigMapOptional:       <nil>
    DownwardAPI:             true
QoS Class:                   BestEffort
Node-Selectors:              <none>
Tolerations:                 node.kubernetes.io/not-ready:NoExecute op=Exists for 300s
                             node.kubernetes.io/unreachable:NoExecute op=Exists for 300s
Events:
  Type     Reason            Age   From               Message
  ----     ------            ----  ----               -------
  Warning  FailedScheduling  35m   default-scheduler  0/1 nodes are available: 1 pod has unbound immediate PersistentVolumeClaims.
  Normal   Scheduled         35m   default-scheduler  Successfully assigned default/neo4j-application-7757948b98-2pxr2 to minikube
  Normal   Pulling           35m   kubelet            Pulling image "neo4j:4.1.4"
  Normal   Pulled            35m   kubelet            Successfully pulled image "neo4j:4.1.4" in 3.087215911s
  Normal   Created           34m   kubelet            Created container neo4j
  Normal   Started           34m   kubelet            Started container neo4j

Name:              kubernetes
Namespace:         default
Labels:            component=apiserver
                   provider=kubernetes
Annotations:       <none>
Selector:          <none>
Type:              ClusterIP
IP Family Policy:  SingleStack
IP Families:       IPv4
IP:                10.96.0.1
IPs:               10.96.0.1
Port:              https  443/TCP
TargetPort:        8443/TCP
Endpoints:         192.168.49.2:8443
Session Affinity:  None
Events:            <none>

Name:                     neo4j-service
Namespace:                default
Labels:                   <none>
Annotations:              <none>
Selector:                 app=neo4j
Type:                     NodePort
IP Family Policy:         SingleStack
IP Families:              IPv4
IP:                       10.98.131.77
IPs:                      10.98.131.77
Port:                     neo4j-port-7474  7474/TCP
TargetPort:               neo4j-7474/TCP
NodePort:                 neo4j-port-7474  30001/TCP
Endpoints:                172.17.0.4:7474
Port:                     neo4j-port-7687  7687/TCP
TargetPort:               neo4j-7687/TCP
NodePort:                 neo4j-port-7687  30002/TCP
Endpoints:                172.17.0.4:7687
Session Affinity:         None
External Traffic Policy:  Cluster
Events:                   <none>

Name:                   neo4j-application
Namespace:              default
CreationTimestamp:      Sun, 09 Jan 2022 14:19:27 -0300
Labels:                 app=neo4j
Annotations:            deployment.kubernetes.io/revision: 1
Selector:               app=neo4j
Replicas:               1 desired | 1 updated | 1 total | 1 available | 0 unavailable
StrategyType:           RollingUpdate
MinReadySeconds:        0
RollingUpdateStrategy:  25% max unavailable, 25% max surge
Pod Template:
  Labels:  app=neo4j
  Containers:
   neo4j:
    Image:        neo4j:4.1.4
    Ports:        7474/TCP, 7687/TCP
    Host Ports:   0/TCP, 0/TCP
    Environment:  <none>
    Mounts:
      /data from neo4j-storage (rw)
  Volumes:
   neo4j-storage:
    Type:       PersistentVolumeClaim (a reference to a PersistentVolumeClaim in the same namespace)
    ClaimName:  neo4j-volume-claim
    ReadOnly:   false
Conditions:
  Type           Status  Reason
  ----           ------  ------
  Available      True    MinimumReplicasAvailable
  Progressing    True    NewReplicaSetAvailable
OldReplicaSets:  <none>
NewReplicaSet:   neo4j-application-7757948b98 (1/1 replicas created)
Events:
  Type    Reason             Age   From                   Message
  ----    ------             ----  ----                   -------
  Normal  ScalingReplicaSet  35m   deployment-controller  Scaled up replica set neo4j-application-7757948b98 to 1

Name:           neo4j-application-7757948b98
Namespace:      default
Selector:       app=neo4j,pod-template-hash=7757948b98
Labels:         app=neo4j
                pod-template-hash=7757948b98
Annotations:    deployment.kubernetes.io/desired-replicas: 1
                deployment.kubernetes.io/max-replicas: 2
                deployment.kubernetes.io/revision: 1
Controlled By:  Deployment/neo4j-application
Replicas:       1 current / 1 desired
Pods Status:    1 Running / 0 Waiting / 0 Succeeded / 0 Failed
Pod Template:
  Labels:  app=neo4j
           pod-template-hash=7757948b98
  Containers:
   neo4j:
    Image:        neo4j:4.1.4
    Ports:        7474/TCP, 7687/TCP
    Host Ports:   0/TCP, 0/TCP
    Environment:  <none>
    Mounts:
      /data from neo4j-storage (rw)
  Volumes:
   neo4j-storage:
    Type:       PersistentVolumeClaim (a reference to a PersistentVolumeClaim in the same namespace)
    ClaimName:  neo4j-volume-claim
    ReadOnly:   false
Events:
  Type    Reason            Age   From                   Message
  ----    ------            ----  ----                   -------
  Normal  SuccessfulCreate  35m   replicaset-controller  Created pod: neo4j-application-7757948b98-2pxr2

A: As mentioned in comments and in this post, the way you would expose app running in minikube via NodePort is my running the command:
minikube service <SERVICE_NAME> --url
Which prints out url you can paste in your browser.
You also mentioned:

With the url fro minikube service I could reach the endpoint!   Starting tunnel for service neo4j-service. http://127.0.0.1:49523 and http://127.0.0.1:49524. But considering the domain of the application... What should I do with NodePort 30001? What is the correct way to configure a kubernetes node?

The output you pasted is correct, you are getting a successful response. As for the NodePort - minikube maps this port to url that you are getting when running command mentioned before. Read more on accessing apps running in minikube here


text:
Q: Confusion over passive sentence I am currently writing an instructional document. I thought it'd be a good idea to use a readability tester for my dear future readers.
One sentence I put through the readability tester was detected as a passive sentence. The sentence is:
'All clients who are eligible to be reunited with their loved ones fall into one of the two following categories:'
The passive detector is picking up 'to be'.
I can't figure out how this is passive or how to change it.
I ended up re-writing the sentence: 'There are two categories for clients who are eligible for the program, as follows:'
But, I would like to know what I did wrong in the first place. I realise there is sometimes a place for passive sentences, but I've already used a lot of passive voice in my previous paragraphs.
Can anyone point out exactly what I was doing wrong and how to fix it?

A: The computer is correct that "to be reunited" is a passive construction because the subject of the verb is not the one causing the reuniting. (See the edit below for a more detailed explanation.) A passive construction, however, does not entail that good style demands recasting the sentence.
It is simple minded to object to the passive as an invariable rule. There are sometimes good reasons to prefer the active voice. There are sometimes good reasons to prefer the passive voice. I do agree that careless writers frequently use the passive voice when the active voice is preferable, but good writers freely use the passive voice when it is appropriate. A simple computer program can highlight use of the passive to permit consideration of whether the active voice is superior in a particular case, but that is no substitute for stylistic judgment in each case.
Style is inevitably personal. My personal rule is to avoid the passive when designating the actor is both possible and important. In your original sentence, I presume that the re-uniting actor will be understood by the audience, and thus I find the passive construction unobjectionable in this case. Nevertheless, the sentence is prolix.
Notice that your re-written sentence conveys less information than your original. If the information omitted will be understood by your audience, that is fine, but in that case I would write "Eligible clients fall into two categories" because that gives the important information clearly and quite concisely. But this is a matter of style, not grammar: there was no grammatical error in your original sentence. Computers are not yet great stylists.
EDIT: As tchrist correctly pointed out, the passive phrase was not passive because the actor was unspecified. That is not the defining characteristic of the passive.
A transitive verb used in the active voice specifies who or what performed the action as the subject of the verb and what the action was performed on as the object of the verb. "Mary hugged Bill" means that Mary, the subject of the verb, was the one doing the hugging, and Bill, the object of the verb, was the one getting the hug. If the verb is in the passive voice, the subject of the verb is what the action was performed on. "Bill was hugged" still means that Bill was the one getting the hug even though "Bill" is the subject of the sentence. Notice in that example the actor is unspecified, which is possible when using the passive. But leaving the actor unspecified is not necessary: "Bill was hugged by Mary" identifies who gave the hug, namely Mary, but "Bill" is still the subject of the sentence.


text:
Q: Sudden Website Title Change and Order Email Notification not Working I am not sure about my what happened to my site but the site title suddenly change to

+ADw-/title+AD4-Hacked By Mister Spy +ACYAJg Souheyel.+ADw-DIV style+AD0AIg-DISPLAY: none+ACIAPgA8-xmp+AD4

and my order email is not working properly. Anyone got same problem?
Do you think what happened to my site? Any Solution to this?

A: Ah, the clue is this: "Hacked By Mister Spy".
You got hacked because you are using an old version of WordPress. That's very typical; when running WordPress, keep it and all themes/plugins updated in order to stay safe and secure.
Since version 3.7, WordPress will automatically update itself with security fixes when they are released by WordPress. FYI, these security updates are not full updates to the latest version; they are patches, and you will still see advisories to fully update to the latest full version.
To correctly clean your site and hosting account of the hack, carefully follow https://codex.wordpress.org/FAQ_My_site_was_hacked .
Then take a look at the recommended security measures in https://codex.wordpress.org/Hardening_WordPress and http://codex.wordpress.org/Brute_Force_Attacks


text:
Q: Is a vector of coprime integers column of a regular matrix? Given a vector $a_1=(k_1,\ldots,k_n)^T$ of coprime integers. Are there $a_2,\ldots,a_n \in \mathbb{Z}^n$ such that that the matrix $A := (a_1,\ldots,a_n) \in \mathbb{Z}^{n \times n}$ is regular, i.e. $A \in GL_n(\mathbb{Z})$ ?
In case $n=2$ this is true because there are integers $l_1,l_2$ s.t. $k_1l_1 + k_2l_2 = 1$. Then $a_2=(-l_2 , l_1)^T$ will do.

A: Solution from "Problems From The Book":
Yes, by induction. Let $g= \gcd(k_1,\dots,k_{n-1})$, and do it for $k_1/g, \dots, k_{n-1}/g$, call this matrix $A'$.
Add to $A'$ the following row: $(k_n /g , 0, \dots ,0)$. (almost all zeroes)
$g$ must be coprime to $k_n$, so we can find integers $x,y$ such that $xg+yk_n = 1$.
Now add it the following column: $(yk_1,yk_2, \cdots, y k_{n-1}, xg)^{T}$. (almost proportional to first column)
It can be verified that the matrix has determinant $\pm 1$. To make the entries integral, multiply the first column by $g$ and divide the last column by $g$.

A: You should have specified which sense of coprime you mean: no nontrivial common factor to all at once or no nontrivial common factor to at least two of them. However the answer is "yes" even under the weaker former interpretation of the hypothesis.
More generally a set of independent elements of $\mathbb Z^n$ can be completed to a $\mathbb Z$-basis if the lattice of their $\mathbb Z$-linear combinations is saturated: $\mathbb Z^n$ contains no other rational linear combinations of them. Any saturated lattice is a direct factor of $\mathbb Z^n$, and one can complete the basis by choosing a complementary factor, and a basis of that. In the case of one vector, the weak coprime condition precisely means the rank $1$ lattice it spans is saturated.
The mentioned property can be proved by the Smith normal form for the inclusion map sending $\mathbb Z^r\to\mathbb Z^n$ where $r$ is the rank of the saturated sublattice; the saturated condition means there are no invariant factors greater than $1$.


text:
Q: Flex: Inline Component is not defined? I opened up FB3 today, without making any changes, I press F11 and now I am getting this error that I never have gotten before:
ReferenceError: Error #1065: Variable CaratPicker2_inlineComponent1 is not defined.
I find it strange I am getting this error everytime now, when I never got it before and I didn't make any changes before I started getting it.
Anyways it is coming from line 78 which is <mx:Component> the start of an inline item renderer.
So any ideas how or why this error is being thrown? I have never seen an error like this before and the message isn't very clear to me as to what the issue is.
Thanks!!!

A: I'd start with Flex Builder upper menu -> Project -> Clean...
It looks like there are problems with the generated actionscript code. The mxml components get "translated" to .as files by the compiler but, for efficiency, it tries to keep them for as long as possible instead of generating them again each time.

A: I got this inline component not defined error, too.
But my problem is there are two mxml documents with the same name in the project(not in the same package)
so the solution is change the file name and make sure all mxml files have different name.


text:
Q: LastAccessTime of the very last accessed File of an array of Folder I'd like to get an overview of the latest accessed file per profile directory out of a list of profile directories and then write the result in a file.
Given:
A folder with a ton of profile directories in it. In every profile directory, there are more folders and files.
Wanted:
I need the date with the name of the profile directory of the latest accessed file of each profile directory within the parent folder.
What I already have:
With the following commands, the output file lists the last accessed file out of all files in the whole directory times the count of profile directories in the folder:
cd \\Servername\Patch\Profiles
$folder = Get-ChildItem -Directory
$folder | ForEach-Object {
  Get-ChildItem -Recurse |
    Sort-Object -Property LastAccessTime -Descending |
    Select-Object -First 1
} | Out-File "C:\Users\User-abc\Desktop\Log.txt"

So I tried to add the specific path for each profile folder within the parent folder to the Get-ChildItem command like this:
... ForEach-Object {
  Get-ChildItem -Path ".\$folder" -Recurse |
    Sort-Object ...

I also tried to add a .Name to the $folder variable and to remove the " or put ' instead of ", but nothing helped. I always get the response that there is no parameter found for the parameter -Path.
I also tried to remove the -Path parameter but let the .\$folder or even add a [0] or [1] to the $folder variable, but that also doesn't help.

A: Call Get-ChildItem on the full path of the current object in the pipeline:
Get-ChildItem \\Servername\Patch\Profiles -Directory | ForEach-Object {
  Get-ChildItem $_.FullName -Recurse |
    Sort-Object -Property LastAccessTime -Descending |
    Select-Object -First 1
}


text:
Q: How to programmatically catch which command failed on a try block I'm trying to get some data from an JSON API. I don't want all the data that the API returns so I wrote a method that reads all the data and returns a dictionary with the relevant fields. Sometimes though, some data are missing and I would like to replace the fields that are missing with an underscore. A sample of the method is like that;
return {
    'foo': data['foo'],
    'bar': data['bar']
 }

If a field is missing from the data, this throughs a KeyError. Is it possible to catch programmatically which field produced the error, in a single try-except block and not write a try-except block for every field?
try:
    ret_dict =  {
        'foo': data['foo'],
        'bar': data['bar']
    }
 except KeyError:
    ret_dict[thefailurekey] = '_'

instead of
ret_dict = {}
try:
    ret_dict['foo'] = data['foo']
except KeyError:
    ret_dict['foo'] = '_'
try:
    ret_dict['bar'] = data['bar']
except:
    ret_dict['bar'] = '_'

Thank you

A: You can probably get that information from the members of the KeyError exception object, but a simpler way would be to just use get() that will return a default value if the key is not there.
return {
    'foo': data.get('foo', '_'),
    'bar': data.get('bar', '_'),
 }

Another reason this is better than handling an exception is that you can only handle one exception. What happens if two keys are missing? And on top of that, ret_dict will not even be defined in your example because the code failed.

A: Instead of using try block, you can use dict.get(key, default_val)
For example:
ret_dict = dict(
    foo=data.get('foo', '-'),
    bar=data.get('bar', '-')
)

return ret_dict

A: Use .get method of dict:
def get_data(data):
    return {
        # If you want to accept falsy values from API:
        'foo': data.get('foo', '_'),

        # If you want to override falsy values from API:
        'bar': data.get('bar') or '_',
    }

.get returns its second argument (None by default) if a dict doesn't have requested key, so it is always safe to use it in uncertain situations.
Example:
>>> data = {'foo': False, 'bar': False}
>>> get_data(data)
{'bar': '_', 'foo': False}

A: If you want to avoid the repetitiveness of typing .get(attr, '_') for each key, you can use a defaultdict, setting it to return _ when a key is trying to be accessed but missing.
from collections import defaultdict

data = {
    'foo': 'foo_value',
}

ret_dict = defaultdict(lambda: '_')
ret_dict.update(data)

print(ret_dict['foo'])  # 'foo_value'
print(ret_dict['bar'])  # '_'


text:
Q: Greek Document in LyX - "Corrupted NFSS Tables" I am trying to write a document in Greek using LyX but I get the 5 "Corrupted NFSS tables".
I installed every font package I found and every package related to the greek language. What can I do to fix that?
The log is this.


text:
Q: .net and dnn framework up-gradation I am facing an issue while upgrading my application. My application was built on .net framework 2.0 and DNN 4.09. Now we are going through up-gradation of both. But how can i verify that my .net framework is now 3.5 ? whenever i get an exception it shows .net 2.0 on yellow screen of death. And after it i tried to upgrade my DNN 4.09 to 5.02. Application is running smooth but admin panel is showing many crashing.It shows crashing of htmlmodule.dll
 enter image description hereenter image description here

A: In DNN you can view the .Net version under "Host > Host settings" select the tab "Basic Settings". You will see an "Configuration" section. Here you can find basic hosting environment settings. Note that the names of the pages and tabs can vary a bit from version to version.
You can also check in IIS itself what kind of .Net version the Application Pool is using.

A: You will need to change the app pool .Net version in IIS.
Then in your application you will need to change the .Net version in the assembly info to build against the same version of the DotNetNuke.dll assembly you have referenced in the project.
Here is a link to how to update it in IIS: http://www.dnnsoftware.com/community-blog/cid/134981/upgrading-dotnetnuke-to-aspnet-40
If that doesn't work please attach a screenshot of the error.


text:
Q: creating new VM in azure that uses existing vhd Is it possible to create a new VM (Azure RM) that uses an existing vhd disk (where everything is already set up) that is already on a storage account? In the new portal, I can't find any option for doing that. But can it be done by editing a template or by using PowerShell? Can anyone point me to any docs about this?

A: You can deploy an existing Vhd from both PowerShell and ARM Templates.
There are two methods of using an existing image. You can either directly attach that disk or you can use that disk as an image source.
If you look at the Create a Virtual Machine from a User Image template on Github. There is both a template and a PowerShell script.
Both of those are currently configured to make a copy of the Vhd and use that. If you want to directly attach your Vhd you would need to change this line (currently line 168) in the template
"createOption": "FromImage",

to
"createOption": "Attach",

You would do the same for the createoption of Add-AzureVMDataDisk

A: Yes you can create a Resource Manager VM from a VHD. It is possible through aRMT template. in Github there is a reference template, please edit and deploy that.
Thanks!
Sabha Mahadevan


text:
Q: What is happening with these arrays in C pointer notation? I'm a bit confused about pointer arrays and I just wanna make sure I'm right.
When I write int *arrit is just a pointer to an int variable, not an array yet. It is only that I initialize it (say with malloc) that it becomes an array. Am I right so far?
Also I have another question: were given (in school) a little function that is supposed to return an array of grades, with the first cell being the average. The function was deliberately wrong: what they did was to set
int *grades = getAllGrades();

And than they have decreased the pointer by one for the average 'cell'
*(grades - 1) = getAverage();
 return *(grades - 1)

I know this is wrong because the returned value is not an array, I just don't know how to explain it. When I set a pointer, how does the machine/compiler know if I want just a pointer or an array?
(If I'm not clear its because I'm trying to ask about something that is still vague for me, my apologizes)

A:
how does the machine/compiler know if I want just a pointer or an
  array?

It doesn't, and it never will. Suppose you
int *a = malloc(3 * sizeof(int));

You just allsocated 12 bytes (assuming int is 4). But malloc only sees 12. Is that 1 big object or lots of little ones? It doesn't know. The only one who actually knows is you ;)
Now about your particular example,
int *grades = getAllGrades();

At this point, as you said, there's nothing to say whether grades points to an array. But you know it points to an array, and that's what's important. Or, maybe you know it doesn't point to an array. The key is you have to know what getAllGrades does, to know if it's returning an array or a pointer to 1 thing.
*(grades - 1) = getAverage();
return *(grades - 1)

This is not necessarily wrong, but it does look kind of sketch. If it is an array, you would expect grades[0] == *(grade + 0) to be the first element, so grades[-1] == *(grades - 1) looks like it would be before the first element. Again, it's not necessarily wrong; maybe in getAllGrades they did:
int* getAllGrades() {
    int *grades = malloc(sizeof(int) * 10);
    return grades + 1;
}

ie they scooched the start up by 1. It's been known to happen (look in Numerical Recipes in C) but it's kind of odd.

A: Arrays are not pointers.  Pointers are not arrays.
Perhaps it would be clearer to say that array objects are not pointer objects, and vice versa.
When you declare int *arr, arr is a pointer object.  That's all it is; it cannot be, and never will be, an array.
When you execute arr = malloc(10 * sizeof *arr);, (if malloc() doesn't fail, which you should always check), arr now points to an int object.  That object happens to be the first element of a 10-element array of int (the one created by the malloc call).  Note that there is such a thing as a pointer to an array, but this isn't it.
Arrays, in a very real sense, are not first-class types in C.  You can create and manipulate array objects as you can with any other type of objects, but you'll rarely deal with array values directly.  Instead, you'll deal with the elements of an array object indirectly, via pointers to those elements.  And in the case of the arr declaration above, you can perform arithmetic on the pointer to the first element to obtain pointers to the other elements (and you have to have some other mechanism to remember how many elements there are).
Any expression of array type, in most contexts, is implicitly converted to a pointer to the array's first element (the exceptions are: the operand of a unary & operator, the operand of the sizeof operator, and a string literal in an initializer used to initialize an array (sub)object).  That's the rule that makes it seem as if arrays and pointers are interchangeable.
The array indexing operator [] is actually defined to work on pointers, not arrays.  a[b] is simply another way of writing *((a)+(b)).  If a happens to be the name of an array object, it's first converted to a pointer, as I describe above.
I highly recommend reading section 6 of the comp.lang.c FAQ.  (The link is to the front page, not directly to section 6, because I like to encourage people to browse the whole thing.)
I mentioned that there are array pointers.  Given int foo[10];, &foo[0] is a pointer to an int, but &foo is a pointer to the entire array.  Both point to the same location in memory, but they're of different types, and they behave quite differently under pointer arithmetic.

A:
When I write int *arr it is just a pointer to an int variable, not
  an array yet. It is only that I initialize it (say with malloc) that
  it becomes an array. Am I right so far?

Well, yes and no :). arr is a pointer to (or the address of) some block of memory. Until arr is initialized it probably points to an invalid, or non-sense memory address. So it may be confusing to think of arr as a pointer to an int variable. For example, before the malloc, you can't store an integer in the location that it is pointing to.
Also, it may be easier to understand if you say that after the malloc, arr points to an array, it does not "become" an array. Before the malloc, arr points to some random non-sense location.

When I set a pointer, how does the machine/compiler know if I want
  just a pointer or an array?

If you set a pointer (e.g. arr = <something>) you are just changing where the pointer points. That may be what you want. If don't want to change where arr points but you want to change the values stored in the memory where it is pointing you have to do it one element at a time (e.g. with a for loop that iterates over each element in the array).

A: You are right, the only difference between arrays and pointers is convention. Here's a picture of what memory must look like when the getAllGrades() function returns:
                          | secret malloc() stuff |
                          +-----------------------+
                          | average value         |
                          +-----------------------+  ----\
grades* points here --->  | grade at index 0      |      |  by convention
                          +-----------------------+      |  this stuff is
                          | grade at index 1      |      |  called grades[]
                          +-----------------------+      |
                          | grade at index 2      |      |
                          +-----------------------+      .
                          | ...                   |      .

Now, there is no difference between an array and a pointer. So, when the compiler sees *(grades - 1) it first subtracts 1 from the grades pointer. This is special pointer arithmetic so it knows to go one whole int block upwards, and points at the average value. Then it can operate on this value, for example to set the average with *(grades - 1) = getAverage().
An aside on array indexing: Array indexing gets compiled exactly like pointer arithmetic. For example, grades[2] gets compiled down to *(grades + 2) which does pointer arithmetic to move down 2 blocks to the memory address marked "grade at index 2" in my picture. This means you could change *(grades - 1) = getAverage() to grades[-1] = getAverage() and it would work exactly the same.
If you wanted to experiment you could do (-1)[grades] which compiles down to *(-1 + grades) and works as well, but that's stupid so don't do that :)


text:
Q: Clone a file in linux kernel module I'm having some problem with a linux module, I want to clone a file from a file descriptor. I tried using
vfs_clone_file_range

but i receive EOPNOTSUPP error. So I tried to use vfs_copy_file_range, and the copy works correctly, but I need to have also the same flags of the original one, but in this way, even if the original is open with O_APPEND the pointer of the copy is always at the begin of the file.
This is my code:
//The file descriptor is taken correctly and it works
original_filp = fcheck(o_fd);
copy_filp = filp_open(addr, O_CREAT | O_RDWR  , 0644);
vfs_copy_file_range(original_filp, 0, copy_filp, 0, i_size_read(original_filp->f_inode), 0);

The content is the right but the pointer, as I said is at the begin even with the O_APPEND flag, so I should move the pointer explicitly.
I also tried to add this line, but without results:
copy_filp->f_pos = original_filp->f_pos;

I really have no idea what to change in order to make it working.
Thank you in advance for your help

A: I don't know if I get it, but according with the documentation, the copy_file_range returns EBADF error code when the file_out has the O_APPEND set. So a way to solve can be:
//The file descriptor is taken correctly and it works
original_filp = fcheck(o_fd);
copy_filp = filp_open(addr, O_CREAT | O_RDWR  , 0644);
vfs_copy_file_range(original_filp, 0, copy_filp, 0, `i_size_read(original_filp->f_inode), 0);`
copy_filp->f_flags=original_filp->f_flags

In this way you have the same flags set on the two files


text:
Q: Unrecognized Selector For Scene Transition Button Hey I'm new to Xcode so maybe this has a very easy fix and in that case I'm sorry but I've tried everything and looking online and nothing has worked so far. Basically I created a continueButton to transition to the next scene in the app once the level has been completed. Heres what its code looks like
UIButton *continueButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
continueButton.frame = CGRectMake(120, 150, 80, 44);
[continueButton setTitle:@"Continue" forState:UIControlStateNormal];
[continueButton addTarget:self action:@selector(SKTransition:) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:continueButton];

Then I defined what happens when I click on the continueButton as this.
-(void)buttonPressed:(UIButton *)sender
{
    SKAction *levelChange = [SKAction runBlock:^{

        SKTransition *doors = [SKTransition
                               doorsOpenVerticalWithDuration:2];

        SKScene *Level2Scene  = [[Transition2Scene alloc]
                                 initWithSize:self.size];

        [self.view presentScene:Level2Scene transition:doors];
        [self runAction:levelChange];
    }];
}

However whenever I run that app and click on the continueButton I get this error.

2014-07-27 21:14:14.225 MazeGame[40846:60b] -[Level1Scene
  SKTransition:]: unrecognized selector sent to instance 0x14158670
  (lldb)

at this point in the code.
#import <UIKit/UIKit.h>
#import "SpriteAppDelegate.h"

int main(int argc, char * argv[])
{
    @autoreleasepool {
        return UIApplicationMain(argc, argv, nil, NSStringFromClass([SpriteAppDelegate class]));
    }
}

I don't exactly know what went wrong or what I should do and would really appreciate some help/advice thanks!

A: My guess is that the issue is this line:
[continueButton addTarget:self action:@selector(SKTransition:) forControlEvents:UIControlEventTouchUpInside];

It should be:
[continueButton addTarget:self action:@selector(buttonPressed:) forControlEvents:UIControlEventTouchUpInside];


text:
Q: Getting blank page After uploading the build code into cPanle I am trying to deploy the react code on cPanel and I refer to this link but I am getting a blank page.
Any suggestion on how to solve this?
I have the below code in package.json
{
  "name": "New",
  "homepage": "https://example.com/new/",
  "version": "0.1.0",
  "private": true,
  "dependencies": {
    "@testing-library/jest-dom": "^5.16.4",
    "@testing-library/react": "^13.1.1",
    "@testing-library/user-event": "^13.5.0",
    "bootstrap": "^5.1.3",
    "jquery": "^3.6.0",
    "react": "^18.0.0",
    "react-dom": "^18.0.0",
    "react-router-dom": "^6.3.0",
    "react-scripts": "^2.1.3",
    "react-scroll": "^1.8.7",
    "web-vitals": "^2.1.4"
  },
  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test",
    "eject": "react-scripts eject"
  },
  "eslintConfig": {
    "extends": [
      "react-app",
      "react-app/jest"
    ]
  },
  "browserslist": {
    "production": [
      ">0.2%",
      "not dead",
      "not op_mini all"
    ],
    "development": [
      "last 1 chrome version",
      "last 1 firefox version",
      "last 1 safari version"
    ]
  }
}

A: I'm not sure where you're uploading the build but what you're showing isn't the build.
The build doesn't require a package.json.
If I understand correctly - what you need to do is go to you local folder where the project is and run:
npm run build

It'll create a folder called 'build', take all the files from this folder (you'll see the index.html there) and upload it to you cPanel.


text:
Q: .NET Regex to match repeated character I'm trying to use .NET regular expressions to detect cases where a string has 5 or more characters and the only character in the string is the same.  So these would be seen as matches:

*

*0000000000000

*ZZZZZZZZZ

*AAAAAA

But these wouldn't:

*

*000000A000000

*ZZZZZZ ZZZ  Z

*AA

Is there a regular expression that could detect this pattern?

A: Wiktor was close, but his will only match exactly 5 characters. Sounds like you want 5 or more. So what I'd use is
^(.)\1{4,}$
The (.)\1 will capture exactly one character. The {4,} specifies that the one character is then repeated 4 or more times. Wrapping it all in ^ and $ means the string starts immediately before that and ends immediately after, so nothing else is allowed to come before or after it.


text:
Q: WPF - "Initialize Component does not exist in the current context" caused when adding project reference I am developing a WPF application which will utilise a class library project within my solution.
I began by creating the view in my Xaml file and adding the UI functionality.
I have now added a reference to my class library which sits in the same solution and I am receiving the error:

The name 'InitializeComponent' does not exist in the current context

When I remove the reference the error disappears and I can compile fine.
Both project utilise the .NET framework 4.5.1 and I have another WPF application which utilises this project and references it without issue.
The only advice I find on this gives advice on ensuring a correctly named class XAML which matches with XAML.cs. I have checked this and it is fine:
<Window x:Class="My.GUI.DirWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="DirWindow" Height="756.7" Width="961">

and
namespace My.GUI
{
/// <summary>
/// Interaction logic for DirWindow.xaml
/// </summary>
public partial class DirWindow : Window
{

    public DirWindow()
    {
        InitializeComponent();

        //Loaded += WindowOnLoaded;

        //Closing += WindowOnClosing;
    }

}

I'm not sure what the issue could be and why referencing/unreferencing this project reliably toggles this error...It's just a class library, but what sort of things should I be looking for in the referenced project?

A: I have resolved the issue. My class library was using log4net and my WPF project was not referencing log4net. I'm not sure exactly why this caused issue as there is no log4net functionality within my WPF application. If anyone has any idea why this issue presented itself in this was it would be nice to know.
In any event this has resolved the issue and my project now compiles fine.


text:
Q: google drive api Cannot access private property Google_Client::$io Good afternoon!
I'm trying to download the file.
My script:
function GetFile($service, $fileId) {
    $fileVars = null;
    try {
        $file = $service->files->get($fileId);
        $fileVars = get_object_vars($file);
        $downloadUrl = $file->getDownloadUrl();
        error_log('Download URL file from Drive: ' . $downloadUrl);
        if ($downloadUrl) {
            $request = new Google_Http_Request($downloadUrl, 'GET', null, null);
            $httpRequest = Google_Client::$io->authenticatedRequest($request);
            error_log(print_r($httpRequest, 1));

            if ($httpRequest->getResponseHttpCode() == 200) {
                $content = $httpRequest->getResponseBody();
                $fileVars['content'] = $content?($content):'';
            } else {
                return null;
            }
        } else {
            return null;
        }

    } catch (apiServiceException $e) {
        error_log('Error retrieving file from Drive: ' . $e->getMessage());
        throw $e;
    }
    return json_encode($fileVars);
}

$requestedFile = GetFile($service,$data[0]['id']);

I deduces that
Fatal error: Cannot access private property Google_Client::$io
Tell me, what is my mistake?
Thanks in advance and sorry for bad english!

A: this works
$SignhttpRequest = $client->getAuth()->sign($request);
$httpRequest = $client->getIo()->makeRequest($SignhttpRequest);

A: Use
$httpRequest = $client->getAuth()->authenticatedRequest($request);
instead of
$httpRequest = Google_Client::$io->authenticatedRequest($request);
See annotations in google-api-php-client/src/Google/Auth/Abstract.php for class Google_Auth_Abstract:

An utility function that first calls $this->auth->sign($request) and then executes makeRequest() on that signed request.

And see Google's migration guide 'Migrating From 0.6.* to 1.0.0'  sections 'Changes in members accessibility' and 'A new home for authenticatedRequest'.


text:
Q: How to change autocomplete braces in Xcode 4
Possible Duplicate:
Xcode 4 with opening brace on new line

I just want to change the braces style to
if (condition)
{

}

from the default style
if(condition) {
}

I cannot find the com.apple.Xcode plist after I installed the Xcode 4. So I'm not able to modify the xccodesenseformattingoptions BlockSeparator to \n.
Please help
Thankz in advance

A: You can replace the SystemCodeSnippets.codesnippets file, as detailed here: http://zurb.com/forrst/posts/Put_that_where_it_might_belong_Xcode-PNL
I don't know if the same file will work in Xcode 4.3, but it's worth a try. Because everything is bundled up together now, the new location of the file you need to replace is /Applications/Xcode.app/Contents/PlugIns/IDECodeSnippetLibrary.ideplugin/Contents/Resources/SystemCodeSnippets.codesnippets.

A: For XCode 4 it's a little more complicated. See detailed answer here:
Xcode 4 with opening brace on new line

A: In xcode 4.3.1 you must manually edit the snippets located at:
/Applications/Xcode.app/Contents/PlugIns/IDECodeSnippetLibrary.ideplugin/Contents/Resources/SystemCodeSnippets.codesnippets

There does not seem to be an easier way.


text:
Q: How do I align list content to the left? I'm trying to align my list content to the left, but can't quite figure out how. Thanks in advance for any suggestions. Here's a sample of the code:

What to bring

Coffee

Tea

Milk

A: Set padding-left: 0; for ul

ul {
  padding: 0;
}

What to bring

Coffee

Tea

Milk

A: Try adding padding: 0; to your
 tag.
It will look something like this:

What to bring

Coffee

Tea

Milk


text: Q: Как поставить таймаут на асинхронную функцию? У меня есть функция которая делает request и мне нужно прерывать ее если запрос идет слишком долго(допустим 5 сек).Пробовал через setTimeout setInterval, не получается


text:
Q: How can I see the application directly underneath a soft keyboard in Android? I am developing a soft keyboard that pipes data (not text) to a receiving intent. Is there any way to see the application/activity that the keyboard is currently overlaying? I am trying to preselect the intent action chooser and develop custom rules to get the data to go to the right place.

A: Just thought I'd answer my own question for this one. Here is the code that returns the activity from the top of the stack.
public String PullTop() {
  final PackageManager pm = getPackageManager();
  //Get the Activity Manager Object
  ActivityManager aManager =
  (ActivityManager) self.getSystemService(ACTIVITY_SERVICE);
  //Get the list of running Applications
  List<ActivityManager.RunningAppProcessInfo> rapInfoList = aManager.getRunningAppProcesses();
  //Iterate all running apps to get their details
  for (ActivityManager.RunningAppProcessInfo rapInfo : rapInfoList) {
    //error getting package name for this process so move on
    if (rapInfo.pkgList.length == 0)
      continue;
    try {
      PackageInfo pkgInfo = pm.getPackageInfo(rapInfo.pkgList[0], PackageManager.GET_ACTIVITIES);
      Log.i("Package",pkgInfo.packageName);
      return pkgInfo.packageName;
    } catch (PackageManager.NameNotFoundException e) {
      e.printStackTrace();
      Log.d("", "NameNotFoundException :" + rapInfo.pkgList[0]);
    }
  }
  return null;
}

To pipe the data to the right process just check for null and:
intent.setPackage(PullTop());


text:
Q: The amlignore file doesn't reduce the size of snapshot To overcome 300MB snapshot size limit I created an .amlignore file in the root of my repository:
/*
!/root

The intention is to exclude everything except /root directory where all python code is. The size of the root directory is less than 1MB, still I get an error of exceeding snapshot limit size of 300MB. What am I doing wrong?

A: This is fixed in version 1.0.74 of azureml-sdk


text:
Q: How can the compilation properties be determined in a procedural macro? I'm working on a procedural macro that does a lot of work that can slow down compilation considerably. The work done does not effect the semantics of the function; that is, if given the same set of arguments, the returned value is does not change depending on whether the macro is applied.
In an effort to make the edit-comp-test loop quicker, I would like to make the macro a no-op depending on conditions that relate to how the crate is being compiled. I would like to be able to determine two properties in particular:

*

*Why the macro is being executed: Build/Run, Documentation, Testing

*Whether the macro being executed for optimized builds.

Cargo exposes the optimization level to build scripts (through environment variables OPT_LEVEL and PROFILE) but does not expose the mode (Build, Documentation, ..). However, none of this information seems to be exposed to procedural macros at all.