text:
Q: Android Printing App for Zebra RW420 printer I mean to start developing a simple android application for printing labels using zebra RW420 printer. They have SDK for android but I cannot figure out where to start from.
I invision an app with a single screen, it asks for the label or purchase order, how many copies we'd like to print, and a print button. Can someone help me get started. Any help will be appreciated.
How I am a going to search for the printer will the SDK will do it for me ?? or I have to use Androids BluetoothAdapter class ... about the label format do I have to create myself or I can use the existing file in the SDK ??
Can I set the printer to print multiple copies ??

A: The SDK provides a bluetooth discovery class. Look at the documentation and the examples. Check out the BluetoothDiscoverer class. It provides a method to find all bluetooth devices and notifies you in a handler. There is a Developer Demo which comes with the SDK which has an example of how to do a discovery:
    try {
        BluetoothDiscoverer.findPrinters(this, new DiscoveryHandler() {

            public void foundPrinter(DiscoveredPrinter printer) {
                String macAddress = printer.address;
                //I found a printer! I can use the properties of a Discovered printer (address) to make a Bluetooth Connection
            }

            public void discoveryFinished() {
                //Discovery is done
            }

            public void discoveryError(String message) {
                //Error during discovery
            }
        });
    } catch (ConnectionException e) {
        e.printStackTrace();
    } catch (InterruptedException e) {
        e.printStackTrace();
    }

A: 1) You have to print from a thread like:
new Thread (new Runnable () {
  public void run () {
    enablePrintButton (false);
    Looper.prepare ();
    doConnectionTest ();
    Looper.loop ();
    Looper.myLooper ().quit ();
  }
}).start ();

2) Then:
private void doConnectionTest () {
    printer = connect ();

    if (printer != null) {
      //print
    } else {
      disconnect ();
    }
  }

3) Print method:
private void sendTestLabel () {
    try {
      ZebraPrinterLinkOs linkOsPrinter = ZebraPrinterFactory.createLinkOsPrinter (printer);

      PrinterStatus printerStatus =
          (linkOsPrinter != null) ? linkOsPrinter.getCurrentStatus () : printer.getCurrentStatus ();

      if (printerStatus.isReadyToPrint) {
        byte[] configLabel = getConfigLabel ();
        connection.write (configLabel);
        setStatus ("Sending Data", Color.BLUE);
      } else if (printerStatus.isHeadOpen) {
        setStatus ("Printer Head Open", Color.RED);
      } else if (printerStatus.isPaused) {
        setStatus ("Printer is Paused", Color.RED);
      } else if (printerStatus.isPaperOut) {
        setStatus ("Printer Media Out", Color.RED);
      }
      DemoSleeper.sleep (1500);
      if (connection instanceof BluetoothConnection) {
        String friendlyName = ((BluetoothConnection) connection).getFriendlyName ();
        setStatus (friendlyName, Color.MAGENTA);
        DemoSleeper.sleep (500);
      }
    } catch (ConnectionException e) {
      setStatus (e.getMessage (), Color.RED);
    } finally {
      disconnect ();
    }
  }

4) Label configuration method:
private byte[] getConfigLabel () {
     byte[] configLabel = null;

     try {
       PrinterLanguage printerLanguage = printer.getPrinterControlLanguage ();
       SGD.SET ("device.languages", "zpl", connection);

       if (printerLanguage == PrinterLanguage.ZPL) {
         configLabel = "^XA^FO17,16^GB379,371,8^FS^FT65,255^A0N,135,134^FDTEST^FS^XZ".getBytes();
       } else if (printerLanguage == PrinterLanguage.CPCL) {

         String msg = setPopratnica ();

         msg = format (msg);

         configLabel = msg.getBytes ("windows-1250");
       }
     } catch (Exception e) {
     }
     return configLabel;
   }

5) Connect method:
public ZebraPrinter connect () {
     setStatus ("Connecting...", Color.YELLOW);
     connection = null;
     connection = new BluetoothConnection (getBluetoothAddressKey ());
    try {
       connection.open ();
       setStatus ("Connected", Color.GREEN);
         } catch (ConnectionException e) {
           setStatus ("Comm Error! Disconnecting", Color.RED);
           DemoSleeper.sleep (1000);
           disconnect ();
         }

         ZebraPrinter printer = null;

         if (connection.isConnected ()) {
           try {
             printer = ZebraPrinterFactory.getInstance (connection);
             setStatus ("Determining Printer Language", Color.YELLOW);
             String pl = SGD.GET ("device.languages", connection);
             setStatus ("Printer Language " + pl, Color.BLUE);
          } catch (ConnectionException e) {
             setStatus ("Unknown Printer Language", Color.RED);
             printer = null;
             DemoSleeper.sleep (1000);
             disconnect ();
           } catch (ZebraPrinterLanguageUnknownException e) {
             setStatus ("Unknown Printer Language", Color.RED);
             printer = null;
             DemoSleeper.sleep (1000);
             disconnect ();
           }
         }
         return printer;
}

6) Disconect method:
public void disconnect () {
    try {
      setStatus ("Disconnecting", Color.RED);
      if (connection != null) {
        connection.close ();
      }
      setStatus ("Not Connected", Color.RED);
    } catch (ConnectionException e) {
      setStatus ("COMM Error! Disconnected", Color.RED);
    } finally {
      enablePrintButton (true);
    }
  }

Plus you have to have a sleeper class :
public class DemoSleeper {
    private DemoSleeper () {
    }

    public static void sleep(int ms) {
        try {
            Thread.sleep(ms);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}


text:
Q: Python to extract a paragraph from a text file: Split string with exact match of multiple nested delimiters I am reading hundreds of pdf files to extract the abstract. My strategy is:
(1) split after the delimiter abstract
(2) read abstract
(3) stop when blank line.
Here is the code that can do this:
import re
raw = ' Some text\n\nABSTRACT\nExtract \nthis text\n\nOther text'
pattern = 'abstract'
abstract = re.split(pattern ,raw, flags=re.IGNORECASE)[1].split("\n\n")[0]
print(abstract)

The problem is that different pdf files would contain different forms for my delimiters such as abstract:,  abstract:\n , abstract\n , which are all nested. Accordingly I tried something like this:
    import re
    raw = ' Some text\n\nAbstract:\n\nExtract \nthis text\n and include
 abstraction and Abstraction \n\nOther text'
    pattern = 'abstract|abstract:|abstract:\n'
    abstract = re.split(pattern, raw, flags=re.IGNORECASE)[1].split("\n\n")[0]
    print(abstract)

Yet it did not work for the above example. Also, this code will not work for exact match. For example, it will not ignore abstraction and Abstraction

A: In the patterns you want to split on, have them ordered such if one is subset of another it comes later in the list
pattern = 'abstract:|abstract'

Don't worry about the trailing whitespace (\n, \n\n, \n\t) in the splitting, take care of that afterwards using .strip() as that will remove all kinds of whitespace from the ends of the string.
text_after_abstract_header = re.split(pattern, raw, flags=re.IGNORECASE)[1]
abstract = text_after_abstract_header.strip().split('\n\n')

A: You can add as much detail to the regexp as possible, in this case, we can add characters before and after abstract
>>> raw=' Some text\n\nABSTRACT:\t\nExtract this text\n adasdd\n\nSome other text'
>>> arr = re.split('(?i)\n{1,2}abstract[:\n\t]+',raw)[1].split('\n\n')
>>> arr
['Extract this text\n adasdd', 'Some other text']
>>> arr[0]
'Extract this text\n adasdd'

(?i) same as the flags=re.IGNORECASE
\n{1,2} 1 or 2 newlines
[:\n\t]+ that list of characters 1 or more times.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Is UNION ALL resulting in slow PostgresSQL query runtime? I have a Postgres query that uses UNION ALL to select the same columns from ~17 different tables. Runtime is very slow and needs to be improved. What is the main determinant in this query's high execution time? Is it the number of SELECTs I have in the query, the number of columns I'm selecting (over 100), or something else?
Tried limiting the number of columns selected and didn't notice an increase in performance. For further context, I have the Postgres query running as an AWS Lambda function triggered by an API Gateway request. New to this so I don't know if the AWS architecture is part of the problem. Would really appreciate any help!


text:
Q: How to separate text on different lines in an email using ACTION_SEND? I was wondering, if anyone could help with this problem, I'm having trouble with ACTION_SEND. I have it setup that all the info is sent to the e-mail and to the address. My problem is I'm not sure if I can or if it possible to separate the information on different lines.
I would like to have my 1's item on one line and my 2's item on another line. I'm trying to get all my different number items to be put on different lines in the e-mail. Is that possible or do I need to redo the code to get that to happen?
Thank you in advance for your help and time!
Here's my code:
String message = pIN1 + " " + pD1 + " " + passM1 + " " + pU1 + " " + pIN2 + " " + pD2 + " " + passM2 + " " + pU2;

String[] to=new String[]{""};
String subject = ("Results");
Intent emailIntent = new Intent(Intent.ACTION_SEND);
emailIntent.putExtra(Intent.EXTRA_EMAIL, to);
emailIntent.putExtra(Intent.EXTRA_SUBJECT, subject);

if (passSN.equals("2")){
    emailIntent.putExtra(Intent.EXTRA_TEXT, message);
    emailIntent.setType("message/rfc822");
    startActivity(Intent.createChooser(emailIntent, "Email"));
} else {
    Toast.makeText(getApplicationContext(), "Error", Toast.LENGTH_LONG).show();
}

A: you can use the new line character \n to achieve what you want:
String message = pIN1 + "\n" + pD1 + "\n" + passM1;

A: Yes:
    String message = "";
    message += pIN1 + " " + pD1 + " " + passM1 + " " + pU1;
    message += "\n" + pIN2 + " " + pD2 + " " + passM2 + " " + pU2;

    String[] to = new String[]{""};
    String subject = ("Results");
    Intent emailIntent = new Intent(Intent.ACTION_SEND);
    emailIntent.putExtra(Intent.EXTRA_EMAIL, to);
    emailIntent.putExtra(Intent.EXTRA_SUBJECT, subject);
    emailIntent.putExtra(Intent.EXTRA_TEXT, message);
    emailIntent.setType("message/rfc822");

    startActivity(Intent.createChooser(emailIntent, "Send Email"));


text:
Q: Making a function that takes as an input a list not care about the order of the elements of the list I would like a function f, that takes as input a list, not care about the order of elements of the list. So,for example:

f[{3,2}]=f[{2,3}]

Is this possible? Or is it necessary to convert the list into a set? If so how can I the conversion be done?
Thank you in advance

A: You can also use OrderlessPatternSequence:
ClearAll[f1]
f1[{OrderlessPatternSequence[x_, y_, z_]}] := {{{x}, {z}, {y}}}

f1[{2, 3, 1}]

{{{1}, {3}, {2}}}

f1[{3, 2, 1}]

{{{1}, {3}, {2}}}

You can use it with a subset of arguments:
ClearAll[f2]
f2[arg1_, OrderlessPatternSequence[x_, y_, z_], arg2_List] := {x, y, z, arg1, arg2}

f2[t, 2, 1, 3, {x}]

{1, 2, 3, t, {x}}

f2[t, 1, 2, 3, {x}]

{1, 2, 3, t, {x}}

A: I'm guessing that you want to compare lists for equality using == (not =), but ignoring order. There are many ways. One way is to make a new kind of list wrapper:
SetAttributes[orderlessList, Orderless]

You need not define any values for orderlessList: it's just a wrapper. Now, a conversion from List to orderlessList:
orderless[x_List] := Apply[orderlessList, x]
Then,
orderless[{3, 2}] == orderless[{2, 3}]
(* True *)


text:
Q: Android animation clipping when going between layouts I have a fairly complex layout. I use a relative layout as the root and then inside of it I have a few table views and some further nesting. When I animate an imageview between these layouts my image clips. I have a background on the parent layout and the animation looks like it's going under it. I have set android:clipChildren="false" and android:clipToPadding="false" on all of the layouts. I've also set anim.setZAdjustment(Animation.ZORDER_TOP); on all of my animations. What am I doing wrong?
EDIT: I've found at least 2 bugs so far. android:background= with a hex color causes major animation issues. Table layouts also seem to have a regoin under them that causes clipping. I am also seeing the same thing with framelayouts. I'll add an answer once I actually get my stuff working the way I want it to. I have a feeling using only linear layouts is the solution.
Here is some sample code that produces the issue. If you remove the two child relative layouts then the animation completes as expected.

Java:
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    ImageView imageViewtop = (ImageView) findViewById(R.id.ImageView01);
    imageViewtop.setOnClickListener(btnCardListener);
}

private OnClickListener btnCardListener = new OnClickListener() {
    public void onClick(View v) {

        ImageView ImageView03 = (ImageView) findViewById(R.id.ImageView03);
        ImageView ImageView05 = (ImageView) findViewById(R.id.ImageView05);

        int[] playLoc = { 0, 0 };
        int[] botLoc = { 0, 0 };
        ImageView05.getLocationOnScreen(playLoc);
        ImageView03.getLocationOnScreen(botLoc);
        int xMove = playLoc[0] - botLoc[0];
        int yMove = playLoc[1] - botLoc[1];

        AnimationSet animSet = new AnimationSet(true);

        RotateAnimation ranim = new RotateAnimation(0f, 180f,
                Animation.RELATIVE_TO_SELF, 0.5f,
                Animation.RELATIVE_TO_SELF, 0.5f); // , 200, 200); //
                                                    // canvas.getWidth()
        // 2, canvas.getHeight() / 2);
        ranim.setDuration(400);
        ranim.setInterpolator(new DecelerateInterpolator());

        TranslateAnimation transAnim = new TranslateAnimation(
                Animation.ABSOLUTE, 0.0f, Animation.ABSOLUTE, xMove, // +80.0f,
                Animation.ABSOLUTE, 0.0f, Animation.ABSOLUTE, yMove // -100.0f
        );
        transAnim.setInterpolator(new DecelerateInterpolator()); // AccelerateInterpolator
                                                                    // ,
                                                                    // LinearInterpolator
        transAnim.setZAdjustment(Animation.ZORDER_TOP);
        transAnim.setAnimationListener(new AnimationListener() {
            public void onAnimationStart(Animation animation) {
            }

            public void onAnimationEnd(Animation animation) {
                ImageView ImageView03 = (ImageView) findViewById(R.id.ImageView03);
                ImageView ImageView05 = (ImageView) findViewById(R.id.ImageView05);

                ImageView05.setVisibility(View.VISIBLE);
                ImageView03.setVisibility(View.INVISIBLE);
            }

            public void onAnimationRepeat(Animation animation) {
            }
        });
        transAnim.setDuration(1000);

        // Order matters...
        animSet.addAnimation(ranim);
        animSet.addAnimation(transAnim);

        ImageView03.startAnimation(animSet);
    }
};

XML:
<RelativeLayout android:id="@+id/relativeParentLayout"
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="fill_parent"
    android:layout_height="fill_parent" android:clipToPadding="false">
    <RelativeLayout android:id="@+id/relativeParentLayout1"
        xmlns:android="http://schemas.android.com/apk/res/android"
        android:orientation="vertical" android:layout_width="fill_parent"
        android:layout_height="150dip" android:background="#440000"
        android:layout_alignParentTop="true" android:clipChildren="false"
        android:clipToPadding="false">
        <ImageView android:layout_height="wrap_content" android:id="@+id/ImageView01"
            android:layout_width="wrap_content" android:src="@drawable/card_back"
            android:layout_weight="0" android:layout_alignParentTop="true" />

        <ImageView android:layout_height="wrap_content" android:id="@+id/ImageView03"
            android:layout_width="wrap_content" android:src="@drawable/card_back"
            android:layout_weight="0" android:layout_gravity="center_vertical"
            android:layout_alignParentRight="true" />
    </RelativeLayout>
    <RelativeLayout android:id="@+id/relativeParentLayout2"
        xmlns:android="http://schemas.android.com/apk/res/android"
        android:orientation="vertical" android:layout_width="fill_parent"
        android:layout_height="150dip" android:background="#000044"
        android:layout_alignParentBottom="true" android:clipChildren="false"
        android:clipToPadding="false">

        <ImageView android:layout_height="wrap_content"
            android:layout_below="@+id/LinearLayout01" android:id="@+id/ImageView05"
            android:layout_width="wrap_content" android:src="@drawable/card_back"
            android:layout_weight="0" android:layout_alignParentBottom="true" />
    </RelativeLayout>
</RelativeLayout>

A: I had the same problem and after few days I found the solution ... thanx to:
http://www.mail-archive.com/android-developers@googlegroups.com/msg67535.html

I figured out a solution to this problem.  The clue came from the fact that when showing the view, everything worked fine. Apparently, when the animation is running, the update that would be forced by the show happens in the background and doesn't cause the flicker.  Adding a short animation to the back end of the onAnimationEnd() when we are hiding the view makes the flicker go away.
Here is the new onAndimationEnd() in the working code
    public void onAnimationEnd(Animation animation) {
             animation = new TranslateAnimation(0.0f, 0.0f, 0.0f, 0.0f);
                    animation.setDuration(1);
                    mPlayer0Panel.startAnimation(animation);
    }

A: the trick was setting setClipChildren to the layout that enclosed the view.

A: I wish I had a better answer for you, but I solved the problem by adding the object that I wanted to animate to the top level view, doing the animation there, and then hiding it. Not very satisfactory, have you found a better way?


text:
Q: SQL filling one table's fields with values from another table I'm fairly new to SQL (Mostly building tables and modifying, with some select/insert statements along the way) but I have a task at hand that I'm stuck on.
I've been filling html tables on one of my pages with database info through PHP. Everything fills up correctly, but I need to populate some values in my database  table so that I can show them in the HTML table.
I have a large staging table and a smaller pricing table. When a CSV file is uploaded on the site I have it inserted into the staging table. I want to find a way to fill up the pricing fields from info in the pricing table.
The prices are built from three things (all of which are in the staging table): meterType, meterSize and workOrderType2. There is another field in my staging table called onsiteSurveyTestCost.
My pricing table contains the priceID, meterSize, meterType, workOrderType, and price.
So, if a CSV is inserted and it has '3"' for meterSize, 'Compound' for meterType and 'Survey and Test' for workOrderType2 then I want it to use priceID '1' which has 3" Compound Survey and Test and I want to save the price into the original staging table as onsiteSurveyTestCost.
I hope that makes sense. Even if it can't be done upon INSERT/CSV upload, I still need to find a way to do this on my form page so that I can display the proper price for the form.
Pricing Table:

Staging Table Fields:

UPDATE:
Incomplete SQL statement:
UPDATE staging
SET onsiteTestSurveyPrice = (
SELECT price from pricing WHERE=
/* meterType of staging matches meterType of pricing*/
/* meterSize of staging matches meterSize of pricing*/
/* workOrderType2 of staging matches workOrderType of pricing*/

)

A: You should be able to do the update by joining your staging table to the pricing table on those columns.
UPDATE staging
INNER JOIN pricing ON
    staging.meterType = pricing.meterType
    AND staging.meterSize = pricing.meterSize
    AND staging.workOrderType2 = pricing.workOrderType
SET staging.onsiteTestSurveyPrice = pricing.price

There may be a better way to do this, but it's hard to tell without knowing more about how your application works.


text:
Q: Did malware take over my BIOS, preventing the utility from reading all of the blocks? At one point I updated my BIOS to add UEFI version for Windows 8. I recently went back to Windows 7 after testing Windows 10 for a bit. However I have now found that my BIOS cannot be flashed, neither with the older version that doesn't include UEFI, nor with the UEFI ROM that was used previously.
The strangest part is that it seems to start at the "middle" of the blocks and then concludes that there isn't enough space for this ROM.
Could this be a sign of some kind of malware?
(Guids match, I know I have the correct ROMS)

(But it always starts halfway down and then thinks there isn't enough space: "3 - Error: ROM file size does not match existing BIOS size.")


text:
Q: three.js ray intersection r58 i want   to   detect   intersection    using    ray   in   collada  object,   three.js    r58   but
var intersects = target.intersectObjects(ai);

not   working  for   me   any   one   solve    this   ?  is   Ray    doesn't    support   intersectObjects()   method   in   r58   or   there   is   any   bug   in the   code?   then    what   is the    alternate   instead    of   Raycasting?
    var sphereMaterial = new t.MeshBasicMaterial({color: 0x333333});
    var sphereGeo = new t.SphereGeometry(2, 6, 6);
    var target;

    function createBullet(obj) {
        if (obj === undefined) {
            obj = cam;
        }
        var sphere = new t.Mesh(sphereGeo, sphereMaterial);
        sphere.position.set(obj.position.x, obj.position.y * 0.8, obj.position.z);

        if (obj instanceof t.Camera) {
            var vector = new t.Vector3(mouse.x, mouse.y, 1);
            projector.unprojectVector(vector, obj);
            target=new t.Ray(obj.position, vector.sub(obj.position).normalize());
        sphere.ray= target;
        }
        else {
            var vector = cam.position.clone();
        target=new t.Ray(obj.position, vector.sub( obj.position ).normalize());
sphere.ray= target;
}

    sphere.owner = obj;

    bullets.push(sphere);
    scene.add(sphere);

    return sphere;
}

A: var sphereMaterialc = new t.MeshBasicMaterial({color: 0x0099FF});
var sphereGeoc = new t.SphereGeometry(5, 5, 5);
function createBullet3(obj) {
    var obj = cam;
    var spherec = new t.Mesh(sphereGeoc, sphereMaterialc);
    spherec.position.set(obj.position.x, obj.position.y, obj.position.z);

        var vector = new t.Vector3(mouse.x, mouse.y, 1);
        projector.unprojectVector(vector, obj);

        spherec.ray = new t.Ray(
                obj.position,
                vector.subSelf(obj.position).normalize()
        );

    spherec.id = 'player';
    spherec.owner = 'player';
    spherec.health = 100;
    spherec.lastfive = Date.now();

    bullets.push(spherec);
    scene.add(spherec);

    return spherec;

}


text:
Q: Filesystem Mechanism to Complement MongoDB in .NET program I'm relatively new to databases, so I'm trying to find a good filesystem mechanism that can work with MongoDB. Ideally, I'd use GridFS, but I don't generally care too much for files breaking into many little pieces and being put back together. I'd also like to keep MongoDB as lean as possible for better performance.
After doing some Googling (although probably not searching for the right things), I haven't had much luck finding anything meaningful for a good filesystem mechanism in a .NET database program that complements MongoDB's .NET API.
As far as I know, I can simply have the directory of the file on a field in MongoDB as a string, but I'd like to know of possible standards or commonly used mechanisms for secure filesystem upload and download (Whether its Linux, Windows, or a standalone server-client system, etc).
Can you recommend anything?


text:
Q: Manipulating X and Y Properties Unity2D-Javascript I'm new to Unity and Javascript, both of which I'm using for my new project, and my question is this: why must it be so difficult to simply access and manipulate x and y values? My whole life I've used AS for Flash and recall better days, when one could simply
trace(mc.x);

and
mc.x++;

But from the research I've done it seems that one can't even access a Game Object without typing out a tedious
GameObject.Find("mc")

And that's just for accessing the Object! As far as finding the object's position or for even moving an object to a point, I have no idea. I tried finding the answer online, but couldn't find anything.
And yes I understand that one can add to an object's position through
GameObject.Find("mc").transform.Translate(1,0,0);

But even that seems clumsy compared to the AS equivalent of a simple
mc.x++;

Thank you for your time.

A: It sounds like maybe you need to learn more about components. Any public GameObject field in your script classes (as long as they extend Component, or even better MonoBehaviour) can be filled with a reference to another GameObject by dragging and dropping the object in the Inspector pane. You can then reference the variable like normal.
GameObjects by themselves are not particularly useful, but you can use GetComponent() to find parts you need on those objects -- like Transform, Renderer, Rigidbody, or your own Component classes. You can also create public fields that have the specific Component sub-type you need, and reference them directly.
For example:
var anObject : GameObject;
var aTransform : Transform;
function Start(){
    if(anObject != null)
        Debug.Log("I know about an object called " + anObject.name);
    if(aTransform != null)
        Debug.Log("I know about a transform at " + aTransform.position);
}

As a side note - GameObject.Find() is really slow! If you use it too much your game will not perform well.


text:
Q: Winding Number with periodic boundary conditions (PBC)? Imagine we have a SC with a vortex of winding number 1 (one flux quanta) described by: $\theta(x,y)$. If we look at a BdG-Hamiltonian with periodic boundary conditions (PBC), it is easy to write down a lattice model for a computer to solve.
PBC is cheating however since the phase winding is different for points across the lattice! In actuality we should use open boundary conditions. This can be done by solving with PBC and taking linear combinations, but there are some challenges in trying this.
I just chopped off the lattice to exclude the boundary and hoped the bulk properties did not matter too much on the BC. I am getting a weird artifact in some plots however (I do not need to explain in detail, but a wave like pattern shows up in the arg of the FFT of the LDOS).
Is there a good way to do this without taking linear combinations of solutions? I was going to set a fixed BC on the winding of $\theta(x,y)$ at some sufficiently big $x^2+y^2$, but this will require some work to implement too. Any ideas, solutions, or critiques?


text:
Q: What is the regex patten for this? I am looking for a regex pattern to find all the content b/w curly brackets. For example, there is a string.
$string = {xxx yyy zzz}

I want to find a regex pattern so that it can extract the "xxx yyy zzz" out but no {}.
Thank you very much for your help.

Thank you for the responses.
I'm using PHP for testing. And here is my test code:
$string ='start {first find me} and {second find me}';
preg_match_all("/{([^{][^}]*)}/", $string, $matches);
  foreach($matches[0] as $value) {
    echo $value;echo "<br/>";
}

I will have:
{first find me}
{second find me}

But I expect:
first find me
second find me

Thanks.

A: If the {} are not nested,
\{([^}]*)\}

If you're using PCRE and they're nested ref,
\{([^{}]++|(?0))*\}

Otherwise, make a simple parser.

A: /\{(.+)\}/

It will be returned in the first capture.

A: building on what Kenny already had, you have to check for extra stuff at the beggining, and add the global modifier.  I'm not sure about php, but I can do it in javascript
var str = "start {first fine me} and {second find me}";
reStr = new RegExp(/[^\{]*\{([^}]*)\}/g);
var result = str.replace(reStr, "$1")

result will be "first fine mesecond find me"


text:
Q: Removing invalid git-subtree-split hash I'm having an issue with a subtree in our repository. I can pull just fine, but when trying to push it chugs along and finally shows me this:
fatal: bad object 9775d8fba16f51e14cba873f78129d3d166f5888

I did some searching in my .git folder and found this:
.git/subtree-cache/81555/549ffeaa00e89a145f24ccdb0735c07d8d84b2ff
1:9775d8fba16f51e14cba873f78129d3d166f5888

Commit 549ffeaa00e89a145f24ccdb0735c07d8d84b2ff is an older commit where I did a pull of the subtree. The pull was a squash (as is the preference on the project) and had no issues at the time.
Looking at the commit itself I see this:
git-subtree-split: 9775d8fba16f51e14cba873f78129d3d166f5888

Which is that bad object causing me issues. This is the only reference to this hash I can find. git show 9775d8fba16f51e14cba873f78129d3d166f5888 reports bad object and searching the .git folder shows only the commit above. So it appears to me that this is the only place where the hash is recorded.
Is there any way to cull this reference out in some way to enable me to push again? I've tried cleaning the repo, re-cloning, deleting the subtree out of my repo and re-pulling it. Nothing seems to remove the reference so I'm guessing there's a deeper issue going on here.

A: I eventually figured out a way to resolve this error. It might be slightly roundabout but it did the trick:

*

*I did a new git subtree split with the --ignore-joins and --rejoin options.

*I pushed my subtree to a new branch on the remote.

*I merged the master branch of the remote into my new branch.

*I merged the new branch back into master.

*I pulled the subtree back into my app project.

This seems to have resolved the issue by creating a "new" subtree in the app that doesn't contain the commit with the invalid references.
Hopefully if someone else sees the same issue, this might help them out. :)


text:
Q: Looking for a command to allow a linebreak with a hyphen I am looking for a command like \allowbreak that inserts a hyphen when breaking the line at this position. So I basically only want to add a hint where to break a word and not allow splitting it into two.

A: Looks like you wish to explicitly give the hyphenation. You can do this locally making use of aver\-ylon\-gword\-here or you can define the hyphenation for some specific word on preamble with \hyphenation{aver-ylon-gword-here} and it will be used any time when necessary.


text:
Q: AudioUnitRender error -50 with odd length buffers I have a RemoteIO unit configured with AVAudioSessionCategoryPlayAndRecord. I find some strange behavior in it. I open the app, and immediately close it before audioUnit initializes fully (it actually initializes in background as I quit the app too soon). Next I bring the app to foreground and immediately on relaunch, I see AudioUnitRender failing with error -50 continuously. I find inNumberFrames to be 1115 and it fails whenever this number is odd.
  func recordingCallback(inRefCon:UnsafeMutableRawPointer,
                ioActionFlags:UnsafeMutablePointer<AudioUnitRenderActionFlags>,
                inTimeStamp:UnsafePointer<AudioTimeStamp>,
                inBusNumber:UInt32,
                inNumberFrames:UInt32,
                ioData:UnsafeMutablePointer<AudioBufferList>?) -> OSStatus
  {
       let controller = unsafeBitCast(inRefCon, to: MicrophoneOutput.self)

      let listPtr = controller.audioBufferList.unsafeMutablePointer

     let buffers = UnsafeBufferPointer<AudioBuffer>(start: &listPtr.pointee.mBuffers, count: Int(listPtr.pointee.mNumberBuffers))

   for var buf in buffers {
       buf.mDataByteSize = inNumberFrames * UInt32(sampleWordSize)
    }

   let status = AudioUnitRender(controller.audioUnit!, ioActionFlags, inTimeStamp, inBusNumber, inNumberFrames, listPtr)

if noErr != status {
   print("Error \(status)");
   NSLog("\(AVAudioSession.sharedInstance().currentRoute.inputs[0])")
   fatalError("Render status \(status)")
  // return status;
}

return noErr

}
Strangely, if I hardcode inNumberFrames to be 1114 in AudioUnitRender call, it succeeds! Does anyone know what is going on? The pattern is as soon as the app resumes from background, there is a route change notification, and then the first sample in callback is of length 1114 frames but the one next to it has 1115 frames which fails.

A: It turned out it was a programming error due to misunderstandings in Swift language. The line that was culprit was this:
for var buf in buffers {
   buf.mDataByteSize = inNumberFrames * UInt32(sampleWordSize)
}

This answer provides more detail -
Swift vs Objective C pointer manipulation issue


text:
Q: PostgreSQL. Как удалить все данные из таблицы большого размера? Есть таблица (назовем ее logs). В ней скопилось 33GB записей. Необходимо ее очистить. Пытался делать
DELETE FROM logs

Но спустя какое-то время после запуска команды в выводе отобразилось, что удалено N-ое (число было большим) кол-во строк, но размер таблицы остался прежним (полагаю, количество строк также не изменилось). Впервые столкнулся с такой задачей и не знаю, что с этим делать.
Собственно, вопрос: как можно удалить все данные из таблицы logs?

У таблицы есть только Primary Key, индексов нет.

A: Если необходимо удалить именно всё - то нужен truncate.
delete никогда не возвращает дисковое пространство напрямую. PostgreSQL - MVCC база, delete только отмечает строку удалённой. Затем приходит autovacuum (либо вручную вызывается vacuum), который вычищает из файлов таблицы мёртвые, никому более недоступные версии строк. В конце работы vacuum проверяет, нет ли в конце таблицы страниц данных, в которых не осталось строк. Если есть - то пробует усечь размер таблицы. Размеры индексов сами никогда не уменьшаются (для этого нужен reindex). Сверх того радости добавляет, что все эти операции пишутся в wal в полном объёме.
truncate же просто выделяет новые пустые датафайлы и удаляет старые. Поэтому для задачи очистить всё - несравнимо эффективнее. Хотя и требует эксклюзивную блокировку.


text:
Q: Did Newton argue that particles speed up when entering a more dense medium? Statement:

Newton argued that particles speed up as they travel from air into a dense, transparent object, such as glass.

From this source, I gather that he did argue that the light particles sped up when entering a more dense medium. However, it just doesn't make sense. I thought they seemed to slowed down.

A: Like all good physicists Newton proposed a hypothesis for why light refracts when it crosses a boundary between different refractive indices. And his hypothesis makes a certain amount of sense:

If the initial velocity of the light is $v$, then the velocity parallel to the boundary is:
$$ v_p = v\sin i $$
and the velocity normal to the boundary is:
$$ v_n = v\cos i $$
Newton's hypothesis for the bending of the light ray is that the component of velocity normal to the boundary increases in the denser medium (while the parallel component is unchanged). Since the parallel component is unchanged we have:
$$ v'_p = v_p = v\sin i = v' \sin r $$
And therefore:
$$ \frac{v'}{v} = \frac{\sin i}{\sin r} $$
which is exactly the reciprocal of what Snell's law predicts!
Until some way was found to measure $v'$ the theory wasn't testable, but it was predictive and indeed gave the correct values for $r$ given any initial value $i$ and constant $v'/v$. Not surprising as it is Snell's law - just derived from a mistaken assumption.
Until some way was found to measure $v'$ Newton's theory was as good as any other. The problem is that when the measurements were done $v'$ turned out to be less than $v$. Explaining this required treating light as a wave rather than a particle. However the measurement wasn't done until nearly two centuries after Newton's suggestion.
A critic could point out that the change in the normal component of velocity, i.e. the acceleration of the light towards the boundary, would have to depend on angle for the theory to work, and no mechanism for this was suggested. But then Newton suggested no mechanism for his theory of gravity and it took nearly three centuries for Einstein to provide one and show that in this case Newton was right.

A: "From this source, I gather that he did argue that the light particles sped up when entering a more dense medium. However, it just doesn't make sense."
It does make sense. They enter the medium at a higher speed, then slow down. If Newton had said they continue to move at a higher speed within the medium, he would have been wrong. But I don't think he said so - "higher speed in a more dense medium" seems to be a mythology serving the opponents of Newton's emission theory of light.


text:
Q: reading "prettified" JSON back into python Suppose I have a dict in python, like so:
original = {
    "x": 1.0,
    "y": "Floyd",
    "z": "Floyd\'s friend Larry",
}

The dict gets JSON encoded and then written to an .ipynb file that prettifies it for human consumption when viewed in a browser.  I want to read in the .ipynb file and recover the original dict.
The .ipynb file, when viewed in the browser, renders as so:
renders_as = {
    'x': 1.0,
    'y': 'Floyd',
    'z': "Floyd\'s friend Larry",
}

This is manually copy-and-paste-able as a python dict equivalent to the original.
However, when I read in the .ipynb file using python I instead get the following string:
'{\'x\': 1.0, \'y\': \'Floyd\', \'z\': \\"Floyd\'s friend Larry\\"}'

This is not proper JSON, so I can't json.loads, and it is not a string literal that can be assigned using something like ast.load_literal because the double back-slashes parse as line continuations.
What is the best way for me to take this string and produce the original input, while protecting myself from the usual string processing issues such as dealing with potentially nested quotes?

A: You can use unicode-escape to process the escaped string first:
import ast

value = '{\'x\': 1.0, \'y\': \'Floyd\', \'z\': \\"Floyd\'s friend Larry\\"}'
value = value.encode("utf-8")
value = value.decode("unicode-escape")
value = ast.literal_eval(value)

# value = {'x': 1.0, 'y': 'Floyd', 'z': "Floyd's friend Larry"}

A: The solution I went with was to read the .ipynb file back into memory as JSON.    (I had been reading line by line as ordinary strings).  By reading the file as JSON, the call to json.load() handled the nested quotes for me, and left the object as a proper dict that I could read in using ast.literal_eval.


text:
Q: Disable scrolling for 0.5 seconds after the user scrolls once in JavaScript I have a resizing header with heigth:100%. I need to disable scrolling for 0.5 seconds after the user scrolls once. Is there any way to do that in JavaScript ?
Here is my code:
<script>
    function init() {
        window.addEventListener('scroll', function(e){
            var distanceY = window.pageYOffset || document.documentElement.scrollTop,
                shrinkOn = 50,
                header = document.querySelector("header");
            if (distanceY > shrinkOn) {
                classie.add(header,"smaller");
            } else {
                if (classie.has(header,"smaller")) {
                    classie.remove(header,"smaller");
                }
            }
        });
    }
    window.onload = init();
</script>

A: I would recommend checking out the accepted answer to this question:  How to disable scrolling temporarily?  To make this disabling temporary, one strategy would be to set the event handlers mentioned in the answer, then use setTimeout with a duration of 500 milliseconds.  The callback function within your setTimeout could then remove the event handlers.  Thus, after a delay, browser behavior would return to normal.

A: With the script below, if the user starts scrolling the function will be triggered and it will disable scrolling after 0.5 seconds.
<script>
    window.onload = function() {
        window.addEventListener('scroll', function(){
            setTimeout(function() {
                var header = document.getElementById("header");
                header.style.overflow = "hidden";
            }, 500 /* miliseconds */);
    };
</script>

If you want to disable scrolling for 0.5s after the user starts scrolling you can use this:
<script>
    window.onload = function() {
        window.addEventListener('scroll', function(){
            var header = document.getElementById("header");
            header.style.overflow = "hidden";
            setTimeout(function() {
                header.style.overflow = "auto";
            }, 500 /* miliseconds */);
    };
</script>


text:
Q: What distinguishes a predicative complement from an object? Asked this on ELL but with no answer:
What makes be an intransitive verb? How do we know that the analysis of It is me as transitive by tradtional grammars is incorrect?
Take for example:
1. I gave an [dO apple] to [iO her] 2. It was her.
In 1, gave is a transitive verb with the direct object "an apple" . In 2, it is argued that "her" is not an  object because be is an intransitive verb (?), so "her" is not a direct object in 2, like it is in 1 (indirect object).
And how does this analysis apply to other verbs, like hurt from the example below:

How to tell if hurt in It hurt me is a a predicative complement? "Hurt" can be replaced by other to be linking verbs (is, was etc.). Even though (is, was) are stative verbs and hurt is more of an action verb.

The following verbs are true linking verbs: any form of the verb be [am,is, are, was, were, has been, are being, might have been, etc.],become, and seem. These true linking verbs are always linking verbs.
Then you have a list of verbs with multiple personalities: appear, feel,grow, look, prove, remain, smell, sound, taste, and turn. Sometimes these verbs are linking verbs; sometimes they are action verbs.
How do you tell when they are action verbs and when they are linking verbs?
If you can substitute am, is, or are    and the sentence still sounds logical, you have a linking verb on your hands.
If, after the substitution, the sentence makes no sense, you are dealing with an action verb instead.
Source: http://www.chompchomp.com/terms/linkingverb.htm

Normally action verbs have direct objects, but nearly all verbs can be used as transitve and intransitive. For example the verb drive. Compare:

He drives fast
and
"He drives the car fast".

The first is a predicative complement, while the second is not as drives is being used transitively with its object "the car".
In

It was given to her

Her is an object because of the verb "given" being used transitively and is not a predicative complement.
But in,

It hurt me
  It is me

Why is me automatically an object in It is me, even though verbs themselves can be transitive or intransitive: what makes be automatically intransitive? and why is me in It hurt me automatically an object when hurt can be a transitive and intransitive verb:

I am hurt (intransitive) - predicative complement  He says his tooth hurts (intransitive) - ?  [He/she] has been hurting ever since learning of her friend's betrayal (intransitive) - ?

According to above, can the verb "hurt" be a reporting verb relating the feelings of the subject like (I feel hurt) or (I am hurt) in "It hurt me", rather than an action verb?

If it is seen as an action verb, me is an object, while the other interpretation is that there is no object and hurt is being used intransitively in "It hurt me". If hurt is being used intransitively, does that mean the pronoun me is a complement? If not what is "me" in "It hurt me"?

A: Here is a useful link regarding subject movement and case theory. Particularly, the Specifier-head agreement section:
Note:   We discuss the grammatical counterpart of (13b), He claims to be a rock star, in Chapter 7: Nonfinite clausal complementation.

Since the subordinate verb is a form of the same verb (namely, be) in
  both examples, the grammaticality contrast in (13) would remain
  mysterious if it were the verb that bears a nominative case feature.
  The obvious alternative is that nominative case is instead a feature
  of I—specifically, of finite I.

Without more information:

It hurt me
I am hurt or I feel hurt

poses the same problem as example (13). The pronoun me in both cases is known as the oblique form.

The answer is that the grammar of English requires subjects and
  objects to appear in a specific case form:

Consider

As is evident, both of the subjects in (2) are oblique forms, and both
  of the objects are nominative forms. Each of the sentences in (2)
  therefore contradicts the case requirement just stated in two ways.
In general, subjects appear in the nominative, and objects appear in
  the oblique.
Morphological case
As the leftward-pointing arrows in the table in (3) indicate, not all
  pronouns have distinct forms for the nominative and the oblique case.
  Full noun phrases in English also show no morphological distinction
  between nominative and oblique forms, as shown in (4).

In traditional grammar, the concept of case is apt to be equated with
  morphological case. But generative grammar is less interested in the
  case forms themselves than in their structural licensing conditions
  (that is, the conditions under which it is grammatical for them to
  appear). Consider (1), repeated here as (10), and (11).

As is evident, they and she exhibit distinct forms in the nominative
  and oblique, whereas you doesn't. But in generative grammar, the focus
  is not on this morphological difference, but instead on the fact that
  the form you appears in the same structural position as they and she
  in (11a), but as them and her in (11b). Contrary to superficial
  appearances, the two instances of you in (11) are therefore treated
  not as tokens of a single type, but rather as two grammatically
  distinct forms that happen to be homonymous.
Besides failing to express its case distinctions in a robust manner,
  English also exhibits a comparatively limited range of case forms: the
  nominative and the oblique just discussed, and the possessive. Other
  languages have more grammatical cases.

With simple transitive verbs, the situation is more complex. Such
  verbs are said to govern the case of their object. That is, depending
  on the verb, the object appears in the accusative, in the dative, or
  (rarely) in the genitive.

Accusative:

Charlie bit me!

Dative:

Kim passed me the pancakes.  Kim passed the pancakes to me.

Genitive:

ib. [the man opposite me's] facial expression
iia. [my friend's] father
iib. [a friend of mine's] father
In (iia) and (iib), we have 2 genitives: in (iia) one is again realised as my and the other as
  friend's, whereas in (iib) they combine in the single word mine's.
  Both me's and mine's thus have double-case marking, an inner case and
  an outer case. In me's the inner case is accusative, required because the
  pronoun is object of the preposition opposite, while in (iib) the
  inner case is genitive because the pronoun is functioning in the
  oblique genitive construction. The phrasal genitive is the outer
  case, morphologically added to the form that realise the inner case.
  In examples like [the King of England's] daughter, the inner case of
  England is the plain case, which has no morphological marking, but the
  principle is the same: the outer genitive is added to form required by
  England within the inner NP "the king of England".
pg 479-480 of CaGEL

Prepositions, too, idiosyncratically govern the dative, the
accusative, or (rarely) the genitive.

That picture of me was blurry.  (cf. That picture of mine was stolen.)

  English does not have distinct prepositional forms of pronouns.
  The same set of object pronouns are used after verbs and prepositions (e.g. watch him, look at him).


text:
Q: Keyboard cursor position goes at beginning when I set the text in jquery I am having 1 div and I have set conenteditable attribute to true.
Whenever I change the text of that div the cursor goes to beginning of the line.
var tmp = this.innerHTML;

this.innerHTML = tmp+"123";

I do not want the cursor position goes to beginning of the line.


text:
Q: How to always return login/sign in view when I'm unauthorized in asp.net core mvc? I've a problem with the implementation of the functionality which always returns view to sign in when I'm unauthorized. My project is created in ASP.NET CORE MVC 3.1 with JWT Bearer. I can sign in when I go to the view Login.cshtml directly (after click Sign In), and then my methods with [Autorize] attribute working fine.
I'd like to always return view to sign in, when I go to the method with [Authorize] attribute.
I've found some examples with cookie which return sign in view, but I'm using JWT Bearer with Session and I don't know it's necessary. Thank's in advance for help.

A: Finnally I found way which working in .NET Core 3.1. This code redirect to login/signIn page when status code is 401 - unauthorized.
app.UseStatusCodePages(async context => {
   var request = context.HttpContext.Request;
   var response = context.HttpContext.Response;

   if (response.StatusCode == (int)HttpStatusCode.Unauthorized)
   {
    response.Redirect("/Home/Login?returnUrl=" + request.Path);
   }

});

A: Whenever you call an API with authorize attribute, if the bearer token is expired you must be returning 401 - Unauthorized error code to the caller. As soon as you get a 401 error code, you can redirect to sign-in page with your frontend logic only.


text:
Q: Nested Horizontal RecyclerView I wanna create a nested RecyclerView were the Parent RV is horizontal layout manager with > 3 items and the child is horzinotl too, but I can't scroll the child it's only indicate the parent gesture.
Parent LayoutManager
 LinearLayoutManager layoutManager = new LinearLayoutManager(context, LinearLayoutManager.HORIZONTAL, false);
    listItem.setLayoutManager(layoutManager);
    listItem.setAdapter(adapter);

Child LayoutManager
 RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(context, LinearLayoutManager.HORIZONTAL, false);
    list.setHasFixedSize(true);
    list.setLayoutManager(layoutManager);
    list.setItemAnimator(new DefaultItemAnimator());
    list.setAdapter(adapter);

XML - Parent
  <androidx.cardview.widget.CardView
        android:id="@+id/card"
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <androidx.recyclerview.widget.RecyclerView
            android:id="@+id/list_item"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:clipToPadding="false" />

    </androidx.cardview.widget.CardView>

XML - Parent Item
     <androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/roundColor_svprogresshuddefault"
    android:elevation="160dp"
    android:padding="@dimen/home_cell_margin">

                <androidx.recyclerview.widget.RecyclerView
                    android:id="@+id/list_item"
                    android:layout_width="wrap_content"
                    android:layout_height="150dp"
                    android:layout_gravity="center"
                    android:nestedScrollingEnabled="false" />
 </androidx.constraintlayout.widget.ConstraintLayout>

XML - Child
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:id="@+id/listHolder">
    <ImageView
        android:id="@+id/img"
        android:layout_width="match_parent"
        android:layout_height="match_parent" ></ImageView>
</LinearLayout>

Result Example

A: I fixed it by creating a simple custom RecyclerView and below the final code
public class DJHRecyclerView extends RecyclerView {
    public DJHRecyclerView(Context context) {
        super(context);
    }

    public DJHRecyclerView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public DJHRecyclerView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    @Override
    public boolean onInterceptTouchEvent(MotionEvent event) {
        getParent().requestDisallowInterceptTouchEvent(true);
        return super.onInterceptTouchEvent(event);
    }

}


text:
Q: Как уменьшить размер файла с индексом Сфинкса? И где этот файл хранится? Как можно посмотреть файл с индексом Сфинкса, сколько он занимает места, и где вообще находится?
Возможно ли уменьшить размер этого файла, например, заархивировав (пусть даже будет потеря скорости работы поиска)
Можно ли этот файл скопировать на другой сервер, без выполнения индексации заново, просто подключив?
Система - Ubuntu 18, находится на сервере (доступ только через терминал)

A:
Как можно посмотреть файл с индексом Сфинкса, сколько он занимает места, и где вообще находится?

Ищите в конфиге сфинкса по path, там указан путь до файла индекса.

Возможно ли уменьшить размер этого файла, например, заархивировав (пусть даже будет потеря скорости работы поиска)

Заархивировать нельзя. Можно только изменить структуру индекса, пожертвовав какими-либо атрибутами или полнотекстовыми полями или отключить min_prefix_len/min_infix_len или увеличить min_word_len. Можно еще поменять формат хранения словаря через dict=crc (не поддерживается в Sphinx 3, поддерживается в Manticore Search - форке Sphinx)

Можно ли этот файл скопировать на другой сервер, без выполнения индексации заново, просто подключив?

Да, можно.


text:
Q: Upload File on SharePoint Online through a Javascript app hosted externally I am working on a SharePoint Site , and I have got a new requirement from a user (Office 365 User), to provide them a way of directly uploading a file from the web app instead of going to the SharePoint.
Additionally, the web app team managing the app wants to have the page hosted in the app, instead of SharePoint.
I saw lot of examples online on uploading files to the SharePoint site, but it isn't very clear if I have to host the page within the SharePoint itself.
Is there a recommended way of doing this?

A: This can easily be done by leveraging the REST API. There is a good example on MSDN located here:
https://msdn.microsoft.com/en-us/library/office/dn769086.aspx


text:
Q: Find date sequence in PostgreSQL I'm trying to find the maximum sequence of days by customer in my data. I want to understand what is the max sequence of days that specific customer made. If someone enter to my app in the 25/8/16 AND 26/08/16 AND 27/08/16 AND 01/09/16 AND 02/09/16 - The max sequence will be 3 days (25,26,27).
In the end (The output) I want to get two fields: custid | MaxDaySequence
I have the following fields in my data table: custid | orderdate(timestemp)
For exmple:
custid  orderdate
1   25/08/2007
1   03/10/2007
1   13/10/2007
1   15/01/2008
1   16/03/2008
1   09/04/2008
2   18/09/2006
2   08/08/2007
2   28/11/2007
2   04/03/2008
3   27/11/2006
3   15/04/2007
3   13/05/2007
3   19/06/2007
3   22/09/2007
3   25/09/2007
3   28/01/2008

I'm using PostgreSQL 2014.
Thanks

Trying:
select custid, max(num_days) as longest
from (
       select custid,rn, count (*) as num_days
       from (
           select custid, date(orderdate),
                  cast (row_number() over (partition by custid order by date(orderdate)) as varchar(5)) as rn
           from table_
       ) x group by custid, CURRENT_DATE - INTERVAL rn|| ' day'
 ) y group by custid

A: Try:
SELECT custid, max( abc ) as max_sequence_of_days
FROM (
  SELECT custid, yy, count(*) abc
  FROM (
    SELECT * ,
          SUM( xx ) OVER (partition by custid order by orderdate ) yy
    FROM (
      select * ,
          CASE WHEN
              orderdate - lag( orderdate ) over (partition by custid order by orderdate )
              <= 1
         THEN 0 ELSE 1 END xx
      from mytable
    ) x
  ) z
  GROUP BY custid, yy
) q
GROUP BY custid

Demo: http://sqlfiddle.com/#!15/00422/11

===== EDIT ===========

Got "operator does not exist: interval <= integer"

This means that orderdate column is of type timestamp, not date.
In this case you need to use <= interval '1' day condition instead of <= 1:
Please see this link: https://www.postgresql.org/docs/9.0/static/functions-datetime.html to learn more about date arithmetic in PostgreSQL

Please see this demo:
http://sqlfiddle.com/#!15/7c2200/2
SELECT custid, max( abc ) as max_sequence_of_days
FROM (
  SELECT custid, yy, count(*) abc
  FROM (
    SELECT * ,
          SUM( xx ) OVER (partition by custid order by orderdate ) yy
    FROM (
      select * ,
          CASE WHEN
              orderdate - lag( orderdate ) over (partition by custid order by orderdate )
              <= interval '1' day
         THEN 0 ELSE 1 END xx
      from mytable
    ) x
  ) z
  GROUP BY custid, yy
) q
GROUP BY custid


text:
Q: How to get rails app to work in production [heroku deployment] In short: My application works fine in development using Devise, however in production I'm getting the error shown below. Bare in mind that I am using KatanaCode's BlogIt engine but I have re-built the user model, and schema and it is only using Devise's model.
github: https://github.com/Apane/Blogit_blog
Please advice.
   2013-05-29T03:21:40.998554+00:00 heroku[web.1]: Process exited with status 1
2013-05-29T03:21:41.015407+00:00 heroku[web.1]: State changed from starting to crashed
2013-05-29T03:21:43.320094+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path=/ host=infinite-springs-1056.herokuapp.com fwd="99.233.170.104" dyno= connect= service= status=503 bytes=
2013-05-29T03:30:35.867092+00:00 heroku[slugc]: Slug compilation started
2013-05-29T03:31:18.246368+00:00 heroku[api]: Deploy 40e00ad by "email"
2013-05-29T03:31:18.259954+00:00 heroku[api]: Release v32 created by "email"
2013-05-29T03:31:18.303244+00:00 heroku[api]: Deploy 40e00ad by "email"
2013-05-29T03:31:18.793210+00:00 heroku[slugc]: Slug compilation finished
2013-05-29T03:31:18.954842+00:00 heroku[web.1]: State changed from crashed to starting
2013-05-29T03:31:21.260593+00:00 heroku[web.1]: Starting process with command `bundle exec rails server -p 17013`
2013-05-29T03:31:26.046042+00:00 app[web.1]: DEPRECATION WARNING: You have Rails 2.3-style plugins in vendor/plugins! Support for these plugins will be removed in Rails 4.0. Move them out and bundle them in your Gemfile, or fold them in to your app as lib/myplugin/* and config/initializers/myplugin.rb. See the release notes for more on this: http://weblog.rubyonrails.org/2012/1/4/rails-3-2-0-rc2-has-been-released. (called from <top (required)> at /app/config/environment.rb:5)
2013-05-29T03:31:26.046145+00:00 app[web.1]: DEPRECATION WARNING: You have Rails 2.3-style plugins in vendor/plugins! Support for these plugins will be removed in Rails 4.0. Move them out and bundle them in your Gemfile, or fold them in to your app as lib/myplugin/* and config/initializers/myplugin.rb. See the release notes for more on this: http://weblog.rubyonrails.org/2012/1/4/rails-3-2-0-rc2-has-been-released. (called from <top (required)> at /app/config/environment.rb:5)
2013-05-29T03:31:26.046393+00:00 app[web.1]: DEPRECATION WARNING: You have Rails 2.3-style plugins in vendor/plugins! Support for these plugins will be removed in Rails 4.0. Move them out and bundle them in your Gemfile, or fold them in to your app as lib/myplugin/* and config/initializers/myplugin.rb. See the release notes for more on this: http://weblog.rubyonrails.org/2012/1/4/rails-3-2-0-rc2-has-been-released. (called from <top (required)> at /app/config/environment.rb:5)
2013-05-29T03:31:27.383898+00:00 app[web.1]: [Blogit]: Blogit::Configuration#rss_feed_language has been deprecated. You can remove this from your blogit.rb configuration file
2013-05-29T03:31:28.147889+00:00 app[web.1]: Exiting
2013-05-29T03:31:28.147889+00:00 app[web.1]: => Booting WEBrick
2013-05-29T03:31:28.147889+00:00 app[web.1]: => Rails 3.2.13 application starting in production on http://0.0.0.0:17013
2013-05-29T03:31:28.147889+00:00 app[web.1]: => Call with -d to detach
2013-05-29T03:31:28.147889+00:00 app[web.1]: => Ctrl-C to shutdown server
2013-05-29T03:31:28.192463+00:00 app[web.1]:    from /app/app/models/user.rb:1:in `<top (required)>'
2013-05-29T03:31:28.192463+00:00 app[web.1]:    from /app/vendor/bundle/ruby/1.9.1/gems/activesupport-3.2.13/lib/active_support/dependencies.rb:251:in `require'
2013-05-29T03:31:28.192463+00:00 app[web.1]:    from /app/app/models/user.rb:4:in `<class:User>'
2013-05-29T03:31:28.192463+00:00 app[web.1]:    from /app/vendor/bundle/ruby/1.9.1/gems/activesupport-3.2.13/lib/active_support/dependencies.rb:502:in `load_missing_constant'
2013-05-29T03:31:28.192840+00:00 app[web.1]:    from /app/vendor/bundle/ruby/1.9.1/gems/activesupport-3.2.13/lib/active_support/dependencies.rb:190:in `const_missing'
2013-05-29T03:31:28.192463+00:00 app[web.1]:    from /app/vendor/bundle/ruby/1.9.1/gems/activesupport-3.2.13/lib/active_support/dependencies.rb:359:in `require_or_load'
2013-05-29T03:31:28.193094+00:00 app[web.1]:    from /app/vendor/bundle/ruby/1.9.1/gems/devise-2.2.4/lib/devise.rb:306:in `add_mapping'
2013-05-29T03:31:28.192840+00:00 app[web.1]:    from /app/vendor/bundle/ruby/1.9.1/gems/activesupport-3.2.13/lib/active_support/dependencies.rb:588:in `constantize'
2013-05-29T03:31:28.192840+00:00 app[web.1]:    from /app/vendor/bundle/ruby/1.9.1/gems/devise-2.2.4/lib/devise.rb:272:in `get'
2013-05-29T03:31:28.192463+00:00 app[web.1]: /app/vendor/bundle/ruby/1.9.1/gems/activerecord-3.2.13/lib/active_record/dynamic_matchers.rb:55:in `method_missing': undefined method `devise' for User(id: integer, created_at: datetime, updated_at: datetime):Class (NoMethodError)
2013-05-29T03:31:28.192463+00:00 app[web.1]:    from /app/vendor/bundle/ruby/1.9.1/gems/activesupport-3.2.13/lib/active_support/dependencies.rb:251:in `require'
2013-05-29T03:31:28.192463+00:00 app[web.1]:    from /app/vendor/bundle/ruby/1.9.1/gems/activesupport-3.2.13/lib/active_support/dependencies.rb:251:in `block in require'
2013-05-29T03:31:28.192840+00:00 app[web.1]:    from /app/vendor/bundle/ruby/1.9.1/gems/activesupport-3.2.13/lib/active_support/dependencies.rb:554:in `get'
2013-05-29T03:31:28.193094+00:00 app[web.1]:    from /app/vendor/bundle/ruby/1.9.1/gems/devise-2.2.4/lib/devise/mapping.rb:66:in `initialize'
2013-05-29T03:31:28.192840+00:00 app[web.1]:    from /app/vendor/bundle/ruby/1.9.1/gems/activesupport-3.2.13/lib/active_support/dependencies.rb:190:in `each'
2013-05-29T03:31:28.192840+00:00 app[web.1]:    from /app/vendor/bundle/ruby/1.9.1/gems/activesupport-3.2.13/lib/active_support/inflector/methods.rb:229:in `each'
2013-05-29T03:31:28.192840+00:00 app[web.1]:    from /app/vendor/bundle/ruby/1.9.1/gems/activesupport-3.2.13/lib/active_support/inflector/methods.rb:229:in `constantize'
2013-05-29T03:31:28.193316+00:00 app[web.1]:    from /app/vendor/bundle/ruby/1.9.1/gems/actionpack-3.2.13/lib/action_dispatch/routing/route_set.rb:267:in `draw'
2013-05-29T03:31:28.193094+00:00 app[web.1]:    from /app/vendor/bundle/ruby/1.9.1/gems/devise-2.2.4/lib/devise/rails/routes.
rb:207:in `devise_for'
2013-05-29T03:31:28.193316+00:00 app[web.1]:    from /app/vendor/bundle/ruby/1.9.1/gems/activesupport-3.2.13/lib/active_support/dependencies.rb:245:in `load'
2013-05-29T03:31:28.193316+00:00 app[web.1]:    from /app/vendor/bundle/ruby/1.9.1/gems/railties-3.2.13/lib/rails/application/routes_reloader.rb:40:in `block in load_paths'
2013-05-29T03:31:28.193548+00:00 app[web.1]:    from /app/vendor/bundle/ruby/1.9.1/gems/activesupport-3.2.13/lib/active_support/lazy_load_hooks.rb:34:in `call'
2013-05-29T03:31:28.193762+00:00 app[web.1]:    from /app/vendor/bundle/ruby/1.9.1/gems/railties-3.2.13/lib/rails/initializable.rb:55:in `block in run_initializers'
2013-05-29T03:31:28.193548+00:00 app[web.1]:    from /app/vendor/bundle/ruby/1.9.1/gems/railties-3.2.13/lib/rails/application/routes_reloader.rb:16:in `reload!'
2013-05-29T03:31:28.193548+00:00 app[web.1]:    from /app/vendor/bundle/ruby/1.9.1/gems/railties-3.2.13/lib/rails/application.rb:108:in `reload_routes!'
2013-05-29T03:31:28.193548+00:00 app[web.1]:    from /app/vendor/bundle/ruby/1.9.1/gems/activesupport-3.2.13/lib/active_support/lazy_load_hooks.rb:42:in `run_load_hooks'
2013-05-29T03:31:28.192463+00:00 app[web.1]:    from /app/vendor/bundle/ruby/1.9.1/gems/activesupport-3.2.13/lib/active_support/dependencies.rb:236:in `load_dependency'
2013-05-29T03:31:28.192840+00:00 app[web.1]:    from /app/vendor/bundle/ruby/1.9.1/gems/devise-2.2.4/lib/devise/mapping.rb:77:in `to'
2013-05-29T03:31:28.192463+00:00 app[web.1]:    from /app/vendor/bundle/ruby/1.9.1/gems/activesupport-3.2.13/lib/active_support/dependencies.rb:192:in `block in const_missing'
2013-05-29T03:31:28.193973+00:00 app[web.1]:    from /app/vendor/bundle/ruby/1.9.1/gems/activesupport-3.2.13/lib/active_support/dependencies.rb:251:in `require'
2013-05-29T03:31:28.193762+00:00 app[web.1]:    from /app/vendor/bundle/ruby/1.9.1/gems/activesupport-3.2.13/lib/active_support/dependencies.rb:236:in `load_dependency'
2013-05-29T03:31:28.193094+00:00 app[web.1]:    from /app/vendor/bundle/ruby/1.9.1/gems/devise-2.2.4/lib/devise/rails/routes.rb:208:in `block in devise_for'
2013-05-29T03:31:28.193762+00:00 app[web.1]:    from /app/vendor/bundle/ruby/1.9.1/gems/railties-3.2.13/lib/rails/initializable.rb:54:in `each'
2013-05-29T03:31:28.193094+00:00 app[web.1]:    from /app/vendor/bundle/ruby/1.9.1/gems/devise-2.2.4/lib/devise.rb:306:in `new'
2013-05-29T03:31:28.193094+00:00 app[web.1]:    from /app/vendor/bundle/ruby/1.9.1/gems/devise-2.2.4/lib/devise/mapping.rb:156:in `default_used_route'
2013-05-29T03:31:28.193548+00:00 app[web.1]:    from /app/vendor/bundle/ruby/1.9.1/gems/activesupport-3.2.13/lib/active_support/lazy_load_hooks.rb:43:in `block in run_load_hooks'
2013-05-29T03:31:28.193973+00:00 app[web.1]:    from /app/vendor/bundle/ruby/1.9.1/gems/railties-3.2.13/lib/rails/commands/server.rb:46:in `app'
2013-05-29T03:31:28.193973+00:00 app[web.1]:    from /app/config.ru:in `new'
2013-05-29T03:31:28.193973+00:00 app[web.1]:    from /app/vendor/bundle/ruby/1.9.1/gems/rack-1.4.5/lib/rack/server.rb:200:in `app'
2013-05-29T03:31:28.193762+00:00 app[web.1]:    from /app/vendor/bundle/ruby/1.9.1/gems/railties-3.2.13/lib/rails/initializable.rb:54:in `run_initializers'
2013-05-29T03:31:28.194186+00:00 app[web.1]:    from /app/vendor/bundle/ruby/1.9.1/gems/railties-3.2.13/lib/rails/commands/server.rb:70:in `start'
2013-05-29T03:31:28.194186+00:00 app[web.1]:    from /app/vendor/bundle/ruby/1.9.1/gems/rack-1.4.5/lib/rack/server.rb:254:in `start'
2013-05-29T03:31:28.194186+00:00 app[web.1]:    from /app/vendor/bundle/ruby/1.9.1/gems/railties-3.2.13/lib/rails/commands.rb:55:in `block in <top (required)>'
2013-05-29T03:31:28.194186+00:00 app[web.1]:    from /app/vendor/bundle/ruby/1.9.1/gems/rack-1.4.5/lib/rack/server.rb:304:in `wrapped_app'
2013-05-29T03:31:28.194186+00:00 app[web.1]:    from /app/vendor/bundle/ruby/1.9.1/gems/railties-3.2.13/lib/rails/commands.rb:50:in `tap'
2013-05-29T03:31:28.194186+00:00 app[web.1]:    from script/rails:6:in `require'
2013-05-29T03:31:28.194186+00:00 app[web.1]:    from /app/vendor/bundle/ruby/1.9.1/gems/railties-3.2.13/lib/rails/commands.rb:50:in `<top (required)>'
2013-05-29T03:31:28.192840+00:00 app[web.1]:    from /app/vendor/bundle/ruby/1.9.1/gems/activesupport-3.2.13/lib/active_support/inflector/methods.rb:230:in `block in constantize'
2013-05-29T03:31:28.192840+00:00 app[web.1]:    from /app/vendor/bundle/ruby/1.9.1/gems/devise-2.2.4/lib/devise/mapping.rb:72:in `modules'
2013-05-29T03:31:28.193316+00:00 app[web.1]:    from /app/vendor/bundle/ruby/1.9.1/gems/actionpack-3.2.13/lib/action_dispatch/routing/route_set.rb:289:in `eval_block'
2013-05-29T03:31:28.193094+00:00 app[web.1]:    from /app/vendor/bundle/ruby/1.9.1/gems/devise-2.2.4/lib/devise/mapping.rb:89:in `routes'
2013-05-29T03:31:28.193094+00:00 app[web.1]:    from /app/vendor/bundle/ruby/1.9.1/gems/actionpack-3.2.13/lib/action_dispatch/routing/route_set.rb:289:in `instance_exec'
2013-05-29T03:31:28.193094+00:00 app[web.1]:    from /app/config/routes.rb:4:in `block in <top (required)>'
2013-05-29T03:31:28.193316+00:00 app[web.1]:    from /app/vendor/bundle/ruby/1.9.1/gems/activesupport-3.2.13/lib/active_support/dependencies.rb:245:in `block in load'
2013-05-29T03:31:28.193316+00:00 app[web.1]:    from /app/vendor/bundle/ruby/1.9.1/gems/railties-3.2.13/lib/rails/application/routes_reloader.rb:40:in `each'
2013-05-29T03:31:28.193094+00:00 app[web.1]:    from /app/vendor/bundle/ruby/1.9.1/gems/devise-2.2.4/lib/devise/rails/routes.rb:207:in `each'
2013-05-29T03:31:28.193316+00:00 app[web.1]:    from /app/vendor/bundle/ruby/1.9.1/gems/railties-3.2.13/lib/rails/application/routes_reloader.rb:40:in `load_paths'
2013-05-29T03:31:28.193316+00:00 app[web.1]:    from /app/vendor/bundle/ruby/1.9.1/gems/activesupport-3.2.13/lib/active_support/dependencies.rb:245:in `load'
2013-05-29T03:31:28.193316+00:00 app[web.1]:    from /app/vendor/bundle/ruby/1.9.1/gems/activesupport-3.2.13/lib/active_support/dependencies.rb:236:in `load_dependency'
2013-05-29T03:31:28.193548+00:00 app[web.1]:    from /app/vendor/bundle/ruby/1.9.1/gems/activesupport-3.2.13/lib/active_support/lazy_load_hooks.rb:42:in `each'
2013-05-29T03:31:28.193548+00:00 app[web.1]:    from /app/vendor/bundle/ruby/1.9.1/gems/devise-2.2.4/lib/devise/rails.rb:14:in `block in <class:Engine>'
2013-05-29T03:31:28.193316+00:00 app[web.1]:    from /app/config/routes.rb:1:in `<top (required)>'
2013-05-29T03:31:28.193762+00:00 app[web.1]:    from /app/vendor/bundle/ruby/1.9.1/gems/railties-3.2.13/lib/rails/initializable.rb:30:in `run'
2013-05-29T03:31:28.193548+00:00 app[web.1]:    from /app/vendor/bundle/ruby/1.9.1/gems/railties-3.2.13/lib/rails/application/finisher.rb:52:in `block in <module:Finisher>'
2013-05-29T03:31:28.193548+00:00 app[web.1]:    from /app/vendor/bundle/ruby/1.9.1/gems/activesupport-3.2.13/lib/active_support/lazy_load_hooks.rb:34:in `execute_hook'
2013-05-29T03:31:28.193973+00:00 app[web.1]:    from /app/config.ru:3:in `block in <main>'
2013-05-29T03:31:28.193762+00:00 app[web.1]:    from /app/vendor/bundle/ruby/1.9.1/gems/railties-3.2.13/lib/rails/railtie/configurable.rb:30:in `method_missing'
2013-05-29T03:31:28.193762+00:00 app[web.1]:    from /app/vendor/bundle/ruby/1.9.1/gems/railties-3.2.13/lib/rails/application.rb:136:in `initialize!'
2013-05-29T03:31:28.193548+00:00 app[web.1]:    from /app/vendor/bundle/ruby/1.9.1/gems/railties-3.2.13/lib/rails/initializable.rb:30:in `instance_exec'
2013-05-29T03:31:28.193973+00:00 app[web.1]:    from /app/vendor/bundle/ruby/1.9.1/gems/rack-1.4.5/lib/rack/builder.rb:40:in `parse_file'
2013-05-29T03:31:28.193762+00:00 app[web.1]:    from /app/config/environment.rb:5:in `<top (required)>'
2013-05-29T03:31:28.193762+00:00 app[web.1]:    from /app/vendor/bundle/ruby/1.9.1/gems/activesupport-3.2.13/lib/active_support/dependencies.rb:251:in `require'
2013-05-29T03:31:28.193973+00:00 app[web.1]:    from /app/config.ru:in `<main>'
2013-05-29T03:31:28.194186+00:00 app[web.1]:    from script/rails:6:in `<main>'
2013-05-29T03:31:28.193762+00:00 app[web.1]:    from /app/vendor/bundle/ruby/1.9.1/gems/activesupport-3.2.13/lib/active_support/dependencies.rb:251:in `block in require'
2013-05-29T03:31:28.193973+00:00 app[web.1]:    from /app/vendor/bundle/ruby/1.9.1/gems/rack-1.4.5/lib/rack/builder.rb:40:in `eval'
2013-05-29T03:31:28.193973+00:00 app[web.1]:    from /app/vendor/bundle/ruby/1.9.1/gems/rack-1.4.5/lib/rack/builder.rb:51:in `instance_eval'
2013-05-29T03:31:28.193973+00:00 app[web.1]:    from /app/vendor/bundle/ruby/1.9.1/gems/rack-1.4.5/lib/rack/builder.rb:51:in `initialize'
2013-05-29T03:31:29.377624+00:00 heroku[web.1]: Process exited with status 1
2013-05-29T03:31:29.396876+00:00 heroku[web.1]: State changed from starting to crashed
2013-05-29T03:31:29.397413+00:00 heroku[web.1]: State changed from crashed to starting
2013-05-29T03:31:32.474515+00:00 heroku[web.1]: Starting process with command `bundle exec rails server -p 20203`

A: Try removing gem 'activerecord' from your Gemfile and then run rails generate devise:install in your bash.


text:
Q: How many leaves will be contained in a full binary tree of height 5? According to my class definition, a full binary tree is a tree where:

*

*Every leaf node has the same depth

*Every non-leaf node has two children

This is confusing me (the first part in particular) because this sounds like a perfect binary tree. I have read multiple definitions of a full binary tree on the internet and I don't see the "Every leaf node has the same depth" part. I have came across a question I have to answer: How many leaves will be contained in a full binary tree of height 5?
I think this answer is a range of numbers between 11 and the perfect binary tree of height 5 (63). But the question seems like there is only one answer, and going by my class definition, the answer would be just 63? To me the definition of full binary tree is ambiguous and it is confusing me. Am I missing something?


text:
Q: Hide div tag / javascript from mobile phones? I would like to hide this div tag from mobile browsers only, is this possible?

A: You can detect of the user is on a handheld device like this:
if( /Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent) ) {
 // some code..
}

Replace //some code... with the code you want to use to hide the div.

A: Or if you want to hide dive because of screen size you can use css media queries and hide div for screens which less than some size


text:
Q: KeyCloack integration wirh DRF (Django Rest Framework) I am a beginner level DRF developer. I am trying to integrate Keycloak with Django Rest Framework. Unfortunately, I was unable to find any type of help/blog/tutorial online.

A: You can use KeyCloack's Oauth2 API to authenticate and authorize your djagno users. Is is the same as implementing Sign-in with Google or any other provider.
My favorite package to implement social auth is python-social-auth, and it even has an existing backend for KeyCloack.
Here is how a configuration for Oauth2 against KeyCloack should look like:
First, setup social auth in your project like so
$ pip install social-auth-app-django

In your settings.py
INSTALLED_APPS = (
    # ...
    'social_django',
    # ...
)

AUTHENTICATION_BACKENDS = (
    'social_core.backends.keycloak.KeycloakOAuth2',
    'django.contrib.auth.backends.ModelBackend',
)

# Add you connection settings here
SOCIAL_AUTH_KEYCLOAK_KEY = 'test-django-oidc'
SOCIAL_AUTH_KEYCLOAK_SECRET = 'a7a41-245e-...'
SOCIAL_AUTH_KEYCLOAK_PUBLIC_KEY = \
    'MIIBIjANBxxxdSD'
SOCIAL_AUTH_KEYCLOAK_AUTHORIZATION_URL = \
    'https://iam.example.com/auth/realms/voxcloud-staff/protocol/openid-connect/auth'
SOCIAL_AUTH_KEYCLOAK_ACCESS_TOKEN_URL = \
    'https://iam.example.com/auth/realms/voxcloud-staff/protocol/openid-connect/token'

In your urls.py
urlpatterns = [
    ...
    path('auth/', include('social_django.urls', namespace='social'))
    ...
]

Then add this to your login page template:
Login with KeyCloack


text:
Q: Datatables doesnt get fit width columns on print? I try to print datatables, but why when I print it doesnt get fit width coulmns,?
here's my result Screenshot from 2016-10-17 06-38-39.png
any way to add in my code.? I'm totaly newbie

A: Assign your table columns a width.


text:
Q: Alamofire Nested Requests I need to make three different requests to the same API. None of these calls are dependent on the other. I currently have my requests nested like so:
API.getPopularMovies() { responseObject, error in
        if let results = responseObject {
            self.popularMovies = results

            self.API.getNowPlayingMovies() { responseObject, error in
                if let results = responseObject {
                    self.nowPlayingMovies = results

                    self.API.getUpcomingMovies() { responseObject, error in
                        if let results = responseObject {
                            self.upcomingMovies = results

                            self.movies = [self.popularMovies, self.nowPlayingMovies, self.upcomingMovies]
                            self.tableView.reloadData()
                        }
                    }
                }
            }
        }
    }
}

I feel like this may not be a good approach, and am looking for some guidance towards a better way of going about this. Currently, the resulting arrays seem to properly populate my table view, but I can't help but feel like this nested approach is incorrect.

A: If none of your operations are dependent, then why do you nest them? I see that you don't reload your UITableView until the third one completes - if that's a hard requirement, then they are dependent.
When they are dependent, this kind of nesting is sometimes called a 'Pyramid of Doom'. A great way to clean it up is to wrap the nested code as a monad, which would allow the following:

*

*Code can be chained neatly, rather than nested, improving readability.

*You can use single rather than repeated error handling

*Any final/always tasks can be expressed neatly.

This is called a Promise. Here's an excellent tutorial on how they work.
And there's some great libraries. PromiseKit is a popular one.


text: Q: QtWebSockets QtWebSockets is a module from the Qt Toolkit which provides interfaces that enable Qt applications to act as a server that can process WebSocket requests, or a client that can consume data received from the server, or both.


text:
Q: Independent multi columns for categories highcharts So basically I have a use case which I couldn't replicate to the existing higcharts example. The scenario is
On X Axis I want to have 5 different categories say A,B,C,D,E,F
and now on category A I want to have 4 columns with a numerical value (based on Y Axis).
so the way I want to pass data is like
data = [
   {
      name:"A",
      data:[
             12, 13, 15, 16
           ] // They should come as the columns on A and these columns can have different names as well.
   }
]


text:
Q: Indefinite generalized Tikhonov regularization Suppose we want to choose $x$ to minimise the following (generalized) Tikhonov regularized least squares objective:
$$(Ax-b)^\top (Ax-b) + \lambda [(x-c)^\top W (x-c)],$$
where $W$ is symmetric, but we do not impose that $W$ is positive definite. (Here: $A$ is a real matrix with at least as many rows as columns, $W$ is a square real matrix, and $x$, $b$ and $c$ are real vectors.) We assume that $A^\top A$ is (strictly) positive definite.
For small enough $\lambda$, the solution has:
$$x^* = (A^\top A + \lambda W )^{-1} (A^\top b + \lambda W c ),$$
so:
$$x^*-c = (A^\top A + \lambda W )^{-1} [ A^\top ( b - A c ) ],$$
(see https://en.wikipedia.org/wiki/Tikhonov_regularization#Generalized_Tikhonov_regularization).
For small $\lambda$, $A^\top A + \lambda W$ is positive definite. As $\lambda$ increases though, the minimum eigenvalue of $A^\top A + \lambda W$ eventually hits zero. Call the value of $\lambda$ at which this happens $\lambda_0$.
My questions are the following (the final is the most important):
What happens to $x^*$ and $(x^*-c)^\top W (x^*-c)$ as $\lambda \rightarrow \lambda_0$?
Numerical experiments suggest that $(x^*-c)^\top W (x^*-c)$ is negative for $\lambda$ near $\lambda_0$ with $\lambda<\lambda_0$. Is there guaranteed to be a value of $\lambda$ for which $(x^*-c)^\top W (x^*-c)=0$? What is this value?

A: \begin{equation}
(A^TA + \lambda W)e_{i} = \lambda_{i}e_i
\end{equation}
Since $\lambda_i$ is zero when $\lambda = \lambda_0$, then:
\begin{equation}
(A^TA + \lambda_0 W)e_{i} = 0
\end{equation}
\begin{equation}
A^TAe_i = -\lambda_0 We_{i}
\end{equation}
\begin{equation}
\lambda_0 =  -A^TAe_{i}(We_{i})^{-1}
\end{equation}
\begin{equation}
\lambda_0 =  -A^TAW^{-1}
\end{equation}
If we replace $\lambda$ in the expression $x^{*} - c$ with $\lambda_0$, we can see that $(A^TA + \lambda W)$ is zero. For the second part, one solution might be $x^{*} = c$. This suggests that
\begin{equation}
(A^TA + \lambda W)c = A^Tb + \lambda Wc
\end{equation}
If we solve for c, then
\begin{equation}
c = (A^TA)^{-1}A^Tb
\end{equation}
which does not depend on $\lambda$. So, there is some lambda which satisfies the equation.


text:
Q: What level of magic prowess did Harry Potter have? I have a question in reading Harry Potter yet again.  How strong, vs. Voldemort aside, is Harry?  We see all these comparisons, like Snape and his potions book, Tom and his accomplishments, the twins and their abilities, and Dummbldor.  So, is there anything that we might base his magic level on?  I mean, it seems that he lacks a strong magic knowledge.  He mentions at the end of Goblet of knowing a boatload of hexes when giving the gold to the twins.  I reference Robert Jordan and his epic Wheel of Time where each user of the Power could sense strength, how do we know relative strengths with magic, and where would Harry stand?

A: There are a few instances where Harry shows he's quite adept at magic...
One such example is the Patronus Charm, in the Harry Potter Universe he was one of the youngest wizards able to cast Patronus.  He was even able to give it a corporeal form as a stag.


text:
Q: Upsell products in drawer cart So, after i add an item to cart it will open a drawer with the information of that product added to cart and below that all his upsell products. In my CartController.php the code is like that:
$product = $this->_initProduct();
productId = $this->__(Mage::helper('core')->htmlEscape($product->getId()));
                    Mage::register('product', Mage::getModel('catalog/product')->load($productId));
                    $block = Mage::app()->getLayout()->createBlock('catalog/product_list_upsell')->setTemplate('catalog/product/list/upsell.phtml');
                    //set the product
                    $message2 .= $block->toHTml();

These upsell products are displayed like card, but i want them to be displayed like a table and i want to display only the image, price, name and i want to add 2 buttons: "Details" that will sent you to product page and "Add to cart" that will add that product also in cart. How can i do this? I tried with $product->getUpSellProductCollection() and foreach but nothing happen.

A: If somebody need this, this is the answer:
$_product = Mage::getModel('catalog/product')->load($productId);
$upsell = $_product->getUpsellProductCollection();
foreach ($upsell as $product) {
       $productId = $product->getId();
       $model_upsell = Mage::getModel('catalog/product');
       $_product_upsell = $model_upsell->load($productId);
       $upsell_name = $_product_upsell->getName();
       $message2.='getMediaUrl($_product_upsell>getSmallImage()).'"width="200px">' . "
";
}


text:
Q: Filter and format date array I have an array of dates which starts from 1950 up till 2019. Task is to filter the date so that dates array contains dates after 1970 and we need to map the dates to the given format like change the format.
let dateformat="April 2015"
var endDate =  ["1950-09-02T23:00:00.000Z",
             "1951-06-02T23:00:00.000Z"
             ..........
            "2016-09-02T23:00:00.000Z",
            .........
            "2019-09-02T23:00:00.000Z"]

  my solution:
   endDate.filter(item => item > 1970).map(item => item = new Date(dateFormat))

Expected result is that date array changes the dates from given format to April 2015 - Month - year only. I am able to filter dates so that date are greater than 1970 but not able to map to the given format. Also I am trying to do it using ES6 syntax. The array was generated dynamically by pushing the dates into array.

A: Map the strings to Date objects, filter by the year, and then map the dates to the requested format using Date.toLocaleString():

const dateformat = "April 2015"
const endDate = ["1950-09-02T23:00:00.000Z", "1951-06-02T23:00:00.000Z",  "2016-09-02T23:00:00.000Z", "2019-09-02T23:00:00.000Z"]

const result = endDate
  .map(item => new Date(item))
  .filter(item => item.getFullYear() > 1970)
  .map(item => item.toLocaleString('en-US', {
    month: 'long',
    year: 'numeric'
  }))

console.log(result)

A: This is very close to Ori Drori's answer, but with a single loop:

const endDate = [
  "1950-09-02T23:00:00.000Z",
  "1951-06-02T23:00:00.000Z",
  "2016-09-02T23:00:00.000Z",
  "2019-09-02T23:00:00.000Z"
]

const dates = endDate.reduce((dates, date) => {
  date = new Date(date)

  date.getFullYear() > 1970 && dates.push(date.toLocaleString('en-US', {
    month: 'long',
    year: 'numeric'
  }))

  return dates
}, [])

console.log(dates)

A: Just for kicks, an alternative utilizing the sortability of the the ISO date format.  Also prevents conversion from UTC causing edge case where year may be 1969 in local time zone.

const input = ["1950-09-02T23:00:00.000Z",
  "1951-06-02T23:00:00.000Z",
  "2016-09-02T23:00:00.000Z",
  "1970-01-01T00:00:00.000Z",
  "1969-12-31T23:59:59.999Z",
  "2019-09-02T23:00:00.000Z"
];

// ISO date format string is sortable already
const sorted = input.sort();
// find the first date greater than or = 1970
const firstIdx = sorted.findIndex(d => Number(d.substring(0,4)) >= 1970);
// take all of the dates after the first one with 1970
const output = sorted.slice(firstIdx)
        // keep date formatting in UTC timezone like the input dates,
        // otherwise depending  on local time zone, the year may be 1969
        .map(d => new Date(d).toLocaleString('default', {timeZone: 'UTC', month: 'long', year: 'numeric'}));

console.log(output);


text:
Q: React-native android issues with Windows 10 I am running react-native on windows 10 and I'm having a bunch of issues.
Firstly, at the root directory of the project, when I run
react-native run-android

I get this error:

JS server already running. Building and installing the app on the
  device (cd android && gradlew.bat installDebug... Could not install
  the app on the device, read the error above for details. Make sure you
  have an Android emulator running or a device connected and have set up
  your Android development environment:
  https://facebook.github.io/react-native/docs/android-setup.html

And running it with --stacktrace --info did not help.
I then decided to manually do what the run-android script seems to be trying to achieve by going into the android directory and build my self by running
cd android && gradlew.bat installDebug

That, produced a bunch of result but still ended in error.

:app:compileDebugJavaWithJavac :app:compileDebugJavaWithJavac - is not
  incremental (e.g. outputs have changed, no previous execution, etc.).
  C:\Users\jiangyaokai\workspace\maincourse\android\app\src\main\java\com\maincourse\MainApplication.java:30:
  error: cannot find symbol
              new CodePush(this.getResources().getString(R.strings.reactNativeCodePush_androidDeploymentKey),
  this, BuildConfig.DEBUG),
                                                          ^   symbol:   variable strings   location: class R
  C:\Users\jiangyaokai\workspace\maincourse\android\app\src\main\java\com\maincourse\MainApplication.java:30:
  error: cannot find symbol
              new CodePush(this.getResources().getString(R.strings.reactNativeCodePush_androidDeploymentKey),
  this, BuildConfig.DEBUG),
                               ^   symbol: method getResources()
2 errors :app:compileDebugJavaWithJavac FAILED
FAILURE: Build failed with an exception.

*

*What went wrong: Execution failed for task ':app:compileDebugJavaWithJavac'.  Compilation failed; see the
  compiler error output for details.

*Try: Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output.
BUILD FAILED
Total time: 8.109 secs

I wonder what I am doing wrong? Thanks.

A: Here's a snippet from your error message:
MainApplication.java:30: error: cannot find symbol new CodePush(this.getResources().getString(R.strings.reactNativeCodePush_androidDeploymentKey), this, BuildConfig.DEBUG), ^ symbol: method getResources()

it looks like it has something to do with CodePush plugin that you are using.
Could you follow the setup instruction here: https://github.com/Microsoft/react-native-code-push#android-setup and try again.

A: Solved.
symbol: variable strings location: class R
this is caused by the fact that R only has string but not strings, not sure why the code (auto generated) refers to strings.
symbol: method getResources()
This is missing because "this" refers to the inner class, wheres getResources() is only found in the outer class.
Overall, basically the code was wrong and correctly could not be compiled.
Thanks to all.


text:
Q: HT ACCESS PROBLEMS I have an opencart SSL (https) ecommerce site with the following issue. When I search on google for my site it defaults to https://ricambimoto.uk which causes some of the font awesome icons not to show up on first loading the browser with the cache cleared. If I refresh the browser page it changes the URL to https://www.ricambimoto.uk and all is well. My htaccess file in the ReWrite section is as follows:
RewriteBase /
# Force HTTPS
RewriteEngine On
RewriteCond %{HTTPS_HOST} !^www\.
RewriteRule ^(.*)$ https://www.%{HTTP_HOST}/$1 [R=301,L]
RewriteCond %{REQUEST_URI} ^/ [NC]
RewriteCond %{SERVER_PORT} !^443$
RewriteRule ^(.*)$ https://%{SERVER_NAME}%{REQUEST_URI} [L,R]
RewriteRule ^sitemap.xml$ index.php?route=extension/feed/google_sitemap [L]
RewriteRule ^googlebase.xml$ index.php?route=extension/feed/google_base [L]
RewriteRule ^system/storage/(.*) index.php?route=error/not_found [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_URI} !.*\.(ico|gif|jpg|jpeg|png|js|css)
RewriteRule ^([^?]*) index.php?_route_=$1 [L,QSA]

Is there a glaring error here as I can't see what could be causing it? I need to force the URL to add the www element every time.
I should add that I have amended the root and admin config files as follows as well
root config.php
// HTTP
define('HTTP_SERVER', 'https://www.ricambimoto.uk/');

// HTTPS
define('HTTPS_SERVER', 'https://www.ricambimoto.uk/');

admin config.php
// HTTP
define('HTTP_SERVER', 'https://www.ricambimoto.uk/admin/');
define('HTTP_CATALOG', 'https://www.ricambimoto.uk/');

// HTTPS
define('HTTPS_SERVER', 'https://www.ricambimoto.uk/admin/');
define('HTTPS_CATALOG', 'https://www.ricambimoto.uk/');

A: Try to force non www. Add to your  .htaccess file:
RewriteEngine On
RewriteBase /
RewriteCond %{HTTP_HOST} ^www\.(.*)$ [NC]
RewriteRule ^(.*)$ https://%1/$1 [R=301,L]

A:
RewriteCond %{HTTPS_HOST} !^www\.
RewriteRule ^(.*)$ https://www.%{HTTP_HOST}/$1 [R=301,L]

It should be HTTP_HOST in the first line (RewriteCond directive), not HTTPS_HOST (which doesn't exist).
However, as written, this should have generated an endless redirect-loop? And you have inconsistencies between a route and _route_ URL parameter in your rules. And the URLs throughout your site use the form /index.php?route=<page> which doesn't require .htaccess. This makes me wonder whether your .htaccess file is actually doing anything?


text:
Q: Dictionary from XML based on parent and child nodes I write an application in WPF and I have the following XML:
<NewDataSet>
  <EYE>
    <DAD>Blue</DAD>
    <MOM>Brown</MOM>
  </EYE>
  <HAIR>
    <DAD>Black</DAD>
    <MOM>Brown</MOM>
  </HAIR>
  <SKIN>
    <DAD>White</DAD>
    <MOM>White</MOM>
  </SKIN>
</NewDataSet>

I would like to read that XML into a dictionary so if I choose to read "DAD" data I would get:
public Dictionary<string, string> values = new Dictionary<string, string>()
{
    {"EYE", Blue},
    {"HAIR", Black},
    {"SKIN", White}
};

Is it possible, and if so, who can I do it?
Any code snippets would be very helpful.

A: It's really quite simple:
    var xd = XDocument.Parse(@"<NewDataSet>
  <EYE>
    <DAD>Blue</DAD>
    <MOM>Brown</MOM>
  </EYE>
  <HAIR>
    <DAD>Black</DAD>
    <MOM>Brown</MOM>
  </HAIR>
  <SKIN>
    <DAD>White</DAD>
    <MOM>White</MOM>
  </SKIN>
</NewDataSet>");

Dictionary<string, string> values =
    xd
        .Root
        .Elements()
        .ToDictionary(
            xe => xe.Name.LocalName,
            xe => xe.Element("DAD").Value);

A: Using xml linq :
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            string xml =
                "<NewDataSet>" +
                    "<EYE>" +
                       "<DAD>Blue</DAD>" +
                       "<MOM>Brown</MOM>" +
                    "</EYE>" +
                    "<HAIR>" +
                       "<DAD>Black</DAD>" +
                       "<MOM>Brown</MOM>" +
                    "</HAIR>" +
                    "<SKIN>" +
                       "<DAD>White</DAD>" +
                       "<MOM>White</MOM>" +
                    "</SKIN>" +
                "</NewDataSet>";

            XElement dataset = XElement.Parse(xml);

            Dictionary<string, string> dadDict = dataset.Elements()
                .GroupBy(x => x.Name.LocalName, y => (string)y.Element("DAD"))
                .ToDictionary(x => x.Key, y => y.FirstOrDefault());
        }
    }
}


text:
Q: Commas before and after therefore? Is it correct to use commas around therefore in the following quote?

An important prerequisite to meet the requirements of ... is, therefore, the ability to ...

Or should I omit the first comma to make the sentence correct?

An important prerequisite to meet the requirements of ... is therefore, the ability to ...

A: You can either not use commas at all

is therefore the ability to...

Or use commas before and after:

is, therefore, the ability to...

The commas are parenthetical, which can often be omitted when the interruption is brief, as in this example, but you should never use a comma before a parenthetical phrase and not after it (or vice versa).
See the section on parenthetical commas here to learn more.


text:
Q: ACF Page Field group incorrectly appearing on Default Wordpress Posts page I have some text fields I have added to a field group which I intend to show on pages only.
Screenshots on Field group Settings
But they are showing on the standard block editor within posts edit page. Any idea why this may be?
Thanks!
I tried Post Type is not equal to Post but its still showing

A: You can solve this by adding a validation to each of the rules by pressing the "and" button and adding a validation of "Post Type is equal to page". So the field group will only appear on the post type of pages.


text:
Q: API key is not check that metadata react native Hy I'm using react-native-maps first time I install and also configure it properly but when I run the app is display the following error:
API key not found. Chech that <Meta-data android:name:".." ...... is in the <application> element of AndroidManifest.xml

I try to clean the cache, clean gradlew, but didn't solve me.
AndroidManifest
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
  package="com.dateapp">

    <uses-permission android:name="android.permission.INTERNET" />

    <application
      android:name=".MainApplication"
      android:label="@string/app_name"
      android:icon="@mipmap/ic_launcher"
      android:roundIcon="@mipmap/ic_launcher_round"
      android:allowBackup="false"
      android:theme="@style/AppTheme">
      <activity
        android:name=".MainActivity"
        android:label="@string/app_name"
        android:configChanges="keyboard|keyboardHidden|orientation|screenSize|uiMode"
        android:launchMode="singleTask"
        android:screenOrientation="portrait"
        android:windowSoftInputMode="adjustResize">
        <meta-data
     android:name="com.google.android.geo.xxxxxxxxxx"
     android:value="xxxxxxxxxx"/>

        <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
      </activity>
    </application>
</manifest>

Does someone know what I'm missing?

A: <manifest
  xmlns:android="http://schemas.android.com/apk/res/android"
  package="com.dateapp">

   <uses-permission android:name="android.permission.INTERNET" />

<application
  android:name=".MainApplication"
  android:label="@string/app_name"
  android:icon="@mipmap/ic_launcher"
  android:roundIcon="@mipmap/ic_launcher_round"
  android:allowBackup="false"
  android:theme="@style/AppTheme">
  <activity
    android:name=".MainActivity"
    android:label="@string/app_name"
    android:configChanges="keyboard|keyboardHidden|orientation|screenSize|uiMode"
    android:launchMode="singleTask"
    android:screenOrientation="portrait"
    android:windowSoftInputMode="adjustResize">
    <intent-filter>
        <action android:name="android.intent.action.MAIN" />
        <category android:name="android.intent.category.LAUNCHER"
    />
    </intent-filter>
  </activity>
   <meta-data
      android:name="com.google.android.geo.API_KEY"
      android:value="Your Google API Key Here"/>
  </application>
 </manifest>

You can't change the literal "API_KEY" in android:name, Set the android:name as "com.google.android.geo.API_KEY"
and install build again