text:
Q: How to determine tic tac toe winner using this code? Right now, the code does everything from asking the player's name to ending the game when the grid is full. I'm completely stumped on how to add to the code so if someone gets three in a row, it can say who won and then end the game.
while True:
    from ezgraphics import GraphicsWindow
    #Draw Tic Tac Toe Grid
    def draw_tic_tac_toe(size):
        #Drawing the game board!!
        title= "Tic Tac Toe"
        win = GraphicsWindow(size, size)
        win.setTitle(title)
        win_canvas = win.canvas()
        w, h = size, size
        x1, y1, x2, y2 = 0, h/3, w, h/3
        win_canvas.drawLine(x1, y1, x2, y2)
        win_canvas.drawLine(x1, 2*y1, x2, 2*y2)
        win_canvas.drawLine(y1, x1, y1, x2)
        win_canvas.drawLine(2*y1, x1, 2*y1, x2)
        return(win)

    #Set all the boxes in the tic tac toe grid
    def set_gamebox(win):
        #set h to 300
        h = win.canvas().width()
        #SET COORDINATES FOR THE 9 BOXES
        #I renamed h/3, 2*h/3, and h to make things easier to read
        A = int(h/3)
        B = int(2*h/3)
        C = h
        game_box =  [[[0,0], [A,0], [A,A], [0,A]]] #GAME BOX 1
        #[[[0,0], [A,0], [A,A], [0,A]]]
        game_box = game_box + [[[A,0], [B,0], [A,A], [B,A]]] #GAME BOX 2
        #[[[A,0], [B,0], [A,A], [B,A]]]
        game_box = game_box + [[[B,0], [C,0], [B,A], [C,A]]] #GAME BOX 3
        #[[[B,0], [C,0], [B,A], [C,A]]]
        game_box = game_box + [[[0,A], [A,A], [0,B], [A,B]]] #GAME BOX 4
        #[[[0,A], [A,A], [0,B], [A,B]]]
        game_box = game_box + [[[A,A], [B,A], [A,B], [B,B]]] #GAME BOX 5
        #[[[A,A], [B,A], [A,B], [B,B]]]
        game_box = game_box + [[[B,A], [C,A], [B,B], [C,B]]] #GAME BOX 6
        #[[[B,A], [C,A], [B,B], [C,B]]]
        game_box = game_box + [[[0,B], [A,B], [0,C], [A,C]]] #GAME BOX 7
        #[[[0,B], [A,B], [0,C], [A,C]]]
        game_box = game_box + [[[A,B], [B,B], [A,C], [B,C]]] #GAME BOX 8
        #[[[A,B], [B,B], [A,C], [B,C]]]
        game_box = game_box + [[[B,B], [C,B], [B,C], [C,C]]] #GAME BOX 9
        #[[[B,B], [C,B], [B,C], [C,C]]]
        return(game_box)

    #draw x on the board
    def draw_x(x, y):
        w.canvas().drawLine(x, y, x + w3 / 2, y + w3 / 2)
        w.canvas().drawLine(x + w3 / 2, y, x, y + w3 / 2)
        return(w)
    #draw o on the board
    def draw_o(x, y):
        radius = w3 / 2
        w.canvas().drawOval(x, y, radius, radius)
        return(w)

    def draw_X(box):
        if (box == 1):
            x1 = w3 / 4
            x2 = w3 / 4
        if (box == 2):
            x1 = w3 / 4 + w3
            x2 = w3 / 4
        if (box == 3):
            x1 = w3 / 4 + w3 * 2
            x2 = w3 / 4
        if (box == 4):
            x1 = w3 / 4
            x2 = w3 / 4 + w3
        if (box == 5):
            x1 = w3 / 4 + w3
            x2 = w3 / 4 + w3
        if (box == 6):
            x1 = w3 / 4 + w3 * 2
            x2 = w3 / 4 + w3
        if (box == 7):
            x1 = w3 / 4
            x2 = w3 / 4 + w3 * 2
        if (box == 8):
            x1 = w3 / 4 + w3
            x2 = w3 / 4 + w3 * 2
        if (box == 9):
            x1 = w3 / 4 + w3 * 2
            x2 = w3 / 4 + w3 * 2
        return x1, x2

    def draw_O(box):
        if (box == 1):
            x1 = w3 / 4
            x2 = w3 / 4
        if (box == 2):
            x1 = w3 / 4 + w3
            x2 = w3 / 4
        if (box == 3):
            x1 = w3 / 4 + w3 * 2
            x2 = w3 / 4
        if (box == 4):
            x1 = w3 / 4
            x2 = w3 / 4 + w3
        if (box == 5):
            x1 = w3 / 4 + w3
            x2 = w3 / 4 + w3
        if (box == 6):
            x1 = w3 / 4 + w3 * 2
            x2 = w3 / 4 + w3
        if (box == 7):
            x1 = w3 / 4
            x2 = w3 / 4 + w3 * 2
        if (box == 8):
            x1 = w3 / 4 + w3
            x2 = w3 / 4 + w3 * 2
        if (box == 9):
            x1 = w3 / 4 + w3 * 2
            x2 = w3 / 4 + w3 * 2
        return x1, x2

    w = draw_tic_tac_toe(300)
    game_boxes = set_gamebox(w)
    w3 = w.canvas().width() / 3

    def getBox(x, y):
        for n in range(9):
            if (x > (n % 3) * w3) and ( x < ((n % 3) + 1) * w3 ) and (y > int(n / 3) * w3) and (y < (int(n / 3) + 1) * w3) :
                return n + 1

    playerA = input("Player A, what is your name?: ")
    playerB = input("Player B, what is your name?: ")

    choice = input("Who wants to go first? " +playerA+ "? Or " +playerB+"?: ")
    if choice == playerA:
        print(playerA + " goes first!")

    else:
        print(playerB + " goes first!")

    def secondPlayer():
        if choice == playerA:
            return playerB
        else:
            return playerA

    sign_choice= input(choice + ", do you want to play x or o: ")

    def otherSignChoice():
        if sign_choice == 'x':
            return 'o'
        else:
            return 'x'

    print(choice + " will play " + sign_choice +".\n"+ secondPlayer() +" will play " + otherSignChoice()+ ".")

    i = 0
    while i < 9:
        pt = w.getMouse()
        print(pt, getBox(pt[0], pt[1]))
        nBox = getBox(pt[0], pt[1])
        if sign_choice == 'o':
            if (i % 2 == 0):
                o1, o2 = draw_O(nBox)
                draw_o(o1, o2)
                print('o')
            else:
                x1, x2 = draw_X(nBox)
                draw_x(x1, x2)
                print('x')
            i += 1

        else:
            if (i % 2 == 0):
                x1, x2 = draw_X(nBox)
                draw_x(x1, x2)
                print('x')
            else:
                o1, o2 = draw_O(nBox)
                draw_o(o1, o2)
                print('o')
            i += 1
    while True:
        answer = str(input('Do you want to play again? (y/n): '))
        if answer in ('y', 'n'):
            break
        print("invalid input.")
    if answer == 'y':
        continue
    else:
        print("Game Over")
        break

A: Your code lacks an essential part: a representation of the game in memory. Currently your code has no knowledge of the moves that have already been played, and it cannot verify whether a user attempts to play in a box that already has a symbol from a previous move.
I will not adjust your existing code, but instead show you how you should start:

*

*Create a class that focuses only on maintaining the game's state: it should provide the functions to play a move, to verify that a move is valid, to check whether the game has ended, whether it is a draw or has a winner, ... None of this needs to know about the visualisation of the game, but it will be a class that you can use whether you have a graphical user interface for playing the game, or just a terminal input/output, or a keyboard driven interface, ...etc, ...etc.

*An instance of that class should have attributes that remember what has been played and what the current game looks like. But this should be as simple as possible. For instance, that representation could be a standard list of length 9, where each element of that list indicates with a number or a string what the state is of that cell in the game. "X" could be for when the first player has played there, "O" for when the second player has played there, and then anything else to indicate the cell is still free. The latter could be a space, or -- why not -- the numerical identifier of that cell (0, 1, 2, ... 8).

*The class could also provide a very, very basic string representation, so at least you can debug with print statements.

*The next step is to create the flow of a game -- the driver code: it will have the loop where in each iteration a move is played, and an inner loop where you keep getting the user's next move until that input is valid. The outer loop should exit when the game is over. This code should be simple and rely on the class for any game-logic.
So here is an implementation of that class and a very simple version of the driver code, which uses simple input() and print() calls for the user interface. It will be your job to replace that input/output with the graphical user interface you are using (where input is coming partly from the mouse, and output consists of drawing lines).
class TicTacToe:
    def __init__(self):
        self.board = list("012345678")
        self.moves = []

    def __repr__(self):
        s = " ".join(self.board)
        return "\n".join([s[:5], s[6:11], s[12:]])

    def is_free(self, spot):
        return 0 <= spot < 9 and self.board[spot] not in "XO"

    def turn(self):
        return "XO"[len(self.moves) % 2]

    def move(self, spot):
        if not self.is_free(spot):
            raise ValueError("This is not a valid move")
        symbol = self.turn()
        self.board[spot] = symbol
        self.moves.append(symbol)

    def winner(self):
        # Check each line of 3 for a win
        for a, b, c in ((0,1,2),(3,4,5),(6,7,8),(0,3,6),(1,4,7),(2,5,8),(0,4,8),(2,4,6)):
            if self.board[a] == self.board[b] == self.board[c] and self.board[a] in "XO":
                return self.board[a]
        return ""

    def is_draw(self):
        return not self.winner() and len(self.moves) == 9

    def over(self):
        return self.winner() or self.is_draw()

# Play one game
game = TicTacToe()
while not game.over():
    print(game) # Here you would draw the game
    while True: # Repeat until valid move is entered
        # Here you would get the mouse click, ...etc
        spot = int(input(f"Choose the spot for {game.turn()}: "))
        if game.is_free(spot):
            break
        print("That is not a valid spot...")
    game.move(spot)

print(game)
if game.is_draw():
    print("It's a draw!")
else:
    print(f"{game.winner()} won the game!")

A: You can check every row to see if any of them contains the same three letters.
By the way, don't be surprised if this question is closed soon. Stack Overflow doesn't welcome asking for help about your own program should work. No one is going to write that code for you.


text:
Q: Secure FTP From ColdFusion 9 Using Java FTP Client This is a followup of this question.  The correct answer leads to an attempt to use the SFTPClient class in the Apache Commons library.
I can connect.  The next step is to upload a file.  There is a lot of reference material with sample source code.  I used this one as my guide.  It's not secure FTP, but it's simple to follow.  This is the java code I was attempting to emulate:
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;

public class FTPUploadFileDemo {

    public static void main(String[] args) {
        String server = "www.myserver.com";
        int port = 21;
        String user = "user";
        String pass = "pass";

        FTPClient ftpClient = new FTPClient();
        try {

            ftpClient.connect(server, port);
            ftpClient.login(user, pass);
            ftpClient.enterLocalPassiveMode();

            ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
            // This was considered unnecessary because I was sending n ASCII file

            // APPROACH #1: uploads first file using an InputStream
            File firstLocalFile = new File("D:/Test/Projects.zip");

            String firstRemoteFile = "Projects.zip";
            InputStream inputStream = new FileInputStream(firstLocalFile);

            System.out.println("Start uploading first file");
            boolean done = ftpClient.storeFile(firstRemoteFile, inputStream);
            inputStream.close();
and some more code that's not relevent,

This is my ColdFusion equivalent:
localFilename = "d:\dw\dwtest\dan\textfiles\randomText.txt";
remoteFileName = "randomText.txt";

javaFtpClient = CreateObject("java",
  "org.apache.commons.net.ftp.FTPSClient").init("SSL", JavaCast("boolean",true));
// note that I am using a secure client

 javaInputFile = createObject("java", "java.io.File").init(localFilename);
 javaInputStream = createObject("java", "java.io.FileInputStream").init(javaInputFile);

// connect and login
javaFtpClient.connect(JavaCast("string","something"),990);
loginStatus = javaFtpClient.login('valid username','valid password');
writeoutput("login status " & loginStatus & "
");
javaFtpClient.enterLocalPassiveMode();

uploadStatus = javaFtpClient.storeFile(remoteFileName, javaInputStream);
writeOutput("upload status " & uploadStatus & "
"); javaInputStream.close();

// logout and disconnect
javaFtpClient.logout();
javaFtpClient.disconnect();

writeoutput("done" & "
");

The output shows a successful login and an unsuccessful file upload.  The lack of file was confirmed using FileZilla.
Can anybody see why the file was not uploaded?

A: The command javaFtpClient.execProt("P") is required. Setting PROT to "P" sets the Data Channel Protection Level to private.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Can't decode UTF-8 umlaut in C# I have the fallowing problem:
I request a HTML-document which includes an array like this:
"entries":[{"element1":"Gem\u00fcse","element2":"zw\u00f6lf","element3":"n\u00e4chster"}]

by using the following code:
        WebRequest wRequest = WebRequest.Create(URL);
        wRequest.Method = WebRequestMethods.Http.Get;

        using (WebResponse wResponse = wRequest.GetResponse() as WebResponse)
        {
            using (Stream strm = wResponse.GetResponseStream())
            {
                using (StreamReader strmReader = new StreamReader(strm))
                {
                    string htmlDoc = strmReader.ReadToEnd();
                }
            }
        }

Now I want, that all umlaute appear like ä,ö,ü so that the string htmlDoc looks like this:
"entries":[{"element1":"Gemüse","element2":"zwölf","element3":"nächster"}]

How can I do this?


text:
Q: Group Date ranges with separate groups if other date in between I have a Table like this:
Specification    Date
ADS              2020-09-04 00:00:00.000
ADS              2020-09-05 00:00:00.000
ADS              2020-09-06 00:00:00.000
AZR              2020-09-07 00:00:00.000
AZR              2020-09-08 00:00:00.000
ADS              2020-09-09 00:00:00.000
ADS              2020-09-10 00:00:00.000

I want to select an Start Date and an End date and group them by Specification.
So my Output should look like this:
Specification    Start                     End
ADS              2020-09-04 00:00:00.000   2020-09-06 00:00:00.000
AZR              2020-09-07 00:00:00.000   2020-09-08 00:00:00.000
ADS              2020-09-09 00:00:00.000   2020-09-10 00:00:00.000

I tried it with:
select
Specification, MIN(Date) as Start, MAX(Date) as End
from CUSTOMERS
group by Specification

but this doesnt give my desired result. Does anyone have an Idea?

A: You can try the below - it's a gap & island problem
select col1, min(dateval) as start, max(dateval) as end
from
(
select *,row_number() over(order by dateval)-
row_number() over(partition by col1 order by dateval) as grp
from t
)A group by col1, grp


text:
Q: Issue on creating folder in internal storage with the below code
String path = Environment.getExternalStorageDirectory()
                    .getAbsolutePath() + "/ordinazioni";

I have created folder into storage/sdcard/.
But I want to create the same folder "ordinazioni" in internal storage.

A: Your code creates a directory on external storage. Though, it would be much better to use:
File f = new File(Environment.getExternalStorageDirectory(), "ordinazioni");

If you want to create a directory on internal storage, replace Environment.getExternalStorageDirectory() in the above code snippet with a location for internal storage, such as getFilesDir() or getCacheDir() called on a Context (e.g., called on an Activity or Service).

A: Your code is well but its only the String of in path variable.
So with this same path String we will create a Folder or Directory:
Lets Do it here :
// Your code
String path = Environment.getExternalStorageDirectory()
                         .getAbsolutePath() + "/ordinazioni";
// After this
file=new File(path);
if(!file.isDirectory())
{
    file.mkdirs();
}

Remember give Write Storage Permission if you are using Marsmallow then given Run time Permission also.
Now you issue is that you want to create it in Internal Storage so i want to say that this code made only for Internal storage for external you can do like this :
File newfile= new File("/sdcard/"+"ordinazioni");

But check your mobile have memory card or other External Drive.
I hope this will work for you


text:
Q: Get the name of current app style sheet in PyQt How can I get the name of current style sheet of my PyQt app?
app = QtGui.QApplication.instance()
print app.styleSheet()

app.styleSheet() returns nothing.
app = QtGui.QApplication.instance()
print app.style()

return <PyQt4.QtGui.QCommonStyle object at 0x0000000019BB4678>
I need a string, for example 'plastique'

A: You can get the class name of the current style, if that's what you're looking for.
print app.style().metaObject().className()

A: Qt does not use stylesheets for rendering of GUI. When you set up a stylesheet Qt generates corresponding QProxyStyle and use it. It is not possible to reverse this operation. When stylesheet is not set - then Qt may use native OS API for rendering controls.


text:
Q: How can I ensure everything is removed when I delete an account from Opera 10? I am using Opera 10. I have added my Gmail account to it. Today I have deleted the account from 'Tools -> Mail and Chat accounts'. Now I want to ensure that all messages together with other relevant stored data are deleted from my Hard Drive. Please guide me to check this thing.

A: if you're using windows, you can go to c:\users\username\appdata\local\opera\opera\mail
that's where it stores everything.  If you have no other mail accounts, you can delecte the whole folder, otherwise, you'll have to look inside to see which one to delete.


text:
Q: Do gravitational lenses have a focus point? Do gravitational lenses have a focus point? Could I burn space ants?

A: Thinking simply about a point source such as a black hole, the equivalent optical lens created by such an object looks like the image below (taken from this article).  That is to say it falls off as $\frac{1}{r}$ as pointed out by Lubos Motl in his answer.

This object has some interesting optical properties.  The $\frac{1}{r}$ potential will act as a diverging optical lens for objects far from the axis.  This is why gravitational lenses can be used to magnify distant objects.  I.E. you wouldn't be able to burn the space ants, but you could use it to see them more clearly.
The discontinuity at the center of the lens will make it act like an optical object known as an axicon which, as is pointed out both in the linked wikipedia article and by Brandon in his answer, will image a point source to a line along the optical axis.

(source: edmundoptics.com)
There is a good paper on the properties of axicon's here at Optics InfoBase.  One of the most interesting properties is that it can turn an image inside out; imaging points near the optical axis further from the axis than those that started further away. This property is what allows gravitational lenses to form multiple images of the same object in a ring-like pattern such as in the below image.

A: It's pretty easy to see that the gravitational lens doesn't have a focal point.  Please excuse my very poor drawing:

Rays from the top are focused across a line.  A black hole would have a "focus line" but not a focus point.

A: No.
Ordinary optical lenses deflect the light ray, at least in a linear polarization, by an angle that is linear as a function of the location $(x,y)$ on the lens:
$$\theta \sim ax + by$$
Well, we should really talk about $\vec k$, the wave vector, a two-dimensional angle of a sort.
On the other hand, the deflection by the gravitational lens goes like an inverse power law
$$ |\theta| \sim \frac{1}{r^n} $$
for some positive $n$, just like a gravitational force. The convergence requires the linear dependence from the first formula; the second formula doesn't imitate it in any approximation.

A: The gravitation lens generates smaller angular deflections at large impact factors. A converging lens generates larger angular deflections at larger impact parameters.
So, a first guess would be "no way".


text:
Q: Child's padding mixes with Parent's padding I'm facing trouble understanding what's going on. The problem is with the  tag to which I've set some padding and radius to make it like a button. But I see it overflows the container like this-

It seems like the container sets its boundary immediately after get started text. So I want to know why does the 's padding overflow the container?
Here's react component-
JSX-
const topSection = ()=> {
    return (

All your files in one secure location, accessible anywhere.

Fylo stores all your most important files in one secure location. Access them wherever
            you need, share and collaborate with friends family, and co-workers.

            Get Started          //ISSUES WITH THIS ONE

    )
}

SASS-
@import "../../colors.scss";

.top-section {
    text-align: center;
    background: url("/images/bg-curvy-mobile.svg") center bottom/150% 75% no-repeat border-box;
    margin-top: 5%;

    img {
        width: 100%;
        margin-bottom: 10%;
    }

    h1, p, a {
        margin-top: 5%;
        margin-bottom: 5%;
    }
    h1 {
        font-size: 1.4rem;
        line-height: 1.5;
    }
    a {
        color: white;
        background: color(get-started);
        padding: 1em 6em;
        border-radius: 2em;
        margin: 10% auto;
    }
}

A: The issue there is that  tag is always display: inline by default.
Please try changing it to display: block and work from there.
Wrote some example which is based on yours:

.top-section {
    text-align: center;
    background: url("https://upload.wikimedia.org/wikipedia/commons/c/c3/Aurora_as_seen_by_IMAGE.PNG") center bottom/150% 75% no-repeat border-box;
    margin-top: 5%;
}
.top-section img {
        width: 100%;
        margin-bottom: 10%;
    }

 .top-section h1, p, a {
        margin-top: 5%;
        margin-bottom: 5%;
        color: white;
    }
 .top-section h1 {
        font-size: 1.4rem;
        line-height: 1.5;
    }
 .top-section a {
        color: white;
        background: blue;
        padding: 1em 0;
        border-radius: 2em;
        display: block;
        width: 10em;
        margin: auto;
}
    }

All your files in one secure location, accessible anywhere.

Fylo stores all your most important files in one secure location. Access them wherever you need, share and collaborate with friends family, and co-workers.

  Get Started


text:
Q: ArcPy Select by attribute using create date I'm writting a Python script that will look for newly created features and update them. This script will be automated to run every day at the end of the day.
I'm using the Select by attribute tool to select features created on or before now (variable). I'm using UTC time zone because the "Create Date" field was created by the Enable Editor Tracking tool and by default the date is in UTC time zone.
import arcpy, datetime
from datetime import timezone

Now = datetime.datetime.now(timezone.utc)
arcpy.SelectLayerByAttribute_management(LayerName, "New_Selection", "CreateDate <= Now")

I'm getting an invalid expression error
arcgisscripting.ExecuteError: ERROR 000358: Invalid expression
Failed to execute (SelectLayerByAttribute).

How do I use the variable Now in the expression?

A: Try using datetime with strftime:
import datetime as dt
import arcpy

fc = r'C:\data.gdb\featureclass'
date_field = 'CreateDate'

LayerName = 'layer123'
arcpy.MakeFeatureLayer_management(fc, LayerName)

today = dt.datetime.now().strftime(format='%Y-%m-%d') #'2021-05-26'
where = "{0} = date '{1}'".format(arcpy.AddFieldDelimiters(datasource=fc, field=date_field), today) #https://desktop.arcgis.com/en/arcmap/10.3/map/working-with-layers/sql-reference-for-query-expressions-used-in-arcgis.htm#GUID-85C03D85-F4A5-48FC-8E8C-3F79919430DB
arcpy.SelectLayerByAttribute_management(in_layer_or_view=LayerName, where_clause=where)

I'm not sure if you need to add 00:00:00 after the date:
where = "{0} = date '{1} 00:00:00'".format(arcpy.AddFieldDelimiters(datasource=fc, field=date_field), today)


text: Q: Get large window preview back in ubuntu 18 In Ubuntu 16 when you had say 10 terminals and you'd click them in the task bar, you would get a preview like the one we get in 18 with the super key except only with the windows of that application. How do I get that in 18? Having to look through 15 Terminals without that preview kind of breaks the workflow ;)


text:
Q: How to print backslash in single quoted string in ruby I have the following string in ruby version 2.3.3:
'\x89PNG\r\n\x1A\n\x00\x00\x00\rIHDR\x00\x00\x01u\x00\x00\x01u\b'

I would like to compare it to another string. However, the following occurs:
x = '\x89PNG\r\n\x1A\n\x00\x00\x00\rIHDR\x00\x00\x01u\x00\x00\x01u\b'
 => "\\x89PNG\\r\\n\\x1A\\n\\x00\\x00\\x00\\rIHDR\\x00\\x00\\x01u\\x00\\x00\\x01u\\b"

Where the addition of the extra slash messes up the comparison. Equally confusing, the following happens:
 x.gsub("\\\\", "\\")
 => "\\x89PNG\\r\\n\\x1A\\n\\x00\\x00\\x00\\rIHDR\\x00\\x00\\x01u\\x00\\x00\\x01u\\b"

I have tried double quoting the string, using %{} and %Q[]. None of them simply store the string without interpreting escape sequences. How do I store this string without altering it?

A: So long as the strings share the same encoding, byte comparison would be elegant solution without the need for additional escaping.
str.bytes == other.bytes

To display a backslash, you simply escape it with a single backslash:
puts '\\'
\

Additionally, depending on your exact usage, could use the <=> operator:
(str <=> other).zero?

EDIT
To expand a little more, there is a difference in what is displayed to you if you just did something like this:
a = '\\'
p a
=> '\\'

This will show itself as two backslashes, but it is still in fact a single character, not two.
a = '\\'
a.bytes
=> [92] # ASCII code for a backslash (single byte)


text:
Q: Using await with Task.Run but UI still hangs for a few seconds? I am using SAP .NET Connector 3.0 and trying to login on using a separate thread so I can have the UI displaying a kind of login animation.
I am using Async and Await to start the login but the UI hangs for about 10 seconds during login.
Here is the code, its rough because I am quickly drafting a program.
async void MainWindow_Loaded(object sender, RoutedEventArgs e)
{
    Busy.Visibility = System.Windows.Visibility.Visible; // Shows progress animation

    if (await SAPLogin()) // Waits for login to finish, will always be true at the moment
    {
        await GetData(); // does things with sap

        Busy.Visibility = System.Windows.Visibility.Collapsed; // Hides progress animation
    }
 }

private Task<bool> SAPLogin()
{
    bool LoggedIn = true;

    return Task.Run(() =>
        {
           Backend = new BackendConfig();
           RfcDestinationManager.RegisterDestinationConfiguration(Backend);
           SapRfcDestination = RfcDestinationManager.GetDestination(MyServer);  // MyServer is just a string containing sever name

           SapRap = SapRfcDestination.Repository;

           BapiMD04 = SapRap.CreateFunction("MD_STOCK_REQUIREMENTS_LIST_API");

           BapiMD04.SetValue("WERKS", "140");

                return LoggedIn;
         });
}

I can only imagine that something in the Task is using the UI?
EDIT 1:
Sorry forgot to explain what GetData() does.
GetData() runs various reports in SAP (lots of code). Visually, I know when its there because my little login animation will change from "Logging In" to "Grabbing Data".
When I see the UI hang I see it is during the "Logging In" phase. The login animation has a simple circle spinning. This stops part way through the login and then continues after about 5 seconds.
EDIT 2:
The hanging seems to occour at this line here
SapRfcDestination = RfcDestinationManager.GetDestination(MyServer);

EDIT 3:
Added a Photo of the threads when pausing application at the point where I see the UI hang.

A: Presumably, nothing inside GetData or the Task.Run lambda inside SAPLogin is trying to callback the UI thread with Dispatcher.Invoke, Dispatcher.BeginInvoke or Dispatcher.InvokeAsync. Check for such possibility first.
Then, try changing your code like below. Note how Task.Factory.StartNew with TaskCreationOptions.LongRunning is used instead of Task.Run and how GetData is offloaded (despite it's already async, so mind .Unwrap() here). If that helps, try each change independently, to see which one particularly helped, or whether it was a combination of both.
async void MainWindow_Loaded(object sender, RoutedEventArgs e)
{
    Busy.Visibility = System.Windows.Visibility.Visible; // Shows progress animation

    if (await SAPLogin()) // Waits for login to finish, will always be true at the moment
    {
        //await GetData(); // does things with sap
        await Task.Factory.StartNew(() => GetData(),
            CancellationToken.None,
            TaskCreationOptions.LongRunning,
            TaskScheduler.Default).Unwrap();

        Busy.Visibility = System.Windows.Visibility.Collapsed; // Hides progress animation
    }
}

private Task<bool> SAPLogin()
{
    bool LoggedIn = true;

    return Task.Factory.StartNew(() =>
    {
        Backend = new BackendConfig();
        RfcDestinationManager.RegisterDestinationConfiguration(Backend);
        SapRfcDestination = RfcDestinationManager.GetDestination(MyServer);  // MyServer is just a string containing sever name

        SapRap = SapRfcDestination.Repository;

        BapiMD04 = SapRap.CreateFunction("MD_STOCK_REQUIREMENTS_LIST_API");

        BapiMD04.SetValue("WERKS", "140");

        return LoggedIn;
    },
    CancellationToken.None,
    TaskCreationOptions.LongRunning,
    TaskScheduler.Default);
}


text:
Q: Why are my jqGrid rows not editable even when optioned as such? I am trying to add a jqGrid to a ASP.NET MVC3 partial view. This grid will be for the client side only as a shortcut calculator, they press a button and the grid generates based on some entered parameters. I can get the grid to show up and even addDataRow to it however the rows is not editable even though the fields are designated as such.  I have tried it in IE9, Chrome, FF, Safari all the same outcome.
I pulled it out into a simple HTML page to see if it was related to the MVC partial view interfering but still no luck with the editable rows.  The row is selectable but does not open up for editing.
I double checked to make sure I downloaded the full jqGrid package from here
Is a row added via addDataRow not editable by default?  From all the documentation on the jqGrid Wiki I couldn't find where it isn't.  I've read the inline editing wiki page several times and it seems like this should just work.  What am I missing?
not editable http://bigpichost.com/files/noteditable_zm7rflo0.png
When I click on the row it selects but doesn't open up for editing!
Here is the HTML page that I'm testing with:

    <meta charset="utf-8">
     <title>Testing JQGrid</title>
        <link rel="stylesheet" href="../Content/themes/base/jquery.ui.all.css">
        <link href="Content/ui.jqgrid.css" rel="stylesheet" type="text/css" />
        <link href="Content/themes/redmond/jquery-ui-1.8.18.custom.css" rel="stylesheet" type="text/css" />

A: Something must switch the row into the editable state. If you want the row to be in edit mode after adding it, you just need to call editRow method:
$("#jqgRequests").jqGrid('editRow', "1", false);

If you want the row to switch into editable state when you select it, you should use onSelectRow callback:
var previousSelectedRowId;

$('#jqgRequests').jqGrid({
    ...
    onSelectRow: function(currentSelectedRowId) {
        if(currentSelectedRowId && currentSelectedRowId !== previousSelectedRowId) {
            $('#jqgRequests').jqGrid('restoreRow', previousSelectedRowId);
            previousSelectedRowId = currentSelectedRowId;
        }
        $('#jqgRequests').jqGrid('editRow', currentSelectedRowId, false);
    },
    ...
};

If you want to add row, which is already in edit mode, you should use addRow method:
$('#jqgRequests').jqGrid('addRow', { rowID: "1", initdata: myFirstRow });


text:
Q: Wp8 xaml design I have a problem with the first element in a listbox, the arranging is being changed in it.
This is the code:
<Grid x:Name="ContentPanel" Margin="12,10,0,0" Grid.RowSpan="2" Grid.ColumnSpan="2">
        <ListBox Margin="10,233,10,0" BorderBrush="White" Hold="ListBox1_Hold" SelectionChanged="ListBox1_SelectionChanged" Height="516"  x:Name="ListBox1" VerticalAlignment="Top">
            <ListBox.ItemTemplate>
                <DataTemplate>
                    <StackPanel Width="500" Orientation="Vertical" >
                        <Image Margin="10,30,0,0"  HorizontalAlignment="Left" Height="100" Width="150" Source="{Binding Img}" ></Image>

                        <TextBlock Visibility="Collapsed" Text="ID: "/>
                        <TextBlock Visibility="Collapsed" Text="{Binding Id}"/>

                        <TextBlock Visibility="Collapsed" FontSize="30" Text="Place Name: "/>
                        <TextBlock Margin="160,-110,0,0"  HorizontalAlignment="Left" Foreground="Blue" FontSize="30" Text="{Binding PlaceName}"/>

                        <TextBlock Visibility="Collapsed" Text="Description: "/>
                        <TextBlock Margin="160,-80,0,0"  HorizontalAlignment="Left" TextWrapping="Wrap" Text="{Binding Description}" />

                        <TextBlock Visibility="Collapsed" Text="Keyword: "/>
                        <TextBlock Visibility="Collapsed" Text="{Binding Keyword}"/>

                        <TextBlock Visibility="Collapsed" Text="Longitude: "/>
                        <TextBlock Visibility="Collapsed" Text="{Binding Long}"/>

                        <TextBlock Visibility="Collapsed" Text="Latitude: "/>
                        <TextBlock Visibility="Collapsed" Text="{Binding Latit}"/>
                    </StackPanel>
                </DataTemplate>
            </ListBox.ItemTemplate>
        </ListBox>

And here the result of this code:
The Picture

A: <Grid>
    <Grid.RowDefinitions>
        <RowDefinition Height="Auto" />
        <RowDefinition Height="Auto" />
        <RowDefinition Height="Auto" />
        <RowDefinition Height="Auto" />
        <RowDefinition Height="Auto" />
        <RowDefinition Height="Auto" />
    </Grid.RowDefinitions>
    <Grid.ColumnDefinitions>
        <ColumnDefinition Width="Auto" />
        <ColumnDefinition Width="200" />
    </Grid.ColumnDefinitions>

    // First block
   <grid grid.colum="0" grid.row="0" grid.rowspan="2"><image></grid>
   <grid grid.colum="1" grid.row="0" ><textblock></grid>
   <grid grid.colum="1" grid.row="1" ><textblock></grid>

    // Seconde block
   <grid grid.colum="0" grid.row="1" grid.rowspan="2"><image></grid>
   <grid grid.colum="1" grid.row="2" ><textblock></grid>
   <grid grid.colum="1" grid.row="3" ><textblock></grid>

   // third block
   <grid grid.colum="0" grid.row="2" grid.rowspan="2"><image></grid>
   <grid grid.colum="1" grid.row="4" ><textblock></grid>
   <grid grid.colum="1" grid.row="5" ><textblock></grid>

</Grid>


text:
Q: Spring Boot - how to automatically redirect user from www domain to non-www domain? I have classic Spring Boot application on my VM.
A user can go to https://www.fakeurl.com which is pointing to my VM , or, a user can go to https://fakeurl.com which is pointing to my VM.
The problem is that this is bad for SEO. When a user goes to https://www.fakeurl.com (with www) I need to automatically redirect him to non-www domain https://fakeurl.com
How can I do this in SpringBoot?


text:
Q: Can i disable Tls verify on minikube? I have a local minikube cluster on hyper-v, when i try to pull images from my private repository i get this error :
Failed to pull image "my-repolink/image": rpc error: code = Unknown desc = Error response from daemon: Get my-repolink/v2/: x509: certificate signed by unknown authority
When running  minikube docker-env  i get:
$Env:DOCKER_TLS_VERIFY = "1"
$Env:DOCKER_HOST = "tcp://IP:2376"
$Env:DOCKER_CERT_PATH = "C:\Users\myuser\.minikube\certs"
$Env:MINIKUBE_ACTIVE_DOCKERD = "minikube"

I was wanderring if i can change the DOCKER_TLS_VERIFY to "0" (if yes how plz?) and if it will have any effect on this error?

A: You need to tell minikube which certificates to trust. The official doc mentions this specific issue.
The suggestion is to put the appropriate self-signed ceritificate of your private registry into ~/.minikube/files/etc/ssl/certs; then run minikube delete followed by minikube start.

A: minikube docker-env is used to configure the shell:
$ minikube docker-env
...
# Run this command to configure your shell:
# eval $(minikube docker-env)

These envs are not set in docker but these are envs you can set in your shell to connect to the docker that is inside of a minikube vm from local machine.
So if you want to change it you can run: export DOCKER_TLS_VERIFY="0" in the shell.
But notice what is written in docker documentation:

Setting the DOCKER_TLS_VERIFY environment variable to any value other
  than the empty string is equivalent to setting the --tlsverify flag.

So setting this value to "0" is the same as setting is to "1" so it's not going to change anything. So no, it won't have any effect on this error.


text:
Q: How to order properties alphabetically (Visual Studio 2008) I'm really anal and would like to order my class properties alphabetically/by type.
Is this possible using a pre-existing feature in VS, or a macro that can do this?
Eg:
public string foo {get; set;}
public string bar {get; set;}
public int fong {get; set;}
public string loo {get; set;}

to (if you want to order alphabetically)
public string bar {get; set;}
public int fong {get; set;}
public string foo {get; set;}
public string loo {get; set;}

or (if you want to order by type, and then alphabeticall)
public string bar {get; set;}
public string foo {get; set;}
public string loo {get; set;}
public int fong {get; set;}

Many thanks!

A: I know a different solution. Copy your code into Excel then copy it back to Visual Studio.

*

*Copy your text/code in VS

*Start Excel

*Insert your text/code in Excel

*Select you text/code

*List item

*Right-click on it

*Click on sort

*Click on From A to Z

*Your text/code is now sorted. Select your text/code in Excel

*Copy your text/code and paste it in VS

A: Not to my knowledge - but both DevExpress' CodeRush/Refactor (through an add-on) as well as Resharper through their code formatting features support this.
Marc


text:
Q: Event bus trigger duplicating In the edit modal for my company entity, I open the address entity create modal. This allows the user to create an address for the company. On the .done of the address create app service method, I trigger an event using the abp.event.trigger method. The company edit modal then watches for this event so that it can create an entry into the companyAddress entity. Soon as the companyAddress entity app service method ends, on .done event, I turn off the event trigger. However, after the first instance of creating an address, when the user adds more addresses the trigger mechanism is firing multiple times and causing duplicate entries in the companyAddress table. I have debugged this over and over and read the docs for abp event triggers and cannot figure out how this happening. Any help would be much appreciated.
Create address modal js
    this.save = function () {
        if (!_$form.valid()) {
            return;
        }
        var address = _$form.serializeFormToObject();
        _modalManager.setBusy(true);
        _addressService.createAddress(
            address
        ).done(function (result) {
            abp.notify.info(app.localize('SavedSuccessfully'));
            abp.event.trigger('addressCreated', {
                id: result
            });
            console.log('addressCreated event triggered for id: ' + result);
            _modalManager.close();
        }).always(function () {
            _modalManager.setBusy(false);
        });
    };

Edit company modal js
    abp.event.on('addressCreated', function (item) {
        console.log('addressCreated event caught for id: ' + item.id);
        //Call company address service
        var _companyAddressService = abp.services.app.companyAddress;
        _companyAddressService.createCompanyAddress({
            CompanyId: $("#CompanyId").val(),
            AddressId: item.id
        }).done(function () {
            abp.event.off('addressCreated', {
                id: null
            });
            console.log('addressCreated event turned off for id: ' + item.id);
            abp.notify.success(app.localize('AddressCreated'));
            abp.ui.clearBusy('.modal-body');
        });
    });

Here is google chrome console showing the duplication.

I just tested the modals again, I entered about 8 different addresses via the create modal for 2 differnt companies. For this test, the duplication issue did not happen. But the issue where the event does not fire for each address created keeps happening. As you can see from the console log below, the ID number 2,3,5 and 6 did not generate the "started" log entry. My companyAddress table is also missing the entry for these 4 IDs, so the event did not trigger.

Edit company modal.js full updated code
var EditCompanyModal = (function ($) {
app.modals.EditCompanyModal = function () {

    var _modalManager;
    var _companyService = abp.services.app.company;

    var _$Form = null;
    this.init = function (modalManager) {
        _modalManager = modalManager;

        _$Form = _modalManager.getModal().find('form[name=EditCompany]');
        $(".modal-dialog").addClass("modal-lg");
        _$Form.validate();
    };

    this.save = function () {
        if (!_$Form.valid()) {
            return;
        }
        var company = _$Form.serializeFormToObject();
        _modalManager.setBusy(true);
        _companyService.updateCompany(
            company
        ).done(function () {
            abp.notify.info(app.localize('SavedSuccessfully'));
            _modalManager.close();
            abp.event.trigger('app.editCompanyModalSaved');
        }).always(function () {
            _modalManager.setBusy(false);
        });

        abp.event.off('addressCreated', addressCreated); // Turn off this handler
    };

    var _editModal = new app.ModalManager({
        viewUrl: abp.appPath + 'Nursing/Address/EditModal',
        scriptUrl: abp.appPath + 'view-resources/Areas/Nursing/Views/Address/_EditModal.js',
        modalClass: 'EditAddressModal'
    });

    var _createModal = new app.ModalManager({
        viewUrl: abp.appPath + 'Nursing/Address/CreateModal',
        scriptUrl: abp.appPath + 'view-resources/Areas/Nursing/Views/Address/_CreateModal.js',
        modalClass: 'CreateAddressModal'
    });

    $('#add_new_address').click(function (e) {
        _createModal.open();
    });

    $('#addressTiles').on('click', '.btnEditAddress', function () {
        var addressID = $(this).parent().find("input").first().val();
        _editModal.open({ id: addressID });
    });

    abp.event.on('addressCreated', addressCreated);

     //After address create event, save company address Id
    function addressCreated(item) {
        console.log(new Date().toUTCString() + ' - addressCreated started for id: ' + item.id);
        //Call company address service
        var _companyAddressService = abp.services.app.companyAddress;
        _companyAddressService.createCompanyAddress({
            CompanyId: $("#CompanyId").val(),
            AddressId: item.id
        }).done(function () {
            console.log('addressCreated event turned off for id: ' + item.id);
            abp.notify.success(app.localize('AddressCreated'));
            abp.ui.clearBusy('.modal-body');
        });
    }

};})(jQuery);

Chrome console logs for updated JS code

A: From the documentation on Register To Events:

You can use abp.event.off method to unregister from an event. Notice that; same function should be provided in order to unregister. So, for the example above, you should set the callback function to a variable, then use both in on and off methods.

You're passing in a dummy object:
abp.event.off('addressCreated', {
    id: null
});

Do this:
function addressCreated(item) {
    console.log('addressCreated event caught for id: ' + item.id);
    //Call company address service
    var _companyAddressService = abp.services.app.companyAddress;
    _companyAddressService.createCompanyAddress({
        CompanyId: $("#CompanyId").val(),
        AddressId: item.id
    }).done(function () {
        abp.event.off('addressCreated', addressCreated); // Turn off this handler
        console.log('addressCreated event turned off for id: ' + item.id);
        abp.notify.success(app.localize('AddressCreated'));
        abp.ui.clearBusy('.modal-body');
    });
}

abp.event.on('addressCreated', addressCreated);

The addressCreated function is executing not at all sometime[s]

You're only calling .on once per EditCompanyModal, and then .off-ing it.
Move the .off into this.save = ....
Update
Move the .off into this.init = ....
this.init = function (modalManager) {
    _modalManager = modalManager;

    // ...

    _modalManager.onClose(function () {
        abp.event.off('addressCreated', addressCreated); // Turn off this handler
    });
};


text:
Q: asp button and history back onclientclick hi I have an asp button  which is created using the following code:
<asp:Button ID="btnBack" OnClientClick='javascript:history.back()' runat="server" Text="back">
</asp:Button>

However, now the javascript doesn't work to go a history back. On the other hand, if I make an alert() it works...why. Why is it not working to go a history back?

A: Try with return false at end:
 <asp:button id="btnBack" runat="server" text="Back"
OnClientClick="JavaScript: window.history.back(1); return false;"></asp:button>

A: Try:
parent.history.back();

Or
history.go(-1)

A: Had the same problem in DevExpress project. Using ASPxButton without initializing the property "AutoPostBack" will result in redirect to self page before any client-side function call.
Try AutoPostBack="false" for the button.


text:
Q: How to Hide Footer when List view is Empty in android? I have a List View in which items are loaded from server and have a footer in listview,problem is that when there is no item i.e. list view is Empty footer is visible to user .what I want If there is no item in listview then footer is not visible to user .How can I do that kindly help me .
I will be very appreciate.
here is my code:-
protected void onPostExecute(final String result) {

        m_ProgressView.setVisibility(View.GONE);
        try {
            m_oResponseobject = new JSONObject(result);// getting response from server
            JSONArray posts = m_oResponseobject.optJSONArray("dealList");

            for (int i = 0; i < posts.length(); i++) {
                JSONObject post = posts.getJSONObject(i);
                item = new CDealAppDatastorage();
                item.setM_szHeaderText(post.getString("dealname"));
                item.setM_szsubHeaderText(post.getString("dealcode"));
                item.setM_n_Image(m_n_FormImage[i]);
                s_oDataset.add(item);

            }

            // LoadMore button
            Button btnLoadMore = new Button(getActivity());
            btnLoadMore.setText("LOAD MORE DEALS");
            btnLoadMore.setBackgroundResource(R.drawable.button_boarder);
            btnLoadMore.setTextAppearance(getActivity(), android.R.style.TextAppearance_DeviceDefault_Small);
            btnLoadMore.setTextColor(Color.WHITE);
            btnLoadMore.setGravity(Gravity.CENTER);

            // Adding Load More button to lisview at bottom
            m_ListView.addFooterView(btnLoadMore);
            m_oAdapter = new CDealAppListingAdapter(getActivity(), s_oDataset);// create adapter object and add arraylist to adapter
            m_ListView.setAdapter(m_oAdapter);//adding adapter to recyclerview
            m_oAdapter.notifyDataSetChanged();
            }

A: Hide your footer like this :
// Firs check the list size is greater than 0:

if(s_oDataset.size > 0)
{
 // Add your footer here

}else
{
 // Dont not add your footer or Hide your footer
}

A: You can get the size of your listview
listview.getCount();

then if it is equal to zero then change your button visibility
btnLoadMore.setVisibility(View.GONE);

A: see below code that can e you can hide ListView footer when ListView is empty
 if(!s_oDataset.isEmpty()){
        m_ListView.addFooterView(btnLoadMore);
        m_oAdapter = new CDealAppListingAdapter(getActivity(), s_oDataset);// create adapter object and add arraylist to adapter
        m_ListView.setAdapter(m_oAdapter);//adding adapter to recyclerview
        m_oAdapter.notifyDataSetChanged();
  }

A: Here is code, hope so it will work
protected void onPostExecute(final String result) {

    m_ProgressView.setVisibility(View.GONE);
    try {
        m_oResponseobject = new JSONObject(result);// getting response from server
        JSONArray posts = m_oResponseobject.optJSONArray("dealList");

        for (int i = 0; i < posts.length(); i++) {
            JSONObject post = posts.getJSONObject(i);
            item = new CDealAppDatastorage();
            item.setM_szHeaderText(post.getString("dealname"));
            item.setM_szsubHeaderText(post.getString("dealcode"));
            item.setM_n_Image(m_n_FormImage[i]);
            s_oDataset.add(item);

        }

        // LoadMore button
        Button btnLoadMore = new Button(getActivity());
        btnLoadMore.setText("LOAD MORE DEALS");
        btnLoadMore.setBackgroundResource(R.drawable.button_boarder);
        btnLoadMore.setTextAppearance(getActivity(), android.R.style.TextAppearance_DeviceDefault_Small);
        btnLoadMore.setTextColor(Color.WHITE);
        btnLoadMore.setGravity(Gravity.CENTER);

        // Adding Load More button to lisview at bottom
        if(listview.getCount()>0){
        m_ListView.addFooterView(btnLoadMore);
        }

        m_oAdapter = new CDealAppListingAdapter(getActivity(), s_oDataset);// create adapter object and add arraylist to adapter
        m_ListView.setAdapter(m_oAdapter);//adding adapter to recyclerview
        m_oAdapter.notifyDataSetChanged();
        }

A:    protected void onPostExecute(final String result) {

    m_ProgressView.setVisibility(View.GONE);
    try {
        m_oResponseobject = new JSONObject(result);// getting response from server
        JSONArray posts = m_oResponseobject.optJSONArray("dealList");

        for (int i = 0; i < posts.length(); i++) {
            JSONObject post = posts.getJSONObject(i);
            item = new CDealAppDatastorage();
            item.setM_szHeaderText(post.getString("dealname"));
            item.setM_szsubHeaderText(post.getString("dealcode"));
            item.setM_n_Image(m_n_FormImage[i]);
            s_oDataset.add(item);

        }

        // LoadMore button
        Button btnLoadMore = new Button(getActivity());
        btnLoadMore.setText("LOAD MORE DEALS");
        btnLoadMore.setBackgroundResource(R.drawable.button_boarder);
        btnLoadMore.setTextAppearance(getActivity(), android.R.style.TextAppearance_DeviceDefault_Small);
        btnLoadMore.setTextColor(Color.WHITE);
        btnLoadMore.setGravity(Gravity.CENTER);

        // Adding Load More button to lisview at bottom

if(!s_oDataset.size()==0)
{
m_ListView.addFooterView(btnLoadMore);
}

        m_oAdapter = new CDealAppListingAdapter(getActivity(),      s_oDataset);// create adapter object and add arraylist to adapter
        m_ListView.setAdapter(m_oAdapter);//adding adapter to recyclerview
        m_oAdapter.notifyDataSetChanged();
        }


text:
Q: Extending ORM classes in CakePHP 3 I would like to extend Query class in order to create function customContain() available in every Table model. How should I do it?

A:
I want to use that BleMethod() in all table models in cakephp. Where I have to add code of that function? Where I have to implements BleMethod?

Unlike Cake2 Cake3 does not feature an application level class like AppModel from where all other classes inherit from. So you have two options:

*

*Trait

*Behavior
The behavior can be loaded globally to all models by using the Model.initialize event. And then loading the behavior inside the events callback. Read these pages:

*

*Creating a behavior

*Event system

*Model / Table callbacks
But that's not what you want
customContain() indicates for me that you want to setup some contains very often. Well, use finders.
Finders can be combined:
$this->Table->find('foo')->find('myContains')->all();

Each custom find will add something to the query object. You can add your custom contains this way.
Read Custom Finder Methods.


text:
Q: pysparkling H2OConf interfering with my application log Here is my code:
from pysparkling import H2OConf #commenting this line makes it work
import logging

logging.basicConfig(filename='my_log.log',level=logging.INFO)
logging.info('test')

I cannot get the log file to get created, unless I comment the first line of the code. If I do that, then everything works as normal. I'm assuming it's an import inside H2OConf that messes up the handlers. Anybody experience anything similar?
I run the script with
spark-submit --master yarn script.py
Thanks


text:
Q: AlertDialog not showing when i click on marker *I have created alert dialog to show after clicking on marker
*but when i click on marker it crashes the application.
*What could be the problem? Is there anything am i missing?
Thanks in Advance
googleMap.setOnMarkerClickListener(new OnMarkerClickListener() {

            @SuppressWarnings("deprecation")
            @Override
            public boolean onMarkerClick(Marker marker) {

                showAlertDialog();

                return false;

            }

        });

private void showAlertDialog() {

    AlertDialog alert = new AlertDialog.Builder(
            getBaseContext()).create();

    alert.setTitle("Location Selected");
    alert.setMessage("Add this Location to your");
    alert.setButton("Places",

            new DialogInterface.OnClickListener() {

                //code goes here
            });
    alert.setButton("Activities",
            new DialogInterface.OnClickListener() {

                //code goes here
                }

            });
    alert.show();

}

A: Try
AlertDialog.Builder alert = new AlertDialog.Builder(getBaseContext()).create();

instead of
AlertDialog alert = new AlertDialog.Builder(getBaseContext()).create();

A: @SuppressWarnings("deprecation")
    void showAlertDialog(final LatLng markerPosition) {

        AlertDialog alertDialog = new AlertDialog.Builder(GoogleMapViewer.this)
                .create();

        alertDialog.setTitle("Location Selected");

        alertDialog.setMessage("Add this Location to your");

        alertDialog.setButton2("Places", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
                Toast.makeText(getApplicationContext(),
                        "You clicked on Places", Toast.LENGTH_SHORT).show();
            }
        });

        alertDialog.setButton3("Activities",
                new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        Intent act_intent = new Intent();
                        act_intent.setClass(GoogleMapViewer.this,
                                addActivities.class);
                        act_intent.putExtra("username", savedUserName);
                        act_intent
                                .putExtra("latitude", markerPosition.latitude);
                        act_intent.putExtra("longitude",
                                markerPosition.longitude);
                        startActivity(act_intent);

                    }
                });

        alertDialog.show();
    }


text:
Q: NoReverseMatch when use get_absolute_url() models:
class Band(models.Model):
B_Name = models.CharField(max_length=30, primary_key=True)
Country = models.CharField(max_length=30)
genre = models.ForeignKey(Genre)
imageband = models.ImageField(upload_to='images/band')

def __unicode__(self):
    return self.B_Name

@models.permalink
def get_absolute_url(self):
    return ('thu', (), {
        'B_Name': self.B_Name})

urls:
url(r'^genre/(\d+)/$', 'genre', name="genre"),
url(r'^thu/(?P<B_Name>[-\w]+)/$', 'thu', name='thu'),

view:
def genre(request, url):
   template = 'genre/genre.html'
   if url=='1':
      tmp = Band.objects.raw('SELECT B_Name, Country FROM data_band WHERE genre_id=%s',    ...)
   if ....
   return render_to_response(template,{'tmp':tmp})

def thu(request):
      template = 'genre/thu.html'
      tmp = Band.objects.raw('SELECT B_Name, genre FROM data_band')
      return render_to_response(template,{'tmp':tmp})

If i use B_Name="AB", it's working, but i use B_Name="A B", it's error:
NoReverseMatch: Reverse for 'thu' with arguments '()' and keyword arguments '{'B_Name': u'A B'}' not found.

A: Of course. Your urlpattern is:
url(r'^thu/(?P<B_Name>[-\w]+)/$', 'thu', name='thu'),

[-\w]+ means "any non-space character or '-' one or more times". You've explicitly told it to not accept a space, so it doesn't.
Just substitute that regex with something like [-\w ]+ (notice the space before the closing bracket) and it'll work. However, it's really not a good idea to include spaces in URLs.

A: Your url named thu does not allow spaces in the B_Name parameter. It should be
url(r'^thu/(?P<B_Name>[-\w ]+)/$', 'thu', name='thu'),

Note the space in [-\w ].
It is common to create a slug field for your model that does not contain any spaces, and use that in your urls.


text:
Q: Material UI Popover is thrown to the top left when used on an inline button in a table with a unique key I'm having some issues when using shortid or any other unique uid generator. The moment I use shortid.generate() as key in a table, the anchor point of my Material UI Popover is thrown to its default position rather than appearing where the button is.
Here's a sandbox! - try removing/adding back shortid.generate() from line 72.
I even tried uniqueId from lodash and the same thing happens - not using a key does render the dialog on the right place though. I even changed versions of Material UI/React and nothing happened.
Any ideas?
Thanks!
EDIT - I usually use item.uid as key since I always fetch items from a service, but if I just created the object, item.uid is undefined - what I did until now was to set item.uid = shortid.generate() (a temporary uid) when I create the object and then just leave <TableRow key={item.uid}> as is. But then I have to remove the temporary uid before I save the object.

A: You should never use random ids as keys (at least not random ids generated during render).
When your state changes (e.g. due to handleClick) your table rows will all be re-rendered with new keys. This means that instead of a simple re-render, all of the table rows will be unmounted and new DOM elements mounted. The anchorEl in your state will point at an element that has been removed from the DOM, so its position cannot be determined.
If you don't have unique keys related to your data, then just use an index as a key so that it is at least stable across renders (so long as you aren't adding/removing rows). Another option would be to generate the unique ids when creating your data instead of during rendering.


text:
Q: Can't perform a React state update on an unmounted component, when adding Select in ReactJS I'm trying to add a Select component in reactjs (from React95 library), however, it prompts me with a warning:
"Can't perform a React state update on an unmounted component. This is a no-op, but it indicates a memory leak in your application. To fix, cancel all subscriptions and asynchronous tasks in a useEffect cleanup function."
However, I am not using a useEffect function.
I created my Select.js component like this:
import React from 'react';
import { Select, Fieldset } from '@react95/core';

function SelectDrop(){
    return(
      <Select/>
    )
}

export default SelectDrop

And using it by just adding this to my Contact.js component:
<SelectDrop></SelectDrop>

If I use a button component, or any other component from the library, it works fine, but with Select, I get an error, and the page just wouldn't load
I'm trying to use React95 Library and using this as an example:
https://storybook.react95.io/?path=/story/select--default
Moreover, even if I don't add any options/labels/values etc. to the Select itself I still get this error just by adding the  component from the library, what problem could it be? My Contact.js file just has a couple of "divs" and that's it, I do not think that they are causing the problem.


text:
Q: nuxt-auth setting user object after login im using the nuxt-auth module.
I've got it to work so far. I am able to login properly.
But whenever i login, the user object in my store does not get set.
It seems like my API is getting called without parameters so it does not know which user to set.
nuxt.config.js
auth: {
    redirect: {
      login: '/login',
      logout: '/login',
      callback: '/login',
      home: '/'
    },
    strategies: {
      local: {
        endpoints: {
          login: {
            url: 'token',
            method: 'post',
            propertyName: 'token'
          },
          user: {
            url: 'microservice/user',
            method: 'get',
            propertyName: false
          },
          logout: false
        }
      },
      watchLoggedIn: true,
      resetOnError: true
    }
  },

logging in
 await this.$auth.loginWith('local', {
          data: {
            username: this.username,
            password: this.passwort
          }
        })

example API-User
{
  "method": "GET",
  "path": "/user/102",
  "query": "",
  "response": {
    "type": "single",
    "payload": {
      "id": 102,
      "firstname": "super",
      "name": "test",
      "username": "stest1",
     //some data
    }
  }
}

After retrieving a token and setting it, my app sends a request without query/parameters to my user-API. Either im doing something wrong, or am just too dumb too see the right way to set my user. However, if i set my user-Route to for example 'microservice/user/102' it is able to retrieve that one specific user.
Hoping anyone can help! :D

A: I think you should set it propertyName for user endpoint
user: {
    url: 'microservice/user',
    method: 'get',
    propertyName: payload
},


text:
Q: Use GIT and Gitlab We want to use Git and Gitlab in our team. So far I just worked with git on my local comuter. My question: Is it possible to use this normal git version in combination with the online repository Gitlab?
Thank you very much

A: It is safe to make it work if your git version must be no earlier than 1.7.10, as explained in the doc.
Also, note that Gitlab also uses the normal git in the backend. It is merely a web frontend of git.

A: Yes, it's possible.
On the command line, you need to add a remote source where you can push to and pull from.
To do this, you need to set up a RSA key for your account.
ssh-keygen -t rsa

Now you need to put that in your Gitlab profile (profile/keys/new)
cat ~/.ssh/id_rsa.pub

Now you need to add your remote url
git remote add origin <<remote_url>>

You should now be able to push/pull to your GitLab instance.


text:
Q: Android OpenCV 2.4.2 Tutorials Eclipse - cannot dlopen camera wrapper library I am trying to get all the OpenCV tutorials running, but so far, cannot get Tutorial 2, face-detection, color blob detection, working;  I can, however, run Tutorial 0, 1, 3, and 4.  I have corrected a number of errors, including having to add all the include paths:
<includepath>${NDKROOT}/platforms/android-9/arch-arm/usr/include</includepath>
<includepath>C:\android-ndk-r8b\sources\cxx-stl\gnu-libstdc++\4.6\libs\armeabi\include</includepath>
<includepath>${NDKROOT}/sources/cxx-stl/gnu-libstdc++/4.6/include</includepath>
<includepath>C:\android-opencv\sdk\native\jni\include</includepath>
<includepath>C:\android-ndk-r8b\toolchains\arm-linux-androideabi-4.6\prebuilt\windows\lib\gcc\arm-linux-androideabi\4.6.x-google\include</includepath>

I have also updated the Application.mk files to use APP_ABI := armeabi, and this allowed Tuts 3 and 4 to work.  The Android versions are all correct.
Some of the examples don't use C++ code at all, and yet they still fail on being unable to open the camera wrapper library.  This is after it appears to go through a sequence of trying to link each version of the library, such as libnative_camera_r2.3.3, r2.2.0, etc.
It was doing this also for Tuts 3 and 4 before I updated the APP_ABI := armeabi-v7 to APP_ABI := armeabi, but this does not correct the problem for the other Tuts.
Please help.  I am new to the Android NDK, and only have Open CV experience using in Windows. Thanks in advance.
I did notice that in the tutorials that I can run, the phone camera is of type Camera and is opened using .open() command; the cameras that will not run, the phone camera is declared as type VideoCapture, and that apparently needs the wrapper library.  Just not sure how to get that onto the phone.

A: Apparently, it is something to do with my phone that I am testing it on: Samsung Galaxy S.  I found someone else with a very similar problem: Camera not working
Rather than go through the superhuman programming leaps that Pete went through to solve this, I decided to try it on another phone, an HTC slide.  Lo and behold, all the tutorials worked fine with no problems, no recoding.
In the interest of getting things done, I am going to work with the HTC slide for my project.
If anyone comes across a better solution, please let me know!
UPDATE: I did some more research: http://answers.opencv.org/question/1223/android-opencv-support/
It appears that OpenCV Android Native Camera is not supported by all devices due to it being modified by hardware paltform vendors.
FINAL UPDATE: I did some more experimenting with the tutorials, and had a major DUH moment. You can actually use OpenCV without using the OpenCV Native Camera.  I tested this by converting the SampleViewBase class in Tutorial 3 to replace the SampleCvViewBase class in the face detection sample, and it worked great!  The major trick was converting the data during the processImage call so:
capture.retrieve(mRgba, Highgui.CV_CAP_ANDROID_COLOR_FRAME_RGBA);
capture.retrieve(mGray, Highgui.CV_CAP_ANDROID_GREY_FRAME);

became
Mat mYuv = new Mat(getFrameHeight()+getFrameHeight()/2, getFrameWidth(), CvType.CV_8UC1);
mYuv.put(0, 0, data);
Imgproc.cvtColor(mYuv, mRgba, Imgproc.COLOR_YUV420sp2RGB, 4);
Imgproc.cvtColor(mRgba, mGray, Imgproc.COLOR_RGB2GRAY, 0);

Major help came from another stackoverflow article: Capture camera preview for using in OpenCV. Converting to RGB and Gray Mat's. Java. Android
In case I don't see you, good afternoon, good evening, and good night!

A: I think it is because of your phone because i could run all the samples perfectly in my Samsung Galaxy Note Phone. Try changing your phone and then run the samples.


text:
Q: Cross platform file modification tracking I'd like to be able to track file modifications to a set of files in a platform-agnostic way.
I don't need any particular information, just the file's full path will do.
I'd prefer to avoid:

*

*Looping constantly over the files.  That's just horrible!

*Writing platform-specific code.  Especially for Windows or Mac OS X,
since I have no access to machines running any of those.

Disclaimer: I've noticed similar questions on SO, but since most are over 4 years old, I feel this may have changed a lot since then, and they may be outdated.


text:
Q: Concatenate a list of lists At first I have 2 lists, l1 and l2
l1 = [['a','1','b','c','now'],['d','2','e','f','tomorrow']]

l2 = [['11:30', '12:00'],['13:00', '13:30']]

What I want is to create a new list of list with the first two elements of each list from the l1, getting: newList = [['a', '1'], ['d', '2']]
Then, from each list in newList I want to add a list from l2, to get:
newList = [['a', '1', '11:30', '12:00'], ['d', '2', '13:00', '13:30']]

At last I want to add the last element from each list in l1:
newList = [['a', '1', '11:30', '12:00','now'], ['d', '2', '13:00', '13:30','tomorrow']]

What I have until now is this:
newList =[]

for i in l1:
   names = i[:2]
   newList.append(names)

But now I don't know how I do extend to get the other elements..

A: With list comprehension:
newList = [x[: 2] + y + x[-1:] for x, y in zip(l1, l2)]

A: Use zip along with list comprehension.
>>> l1 = [['a','1','b','c','now'],['d','2','e','f','tomorrow']]
>>> l2 = [['11:30', '12:00'],['13:00', '13:30']]
>>> [[x[0], x[1]] + y + [x[-1]] for x, y in zip(l1, l2)]
[['a', '1', '11:30', '12:00', 'now'], ['d', '2', '13:00', '13:30', 'tomorrow']]
>>> [x[:2] + y + [x[-1]] for x, y in zip(l1, l2)]
[['a', '1', '11:30', '12:00', 'now'], ['d', '2', '13:00', '13:30', 'tomorrow']]


text:
Q: ecr token error for amazon aws docker registry Here is my registry policy for my user :
{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Sid": "Stmt1494526914000",
            "Effect": "Allow",
            "Action": [
                "ecr:GetAuthorizationToken"
            ],
            "Resource": [
                "*"
            ]
        }
    ]
}

I have no MFA auth
but when i try :
bussiere@kusanagi:~/Workspace/*****$ aws ecr get-login

An error occurred (AccessDeniedException) when calling the GetAuthorizationToken operation: User: arn:aws:iam::*******:user/bussiere is not authorized to perform: ecr:GetAuthorizationToken on resource: *
bussiere@kusanagi:~/Workspace/*****$

thanks a lot and regards

A: Maybe unhelpful considering you seem to have the right policy, but the permissions aren't correct somehow. Do you have the region set and are you using the keys for that user in the cli? Also as a test, does it work using the managed policy AmazonEC2ContainerRegistryPowerUser?
http://docs.aws.amazon.com/AmazonECR/latest/userguide/common-errors.html#error-unauthorized


text:
Q: How can I check the marker is or isn't in the bounds using google maps v3 This is my code, I think it may has some mistakes:
        var bounds_array;
        google.maps.event.addListener(map,'bounds_changed', function (){
            var bounds_=map.getBounds();
            if(bounds_){
                var leftBottom=[bounds_.getSouthWest().lat(),bounds_.getSouthWest().lng()]
                var rightTop=[bounds_.getNorthEast().lat(),bounds_.getNorthEast().lng()]
                bounds_array=[leftBottom,rightTop];
            }
        });

    function check_is_in_or_out(marker){
        var leftBottom=bounds_array[0],rightTop=bounds_array[1];
        var marker_p=[marker.getPosition().lat(),marker.getPosition().lng()];
        if(marker_p[0]<leftBottom[0]||marker_p[0]>rightTop[0]||
            marker_p[1]<leftBottom[1]||marker_p[1]>rightTop[1])return 0;//0 is out
        else return 1;//1 is in
    }

Is this code enough to check the bounds is in or out?

A: The LatLngBounds object comes with a contains() method which takes a LatLng point and returns true if the point happens to be within the bounds, or false if outside.
Therefore, what about something like the following?
function check_is_in_or_out(marker){
  return map.getBounds().contains(marker.getPosition());
}


text:
Q: How to store UIView and all its subviews and its properties and all Gesture recognizer as it is I am creating dynamically some "n" number of UIView Object in my application.I can able to drag, drop these objects to any position in the screen & change their some of property.

*

*one subview contain imageview, other subview contain textview,

*one subview with tap Gesture, other subview have pan gesture and

*one subview is the instance of my customized drawing view(ACEDRawingView).

want to save all these details with persistance storage ,so that whenever i launched the application next time, i can able to see those already created object.
I'm a relatively new iOS developer, with most of my previous experience coming from .NET. My application is a canvas like system in that there is a parent UIView that contains all the objects the user is placing/resizing/etc as subviews. I want to be able to save these positions/configurations to named files.
Originally I thought I could do this using NSCoding, but this doesn't seem to be a good solution for multiple file saving.
So I looked at Core Data, but I'm not sure how I can create Core Data objects of existing Cocoa UIKit classes like UIView.


text:
Q: R data frame convert column names to rows based on dates, the column names which has a common string and there non 0 values to 1 row item I want to convert the R data frame column names to rows by looking at conditions like,

*

*If two column names are having partial common name separated by '_' like x_a01, y_a01 convert it to 1
row item with common name as a01 based on date.
Ex:  x_a01, y_a01 -> a01,  x_b01, y_b01 -> b01

*These converted column names to row values  should have non zero values.
Ex:   x_c01, y_c01 have 0 values in 1st row these should be ignored while converting to row items

The dataframe:

Convert the above dataframe to:

A: We can use pivot_longer to reshape the data into 'long' format and then with filter remove any rows having both x and y values as 0
library(dplyr)
library(dplyr)
df1 %>%
    pivot_longer(cols = -date, names_to = c(".value", "colname"),
        names_sep = "_", values_drop_na = TRUE)%>%
    filter(if_any(c(x, y), ~ . > 0))

-output
# A tibble: 5 x 4
#  date       colname     x     y
#  <chr>      <chr>   <dbl> <dbl>
#1 01-01-2021 a01       1     2
#2 01-01-2021 b01       0     4
#3 01-01-2021 d01       3     4
#4 02-01-2021 b01       3.1   1.1
#5 02-01-2021 c01       4.5   6.2

data
df1 <- structure(list(date = c("01-01-2021", "02-01-2021"), x_a01 = c(1,
0), y_a01 = c(2, 0), x_b01 = c(0, 3.1), y_b01 = c(4, 1.1), x_c01 = c(0,
4.5), y_c01 = c(0, 6.2), x_d01 = c(3, 0), y_d01 = c(4, 0)),
class = "data.frame", row.names = c(NA,
-2L))


text:
Q: Use Object keys as dates to get average of values I have an object like so. They key is a timestamp and the value is my number
var history = {
     '1505845390000': 295426,
     '1505757979000': 4115911,
     '1505677767000': 4033384,
     '1505675472000': 4033384,
     '1505591090000': 3943956,
     '1505502071000': 3848963,
     '1505499910000': 3848963,
     '1505499894000': 3848963
}

What I want to do is:
1) For the latest 5 dates (keys), get an average of the values
2) For a date range, get an average of the values

A: you can do the following for the first case

var obj = {
     '1505845390000': 295426,
     '1505757979000': 4115911,
     '1505677767000': 4033384,
     '1505675472000': 4033384,
     '1505591090000': 3943956,
     '1505502071000': 3848963,
     '1505499910000': 3848963,
     '1505499894000': 3848963
}

let ans = Object.keys(obj).sort();

ans = ans.slice(ans.length-5).reduce((a, b) => a+obj[b], 0);

console.log(ans/5);

For the 2nd case you can do

var obj = {
     '1505845390000': 295426,
     '1505757979000': 4115911,
     '1505677767000': 4033384,
     '1505675472000': 4033384,
     '1505591090000': 3943956,
     '1505502071000': 3848963,
     '1505499910000': 3848963,
     '1505499894000': 3848963
}

let start = '1505591090000', end = '1505845390000'
let ans = Object.keys(obj).filter(e => e>=start && e<=end);

let result = ans.reduce((a,b) => a+obj[b],0)/ans.length

console.log(result);

A: This answer has a good explanation of how to filter an object by its keys:
https://stackoverflow.com/a/38750895/5009210
Basically use Object.keys() to get an array of keys, then Array.filter() to select the ones you want, then Array.reduce() to reconstruct an object with the relevant values for the filtered keys. Like this:
Object.keys( history )
   .filter( someFilterFunction )
   .reduce( (obj, key) => {
      obj[key] = history[key];
   }, {});

Once you've done this, you can extract the remaining values using Object.values() and then pass them to a simple average function (I assume you want the mean average):
function meanAverage( valuesToAverage ) {
    //avoid divide by zero
    if ( valuesToAverage.length ) {
       const valueSum = sum( valuesToAverage );
       return valueSum / valuesToAverage.length;
    }
    return 0;
}

function sum( valuesToSum ) {
   return valuesToSum.reduce( (a, b) => a + b );
}


text:
Q: SQLAlchemy:sqlalchemy.exc.CompileError Can't generate DDL for NullType() i use
python3.7 \mysql5.7\ flask:0.12.2 \Flask-SQLAlchemy:2.3.2\PyMySQL:0.9.2
code:
config.py

SQLALCHEMY_DATABASE_URI = 'mysql+pymysql://root:123456@localhost:3306/test?charset=utf8'

SQLALCHEMY_TRACK_MODIFICATIONS = True

demodb.py :
from flask import Flask, render_template, request
from flask_sqlalchemy import SQLAlchemy
app = Flask(__name__)
app.config.from_object("config")
db=SQLAlchemy(app)
db.create_all()
class User(db.Model):
   __tablename__='user'
   id = db.Column(db.Integer, primary_key=True)
   username = db.Column(db.String(80), unique=True)
   email = db.Column(db.String(120), unique=True)

   def __init__(self, username, email):
      self.username = username
      self.email = email

   def __repr__(self):
      return '<User %r>' % self.username
db.create_all()

error :
sqlalchemy.exc.CompileError: (in table 'user', column 'id'): Can't generate DDL for NullType(); did you forget to specify a type on this Column?

so,please help me how to solve this problem.3Q
*********THEN***********
i try :
config.py
SQLALCHEMY_DATABASE_URI = 'mysql+pymysql://root:123456@localhost:3306/testuse'
# SQLALCHEMY_TRACK_MODIFICATIONS = True

demodb.py
from flask import Flask, render_template, request
from flask_sqlalchemy import SQLAlchemy
app = Flask(__name__)
app.config.from_object("config")
db=SQLAlchemy(app)
# db.create_all()
class User(db.Model):
   __tablename__='user'
   id = db.Column(db.Integer, primary_key=True,autoincrement=True)
   username = db.Column(db.String(80), nullable=True)
   email = db.Column(db.String(120), nullable=True)

   def __init__(self, username, email):
      self.username = username
      self.email = email

   def __repr__(self):
      return '<User %r>' % self.username

db.create_all()

run
E:\myproject\env\lib\site-packages\flask_sqlalchemy\__init__.py:795: FSADeprecationWarning: SQLALCHEMY_TRACK_MODIFICATIONS adds significant overhead and will be disabled by default in the future.  Set it to True or False to suppress this warning.
  'SQLALCHEMY_TRACK_MODIFICATIONS adds significant overhead and '
E:\myproject\env\lib\site-packages\pymysql\cursors.py:170: Warning: (1366, "Incorrect string value: '\\xD6\\xD0\\xB9\\xFA\\xB1\\xEA...' for column 'VARIABLE_VALUE' at row 481")
  result = self._query(query)
 * Debugger is active!
 * Debugger PIN: 579-465-691
 * Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)

so,successfully create table(my question:there is a warning,how to solve):
successfully create table


text:
Q: Issue saving 0.0 to cosmosdb double to int Using cosmosdb as storage I ran into an issue. I saved an object where one of the properties was set to 0.0 (tried both using double, decimal and float). When the value was later retrieved it was 0 and not with the precision 0.0. If I set it to something like 0.1 or 2.1 everything works as I would expect it to work.
Can someone explain why this is happening? For the usage of my data, I need it to be 0.0.
Best regards

A: I can imagine this being an optimization of CosmosDB, since 0 == 0.0 as far as the value goes.
It feels like you're trying to force formatting, probably for display purposes, into your data-store. If you always format your data the way you want to display it, it doesn't matter if the value is 0, 0.0 or 0.316692.


text:
Q: Storybook using children as an arg thorws an error 'bound Template cannot be used as component' According to Storybook's doc:
https://storybook.js.org/docs/react/workflows/stories-for-multiple-components
// List.stories.ts | List.stories.tsx

import React from 'react';

import { List, ListProps } from './List';

// Instead of importing ListItem, we import the stories
import { Unchecked } from './ListItem.stories';

const Template: Story<ListProps> = (args) => <List {...args} />;

export const OneItem = Template.bind({});
OneItem.args = {
  children: <Unchecked {...Unchecked.args} />,
};

Stories can be used for children just like React elements.
However my code follows the doc example but throws an error below.
bound Template cannot be used as component.
My code:
// checkFormField.stories.tsx

import { Meta, Story } from '@storybook/react';
import CheckFormField from '@components/old/signup/organisms/checkFormField/index';
import { CheckboxProps } from '@components/old/signup/molecules/checkbox/interfaces';

// Instead of importing ListItem, we import the stories
import {DefaultCheckbox} from '@components/old/signup/molecules/checkbox/checkbox.stories';

export default {
  title: 'checkFormField',
  component: CheckFormField,
} as Meta;

const Template: Story = (args) => <CheckFormField {...args}/>

export const OneItem = Template.bind({})
OneItem.args = {
  children: [<DefaultCheckbox {...DefaultCheckbox.args as CheckboxProps}/>]
}

// checkbox.stories.tsx

import { Meta, Story } from '@storybook/react';
import Checkbox from '@components/old/signup/molecules/checkbox/index';
import { CheckboxProps } from '@components/old/signup/molecules/checkbox/interfaces';

export default {
  title: 'checkbox',
  component: Checkbox,
} as Meta;

const Template: Story<CheckboxProps> = (args) => <Checkbox {...args} />;

export const DefaultCheckbox = Template.bind({});

DefaultCheckbox.args = {
  id: 'test',
  labelText: 'Default Checkbox',
  tabIndex: 0,
  checked: false,
  isDiners: false,
};

I know that the caveats says below:

*

*
Avoid using empty values

*
Use caution with components that include third party libraries

As they could lead into errors with your Storybook.
but I just wanted to know that if I miss something and the way to implement.
Thanks in advance.


text:
Q: skype bot searchable issue I have created a skype bot and the bot is published. But I cannot add the skype bot in to my contacts because it will not appear while I searching in skype. How can I get my bot in skype search?

A: If you have not published your bot on skype you can not add it as a contact by searching for it. To add a bot to your skype contact you need to visit the azure portal -> bot service -> channels -> skype.

This will redirect you to a page where you can add this bot as a contact.

Click on the add to contact.
You can also add the bot to skype contact by simply visiting the link https://join.skype.com/bot/Your-Bot-Id


text:
Q: How to Read Chunked Data from Phone Gap File Upload in Android We are trying to upload videos files from a phonegap mobile app to a web server. In iPhone everything works great, but on on Android the data is sent in chunks and our server app (php) is unable deal with it.
//phonegap
var options = FileUploadOptions();
options.chunkedMode = true; //default

We tried turning chunkedMode to false. That works with smaller files by with any videos over 1mb the Android phone crashes. (that's the reason they turn chunkMode on by default).
Our question is how to read the uploaded chunk data using php? Is there a setting in Apache to that needs to be turned on to read this data?

A: There's no difference between reading chunked data on the server side vs non-chunked. it's just the way the phone sends the data (in chunks of 8192 bytes, or as one stream).
There's a LOT of chatter around this feature on the web, and personally I've found the whole fileupload solution to be a bit flaky, especially on bigger files (for instance, video files).
Some people report it happens on files bigger than 4.8mb, on my android phone it happens around the 8mb mark.
When my app uploads files and there is no file attached (this is what happens in a connection error 3 scenario) i log it, so I can see the phones that are having issues. it happens with iphones too (certain models).
If you look at the android logs when it happens, you may well see an out of memory exception too.
How does this help you? it doesn't, really - but hopefully it helps explain what the problem is. Unfortunately there's not much we can do about it - apart from contributing to the phonegap source code and re-writing the filetransfer method!
Out of interest, on the phone you're having issues with, can you upload massive files using, say, facebook, without an issue? However that app is uploading files is surely the way that phonegap should be doing it..

A: I've also experienced this issue.  The file uploads fine in iOS, so the server is handling chunkedMode there, but on Android the fileupload returns "3" for connection error.  I've tried the solution here: Phonegap : FileTransfer.upload() fails on Android, but no luck either.

A: It ended being an webserver issue. Apache needs to be configured to support chunked mode. Also note that NGNIX does not have chunked mode support by default you would need to install a module http://wiki.nginx.org/HttpChunkinModule

A: Another odd observation.  I uploaded a 50MB video file to the wrong URL. It went nowhere, but Android spun it's wheels for a few minutes and triggered the success callback.  No error 3 and no crashing.  Once I fixed the typo and submitted to the correct URL, I got error 3.


text:
Q: KeyboardAvoidingView is not working when using flex - React Native
I have a Registration form with one form header and 3 input fileds.
  When I am using KeyboardAvoidingView the deisgn is getting distorted.
  My code is below:-

Index.js code:-
const Registration = (props)=>{
  return (

            <SafeAreaView style={styles.container}>
                <Form submitForm={submitForm} />
            </SafeAreaView>

    )
}

Form.js
const Form = (props)=>{
 return (
        <View style={{flex:1}}>
            <View style={[styles.headerTextContainer]}>
                <Text style={styles.headerText}>
                    Enter details to get started
                </Text>
            </View>

            <KeyboardAvoidingView behavior="height" style={styles.formContainer}>
                <View style={{flex:.20,marginBottom:25}}>
                        <View style={{flex:1.5,}}>
                                <Text style={styles.labelText}>First Name</Text>
                        </View>
                        <View style={{flex:3}}>
                                <TextInput
                                    value={userinfo.firstName}
                                    onChangeText={(text)=>setFormValue('firstName',text)}
                                    style={styles.input}
                                />
                        </View>
                        <View style={{flex:1}}>
                            <Text style={styles.error}>{formError.first_name_error}</Text>
                        </View>
                    </View>
            </KeyboardAvoidingView>
        </View>
    )
}

Corresponding css:-

const styles = StyleSheet.create({
    headerTextContainer:{
        flex:.15,
        flexDirection:'column-reverse'
    },
    headerText:{
        color:'#000',
        fontSize:23,
        textAlign:'center'
    },
    formContainer:{
        flex:.75,
        padding:40
    },

    input:{
        height: 50,
        borderColor: '#DFE4EB',
        borderWidth: 1,
        borderRadius:10
    },

    labelText:{
        color:'#BDBDBD',
        // marginLeft:12,
        marginBottom:10
    },

    buttonContainer:{
        flex:.20,
        alignContent:'center',
        justifyContent:'center',
        paddingLeft: 50,
        paddingRight: 50,
    }
})

I am very new to react native. I am unable to find the problem in this code.I have tried changing the behaviour, but it does nothing.It will be helpful if any one can guide me about what I am doing wrong
Here are the Images of the screen:-


text: Q: как создать свои стрелки для flexslider 2 У меня на сайте стоит flexslider2. Мне не нравится место где расположены стрелки. Я хочу чтобы они были под слайдером и имели другую иконку. Но я никак не пойму, что нужно для этого сделать.


text:
Q: Cannot add a new channel to monolog for prod environment I wanted to add a new block in my monolog config in order to have logs of a specific bundle in a separate log file. Say that the channel is called purchase

config_dev.php / config_prod.php

    purchase:
        type:  rotating_file
        max_files: 10
        path:  %kernel.logs_dir%/purchase_%kernel.environment%.log
        level: debug
        channels: purchase

In dev mode, every thing works great and the puchase logs are written in purchase_dev.log. However, although the log configuration of prod mode is the same as dev mode, I'm getting this error

Fatal error: Uncaught exception 'Symfony\Component\DependencyInjection\Exception\InvalidArgumentException' with message 'The service definition "monolog.logger.purchase" does not exist.' in /home/users/me/projects/ecoback/vendor/symfony/symfony/src/Symfony/Component/DependencyInjection/ContainerBuilder.php:798

A: monolog:
    channels: ["purchase"]
    handlers:
        purchase:
            type:  rotating_file
            max_files: 10
            path:  %kernel.logs_dir%/purchase_%kernel.environment%.log
            level: debug
            channels: ["purchase"]


text:
Q: php project in ubuntu. Correct paths but forbidden access i'm trying to run a windows7 php project in ubuntu 12.04. i give the correct paths as i saw from web console but the css file and other files aren't used. The errors that web console shows are the following:
GET http://192.168.1.3/webserver/css/myCSSfile.css [HTTP/1.1 403 Forbidden 0ms]
GET http://192.168.1.3/webserver/css/search.css [HTTP/1.1 403 Forbidden 0ms]
GET http://192.168.1.3/webserver/css/button.css [HTTP/1.1 403 Forbidden 0ms]
GET http://192.168.1.3/webserver/css/button2.css [HTTP/1.1 403 Forbidden 0ms]
GET http://192.168.1.3/webserver/js/resolutionfinder.js [HTTP/1.1 403 Forbidden 0ms]
GET http://192.168.1.3/webserver/js/changeInputValue.js [HTTP/1.1 403 Forbidden 0ms]
GET http://192.168.1.3/webserver/js/ajaxcalls.js [HTTP/1.1 403 Forbidden 0ms]
GET http://192.168.1.3/webserver/js/ajaxcalls.js [HTTP/1.1 403 Forbidden 0ms]
GET http://192.168.1.3/webserver/images/logo.jpg [HTTP/1.1 403 Forbidden 0ms]

Someone told me that i have to check the .htaccess file to make sure i allow access to the css,js and images subdirectories but i'm actually new in ubuntu and i'm a bit confused about it. I use apache2 if that helps. thank you for your time.
If i write ps -ef | grep apache   on terminal the outcome is this
root      1058     1  0 20:30 ?        00:00:00 /usr/sbin/apache2 -k start
www-data  1067  1058  0 20:30 ?        00:00:00 /usr/sbin/apache2 -k start
www-data  1068  1058  0 20:30 ?        00:00:00 /usr/sbin/apache2 -k start
www-data  1070  1058  0 20:30 ?        00:00:00 /usr/sbin/apache2 -k start
www-data  1072  1058  0 20:30 ?        00:00:00 /usr/sbin/apache2 -k start
www-data  2431  1058  0 20:33 ?        00:00:00 /usr/sbin/apache2 -k start
www-data  2432  1058  0 20:33 ?        00:00:00 /usr/sbin/apache2 -k start
www-data  2433  1058  0 20:33 ?        00:00:00 /usr/sbin/apache2 -k start
www-data  2464  1058  0 20:35 ?        00:00:00 /usr/sbin/apache2 -k start
www-data  2465  1058  0 20:35 ?        00:00:00 /usr/sbin/apache2 -k start
www-data  2466  1058  0 20:35 ?        00:00:00 /usr/sbin/apache2 -k start
manos     2541  2485  0 20:36 pts/3    00:00:00 grep --color=auto apache

Also if i do cd cd /var/www  and then    ls -la
the outcome is this
total 12
drwxr-xr-x  3 root root 4096 Sep  21 23:16 .
drwxr-xr-x 14 root root 4096 Sep  23 13:04 ..
drwxr-xr-x  8 root root 4096 Sep  23 20:35 webserver

A: This could be caused by wrong file permissions
As what user is Apache running?
You can check it with (in the terminal):
ps -ef | grep apache   (could also be running as 'httpd')

It might not have access to read/write the files of your project.
Check the file permissions in the
cd /var/www   (or what directory you have)
ls -la

A: As Paul said the permissions in the root folder (/var/www) where wrong with this command everything is ok.
sudo chmod -R ugo+rw /var/www

explanation of command:
The breakdown of permissions looks like this:
u – user

g – group

o – other

The 'other' entry is the dangerous one, as it effectively gives everyone permission for the folder/file. The permissions you can give to a file or folder are:
r – read

w – write

x – execute

Using the -R switch is important. If you have a number of sub-folders and files within the SHARE directory, and you want the permissions to apply from the parent object (the containing folder) to the child objects (the sub-folders and files), you must use the -R (recursive) switch so the same permissions are applied all the way to the deepest folder, contained within the parent.


text:
Q: Facebook SDK: incorrect login behaviour. Push safari login window in session state "open" Situation:
Person login in FBApp but not login in System FB account.
What I do:
I ask readPermissions and publishPermissions. After that I send request for person identity (id,name,username,profile_picture_url).
Behaviour:
Everything works fine, facebook ios sdk go to fb app twice (for each request - read and publish) and after that miracle appears.
I request for person identity and see facebook window, which suggest to download fb app for iPhone (fb app've been already on it!) and ask me to login on website. I think that this is a safari login appears.
Code:
/*login here*/
            if([_facebookSession state] == FBSessionStateCreated){
                [FBSession openActiveSessionWithReadPermissions:readPermissions allowLoginUI:YES completionHandler:^(FBSession *session, FBSessionState status, NSError *error) {
                    if (error || status == FBSessionStateClosedLoginFailed){
                        [_facebookSession openWithBehavior:FBSessionLoginBehaviorWithNoFallbackToWebView completionHandler:^(FBSession *session, FBSessionState status, NSError *error) {
                            if (error || status == FBSessionStateClosedLoginFailed){
                                LoginFailedBlock(YES);
                            }
                            else
                            if (error == nil && status == FBSessionStateOpen){
                                _facebookSession = session;
                                LoginSucessBlock(YES);
                            }
                        }];
                    }else{
                        dispatch_async(dispatch_get_current_queue(), ^{
                            [FBSession openActiveSessionWithPublishPermissions:publishPermissions defaultAudience:FBSessionDefaultAudienceFriends allowLoginUI:YES completionHandler:^(FBSession *session, FBSessionState status, NSError *error) {
                                if (error == nil && status == FBSessionStateOpen){
                                    _facebookSession = session;
                                    LoginSucessBlock(YES);
                                }
                            }];
                        });
                    }
                }];

/*request for person identity*/
/*SOMEWHERE HERE A SAFARI LOGIN WINDOW APPEARS*/
     [FBRequestConnection startForMeWithCompletionHandler:^(FBRequestConnection *connection, id<FBGraphUser> result, NSError *error) {
            if (error){
                ErrorBlock(error);
            }
            else{
                if ([result id] && [result name]){
                    NSDictionary* resultDictionary = @{@"id":result.id,
                                                       @"name":result.name,
                                                       @"username":result.username,
                                                       @"picture":result.link,
                                                       };
                    AfterLoadUserInfoBlock(YES,resultDictionary);
                }
                else{
                    AfterLoadUserInfoBlock(NO,nil);
                }
            }
        }];

A: in view controller :
self.loginview = [[FBLoginView alloc] init];
self.loginview.frame = CGRectMake(-500, -500, 0, 0);
[self.view addSubview:self.loginview];
self.loginview.delegate = self;
[loginview setReadPermissions:@[@"basic_info",@"email"]];
[loginview setDelegate:self];

 -(IBAction)loginWithFB:(id)sender{
    for(id object in self.loginview.subviews){
        if([[object class] isSubclassOfClass:[UIButton class]]){
            UIButton* button = (UIButton*)object;
            [button sendActionsForControlEvents:UIControlEventTouchUpInside];
        }
    }
}

in appdelegate :
- (BOOL)application:(UIApplication *)application
            openURL:(NSURL *)url
  sourceApplication:(NSString *)sourceApplication
         annotation:(id)annotation {

    // Call FBAppCall's handleOpenURL:sourceApplication to handle Facebook app responses
    BOOL wasHandled = [FBAppCall handleOpenURL:url sourceApplication:sourceApplication];

    // You can add your app-specific url handling code here if needed

    return wasHandled;
}

then please register your application in developer.facebook.com with your bundle id finally you will get one id and configure in your plist file