text:
Q: Cambiar el contenido del un div dependiendo del botón que uses Buenas, lo que estoy intentando hacer no se si se podrá hacer sin AJAX. Tengo una plantilla en html en el cual tiene unos botones a la izquierda. Mi idea es que al pulsar un botón se agregue al div el contenido correspondiente. Había pensado hacerlo con include y el nombre del archivo que contiene el texto.
Os pongo la imagen de la plantilla:

Código de la plantilla:

        <title>Plantilla</title>
        <meta charset="UTF-8"/>

                EXAMEN PHP

                Mario Guiberteau

                <button name="ejercicio1">Ejercicio 1</button>
                <button>Ejercicio 2</button>
                <button>Ejercicio 3</button>

                <?php
                    if(isset($_GET["ejercicio1"])){ include 'Ejercicio1.html';}
                ?>

El texto que contiene el archivo Ejercicio1.html es: Contenido del botón uno.
La cuestión es si es posible de que a la hora de pulsar un botón me pusiera el contenido del archivo en la zona amarilla.
Gracias de antemano

A: Podrías usar iframe y no necesitarías nada de JavaScript, sólo tendrías que cambiar el target de los enlaces para que apunten al atributo name del iframe. Algo como esto:

#contenedor {
  border: 2px solid black;
  margin: 0 auto;
  background-color: #A9F5BC;
  width: 796px;
  overflow: hidden;
}

#cabecera {
  border-bottom: 2px solid black;
  width: 796px;
  height: 80px;
  font-size: 30px;
  padding-top: 10px;
  text-align: center;
}

#menu {
  float: left;
  border-top: 0px solid black;
  border-bottom: 0px solid black;
  width: 198px;
  padding: 1px;
}

button {
  margin: 0 auto;
  display: block;
  margin-top: 20px;
}

#contenido {
  float: left;
  width: 580px;
  padding: 8px;
  height: auto;
  background-color: #F3F781;
  text-align: center;
  min-height: 400px;
  position: relative;
}

/* el iframe debe ocupar todo el espacio de #contenido */
#contenido iframe {
  position: absolute;
  top: 0;
  left: 0;
  bottom: 0;
  right: 0;
  border: 0;
}

/* le damos estilos a los enlaces para que parezcan botones */
#menu a {
  display: inline-block;
  margin: 3px 10px;
  padding: 4px 10px;
  background: #eee;
  color: #333;
  text-decoration: none;
}

    EXAMEN PHP
 Mario Guiberteau

    Ejercicio 1
    Ejercicio 2
    Ejercicio 3

A:

                <title>Plantilla</title>
                <meta charset="UTF-8"/>

                        EXAMEN PHP

                        Mario Guiberteau

                    <form id="menu">
                        <button name="ejercicio" value="ejercicio1">Ejercicio 1</button>
                        <button name="ejercicio"  value="ejercicio2">Ejercicio 2</button>
                        <button name="ejercicio"  value="ejercicio3">Ejercicio 3</button>
                    </form>

                        <?php
if(isset($_GET["ejercicio"])){

    include $_GET["ejercicio"].'.html';

}

?>

A: Así funciona perfecto, tan solo debes cambiar en el atributo data el nombre de tu archivo html a cargar <object type="text/html" data="ejercicio1.html" ></object>:
Código completo

        <title>Plantilla</title>
        <meta charset="UTF-8"/>

                EXAMEN PHP

                Mario Guiberteau

                <button type="button" id="ejercicio1">Ejercicio 1</button>
                <button type="button" id="ejercicio2">Ejercicio 2</button>
                <button type="button" id="ejercicio3">Ejercicio 3</button>


text:
Q: Cross development aspects between different Java EE implementations (especially Glassfish and JBoss) I am working on an AddOn Web Application for an existing Enterprise Application deployed on a JBoss 4 AS instance. To keep it easy I am using the Glassfish Application Server delivered in Netbeans. For theprototype, I am packing every library I use into the war file which I want to deploy, also Hibernate and some really basic libraries. But in future I also want to use the server delivered libraries and features like JNDI database connection lookup, session and entity beans and so on.
My Questions:

*

*Are there any aspects deploying a simple web application in a war file which was packed for glassfish on a Jboss, which can be a hard to solve problem?

*Are the EJB interfaces accessed in a similar way on both implementations? Means, am I able to access a session bean on Jboss when I developed the code for doing this on a Glassfish server?

*Is JNDI querying performed similar on both implementations?

*Other aspects?

I have to say, that I am only experienced in developing simple servlets. I know some theoretical stuff about Java EE and EJB and I want to get deeper in this. I do know nothing about implementation specific details, so this is what this question is focused on.

A: If your application is relatively simple and you stick to core Java EE standards, in theory you should see no major issues. You might have some problems accessing EJBs since there are differences in JNDI naming.
That being said, JBoss 4 is fairly old. It's J2EE 1.4 compliant, and implements the EJB 2.1 specification. New JBoss and GlassFish servers are Java EE 6 compliant and implement the EJB 3.1 specification. EJB3 is much easier to use, but you cannot deploy a 3.x EJB to a 2.x container (the other way around is possible). So you'll have to be careful to stick to what's possible in an EJB2 container. For example, if you want to use an EJB locally (i.e. from another EJB deployed on the same server), under EJB2 you have to define and implement a local interface. Under EJB3 it's enough to annotate the EJB class with @LocalBean. And don't get me started with all the external descriptors required by EJB2.
A general rule of thumb is to use the same VERSION of the same AS for both development and production. For example, there might be a bug with a certain functionality in aplication server Y version Z, which does not appear in application server A version B. So your application will work in A, but when you deploy it to Y, it will crash, and you'll have hard time debugging it. If you use the same (version of the same) AS, there's a greater chance you'll discover the bug during development.
I once had to transfer a fairly complex application from GlassFish v2 to GlassFish v3, and the process was anything than straightforward.
So, if you have to use JBoss 4 as the target, do all your development under JBoss 4. It will save you a lot of trouble later on. If you can use the latest JBoss 7 as the target, you can develop your application under the latest GlassFish 3.x, and it will most likely work, but I see no good reason for doing this.

redpajama_set_name: RedPajamaStackExchange


text:
Q: for multiindex for columns calculate min/max of columns that share the same name for level=1 Good day,
For the following dataframe with MultiIndex for columns
      1    |    2   |     level = 1
--------------------
   a |  b | a | b |   level = 0
------------------
0  1     2    3   1
1  2     5    6   4
2  85    74   5   92

I am trying to caclulate min and max of columns for level = 1 (max/min of columns a and b for column 1 and max/min of columns a and b for column 2), but have not find the decent way to do it.
I would like to have something like this:
        1    |    2   |     level = 1
-----------------------
      a |  b | a | b  |   level = 0
-----------------------
min    1         1
max    85        92

Could you help me and share your ideas please.


text:
Q: Bland-Altman plot correction for proportional bias I am comparing 2 measurement methods with the Bland-Altman plot methodology.
I found a proportional bias between the 2 measurement systems, by the regression model:
difference = intercept + b1*average
The parameters of the regression are:
intercept = 18.44
b1 = -0.27
both are significant.
How do I correct my new measurement scores with the parameters I found in the regression, so that I that both measurements have the same scores?


text:
Q: How to convert pt into em? Sorry for silly question!
I have psd file and In the header :Some text: has font-size 120pt;
But I don't want to use pt I want to use em so is it possible to convert pt to em?

A: This is the tool I use: PXtoEM.
Just remember that EMs are relative to the base PX font-size.

A: You cannot, any more than you cannot convert dollars to euros without knowing a conversion rate, which varies. Once you know a conversion rate, the problem is trivial.
Questions like this are mostly answered on false premises that expect 1em to be 12pt. This is incorrect on two accounts. First, the em unit is the size of the font of the element (for most properties) or the size of the font of the parent element (for font-size'). Thus, it need not be the same as the root elementemvalue. Second, the root elementemvalue varies. It was common to think that it is12pt` by default, as it often is, but it is easy to see that e.g. in mobile phones, the default font size is nowhere near that.
So, you can't. If you need to produce a specific layout specified in points, then use pt. If you want to produce it in a manner that adapts to the basic font size, then use em and replace the pt values by em according to some consistent scheme. The conversion rate is up to you, or the designer.
(A font size of 120pt might make sense on a page tailored for presentation on a movie screen or comparable huge size. You should compare it with the size set on body text.)

A: You could use any of the following:
http://pxtoem.com/
www.convertunits.com/from/pt/to/em

A: There is no clear cut relationship between EMs and PXs, because EM sizes are based relative to the size of the font, whereas PX sizes are based relative to the screen resolution. Since those two elements are disparate, no exact correlation can be made.
There are ways, however, to get fairly close. One method is to set the base font size (the font-size property on the  element) to around 62.8%. This makes the base font, or 1.0em, approximately equal to 10px. It's not exact, and changes from font to font, but generally speaking it's pretty accurate. With that font setting in the body, you can use EMs as px equivalents like so...
1.0em = 10px
1.1em = 11px
1.2em = 12px
2.0em = 20px
5.0em = 50px

etc.
There are a few caveats, however, the major one being that it isn't a precise conversion so elements that must be EXACTLY Xpx are unlikely to be so. The other big danger is that setting the base font this small makes IE text resizing somewhat problematic, as this 62.8% size becomes the "meduim" setting for IE. Since IE only allows two font-size increases ("large" and "larger"), those who need larger fonts may not get a big enough size to suit their needs. Likewise, sizing down to "small" or "smaller" makes text virtually unreadable.
But otherwise, it's a very practical technique.


text:
Q: Recover LVM without /etc/lvm/backup/ I just thought what if I lost the LVM backup folder and I only have the HDD's belonging to my one and only Volume Group.
Here is a little summary:
root@ubuntu-srv:/# pvs
  PV         VG   Fmt  Attr PSize  PFree
  /dev/sda1  vg00 lvm2 a--  59,62g <59,61g

root@ubuntu-srv:/# vgs
  VG   #PV #LV #SN Attr   VSize  VFree
  vg00   1   1   0 wz--n- 59,62g <59,61g

root@ubuntu-srv:/# lvs
  LV    VG   Attr       LSize  Pool Origin Data%  Meta%  Move Log Cpy%Sync Convert
  test vg00 -wi-ao---- 16,00m

Because of all the metadata and the LVM label sits on all of the HDD's, technically I'm facing a possible recovery - I think.
So the first step is running the pvck command:
root@ubuntu-srv:/# pvck -v /dev/sda1

    Scanning /dev/sda1
  Found label on /dev/sda1, sector 1, type=LVM2 001
  Found text metadata area: offset=4096, size=1044480
    Found LVM2 metadata record at offset=19456, size=1536, offset2=0 size2=0
    Found LVM2 metadata record at offset=17408, size=2048, offset2=0 size2=0

If I correct after that I need to focus the text metadata area because it contains all the previously made metadata history. Then I convert the offset value to its hexadecimal equivalent for hexdump. The size remain untouched because hexdumps -n option need bytes.
Here is the command:
root@ubuntu-srv:/# hexdump -C -s 1000 -n 1044480 /dev/sda1

My questions:

*

*Are my numbers good?

*Is this the correct way to start the recovery in this kind of a situation?


text:
Q: SEM with moderation analysis (cross-lagged-model) in R I want to do structural equation modeling with three moderators. My variables are attractiveness (X), self-worth (Y), age (A), gender (G) and social status (S). The data is longitudinal and collected in two waves: t1 and t2. In order to find out which relation exists between X and Y, in which direction this relation goes and how the relation is moderated by A, G and S, I want to use a cross-lagged-model where X_t2 and Y_t2 are the outcome variables. I use the R-package lavaan. The model looks like the following:
modelCLP <- '
  # regressions
    X_t2 ~ X_t1 + Y_t1 + A + G + S + Y_t1 * A + Y_t1 * G + Y_t1 * S
    Y_t2 ~ Y_t1 + X_t2 + A + G + S + X_t1 * A + X_t1 * G + X_t1 * S

  # co-movements
    X_t2 ~~ Y_t2
    X_t1 ~~ Y_t1

'
fit <- sem(modelCLP, data = datenB)
summary(fit, standardized = TRUE, fit.measures = TRUE)

The problem with my output is that I get the same results for the moderators in equation 1 and for the moderators in equation 2. When I do three separate analyses for the moderators I get three different results. When i calculate the model above, I get theses results:
lavaan 0.6-10 ended normally after 20 iterations

  Estimator                                         ML
  Optimization method                           NLMINB
  Number of model parameters                        13
  Number of equality constraints                     4

                                                  Used       Total
  Number of observations                           871        2406

Model Test User Model:

  Test statistic                                14.959
  Degrees of freedom                                 4
  P-value (Chi-square)                           0.005

Model Test Baseline Model:

  Test statistic                              1024.222
  Degrees of freedom                                11
  P-value                                        0.000

User Model versus Baseline Model:

  Comparative Fit Index (CFI)                    0.989
  Tucker-Lewis Index (TLI)                       0.970

Loglikelihood and Information Criteria:

  Loglikelihood user model (H0)              -1967.499
  Loglikelihood unrestricted model (H1)      -1960.020

  Akaike (AIC)                                3952.999
  Bayesian (BIC)                              3995.926
  Sample-size adjusted Bayesian (BIC)         3967.344

Root Mean Square Error of Approximation:

  RMSEA                                          0.056
  90 Percent confidence interval - lower         0.028
  90 Percent confidence interval - upper         0.088
  P-value RMSEA <= 0.05                          0.320

Standardized Root Mean Square Residual:

  SRMR                                           0.018

Parameter Estimates:

  Standard errors                             Standard
  Information                                 Expected
  Information saturated (h1) model          Structured

Regressions:
                   Estimate  Std.Err  z-value  P(>|z|)   Std.lv  Std.all
  X_t2 ~
    X_t1              0.382    0.018   21.245    0.000    0.382    0.600
    Y_t1              0.100    0.034    2.902    0.004    0.100    0.083
    A       (Y_t1)    0.002    0.002    1.395    0.163    0.002    0.037
    G       (Y_t1)    0.002    0.002    1.395    0.163    0.002    0.001
    S       (Y_t1)    0.002    0.002    1.395    0.163    0.002    0.003
  Y_t2 ~
    Y_t1              0.716    0.034   21.180    0.000    0.716    0.594
    X_t1              0.064    0.018    3.617    0.000    0.064    0.100
    A       (X_t1)    0.004    0.001    2.724    0.006    0.004    0.071
    G       (X_t1)    0.004    0.001    2.724    0.006    0.004    0.002
    S       (X_t1)    0.004    0.001    2.724    0.006    0.004    0.006

Covariances:
                   Estimate  Std.Err  z-value  P(>|z|)   Std.lv  Std.all
 .X_t2 ~~
   .Y_t2              0.104    0.020    5.287    0.000    0.104    0.182

Variances:
                   Estimate  Std.Err  z-value  P(>|z|)   Std.lv  Std.all
   .X_t2              0.580    0.028   20.869    0.000    0.580    0.581
   .Y_t2              0.560    0.027   20.869    0.000    0.560    0.559

What can I do in order to get different results for the three moderators? Is there a better way to do a SEM with multiple moderators in R?

A: I am not sure what exactly is being done by lavaan in your code, but I believe maybe 'A', 'G', and 'S' are considered constrains in the model.
For what I know, we need to prepare the interaction (moderation) terms before running the SEM analysis in almost (?) all tools... There are several ways to do so.

*

*One is computing factor scores for the latent variables and generate the interaction terms as product among factor score and moderator.

*Another way to do so in R, without computing factor scores is, for example, to use the function indProd() from semTools package.

*From your code, it appears you are not dealing with latent variables, so, compute the product among the variables would be sufficient:

modelCLP$A_Y_t1=modelCLP$A*modelCLP$Y_t1
modelCLP$G_Y_t1=modelCLP$G*modelCLP$Y_t1
modelCLP$S_Y_t1=modelCLP$S*modelCLP$Y_t1
modelCLP$A_X_t1=modelCLP$A*modelCLP$Y_t1
modelCLP$G_X_t1=modelCLP$G*modelCLP$X_t1
modelCLP$S_X_t1=modelCLP$S*modelCLP$X_t1

    modelCLP <- '
      # regressions
    X_t2 ~ X_t1 + Y_t1 + A + G + S + A_Y_t1 + G_Y_t1  + S_Y_t1
    Y_t2 ~ Y_t1 + X_t2 + A + G + S + A_X_t1 + G_X_t1 + S_X_t1
      # co-movements
    X_t2 ~~ Y_t2
    X_t1 ~~ Y_t1'

Note: you possibly need to add covariances among all variables (including these interaction terms).
fit <- sem(modelCLP, data = datenB)
summary(fit, standardized = TRUE, fit.measures = TRUE)


text:
Q: How to add a custom view from a xib to a UIScrollView? Problem
I am trying to add a custom view from a xib into a UIScrollView.
I added a UIScrollView to an empty ViewController in my storyboard. I also added 4 constraints for leading, trailing, top, bottom to Safe Area and set them all Equal to 0.
Now in the code I want to add a custom view "EquipmentInfoView" to the existed UIScrollView
class EquipmentInfoVC: UIViewController {
    @IBOutlet var scrollView: UIScrollView!

    override func viewDidLoad() {
        super.viewDidLoad()

        equipmentInfoView = EquipmentInfoView.instantiate()
        scrollView.addSubview(equipmentInfoView)
    }
}

And it does not work as the ScrollView does not scroll. How should I do it instead?
Here is the custom view "EquipmentInfoView"
class EquipmentInfoView: UIView {

    @IBOutlet var nameTextView: UITextView!
    @IBOutlet var descriptionTextView: UITextView!
    @IBOutlet var equipmentImageView: UIImageView!

    static func instantiate() -> EquipmentInfoView {
        let view: EquipmentInfoView = initFromNib()
        return view
    }
}

Extra Notes
I know this is not the normal way to create a custom view from xib. However, this way I dont have to set the File's Owner to "EquipmentInfoView", instead I set the View's Custom Class to "EquipmentInfoView".
(Setting File's Owner to "EquipmentInfoView" gives me EXC_BAD_ACCESS when I do unit testing)
For clarity, this is how I would add this view to a normal (non-scroll) view:
equipmentInfoView = EquipmentInfoView.instantiate()
mainView.addSubview(equipmentInfoView)
equipmentInfoView.frame = mainView.bounds
equipmentInfoView.autoresizingMask = [.flexibleHeight, .flexibleWidth]

A: You are probably missing the contentSize of your scrollView
class EquipmentInfoVC: UIViewController {
    @IBOutlet var scrollView: UIScrollView!

    override func viewDidLoad() {
        super.viewDidLoad()

        equipmentInfoView = EquipmentInfoView.instantiate()
        scrollView.contentSize = equipmentInfoView.frame.size
        scrollView.addSubview(equipmentInfoView)
    }
}


text:
Q: Access pixels in a 16-bit TIFF I have imported a greyscale 16-bit image. I have it bot as a BitmapSource and an Image (of Controls namespace). How can i access the individual pixels? Is the CopyPixels i have read about the only or best way? If so, i don't get how to set the stride, and which pixel contains the pixel intensity value.
Method1:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Threading;
using System.IO;
using Nikon;
using WindowsFormsApplication1;
using System.Windows.Media.Imaging;
using System.Drawing;
using System.Drawing.Imaging;
using System.Windows.Controls;

namespace Map
{
    class OpenTIFF
    {
        static void OpenOne()
        {
        // Open a Stream and decode a TIFF image
        Stream imageStreamSource = new FileStream("C:\\Users\\Me\\Desktop\\"MyTif.tif", FileMode.Open, FileAccess.Read, FileShare.Read);
        TiffBitmapDecoder decoder = new TiffBitmapDecoder(imageStreamSource, BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.Default);
        BitmapSource bitmapSource = decoder.Frames[0];
        System.Windows.Controls.Image image = new System.Windows.Controls.Image();
        image.Source = bitmapSource;
        }
    }
}

I think this might be simpler (found here), but then i am unclear how to access individual pixels in a 1D byte array.
Method 2:

static void OpenTwo()
       {
           System.Drawing.Image imageToConvert = System.Drawing.Image.FromFile("aa.tif", true);
           byte[] Ret = new byte[0];
           using (MemoryStream ms = new MemoryStream())
           {
               imageToConvert.Save(ms, ImageFormat.Tiff);
               Ret = ms.ToArray();
           }
       }

Thanks,
Dan

A: You might want to check out the free image library.
It has a C# wrapper.
http://freeimage.sourceforge.net/index.html
To get you started and give a quick example:

*

*download the binary distribution

*open FreeImage.NET.sln in visual studio (I used 2010)

*build the Library project

*if you receive errors in the XML comments do the following: go in the project properties, under build, change "treat warnings as errors" from "all" to "none"

*Create new console project.

*Add reference to the assembly you built in step 3.
FreeImage3154Win32\FreeImage\Wrapper\FreeImage.NET\cs\Library\bin\Debug\FreeImageNET.dll

*Add the following code to Program.cs
using FreeImageAPI;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            // load image, this can by your 16-bit tif
            FIBITMAP dib = FreeImage.LoadEx("myfile.tif");
            // convert to 8-bits
            dib = FreeImage.ConvertToGreyscale(dib);
            // rotate image by 90 degrees
            dib = FreeImage.Rotate(dib, 90);
            // save image
            FreeImage.SaveEx(dib, "newfile.png");
            // unload bitmap
            FreeImage.UnloadEx(ref dib);
       }
    }

}

*copy the FreeImage binary dll that you downloaded into the bin directory.
FreeImage3154Win32\FreeImage\Dist\FreeImage.dll

*Run the application

There is a good selection of examples in the solution that contained the Library project.

A: Your detailed steps are very much what i needed...much thanks.
I followed directions similar to yours for installation (your steps 1-3) in a related thread. This was successful, and exactly as Romulus said.
Below are some additional details needed and errors I ran into (i hope its not too much detail...hope to help anyone else who runs into this).
I followed your directions from step 4 onwards (except i added it into my exisitng windows application). I copied the FreeImage.dll (step 8) into the bin directory of my project.
I run the code, and get this error:

An unhandled exception of type 'System.BadImageFormatException' occurred in WindowsFormsApplication1.exe
Additional information: An attempt was made to load a program with an incorrect format. (Exception from HRESULT: 0x8007000B)

I had two errors. First was that I had not copied to FreeImage binary dll (step 8 above) into the correct bin directory of the project (I had copied it to bin and not bin\Debug 8-). I copied it to:

\WindowsFormsApplication1\bin\Debug

Second, if I run it now, I get an error:

An unhandled exception of type 'System.TypeInitializationException' occurred in WindowsFormsApplication1.exe
Additional information: The type initializer for 'WindowsFormsApplication1.Form1' threw an exception.

The solution here is to change the Build platform to x86. I found either selecting x86, or Any CPU with the Prefer 32-bit box checked work. Tip for beginners like myself: The Build platform is accessed by right-clicking on the Project name (not the Solution) and selecting Properties. It can also be accessed from the DEBUG menu, where at the bottom will be "MyProject Properties".

or this also works:

So with these two fixes, the code runs fine. However, the file output is 0KB. But that's another post...
Thanks!
Dan


text:
Q: Removin /page/2 from pagination I would like to remove /page from category pagination or translate is so it looks like this:
http://www.example.com/category/catname/2

or
http://www.example.com/category/catname/customword/2

Couldn't find anything while googleing. Can you please suggest a solution?

A: If I understand you correct you would like to edit the url for your posts/pages. If you login to your dashboard as an admin user, you can navigate to settings/Permalinks and choose a pre-made option for you or create a custom one


text:
Q: How to change font color in Excel based on cell value? How do you change the font color of a column of cells based on their entered value? I've got a column with the heading at row 1 and the values starting at row 2 going on down. I want to change font color based on what is entered in the cells. E.g. If the value is Active, than make the color green and if it's Requested make it orange.
Thanks!

A: I'm adding an answer here that combines the actual steps from the tutorial that @JNK supplied, and updates for Excel 2013/2016 that @JohnDyer supplied in his comment.
You never know when one of Microsoft's links just stops working.
+1 @JNK
+1 @JohnDyer
How to Apply Conditional Formatting
To apply conditional formatting to one or more cells:

*

*Highlight your cell or range of cells.

*Select the Conditional Formatting button on the Home tab of the ribbon.

*Select Highlight Cell Rules.

*Select a cell evaluator from the second drop-down box.

*Enter your values in the dialog that pops up.

*Click the OK button.

A: What you are looking for is conditional formatting.
Here's a quick tutorial.


text:
Q: SQL: Changing SELECT Query to Show Different Values on Column A based off Boolean in Column B I have a SQL Query that produces this output:

How would I adjust my query so that the "SCORE" column's value is increased by 3 if the "CROSSDOMAIN" column value is true? I am thinking that I would wrap my existing query with another query that handles this case, but I'm not sure what that query would be.
My existing query is as follows (not the prettiest, but it works):
                SELECT HORSUM.TEAMNAME, HORSUM.EMAIL1, SUM(HORSUM.TOTALSUM) Score, COUNT(*) Count, TEAM.THEME, TEAM.FINALIST, TEAM.WINNER, TEAM.CROSSDOMAIN
                FROM
                    (SELECT "JUDGEEMAIL", "TEAMNAME", "EMAIL1", "DEVOPSPRACTICES" + "BUSINESSIMPACT" +
                    "NEWSKILLS" + "EXECUTION"
                    + "INNOVATION" + "CLARITY" as totalSum
                    FROM "DOMAINSCORES") AS HORSUM
                INNER JOIN (SELECT "THEME", "TEAMNAME" as nameID, "FINALIST", "WINNER", "CROSSDOMAIN" FROM "TEAMS" WHERE "FINALIST" = True) AS TEAM ON HORSUM.TEAMNAME = TEAM.nameID
                GROUP BY "TEAMNAME", EMAIL1, THEME, FINALIST, WINNER, CROSSDOMAIN
                ORDER BY Score DESC;

EDIT: I've tried this query, as suggested by Michael, but I get a syntax error. I also want to add that I am using IBM's DB2, if that makes a difference.
SELECT HORSUM.TEAMNAME
     , HORSUM.EMAIL1
     , case
         when TEAM.CROSSDOMAIN = 'true'
         then SUM(HORSUM.TOTALSUM) + 3
         else SUM(HORSUM.TOTALSUM)
       end as Score
     , COUNT(*) Count
     , TEAM.THEME
     , TEAM.FINALIST
     , TEAM.WINNER
     , TEAM.CROSSDOMAIN
FROM
(SELECT HORSUM.TEAMNAME, HORSUM.EMAIL1, SUM(HORSUM.TOTALSUM) Score, COUNT(*) Count, TEAM.THEME, TEAM.FINALIST, TEAM.WINNER, TEAM.CROSSDOMAIN
                FROM
                    (SELECT "JUDGEEMAIL", "TEAMNAME", "EMAIL1", "DEVOPSPRACTICES" + "BUSINESSIMPACT" +
                    "NEWSKILLS" + "EXECUTION"
                    + "INNOVATION" + "CLARITY" as totalSum
                    FROM "DOMAINSCORES") AS HORSUM
                INNER JOIN (SELECT "THEME", "TEAMNAME" as nameID, "FINALIST", "WINNER", "CROSSDOMAIN" FROM "TEAMS" WHERE "FINALIST" = True) AS TEAM ON HORSUM.TEAMNAME = TEAM.nameID
                GROUP BY "TEAMNAME", EMAIL1, THEME, FINALIST, WINNER, CROSSDOMAIN)
ORDER BY Score DESC;

A: Try this as outer SELECT
SELECT HORSUM.TEAMNAME
     , HORSUM.EMAIL1
     , case
         when TEAM.CROSSDOMAIN = 'true'
         then SUM(HORSUM.TOTALSUM) + 3
         else SUM(HORSUM.TOTALSUM)
       end as Score
     , COUNT(*) Count
     , TEAM.THEME
     , TEAM.FINALIST
     , TEAM.WINNER
     , TEAM.CROSSDOMAIN
     ...


text:
Q: Unable to parse "CET" from formatted DateString Why the DateFormat Parser cant parse CET?
final String dateString = "Sat Jul 05 00:00:00 CET 1975";
final DateTime dateTime =
    DateFormat("EEE MMM dd HH:mm:ss vvv yyyy").parse(dateString);

Results in

FormatException: Trying to read   from Sat Jul 05 00:00:00 CET 1975 at position 21

Position 21 would be "C" if I count right.
Anybody had this problem before?

A: intl package didn't implement parsing time zones yet, as evident in date_format_field class :
      case 'v':
        return formatTimeZoneId(date);
      case 'z':
        return formatTimeZone(date);
      case 'Z':
        return formatTimeZoneRFC(date);

And when you look at these functions implementation :
  String formatTimeZoneId(DateTime date) {
    // TODO(alanknight): implement time zone support
    throw new UnimplementedError();
  }

  String formatTimeZone(DateTime date) {
    throw new UnimplementedError();
  }

  String formatTimeZoneRFC(DateTime date) {
    throw new UnimplementedError();
  }

This issue has been open since 2015, and this is the response of one of the people responsible for it :

We don't expect to implement those until Dart DateTime's have time zone information, and that's not planned. I wouldn't expect it unless/until JavaScript DateTime's have them. Including localized TimeZone names is a lot of data. We should probably just remove those APIs until such time as we actually provide them.


text:
Q: Xgboost objective rank is position sensitive I'm running xgboost with objective rank:NDGC and the input format of the dataset needed to be in libsvm fomart
and I'm wondering if the libsvm is position sensitive for this objective as we know that the position is important for search (higher position higher probability to click)
libsvm example of 1 query group:
0 qid:6 1:1 3:5 4:65 5:281 6:2 7:15
0 qid:6 1:2 3:15 4:68 5:13 6:2 7:14
1 qid:6 1:3 3:75 4:65 5:11 6:2 7:9
0 qid:6 1:4 3:20 4:65 5:113 6:2 7:10
2 qid:6 1:5 3:5 4:68 5:83 6:2 7:51
0 qid:6 1:6 3:20 4:65 5:116 6:2 7:3
1 qid:6 1:7 3:25 4:65

Is the ordering of the position relevance?
I know that for NDCG the position is important, how the position is taking into account in Xgboost implementation


text:
Q: NSCurrentLocaleDidChangeNotification in Swift 3? What's the Notification.Name equivalent for NSCurrentLocaleDidChangeNotification?

A: According to the NSLocale reference there is
class let currentLocaleDidChangeNotification: NSNotification.Name
// Notification that indicates that the user's locale changed.

which you can use as
let notification = NSLocale.currentLocaleDidChangeNotification


text:
Q: Getting error in indexeddbshim: DOM Exception 11: An attempt was made to use an object that is not, or is no longer, usable I'm using the IndexedDBShim polyfill for iOS 7.1 (so underlying is WebSQL) and when I try to run it, I get:
"InvalidStateError: DOM Exception 11: An attempt was made to use an object that is not, or is no longer, usable."

The code:
//Create and open the database
var request = indexedDB.open( "Videos", 1.1 );
var database;

request.onerror = function (event)
{
    console.log( "Unable to create storage for offline videos, an error occurred." );
    console.dir( event );
};

//On success we'll grab the database and store or load the videos
request.onsuccess = function (event)
{
    //Grab the database
    database = request.result;

    //Handle database error
    database.onerror = function (event)
    {
        console.log( "Unable to access storage, an error occurred." );
        console.dir( event );
    };

    downloadVideo();
}

//Create the database and object store
request.onupgradeneeded = function (event)
{
    //Create the video object store (event.target.result is the database)
    event.target.result.createObjectStore( "Videos" );
};

function downloadVideo()
{
    var blob;

    //Start the request
    var videoRequest = new XMLHttpRequest();

    //Get the Video file from the server.
    videoRequest.open( "GET", "videos/test.mp4", true );

    //It's a blob (for storing in database)
    videoRequest.responseType = "blob";

    //Listen for when it's done downloading the video data
    videoRequest.addEventListener(
        "load",
        function ()
        {
            //We got it
            if ( videoRequest.status === 200 )
            {
                //Get the data
                blob = videoRequest.response;

                //Start transaction for videos object store
                var transaction = database.transaction( [ "Videos" ], "readwrite" );

                //Store the video file
                var putRequest = transaction.objectStore( "Videos" ).put( blob, "savedVideo" );

                putRequest.onsuccess = function(e)
                {
                    console.log( "succes!" );
                    console.dir(e);
                }
            }

            //An error occurred
            else console.log( null, "Unable to save, as an error occurred." );
        },
        false
    );

    //Start the request
    videoRequest.send();
}

A: My first guess would be that you encounter this error because of how you are using the database variable. Try setting and opening the connection from within the body of the load callback, and then doing the database-related work within the body of the connection open callback.
Something like the following abbreviated code:
function downloadVideo(path) {
  console.log('Requesting video blob at %s', path);
  var vr = new XMLHttpRequest();
  vr.onload = onVideoDownload.bind(vr);
  vr.responseType = 'blob';
  vr.open('GET', path);
  vr.send();
}

function onVideoDownload(request) {
  console.log('Downloaded video blob, connecting to indexedDB');
  var video = request.response;
  var openRequest = indexedDB.open('Videos', 1);
  openRequest.onupgradeneeded = onUpgradeNeeded;
  openRequest.onsuccess = storeVideo.bind(openRequest, video);
}

function onUpgradeNeeded(event) {
  var database = event.target;
  database.createObjectStore('Videos');
}

function storeVideo(video, event) {
  console.log('Connected to indexedDB, storing a video');
  var database = event.target.result;
  var tx = database.transaction('Videos','readwrite');
  var videoStore = tx.objectStore('Videos');
  var putRequest = videoStore.put('blob', video);
  putRequest.onsuccess = onStoreVideo.bind(putRequest, video);
}

function onStoreVideo(video, event) {
  console.log('Successfully stored a video!');
}

downloadVideo('videos/test.mp4');

A: I was attempting to insert a blob into the database without encoding it in base64 first. As it was on iOS safari 7.1, the backing database is WebSQL which doesn't accept binary data.


text:
Q: iOS 15 Hiding navigation bar on landscape Before iOS 15, I was able to show the site fullscreen while scrolling down. This gesture hid the address and tabs bar (navigation bar) as showed on the gif bellow:

But something changed on iOS Safari and now this gesture doesn't hide it anymore:

I created a simple sandbox to demo this, using Material-UI (MUI) v5 with the CSS Baseline component
The code:
export default function Demo() {
  const [landscapeAvailableHeight, setLandscapeAvailableHeight] = useState(0);

  useEffect(() => {
    setLandscapeAvailableHeight(
      Math.min(window.screen.availHeight, window.screen.availWidth)
    );
  }, []);

  return (
    <Box
      sx={{
        backgroundColor: "tomato"
      }}
    >
      <Box
        sx={{
          backgroundColor: "green",
          display: "flex",
          alignItems: "center",
          justifyContent: "center",
          height: landscapeAvailableHeight + 1
        }}
      >
        landscapeAvailableHeight = {landscapeAvailableHeight}
      </Box>
    </Box>
  );
}

What am I missing here? Any suggestion/help is appreciated. Thanks!


text:
Q: embed video is always autoplaying I don't understand why my embedded is always auto playing.
<div id="body15">
    <video width="480" height="270" controls>
        <source src="videos/ryan1.ogg" type="video/ogg">
        <source src="videos/ryan1.mp4" type="video/mp4">
        <source src="videos/ryan1.webm" type="video/webm">
        <object data="videos/ryan1.mp4" width="480" height="270">
            <embed width="600" height="270" src="movie.swf">
        </object>
    </video>
</div>

A: Have you tried controls="controls"?
<video width="480" height="270" controls="controls">
    <source src="videos/ryan1.ogg" type="video/ogg">
    <source src="videos/ryan1.mp4" type="video/mp4">
    <source src="videos/ryan1.webm" type="video/webm">
    <object data="videos/ryan1.mp4" width="480" height="270">
        <embed width="600" height="270" src="movie.swf">
    </object>
</video>


text:
Q: How to add a blank caption for a figure in AsciiDoc I have an AsciiDoc page which has a number of images. I am converting this into html via antora.
On my AsciiDoc page, some of the images have a caption and some do not.
For the images with a caption, the first one is named "Figure 1. Some interesting caption", then the second one is named "Figure 2. Some fascinating caption" and so on. In fact, the "Figure 1", "Figure 2" text is added automatically by Antora. In AsciiDoc itself, the markup is as follows:
.Some interesting caption;

image::images/image1.png

.Some fascinating caption;

image::images/image2.png

However, now I have a third image which has no caption to display. I would like this image to simply read "Figure 3". However, I do not know how to do this. The only thing I could come up with is to put some character after the "." symbol just above it (I chose a semi-colon), as follows:
.;

image::images/image3.png

This produces "Figure 3;" once converted into html.
It's better than nothing, but I would like to be able to use, for example, a whitespace character, instead of the semi-colon, so that I could simply produce text that reads "Figure 3 " (with an invisible whitespace character that nobody can see). Unfortunately, if I try to do that, the whitespace is ignored and I just see the '.' character in the generated html.

A: You can use an attribute for the non-breaking space: {nbsp}
For example:
.Some interesting caption;
image::images/image1.png[]

.Some fascinating caption;
image::images/image2.png[]

.{nbsp}
image::images/image3.png[]

Note that I added square brackets to each image macro invocation, because those lines are just text with them. And, there doesn't need to be a blank line between the caption and its associated image.


text:
Q: Select middle value for nth rows in Python I am creating new dataframe which should contain an only middle value (not Median!!) for every nth rows, however my code doesn't work!
I've tried several approaches through pandas or simple Python but I always fail.
       value   date        index
   14  40      1983-07-15  14
   15  86      1983-07-16  15
   16  12      1983-07-17  16
   17  78      1983-07-18  17
   18  69      1983-07-19  18
   19  78      1983-07-20  19
   20  45      1983-07-21  20
   21  47      1983-07-22  21
   22  48      1983-07-23  22
   23  .....    .........  ..

   RSDF5 = RSDF4.groupby(pd.Grouper(freq='15D', key='DATE')).[int(len(RSDF5)//2)].reset_index()

I know that the code is wrong and I am completely out of ideas!
   SyntaxError: invalid syntax

A: A solution based on indexes.
df is your original dataframe, N is the number of rows you want to group (assumed to be ad odd number, so there is a unique middle row).
df2 = df.groupby(np.arange(len(df))//N).apply(lambda x : x.iloc[len(x)//2])

Be aware that if the total number or rows is not divisible by N, the last group is shorter (you still get its middle value, though).
If N is an even number, you get the central row closer to the end of the group: for example, if N=6, you get the 4th row of each group of 6 rows.


text:
Q: Is there a maximum limit to a python array? How to handle large data? I'm using a simple python array to store words fetched from a file.
words=[]
words.append(new_word)

This code snippet works perfectly for files with small word counts. However when running the script for larger files, it hangs after some time.(when the array length is around 111166 and the letter count inside the array is high)
Is there a maximum limit for a python array?
Is there a workaround to for this?
Thanks in advance.

A: sys.maxsize is the maximum indices that lists can have:

An integer giving the maximum value a variable of type
Py_ssize_t can take. It's usually 2**31 - 1 on a 32-bit platform and
2**63 - 1 on a 64-bit platform.

But apparently this shouldn't be your problem. There is something else going on with your code. sys.maxsize is much bigger than 111166.
.append() is also O(1) which doesn't slow your code. But when lists become larger than the place they have, new location in memory is allocated for them. This happens rarely.

A: You may consider using a database if your data gets too big.
a viable option is SQLite which is a simple file-based database.
First create a table for your words
try:
    connection = sqlite3.connect("database.db")
    cursor = connection.cursor()
    cursor.execute('''
        CREATE TABLE "words" (
            "id"    INTEGER,
            "word"  TEXT NOT NULL UNIQUE,
            PRIMARY KEY("id" AUTOINCREMENT)
        );
    ''')
except sqlite3.Error as error:
    print("Failed to execute the above query", error)
finally:
    if connection:
        connection.close()

Now you can start adding words to the table
my_word = cat

try:
    connection = sqlite3.connect("database.db")
    cursor = connection.cursor()
    cursor.execute("INSERT INTO words(word) VALUES(?)", [my_word])
except sqlite3.Error as error:
    print("Failed to execute the above query", error)
finally:
    if connection:
        connection.close()

Now to fetch the word from list do
search_word = "cat"

try:
    connection = sqlite3.connect("database.db")
    cursor = connection.cursor()
    cursor.execute("SELECT * FROM words WHERE word=?", [search_word])
    print(cursor.fetchall())
except sqlite3.Error as error:
    print("Failed to execute the above query", error)
finally:
    if connection:
        connection.close()

A: The issue occurred due to invalid character available in the file where the words are extracted. For more information about this issue read UnicodeDecodeError: 'charmap' codec can't decode byte X in position Y: character maps to <undefined>
Thank you everyone who helped in finding the root cause.


text:
Q: ActionReducer Array<> or not for RxJS reducer I want to figure the difference when we define state: IUser and state: Array<IUser>
I will elaborate more with the following lines of codes.
Can you point out the differences of declaring?
// in user.reducer.ts file

ActionReducer<IUser[]> = (state: Array<IUser> = [], action: Action): IUser[]

// in the store file
export interface IAppState {
  profile: IProfile;
  user: IUser[];
}

// all new reducers should be define here
const reducers = {
  profile: profileReducer,
  user: userReducer
};

VERSUS declaring:
ActionReducer<IUser> = (state: IUser, action: Action): IUser

// in the store.ts
export interface IAppState {
  profile: IProfile;
  user: IUser;
}

// all new reducers should be define here
const reducers = {
  profile: profileReducer,
  user: userReducer
};

FULL VERSIONS of the files:
import { Action, ActionReducer } from '@ngrx/store';
import { USER_LIST_GET, USER_LIST_GET_SUCCESS, USER_LIST_GET_FAIL } from './user.actions';

export interface IUser {
  UserList?: Array<{}>;
  UserListError: boolean;
  isFetching: false;
}

export const userReducer: ActionReducer<IUser[]> = (state: Array<IUser> = [], action: Action): IUser[] => {

  switch (action.type) {

    case USER_LIST_GET:

      return Object.assign({}, state, {
        isFetching: true,
        UserListError: false
      });

    case USER_LIST_GET_SUCCESS:

      return Object.assign({}, state, {
        isFetching: false,
        UserList: action.payload
      });

    case USER_LIST_GET_FAIL:

      return Object.assign({}, state, {
        isFetching: false,
        UserListError: true
      });

    default:
      return state;
  }
};

the store file
import { combineReducers, ActionReducer, Action, StoreModule } from '@ngrx/store';
import { EffectsModule } from '@ngrx/effects';
import { ModuleWithProviders, NgModule } from '@angular/core';
import { compose } from '@ngrx/core';
import { storeFreeze } from 'ngrx-store-freeze';
import { StoreDevtoolsModule } from '@ngrx/store-devtools';

import { CommonModule } from '@angular/common';

export interface IAppState {
  profile: IProfile;
  user: IUser[];
}

// all new reducers should be define here
const reducers = {
  profile: profileReducer,
  user: userReducer
};

...


text:
Q: Определить выигрышную стратегию для первого игрока подскажите, как можно ещё подойти к решению такой задачи.
Есть поле размером m×n, которое разделено на сектора размером 1×1.
В левом верхнем углу стоит фишка, которую игроки могут поочерёдно двигать либо на один сектор вниз, либо на один сектор вправо, либо на k секторов по диагонали. Ходить начинает первый.
Проигрывает игрок, который не может сделать ход, т.е. выиграет тот, кто первый поставит фишку в правый нижний угол.

Входные данные:
t - количество партий, в которые нужно сыграть, k - количество ходов по диагонали.(1≤ t ≤ 20; 1≤ k ≤10^9)
n, m - размер игрового поля. (1 ≤ n,m ≤ 10^9).

Выходные данные:
Вывести t-строк результатов игры. В случае, если первый игрок имеет выигрышную стратегию - выведите "+", иначе "-"(Без кавычек).

Как я рассуждал:
Замечу, что количество пройденных клеток, необходимое для победы одного из игроков,  константно и равно n+m - 2 .
Во вторых, я обратил внимание на чётность суммы сторон. Ситуация 1 : Если  сумма сторон чётна - по умолчанию первый игрок проиграет, если и первый и второй не смогут использовать хождение по диагонали. Ситуация 2 : Если сумма сторон нечётная - выигрывает первый игрок, опять же, если не будет ни у кого возможности ходить по диагонали. Другими словами, если k ≥ min(m,n). Если же у нас есть возможность хождения по диагонали, то каждый игрок может применить её в своих целях.
Например, в первой ситуации, если 1 игрок походит по диагонали, то он перетянет победу на себя. Иными словами, если максимальное количество шагов по диагонали (min(m,n) - 1) / k нечётное - у первого игрока есть шанс выиграть.
Во второй ситуации всё наоборот. Только если максимальное количество шагов по диагонали (min(m,n) - 1) / k чётное - у первого игрока есть шанс выиграть.
Мой код:
#include <iostream>

using namespace std;

int main()
{
    int times, k, size, min;
    cin >> times >> k;
    size = times * 2;
    int* arr = new int[size];
    for (int i = 0; i < size; i += 2)
    {
        cin >> arr[i] >> arr[i + 1];
    }

    for (int i = 0; i < size; i += 2)
    {
        arr[i] < arr[i + 1] ? min = arr[i] : min = arr[i + 1];
        if (!((arr[i] + arr[i + 1]) % 2))
        {
            if ((min - 1) / k % 2) cout << "+" << endl;
            else cout << "-" << endl;
        }
        else
        {
            if (k < min)
            {
                if (!((min - 1) / k % 2)) cout << "+" << endl;
                else cout << "-" << endl;
            }
            else cout << '+' << endl;
        }
    }
    return 0;
}

Буду рад любым советам!

A: Давайте сначала абстрагируемся от конкретной задачи и поговорим о теории игр.
В задаче приведен пример равноправной ацикличной игры. Ее прелесть заключается в том, что для любого состояния игры можно однозначно сказать, имеет ли текущий игрок выигрышную стратегию.
Если хотя бы один переход из данного состояния ведет в проигрышное состояние, то данное состояние называем выигрышным. И наоборот, если все переходы из данного состояния ведут в выигрышные, то назовем данное проигрышным. Учитывая, что мы знаем, какие состояния являются конечными и результаты игры в них, то мы можем вычислить функцию "выигрышности" для всех состояний, включая начальное.
Заметим, что в данной игре состояния задаются только положениями фишки, размерами поля и константой K. (На самом деле, состояния однозначно задаются даже только размерами поля, так как при каждом переходе мы фактически начинаем новую игру в левом верхнем секторе какого-то меньшего прямоугольника, сменив текущего игрока). Тогда можно для каждого сектора зафиксированного игрового поля вычислить функцию "выигрышности" по ее определению.
a[n][m] = 0
a[y][x] = !(a[y][x + 1] & a[y + 1][x] & a[y + k][x + k])

Но в данной задаче вычисление этой функции для всех состояний игры является невозможным за разумное время, поэтому игру нужно "хакнуть". Для этого я предлагаю вам написать программу, которая вычислит функцию "выигрышности" для каких-то небольших конкретных полей. (Например n = 20, m = 20, k = 3). Тогда хорошо присмотревшись к полученной матрице, вы сможете увидеть простые закономерности, которые вам лично даже не нужно доказывать, чтобы решить задачу - это проблема составителей задачи.
На всякий случай приведу тут набросанный код на питоне и его вывод для вышеприведенных чисел:
def print_m(a):
    for i in a:
        print(' '.join([str(j) for j in i]))

n, m = 20, 20
k = 3

a = [['-'] * m for _ in range(n)]

for y in range(n - k, n):
    for x in range(m):
        a[y][x] = (m - x + n - y) & 1
for y in range(n):
    for x in range(m - k, m):
        a[y][x] = (m - x + n - y) & 1

for y in range(n - k - 1, -1, -1):
    for x in range(m - k - 1, -1, -1):
        if a[y][x + 1] == 0 or a[y + 1][x] == 0 or a[y + k][x + k] == 0:
            a[y][x] = 1
        else:
            a[y][x] = 0

print_m(a)

1 1 0 1 1 0 1 0 1 1 0 1 1 0 1 0 1 1 0 1
1 0 1 0 1 1 0 1 1 0 1 0 1 1 0 1 1 0 1 0
0 1 0 1 1 0 1 0 1 1 0 1 1 0 1 0 1 1 0 1
1 0 1 0 1 1 0 1 1 0 1 0 1 1 0 1 1 0 1 0
1 1 1 1 1 0 1 0 1 1 0 1 1 0 1 0 1 1 0 1
0 1 0 1 0 1 0 1 1 0 1 0 1 1 0 1 1 0 1 0
1 0 1 0 1 0 1 0 1 1 0 1 1 0 1 0 1 1 0 1
0 1 0 1 0 1 0 1 1 0 1 0 1 1 0 1 1 0 1 0
1 1 1 1 1 1 1 1 1 1 0 1 1 0 1 0 1 1 0 1
1 0 1 0 1 0 1 0 1 0 1 0 1 1 0 1 1 0 1 0
0 1 0 1 0 1 0 1 0 1 0 1 1 0 1 0 1 1 0 1
1 0 1 0 1 0 1 0 1 0 1 0 1 1 0 1 1 0 1 0
1 1 1 1 1 1 1 1 1 1 1 1 1 0 1 0 1 1 0 1
0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 1 0 1 0
1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 1 0 1
0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 1 0 1 0
1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0 1
1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0
0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1
1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0

A: Обозначим:

*

*x, y - текущие координаты

*i - номер игрока

Тогда

*

*Если x<k || y<k, то просто проверяем чётность.

*Иначе если x==k || y==k, то точка (x, y) выигрышная.

*Иначе считаем следующее (все ходы возможны):
best
(
  (x+k, y+k, i^1)
  worst((x+k+1, y+k, i), (x+k+1, y+k-1, i))
  worst((x+k, y+k+1, i), (x+k-1, y+k+1, i))
)

Думаю, этих оптимизаций достаточно чтобы решить задачу рекурсивным алгоритмом с ленивой динамикой.
PS: Попозже объясню, как я это при думал.


text:
Q: Assign count() result to a column in PostgreSQL I want to know how to assign the result of the count function to a column in a table.
I have the following code:
UPDATE my_table
 SET column = count (*) FROM another_table

Obviously it doesn't work. I hope some of you guys could help me.
Greetings!


text:
Q: Unable to unzip files to a folder I am trying to unzip a .zip file, at a specified location. The user inputs the name of the file to be unzipped like "D:\\folder\\sample.zip". I am making use of zip headers and .cpp files from this link https://www.codeproject.com/articles/7530/zip-utils-clean-elegant-simple-c-win
Now below is my code
int main()
{
    char filename[100];
    HZIP hz; DWORD writ;
    printf("Enter filename: \n");
    gets(filename);
    TCHAR *name = (TCHAR *) filename;
    hz = OpenZip(name,0);
    SetUnzipBaseDir(hz,_T("D:\\unzipped\\"));
    ZIPENTRY ze;
    GetZipItem(hz,-1,&ze);
    int numitems=ze.index;
    for (int zi=0; zi<numitems; zi++)
    {
        GetZipItem(hz,zi,&ze);
        UnzipItem(hz,zi,ze.name);
    }
    CloseZip(hz);
    printf("Unzipped\n");
    return 0;
}

I need the filename to be taken as input from the user, for which I had to typecast it by using this statement
TCHAR *name = (TCHAR *) filename;

But this is the statement that is causing problems now. When I debugged the program and added watch to the variable 'name', I saw that after typecasting, it stored some Chinese letters, instead of the path of the zip file
Previously the code worked fine when instead of taking input from user, I hardcoded the path and file name as mentioned below
hz = OpenZip(_T("D:\\folder\\sample.zip"),0);

Any ideas what am I doing wrong?

A: The Windows file systems (NTFS, FAT32) encode file names in Unicode (UTF16). That is why the OpenZip API expect a wchar_t* (string of wide characters) as the file name parameter.
The C++ standard provides a wstring class similar to the ANSI string (or C string) that is supposed to contain Unicode characters, and a wcin and wcout streams for input/output in Unicode encoding.
wstring wfilename;
std::wcin >> wfilename;
OpenZip(wfilename.c_str(), 0); // c_str() retrives the wchar_t* in the buffer, much similarly to the ANSI `string.

EDIT:
Since you need to input into a C-style buffer, here is the easiest way to convert a C-style char[] to wstring and wchar_t[]:
char filename[100]; printf("Enter filename: \n");   cin >> filename;

// conversion
std::wstring wFilename(strlen(filename), L' ');
std::copy(filename, filename + wFilename.length(), wFilename.begin());

OpenZip(wFilename.c_str(), 0);


text:
Q: Can I use co-dependent features in a Random Forest? Let's say my features for a random forest are: x,y,z,x/y,x/z,y/z. These are obviously co-dependent. Now, when training a Random Forest (using sklearn for example), the minimization of the entropy assumes that the features are independent - as this makes the entropy derivation much simpler. Still, these models seems to work - am I missing something?

A: Following the discussion above with EngrStudent and others off this site, the conclusion is that we can use co-dependent features, because:

*

*Not all trees use entropy calculations

*Even those who do, do not necessarily derive it

So it seems as it makes sense, and even improves classification due to better feature engineering.


text:
Q: curl call works, but still returns "Could not resolve host: POST" I run following script in gitlab's job:
after-merge-to-release:
  script:
  - set -x
  - >
    curl\
      --X POST --header 'PRIVATE-TOKEN:xyz' --header 'Content-Type:application/json'\
      --data '{"id":"'$PROJECT_ID'","name":"'${MOST_RECENT_SPRINT_BRANCH//'origin/'/}'","allowed_to_push":[{"access_level":0}],"allowed_to_merge":[{"access_level":0}]}'\
      https://git.xyz.net/api/v4/projects/"$PROJECT_ID"/protected_branches

I can confirm this command works (it adds a new protected branch to my project), but gitlab's output doesn't confirm it:
$ curl\ # collapsed multi-line command
 ++ echo '$ curl\ # collapsed multi-line command'
 ++ curl --X POST --header PRIVATE-TOKEN:xyz --header Content-Type:application/json --data '{"id":"123","name":"origin/sprint/48","allowed_to_push":[{"access_level":0}],"allowed_to_merge":[{"access_level":0}]}' https://git.xyz.net/api/v4/projects/123/protected_branches
   % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                  Dload  Upload   Total   Spent    Left  Speed
   0     0    0     0    0     0      0      0 --:--:-- --:--:-- --:--:--     0curl: (6) Could not resolve host: POST
 100   530  100   413  100   117   3152    893 --:--:-- --:--:-- --:--:--  4045

Why it doesn't return the response from curl request and throws Could not resolve host: POST error?

A: The error is here:
--X POST

Use only a single dash before X to select the http method:
-X POST


text:
Q: Time dimension failed to follow extracted dates from imput individual pentad files names after merging them together I have multiple pentad netcdf (1482) files in a single directory with naming format precip_yyyymmd.nc (e.g., precip_2000061.nc). 'precip_' is common to all files in the directory as 'yyyy' indicate year, 'mm' indicate month and 'd' indicate number of pentad in the month mm. I only have six pentad in a single month and 247 months (from June 2000 to December 2020). I've been trying to merge all these file in the directory and I want the time dimension to contain the extracted dates (yyyy-mm-d) from all the files so that the will have 2000-06-01, 2000-06-02, 2000-06-3, 2000-06-3, 2000-06-4, 2000-06-5, 2000-06-6, 2000-07-01, 2000-07-02, 2000-07-03, 2000-07-04, 2000-07-05, 2000-07-06, 2000-08-01,...2020-12-06. My script worked to some extent but the date keeps overwriting one another. The time dimension only show dates instead of a total of 1482 dates as extracted from the files in the working directory
import xarray as xr
import os

# set the directory path where the files are stored
directory = '/home/wilson/Documents/PYTHON_TUTORIAL/Aggregated_Data_sum'

# get a list of all netCDF files in the directory
file_list = [f for f in os.listdir(directory) if f.endswith('.nc')]

# create an empty list to store the xarray datasets
datasets = []

# loop over each file in the file list
for file in file_list:
    # load the netCDF file into an xarray dataset
    ds = xr.open_dataset(os.path.join(directory, file))
    # extract the year, month, and pentad from the file name
    year=int(file[7:11])
    month=int(file[11:13])
    pentad=int(file[13:14])
    # add the year, month, and pentad as a combined time coordinate
    ds = ds.expand_dims(time=[f"{year:04d}-{month:02d}-pentad:02d}"])
    # append the dataset to the list
    datasets.append(ds)

# concatenate the list of datasets into a single xarray dataset along the 'time' dim
merged_ds = xr.concat(datasets, dim='time')

# sort the merged dataset by the 'time' dimension
merged_ds = merged_ds.sortby('time')

# save the merged dataset as a new netCDF file  merged_ds.to_netcdf(os.path.join(directory, f"merged_pentad.nc"))

print(ds) gives below information
<xarray.Dataset>
Dimensions:  (Lon: 40, Lat: 20, time: 1)
Coordinates:
  * time     (time) <U10 '2019-10-06'
  * Lon      (Lon) float64 -19.5 -18.5 -17.5 -16.5 -15.5 ... 16.5  17.5 18.5 19.5
  * Lat      (Lat) float64 0.5 1.5 2.5 3.5 4.5 5.5 ... 15.5 16.5 17.5 18.5 19.5
  Data variables:
     precip   (time, Lat, Lon) float32 nan nan nan nan nan ... 0.0 0.0 0.0 0.0

Image below is the screenshot of the sample of files I want to merge/concatenate
screenshot of the part of file in the working directory


text:
Q: nginx: mangento 2 instance redirects too many times I follow these 2 tutorials:
(install magento 2)
(install letsencrypt)
When I visit my magento instance. It said "redirects too many times"
Here is my nginx config
upstream fastcgi_backend {
  server unix:/run/php/php7.0-fpm.sock;
}

server {
  listen 80;
  listen [::]:80;

  server_name sub.site.com www.sub.site.com;
  return 301 https://$server_name$request_uri;

}

server {
  listen 443 ssl http2;
  listen [::]:443 ssl http2;
  include snippets/ssl-sub.site.com.conf;
  include snippets/ssl-params.conf;

 server_name server_name sub.site.com www.sub.site.com;
 set $MAGE_ROOT /home/sub_site/public_html;
 set $MAGE_MODE developer;
 include /home/sub_site/public_html/nginx.conf.sample;

 location ~ /.well-known {
   allow all;
  }

}

Update 1: include /home/sub_site/public_html/nginx.conf.sample;
## Example configuration:
# upstream fastcgi_backend {
#    # use tcp connection
#    # server  127.0.0.1:9000;
#    # or socket
#    server   unix:/var/run/php5-fpm.sock;
# }
# server {
#    listen 80;
#    server_name mage.dev;
#    set $MAGE_ROOT /var/www/magento2;
#    include /vagrant/magento2/nginx.conf.sample;
# }
#
## Optional override of deployment mode. We recommend you use the
## command 'bin/magento deploy:mode:set' to switch modes instead.
##
## set $MAGE_MODE default; # or production or developer
##
## If you set MAGE_MODE in server config, you must pass the variable into the
## PHP entry point blocks, which are indicated below. You can pass
## it in using:
##
## fastcgi_param  MAGE_MODE $MAGE_MODE;
##
## In production mode, you should uncomment the 'expires' directive in the /static/ location block

root $MAGE_ROOT/pub;

index index.php;
autoindex off;
charset UTF-8;
error_page 404 403 = /errors/404.php;
#add_header "X-UA-Compatible" "IE=Edge";

# PHP entry point for setup application
location ~* ^/setup($|/) {
    root $MAGE_ROOT;
    location ~ ^/setup/index.php {
        fastcgi_pass   fastcgi_backend;
        fastcgi_index  index.php;
        fastcgi_param  SCRIPT_FILENAME  $document_root$fastcgi_script_name;
        include        fastcgi_params;
    }

    location ~ ^/setup/(?!pub/). {
        deny all;
    }

    location ~ ^/setup/pub/ {
        add_header X-Frame-Options "SAMEORIGIN";
    }
}

# PHP entry point for update application
location ~* ^/update($|/) {
    root $MAGE_ROOT;

    location ~ ^/update/index.php {
        fastcgi_split_path_info ^(/update/index.php)(/.+)$;
        fastcgi_pass   fastcgi_backend;
        fastcgi_index  index.php;
        fastcgi_param  SCRIPT_FILENAME  $document_root$fastcgi_script_name;
        fastcgi_param  PATH_INFO        $fastcgi_path_info;
        include        fastcgi_params;
    }

    # Deny everything but index.php
    location ~ ^/update/(?!pub/). {
        deny all;
    }

    location ~ ^/update/pub/ {
        add_header X-Frame-Options "SAMEORIGIN";
    }
}

location / {
    try_files $uri $uri/ /index.php?$args;
}

location /pub/ {
    location ~ ^/pub/media/(downloadable|customer|import|theme_customization/.*\.xml) {
        deny all;
    }
    alias $MAGE_ROOT/pub/;
    add_header X-Frame-Options "SAMEORIGIN";
}

location /static/ {
    # Uncomment the following line in production mode
    # expires max;

    # Remove signature of the static files that is used to overcome the browser cache
    location ~ ^/static/version {
        rewrite ^/static/(version\d*/)?(.*)$ /static/$2 last;
    }

    location ~* \.(ico|jpg|jpeg|png|gif|svg|js|css|swf|eot|ttf|otf|woff|woff2)$ {
        add_header Cache-Control "public";
        add_header X-Frame-Options "SAMEORIGIN";
        expires +1y;

        if (!-f $request_filename) {
            rewrite ^/static/(version\d*/)?(.*)$ /static.php?resource=$2 last;
        }
    }
    location ~* \.(zip|gz|gzip|bz2|csv|xml)$ {
        add_header Cache-Control "no-store";
        add_header X-Frame-Options "SAMEORIGIN";
        expires    off;

        if (!-f $request_filename) {
           rewrite ^/static/(version\d*/)?(.*)$ /static.php?resource=$2 last;
        }
    }
    if (!-f $request_filename) {
        rewrite ^/static/(version\d*/)?(.*)$ /static.php?resource=$2 last;
    }
    add_header X-Frame-Options "SAMEORIGIN";
}

location /media/ {
    try_files $uri $uri/ /get.php?$args;

    location ~ ^/media/theme_customization/.*\.xml {
        deny all;
    }

    location ~* \.(ico|jpg|jpeg|png|gif|svg|js|css|swf|eot|ttf|otf|woff|woff2)$ {
        add_header Cache-Control "public";
        add_header X-Frame-Options "SAMEORIGIN";
        expires +1y;
        try_files $uri $uri/ /get.php?$args;
    }
    location ~* \.(zip|gz|gzip|bz2|csv|xml)$ {
        add_header Cache-Control "no-store";
        add_header X-Frame-Options "SAMEORIGIN";
        expires    off;
        try_files $uri $uri/ /get.php?$args;
    }
    add_header X-Frame-Options "SAMEORIGIN";
}

location /media/customer/ {
    deny all;
}

location /media/downloadable/ {
    deny all;
}

location /media/import/ {
    deny all;
}

# PHP entry point for main application
location ~ (index|get|static|report|404|503)\.php$ {
    try_files $uri =404;
    fastcgi_pass   fastcgi_backend;
    fastcgi_buffers 1024 4k;

    fastcgi_read_timeout 600s;
    fastcgi_connect_timeout 600s;

    fastcgi_index  index.php;
    fastcgi_param  SCRIPT_FILENAME  $document_root$fastcgi_script_name;
    include        fastcgi_params;
}

gzip on;
gzip_disable "msie6";

gzip_comp_level 6;
gzip_min_length 1100;
gzip_buffers 16 8k;
gzip_proxied any;
gzip_types
    text/plain
    text/css
    text/js
    text/xml
    text/javascript
    application/javascript
    application/x-javascript
    application/json
    application/xml
    application/xml+rss
    image/svg+xml;
gzip_vary on;

# Banned locations (only reached if the earlier PHP entry point regexes don't match)
location ~* (\.php$|\.htaccess$|\.git) {
    deny all;
}


text:
Q: i'm new in work with SQLite in android ,this is my function but that's dosent work public class Rating {

private String _id;
private String _rating;

public Rating(){
}

public Rating(String id, String ration){
    this._id = id;
    this._rating = ration;
 }

public Rating(String ration){
    this._rating= ration;
  }

public String getID(){
    return _id;
}
public void setID(String id){
    this._id = id;
}
 public String getRating(){
    return _rating;
}
public void setRating(String rating){
    this._rating= rating;
}
@Override
public String toString(){
    return _rating;
 }
 }

///////////////////////////////////////////////////
  public class DatabaseHandler extends SQLiteOpenHelper {

private static final int  DATABASE_VERSION = 1;
private static final String DATABASE_NAME ="ratings.db";

public static final String DATABASE_TABLE ="ratings";
public static final String COLUMN_ID = "id";
public static final String COLUMN_RATING = "rating";

private static final String DATABASE_CREATE = "create table "
        + DATABASE_TABLE + "(" +
        COLUMN_ID + " integer primary key autoincrement, " +
        COLUMN_RATING + " text not null);";

public DatabaseHandler(Context context) {
    super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
@Override
public void onCreate(SQLiteDatabase db) {
         db.execSQL(DATABASE_CREATE);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
           Log.w(DatabaseHandler.class.getName(),
            "Upgrading database from version " + oldVersion + " to "
                    + newVersion + ", which will destroy all old data");
    db.execSQL("DROP TABLE IF EXISTS " + DATABASE_TABLE);
    onCreate(db);
    }

///////////////////////////////////////////////////
  public class RatingDataSource {

private SQLiteDatabase database;
private DatabaseHandler dbHelper;
private String[] allColumns = { DatabaseHandler.COLUMN_ID,
        DatabaseHandler.COLUMN_RATING };

public RatingDataSource(Context context) {
    dbHelper = new DatabaseHandler(context);
}

public void open() throws SQLException {
    database = dbHelper.getWritableDatabase();
}

public void close() {
    dbHelper.close();
}

public void addRating(Rating rating) {
    SQLiteDatabase db=dbHelper.getWritableDatabase();
    ContentValues values=new ContentValues();
    values.put(DatabaseHandler.COLUMN_ID,rating.getID());
    values.put(DatabaseHandler.COLUMN_RATING, rating.getRating());
    database.insert(dbHelper.DATABASE_TABLE,null,values);
    db.insert(dbHelper.DATABASE_TABLE,null,values);
    db.close();
}
  public Rating getRating(String id)
{
    SQLiteDatabase db=dbHelper.getWritableDatabase();
    Cursor cursor=db.query(dbHelper.DATABASE_TABLE,new String[]{dbHelper.COLUMN_ID,dbHelper.COLUMN_RATING},dbHelper.COLUMN_ID +"=?" ,new String[]{String.valueOf(id)},null,null,null,null);
    if (cursor!=null)
     cursor.moveToFirst();
    Rating rating=new Rating((cursor.getString(0)),cursor.getString(1));
    return rating;
}
public void deleteRating(Rating rating) {
   SQLiteDatabase db=dbHelper.getReadableDatabase();
    db.delete(dbHelper.DATABASE_TABLE,dbHelper.COLUMN_ID+"?",new String[]{String.valueOf(rating.getID())});
    db.close();
}

public List<Rating> getAllRating()
{
    List<Rating> RatingList=new ArrayList<Rating>();
    Cursor cursor = database.query(DatabaseHandler.DATABASE_TABLE, allColumns, null, null, null, null, null);
    cursor.moveToFirst();
    while (!cursor.isAfterLast()) {
        Rating rating = cursorToRating(cursor);
        RatingList.add(rating);
        cursor.moveToNext();
    }
    cursor.close();
    return RatingList;
}
private Rating cursorToRating(Cursor cursor){
    Rating rating = new Rating();
    rating.setID(cursor.getString(0));
    rating.setRating(cursor.getString(1));
    return rating;
  }
 }

//////////////this is my error
03-04 10:59:47.473: INFO/ActivityManager(277): START u0 {cmp=com.example.sampleebook/.GhasidesingelItem (has extras)} from pid 4030
03-04 10:59:47.483: ERROR/libEGL(36): called unimplemented OpenGL ES API
03-04 10:59:47.483: ERROR/libEGL(36): called unimplemented OpenGL ES API
03-04 10:59:47.483: ERROR/libEGL(36): called unimplemented OpenGL ES API
03-04 10:59:47.483: ERROR/libEGL(36): called unimplemented OpenGL ES API
03-04 10:59:47.483: ERROR/libEGL(36): called unimplemented OpenGL ES API
03-04 10:59:47.483: ERROR/libEGL(36): called unimplemented OpenGL ES API
03-04 10:59:47.483: ERROR/libEGL(36): called unimplemented OpenGL ES API
03-04 10:59:47.483: ERROR/libEGL(36): called unimplemented OpenGL ES API
03-04 10:59:47.483: ERROR/libEGL(36): called unimplemented OpenGL ES API
03-04 10:59:47.483: ERROR/libEGL(36): called unimplemented OpenGL ES API
03-04 10:59:47.483: WARN/WindowManager(277): Failure taking screenshot for (246x410) to layer 21020
03-04 10:59:47.934: DEBUG/dalvikvm(4030): GC_CONCURRENT freed 270K, 7% free 5878K/6312K, paused 75ms+27ms, total 192ms
03-04 10:59:48.113: DEBUG/AndroidRuntime(4030): Shutting down VM
03-04 10:59:48.113: WARN/dalvikvm(4030): threadid=1: thread exiting with uncaught exception (group=0x40a71930)
03-04 10:59:48.173: ERROR/AndroidRuntime(4030): FATAL EXCEPTION: main
        java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.sampleebook/com.example.sampleebook.GhasidesingelItem}: android.database.CursorIndexOutOfBoundsException: Index 0 requested, with a size of 0
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2180)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2230)
        at android.app.ActivityThread.access$600(ActivityThread.java:141)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1234)
        at android.os.Handler.dispatchMessage(Handler.java:99)
        at android.os.Looper.loop(Looper.java:137)
        at android.app.ActivityThread.main(ActivityThread.java:5041)
        at java.lang.reflect.Method.invokeNative(Native Method)
        at java.lang.reflect.Method.invoke(Method.java:511)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
        at dalvik.system.NativeStart.main(Native Method)
        Caused by: android.database.CursorIndexOutOfBoundsException: Index 0 requested, with a size of 0
        at android.database.AbstractCursor.checkPosition(AbstractCursor.java:424)
        at android.database.AbstractWindowedCursor.checkPosition(AbstractWindowedCursor.java:136)
        at android.database.AbstractWindowedCursor.getString(AbstractWindowedCursor.java:50)
        at com.example.sampleebook.RatingDataSource.getRating(RatingDataSource.java:46)
        at com.example.sampleebook.GhasidesingelItem.onCreate(GhasidesingelItem.java:81)
        at android.app.Activity.performCreate(Activity.java:5104)
        at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1080)
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2144)
        ... 11 more
03-04 10:59:48.263: WARN/ActivityManager(277): Force finishing activity com.example.sampleebook/.GhasidesingelItem
03-04 10:59:48.273: WARN/ActivityManager(277): Force finishing activity com.example.sampleebook/.Ghasideh
03-04 10:59:48.643: INFO/Choreographer(277): Skipped 49 frames!  The application may be doing too much work on its main thread.
03-04 10:59:48.643: ERROR/SurfaceFlinger(36): ro.sf.lcd_density must be defined as a build property
03-04 10:59:48.783: WARN/ActivityManager(277): Activity pause timeout for ActivityRecord{410dc930 u0 com.example.sampleebook/.GhasidesingelItem}
03-04 10:59:57.523: WARN/ActivityManager(277): Launch timeout has expired, giving up wake lock!
03-04 10:59:57.523: WARN/ActivityManager(277): Activity idle timeout for ActivityRecord{410dc930 u0 com.example.sampleebook/.GhasidesingelItem}
03-04 10:59:58.857: WARN/ActivityManager(277): Activity idle timeout for ActivityRecord{40f7c650 u0 com.example.sampleebook/.MyActivity}
03-04 11:00:07.615: WARN/ActivityManager(277): Activity destroy timeout for ActivityRecord{4108c680 u0 com.example.sampleebook/.Ghasideh}
03-04 11:00:07.615: WARN/ActivityManager(277): Activity destroy timeout for ActivityRecord{410dc930 u0 com.example.sampleebook/.GhasidesingelItem}
03-04 11:00:23.171: DEBUG/ExchangeService(670): Received deviceId from Email app: null
03-04 11:00:23.171: DEBUG/ExchangeService(670): !!! deviceId unknown; stopping self and retrying
03-04 11:00:28.223: DEBUG/ExchangeService(670): !!! EAS ExchangeService, onStartCommand, startingUp = false, running = false
03-04 11:00:28.233: WARN/ActivityManager(277): Unable to start service Intent { act=com.android.email.ACCOUNT_INTENT } U=0: not found
03-04 11:00:28.233: DEBUG/ExchangeService(670): !!! Email application not found; stopping self
03-04 11:00:28.254: WARN/ActivityManager(277): Unable to start service Intent { act=com.android.email.ACCOUNT_INTENT } U=0: not found
03-04 11:00:28.254: ERROR/ActivityThread(670): Service com.android.exchange.ExchangeService has leaked ServiceConnection com.android.emailcommon.service.ServiceProxy$ProxyConnection@40d3ebb8 that was originally bound here
        android.app.ServiceConnectionLeaked: Service com.android.exchange.ExchangeService has leaked ServiceConnection com.android.emailcommon.service.ServiceProxy$ProxyConnection@40d3ebb8 that was originally bound here
        at android.app.LoadedApk$ServiceDispatcher.<init>(LoadedApk.java:969)
        at android.app.LoadedApk.getServiceDispatcher(LoadedApk.java:863)
        at android.app.ContextImpl.bindService(ContextImpl.java:1418)
        at android.app.ContextImpl.bindService(ContextImpl.java:1407)
        at android.content.ContextWrapper.bindService(ContextWrapper.java:473)
        at com.android.emailcommon.service.ServiceProxy.setTask(ServiceProxy.java:157)
        at com.android.emailcommon.service.ServiceProxy.setTask(ServiceProxy.java:145)
        at com.android.emailcommon.service.ServiceProxy.test(ServiceProxy.java:191)
        at com.android.exchange.ExchangeService$7.run(ExchangeService.java:1850)
        at com.android.emailcommon.utility.Utility$2.doInBackground(Utility.java:551)
        at com.android.emailcommon.utility.Utility$2.doInBackground(Utility.java:549)
        at android.os.AsyncTask$2.call(AsyncTask.java:287)
        at java.util.concurrent.FutureTask.run(FutureTask.java:234)
        at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1080)
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:573)
        at java.lang.Thread.run(Thread.java:856)
03-04 11:00:28.264: ERROR/StrictMode(670): null
        android.app.ServiceConnectionLeaked: Service com.android.exchange.ExchangeService has leaked ServiceConnection com.android.emailcommon.service.ServiceProxy$ProxyConnection@40d3ebb8 that was originally bound here
        at android.app.LoadedApk$ServiceDispatcher.<init>(LoadedApk.java:969)
        at android.app.LoadedApk.getServiceDispatcher(LoadedApk.java:863)
        at android.app.ContextImpl.bindService(ContextImpl.java:1418)
        at android.app.ContextImpl.bindService(ContextImpl.java:1407)
        at android.content.ContextWrapper.bindService(ContextWrapper.java:473)
        at com.android.emailcommon.service.ServiceProxy.setTask(ServiceProxy.java:157)
        at com.android.emailcommon.service.ServiceProxy.setTask(ServiceProxy.java:145)
        at com.android.emailcommon.service.ServiceProxy.test(ServiceProxy.java:191)
        at com.android.exchange.ExchangeService$7.run(ExchangeService.java:1850)
        at com.android.emailcommon.utility.Utility$2.doInBackground(Utility.java:551)
        at com.android.emailcommon.utility.Utility$2.doInBackground(Utility.java:549)
        at android.os.AsyncTask$2.call(AsyncTask.java:287)
        at java.util.concurrent.FutureTask.run(FutureTask.java:234)
        at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1080)
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:573)
        at java.lang.Thread.run(Thread.java:856)
03-04 11:00:28.274: WARN/ActivityManager(277): Unbind failed: could not find connection for android.os.BinderProxy@4109ae40
03-04 11:00:28.274: ERROR/ActivityThread(670): Service com.android.exchange.ExchangeService has leaked ServiceConnection com.android.emailcommon.service.ServiceProxy$ProxyConnection@40cf11b8 that was originally bound here
        android.app.ServiceConnectionLeaked: Service com.android.exchange.ExchangeService has leaked ServiceConnection com.android.emailcommon.service.ServiceProxy$ProxyConnection@40cf11b8 that was originally bound here
        at android.app.LoadedApk$ServiceDispatcher.<init>(LoadedApk.java:969)
        at android.app.LoadedApk.getServiceDispatcher(LoadedApk.java:863)
        at android.app.ContextImpl.bindService(ContextImpl.java:1418)
        at android.app.ContextImpl.bindService(ContextImpl.java:1407)
        at android.content.ContextWrapper.bindService(ContextWrapper.java:473)
        at com.android.emailcommon.service.ServiceProxy.setTask(ServiceProxy.java:157)
        at com.android.emailcommon.service.ServiceProxy.setTask(ServiceProxy.java:145)
        at com.android.emailcommon.service.AccountServiceProxy.getDeviceId(AccountServiceProxy.java:116)
        at com.android.exchange.ExchangeService.getDeviceId(ExchangeService.java:1249)
        at com.android.exchange.ExchangeService$7.run(ExchangeService.java:1856)
        at com.android.emailcommon.utility.Utility$2.doInBackground(Utility.java:551)
        at com.android.emailcommon.utility.Utility$2.doInBackground(Utility.java:549)
        at android.os.AsyncTask$2.call(AsyncTask.java:287)
        at java.util.concurrent.FutureTask.run(FutureTask.java:234)
        at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1080)
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:573)
        at java.lang.Thread.run(Thread.java:856)
03-04 11:00:28.294: ERROR/StrictMode(670): null
        android.app.ServiceConnectionLeaked: Service com.android.exchange.ExchangeService has leaked ServiceConnection com.android.emailcommon.service.ServiceProxy$ProxyConnection@40cf11b8 that was originally bound here
        at android.app.LoadedApk$ServiceDispatcher.<init>(LoadedApk.java:969)
        at android.app.LoadedApk.getServiceDispatcher(LoadedApk.java:863)
        at android.app.ContextImpl.bindService(ContextImpl.java:1418)
        at android.app.ContextImpl.bindService(ContextImpl.java:1407)
        at android.content.ContextWrapper.bindService(ContextWrapper.java:473)
        at com.android.emailcommon.service.ServiceProxy.setTask(ServiceProxy.java:157)
        at com.android.emailcommon.service.ServiceProxy.setTask(ServiceProxy.java:145)
        at com.android.emailcommon.service.AccountServiceProxy.getDeviceId(AccountServiceProxy.java:116)
        at com.android.exchange.ExchangeService.getDeviceId(ExchangeService.java:1249)
        at com.android.exchange.ExchangeService$7.run(ExchangeService.java:1856)
        at com.android.emailcommon.utility.Utility$2.doInBackground(Utility.java:551)
        at com.android.emailcommon.utility.Utility$2.doInBackground(Utility.java:549)
        at android.os.AsyncTask$2.call(AsyncTask.java:287)
        at java.util.concurrent.FutureTask.run(FutureTask.java:234)
        at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1080)
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:573)
        at java.lang.Thread.run(Thread.java:856)
03-04 11:00:28.294: WARN/ActivityManager(277): Unbind failed: could not find connection for android.os.BinderProxy@41067308
03-04 11:00:40.103: WARN/ProcessStats(277): Skipping unknown process pid 4067

A: if (cursor!=null)
 cursor.moveToFirst();
Rating rating=new Rating((cursor.getString(0)),cursor.getString(1));
return rating;

Turn it to:
Rating rating = null;
if (cursor.moveToFirst()) {
    rating = new Rating((cursor.getString(0)),cursor.getString(1));
}
cursor.close();
return rating;


text:
Q: How to convert a list of string into a list of dictionary? I have to generate a list of dictionary of key, value pair from a list of string. For example I have a list as such
my_list = ["John","Google","yes","Sara","TCS","no","John","facebook","yes"]

I want the output as follow:

[
{"name":"John","company":"Google","avaiable":"yes"},
{"name":"Sara","company":"TCS","avaiable":"No"},
{"name":"John","company":"facebook","avaiable":"yes"},

]

A: You can loop through the list. You can step the variable inside your loop (that is going to be 'i' below) by 3.
my_new_list = []
for i in range(0, len(my_list), 3):
    my_dict = {}
    my_dict['name'] = my_list[i]
    my_dict['company'] = my_list[i+1]
    my_dict['available'] = my_list[i+2]
    my_new_list.append(my_dict)

A: Below Code Snippet should do it for you. The idea here is to figure out the length of the list and use list comprehension to build a dictionary of lists. The assumptions are:

*

*List Length is a multiple of 3

*All items are in the order as expected by your output format

my_list = ["John", "Google", "yes", "Sara", "TCS", "no", "John", "facebook", "yes"]
list_len = len(my_list)
dictionary_list = [
    {"name": my_list[i], "company": my_list[i + 1], "available": my_list[i + 2]}
    for i in range(0, list_len, 3)
]
print("dictionary list = %s" % (dictionary_list))

Output:
[{'available': 'yes', 'company': 'Google', 'name': 'John'}, {'available': 'no', 'company': 'TCS', 'name': 'Sara'}, {'available': 'yes', 'company': 'facebook', 'name': 'John'}]

A: [
    {"name": item[0], "company": item[1], "available": item[2]}
    for item in [my_list[i : i + 3] for i in range(0, len(my_list), 3)]
]


text:
Q: Brosershot PDF not loading external images and styles when run on a queue Problem
I have an issue with generating PDFs via Browsershot on a queue. The PDFs do not load any images or stylesheets for some reason however, when generating the same PDF via a browser request the images and stylesheets are loaded as expected.
I suspect the issue is related to the paths used for the images and styles, but I'm not sure beyond that.
The first image shows the expected output, and the second shows what the actual output looks like.

Tried so far

*

*Checked the queue is configured properly

*Checked for queue errors

*Checked the css/js resources exist on the server

*Tried various config settings for Browsershot

Browsershot code
$content = view('site-report.cover-template', ['site' => $this->site])->render();

Browsershot::html($content)
  ->waitUntilNetworkIdle()
  ->noSandbox()
  ->ignoreHttpsErrors()
  ->setNodeBinary('/usr/bin/node')
  ->setNpmBinary('/usr/bin/npm')
  ->margins(0, 2, 0, 2)
  ->format('A4')
  ->noSandbox()
  ->setOption('args', ['--disable-web-security'])
  ->showBackground()
  ->waitUntilNetworkIdle()
  ->save($targetFullPath);

PDF Blade layout
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="csrf-token" content="{{ csrf_token() }}">

    <title>{{ config('app.name', 'Laravel') }}</title>

    <!-- Fonts -->
    <link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Nunito:wght@400;600;700&display=swap">

    <!-- Styles -->
    <link rel="stylesheet" href="{{ asset('css/pdf.css') }}">

    <!-- Scripts -->
    <script src="{{ asset('js/app.js') }}"></script>
</head>

[program:test_worker]
command=/RunCloud/Packages/php81rc/bin/php  /RunCloud/Packages/php81rc/bin/php /server/path/laravel/artisan queue:work database --queue=default --sleep=3 --tries=3 --timeout=1000000
redirect_stderr=true
autostart=true
autorestart=true
user=runcloud
numprocs=2
directory=/
process_name=%(program_name)s_%(process_num)s
null

Any help would be much appreciated!


text:
Q: Let $f:\mathbb R \to \mathbb R$ be continuous. Then which of the following statements implies that $f(0)=0$?
Let $f:\mathbb R \to \mathbb R$ be continuous. Then which of the
  following statements implies that $f(0)=0$?
(A)$\lim_{n \to \infty}\int_{0}^{1}f(x)^n dx=0.$
(B)$\lim_{n \to \infty}\int_{0}^{1}f(x/n) dx=0.$
(C)$\lim_{n \to \infty}\int_{0}^{1}f(nx) dx=0.$
(D) None of the above.

(A)Suppose $f(x)=1-x, \int_{0}^{1}(1-x)^n dx=-\frac{1}{n+1},$ which converges to zero. I tried to find the counter example for the (B) and (C). I couldn't find. please help me.

A: B ) $0=\lim_{n\to \infty} \int_0^1f(\frac{x}{n})\, dx\\=\lim_{n\to \infty} f(\frac{c}{n})(1-0)  for \, some \, c\in (0,1)\\= \lim_{n\to \infty}f(\frac{c}{n})\\= f(0) \, since \, f \, is \, continuous .
$

A: (A) Consider the constant function $f(x) = 1/2$.
(B) $\int_0^1 f(x/n)\, dx = n \int_0^{1/n} f(y)\, dy \to f(0)$ (by the mean value theorem), hence condition (B) implies $f(0) = 0$.
(C) Consider $f(x) = \cos(2\pi x)$.


text:
Q: Scrolling when idle? Can anyone point me to an example of code for a page that begins to automatically scroll when the user is idle for an amount of time? I think this is slightly beyond my skill set. I think JQuery or something similar might be appropriate but I just can't seem to figure it out. I'm designing a site for the nonprofit I work for and we don't have the money to hire a programmer. I wouldn't ask anyone to code anything for me, just to point me in the right direction. Thank you so much.
Julie K.

A: Here is something quick and dirty that will do what you want.  I currently have it set to 2 seconds idle time, but you can change that as you wish.
var now = new Date();
setInterval(function(){
    var nnow = new Date();
    if(nnow.getTime() - now.getTime() >= 2000)
        $('body').animate({scrollTop: '+=50'}, 2000, 'linear');
    }, 2000);
$(document)
    .mousemove(function(){ now = new Date(); $('body').stop(); })
    .keypress(function(){ now = new Date(); $('body').stop(); });

Edit: added .stop in mousemove and keypress events to stop scrolling immediately when user moves mouse or presses a key, rather than waiting for animation to complete.

A: jQuery would definitely help here.
You should handle the keyboard and mouse events to catch user activity.
Then, whenever you see activity, call setTimeout to make your code run 2 minutes after the activity.  Save the return value of the setTimeout call in a global variable, and call clearTimeout on it before setTimeout to clear the last timeout.
For example: (Using jQuery and the scrollTo plugin)
var timeout = false;
$(document.body).bind('keydown keyup mousemove mouseup', function() {
    if (timeout) clearTimeout(timeout);
    timeout = setTimeout(userIsIdle, 120000);    //120,000 milliseconds
});
function userIsIdle() {
    $(document.body).scrollTo('100%', 100000);
}

A: you could use a plugin like this, and set it to use JavaScripts setTimeout() function to trigger it, which could reset every time you detect certain user actions, such as keyDown and Click.

A: First you have to define what you mean by IDLE, I will assume that the user is not moving mouse for x amount of time.
Here are the steps pseudo js.
 var lastTime=0;
var threshold=60000 ; // 1min
var howOftenToCheck = 1000;//1 sec
var inter = 0;
inter = setInterval(function() {
    var delta=lastTime-currentTime;
    if(delta>threashold){
        clearInterval(inter);
        window.scrollTo(xpos,ypos);
    }
}, howOftenToCheck);

This should give you a general idea.

A: I think onBlur event is what you're looking for, so you can do like this :
<body onblur="$('html, body').animate({scrollTop:0}, 'slow');">

You can change the 0 to the vertical position where you want to scroll to.
Note: this will fire the scrolling when you go to other page or tab or where you can't see the page.

A: use the following jQuery functions to scroll the page's body
// Scrolling Down
$('body').animate({
scrollTop: '-=300px'
}, 2000);

// Scrolling Up
$('body').animate({
scrollTop: '+=300px'
}, 2000);


text:
Q: Windows Installer XML(WIX) removing files after i uninstall a patch and install it again I have an Installer Built using Wix Toolset. I have Created a small Framework that generates patch by using pyro tool, I donot want my Installer to Delete Files on Un-install so i marked all Components as Permanent="yes" property. I created a patch that Removes a file by Marking the Component condition as Permanent="no" and by Condition as FALSE FALSE please find the code below

  FALSE

When I install the Patch its not Removing the above file, but if i Uninstall the above patch and install it again its removing the file and working as Expected..Is it Removing the Permanent=yes attribute on First Install and so am able to remove the file on next Install?


text:
Q: MYSQL Combing Two tables From Multiple Row I have two tables, one is for all products, the other is for new purchases products.
Product Table
Item    Qty
301       2
302       5
303       3
304       4
305       6

Purchases Table
Item     Qty    Status    Date
302       5     used      09-15-2015
303       5     reserve   09-20-2015
301       5     used      09-20-2015
302       5     reserve   09-20-2015
304       5     used      10-15-2015
303       5     reserve   10-15-2015

I want to display how many quantity in the product table, and join the quantity of purchases table to Product Table
This is my initial sql query
SELECT product_name, product_quantity, quantity
FROM products
    LEFT OUTER JOIN purchases ON products.ID = purchases.product_ID
WHERE product_status !='deleted' AND status != 'used'`.

However, it only returned the the items from purchases table that is reserve.
what I want to achieve is
Item    Qty    Reserved Qty    Total
301       2     0                 2
302       5     5                 10
303       3     10                13
304       4     0                 4
305       6     0                 6

UPDATE
New sql query
SELECT product_name, product_quantity, p.quantity
FROM products
    LEFT OUTER JOIN (SELECT * FROM purchases
        WHERE status = 'reserved'
        GROUP BY product_ID) AS  p ON p.product_ID = products.ID
WHERE products.product_status !='deleted'`

But it returns 0 on reserved qty.

A: You are almost there in terms of your query except that you need to sum the quantity of reserved items and then use GROUP BY, sort of like this
SELECT
    pd.item AS 'Item', pd.qty AS 'Qty', IFNULL(pr.reserved_quantity, 0) AS 'Reserved Qty', (pd.qty+IFNULL(pr.reserved_quantity, 0)) AS 'Total'
FROM
    product pd
    LEFT OUTER JOIN (SELECT item, SUM(qty) AS 'reserved_quantity' FROM purchases WHERE `status`='reserve' GROUP BY 1) AS pr ON pd.item=pr.item


text:
Q: Matching inner code regardless of any wrapping text If I have a string like:
[code]var foo = {
    bar: 'bar',
    baz: 'baz'
};[/code]

I can use /^(?:\[code\])?([\s\S]*?)(?:\[\/code\])?$/i to get the inner text (between the [code] and [/code]) regardless if it is surrounded with the code tags.
What I'd like to do is to allow the beginning and end tags to be a little more fuzzy. I'm getting this text by user selection of the inner code and therefor the selection may not be perfect, the selection may be into the code tags. The selection may be something like:
ode]var foo = {
    bar: 'bar',
    baz: 'baz'
};[/co

but I still only want the inner code. What's the best way to match the code tags in a way that it'll match even if not all there?

A: You can use just the brackets instead the full tag, like this:
\]([\s\S]*?)\[\/

Working demo


text:
Q: Joining on row if not exists I have a table containing data by year and week. I'd like to select everything from that table that is in a subset of years and months, and rows with default values wherever that week/year combo isn't found.
Here's a test script:
--create test table and insert data
CREATE TABLE [dbo].[TestPD](
    [id] [int] NOT NULL,
    [year] [int] NOT NULL,
    [week] [int] NOT NULL,
    [name] [varchar](50) NOT NULL,
    [item] [int] NOT NULL,
) ON [PRIMARY]

GO
INSERT [dbo].[TestPD] ([id], [year], [week], [name], [item]) VALUES (1, 2013, 15, N'bob', 5)
INSERT [dbo].[TestPD] ([id], [year], [week], [name], [item]) VALUES (1, 2014, 15, N'bob', 4)
INSERT [dbo].[TestPD] ([id], [year], [week], [name], [item]) VALUES (2, 2013, 15, N'joe', 3)
INSERT [dbo].[TestPD] ([id], [year], [week], [name], [item]) VALUES (3, 2014, 15, N'rick', 2)
INSERT [dbo].[TestPD] ([id], [year], [week], [name], [item]) VALUES (1, 2012, 15, N'rick', 1)
GO

--LookupDates contains the year/week combos to extract from the table
WITH LookupDates AS (
    SELECT DATEPART(YEAR, GETDATE()) AS [LookupYear], DATEPART(WEEK, GETDATE()) as [LookupWeek]
    UNION
    SELECT DATEPART(YEAR, GETDATE()) - 1, DATEPART(WEEK, GETDATE())
)
--what I tried (doesn't return "blank" rows)
SELECT t1.[LookupYear], t1.[LookupWeek], ISNULL(id, 0), ISNULL(Name, 'not found'), ISNULL(item, 0)
FROM LookupDates as t1 LEFT JOIN TESTPD as t2 on t1.LookupYear = t2.[year] and t1.LookupWeek = t2.[Week]

What I'd like is data that looks like this (a row for every id/year/month) combo regardless of whether or not it exists in the TestPD table: (rows with 0 values for item do not actually exist, they've just been added in with the default value).

id          year        week        name      item
----------- ----------- ----------- --------- -----------
1           2013        1           bob       5
1           2014        1           bob       4
2           2013        1           joe       3
2           2014        1           joe       0
3           2013        1           rick      0
3           2014        1           rick      2

How can I achieve this? I don't have to use a CTE, I just decided it was the best way to hold the years/weeks I need data for.

A: Edited following comments.
You need to cross join with the ids to get what you want. Here's one way to do, but that's they key.
--create test table and insert data
CREATE TABLE [dbo].[TestPD](
    [id] [int] NOT NULL,
    [year] [int] NOT NULL,
    [week] [int] NOT NULL,
    [name] [varchar](50) NOT NULL,
    [item] [int] NOT NULL,
) ON [PRIMARY]

GO
INSERT [dbo].[TestPD] ([id], [year], [week], [name], [item]) VALUES (1, 2013, 15, N'bob', 5)
INSERT [dbo].[TestPD] ([id], [year], [week], [name], [item]) VALUES (1, 2014, 15, N'bob', 4)
INSERT [dbo].[TestPD] ([id], [year], [week], [name], [item]) VALUES (2, 2013, 15, N'joe', 3)
INSERT [dbo].[TestPD] ([id], [year], [week], [name], [item]) VALUES (3, 2014, 15, N'rick', 2)
INSERT [dbo].[TestPD] ([id], [year], [week], [name], [item]) VALUES (1, 2012, 15, N'rick', 1)
GO

--LookupDates contains the year/week combos to extract from the table
;WITH LookupDates AS (
    SELECT DATEPART(YEAR, GETDATE()) AS [LookupYear], DATEPART(WEEK, GETDATE()) as [LookupWeek]
    UNION
    SELECT DATEPART(YEAR, GETDATE()) - 1, DATEPART(WEEK, GETDATE())
)
,UserDates AS (
    SELECT  *
      FROM LookupDates
           CROSS JOIN
           (SELECT id FROM TESTPD GROUP BY id) a
)
SELECT t1.LookupYear
     , t1.LookupWeek
     , ISNULL(t2.id, 0) id
     , ISNULL(Name, 'not found') Name
     , ISNULL(item, 0) Item
FROM UserDates as t1
     LEFT JOIN
     TESTPD as t2 on t1.LookupYear = t2.[year]
                 and t1.LookupWeek = t2.[Week]
                 and t1.id = t2.id

LookupYear  LookupWeek  id          Name                                               Item
----------- ----------- ----------- -------------------------------------------------- -----------
2013        15          1           bob                                                5
2013        15          2           joe                                                3
2013        15          0           not found                                          0
2014        15          1           bob                                                4
2014        15          0           not found                                          0
2014        15          3           rick                                               2

A: WITH LookupDates AS (
    SELECT DATEPART(YEAR, GETDATE()) AS [LookupYear], DATEPART(WEEK, GETDATE()) as [LookupWeek]
    UNION
    SELECT DATEPART(YEAR, GETDATE()) - 1, DATEPART(WEEK, GETDATE())
)

--this will return "blank" rows
SELECT t1.[LookupYear], t1.[LookupWeek], id, Name, item
FROM LookupDates as t1
JOIN TESTPD as t2 on t1.LookupYear = t2.[year] and t1.LookupWeek = t2.[Week]

UNION ALL

SELECT t1.[LookupYear], t1.[LookupWeek], id, 'Not Found', item
FROM LookupDates AS t1
CROSS JOIN TESTPD AS t2
WHERE NOT EXISTS (SELECT 1
FROM TESTPD t3
WHERE t3.ID = T2.ID
AND t3.item = T2.item
AND t3.[year] = t1.[LookupYear]
and t3.[Week] = t1.[LookupWeek])
ORDER BY 1, 2, 3, 4