text:
Q: No mostrar registros dónde la suma de una columna sea 0 Hola estoy realizando un procedure para mostrar la relación de ventas por marca, tengo lo siguiente:
DECLARE @fechaInicial DATETIME = '01/01/2019'
DECLARE @fechaFinal DATETIME = '31/01/2019'
DECLARE @id_municipio DECIMAL(18,0) = NULL
DECLARE @id_marca DECIMAL(18,0) = NULL
BEGIN

    SET @fechainicial = @fechainicial+' 00:00:00'
    SET @fechafinal = @fechafinal+' 23:59:59'
    SET NOCOUNT ON;

    CREATE TABLE #ConjuntosDatos(
        valor DECIMAL(18,0),
        id_marca DECIMAL(18,0),
        id_municipio DECIMAL(18,0)
    )

    insert into #ConjuntosDatos
            SELECT DISTINCT F.valor,a.id_marca, F.id_municipio
            FROM factura F
            INNER JOIN detalle_factura df ON df.id_factura = F.id_factura
            INNER JOIN articulo a ON a.articuloid = df.articuloid
            WHERE F.fecha >= @fechaInicial and F.fecha <= @fechaFinal
            AND ((@id_municipio IS NULL) OR (f.id_municipio = @id_municipio))
            AND ((@id_marca IS NULL) OR (a.id_marca = @id_marca))
END
        BEGIN

        SELECT m.nombre as marca,
            (select isnull(SUM(valor),0) from #ConjuntosDatos where id_marca = m.id_marca and id_municipio =1048) as Arauca,
            (select isnull(SUM(valor),0) from #ConjuntosDatos where id_marca = m.id_marca and id_municipio =1049) as Arauquita,
            (select isnull(SUM(valor),0) from #ConjuntosDatos where id_marca = m.id_marca and id_municipio =1051) as Fortul,
            (select isnull(SUM(valor),0) from #ConjuntosDatos where id_marca = m.id_marca and id_municipio =1052) as PtoRondon,
            (select isnull(SUM(valor),0) from #ConjuntosDatos where id_marca = m.id_marca and id_municipio =1053) as Saravena,
            (select isnull(SUM(valor),0) from #ConjuntosDatos where id_marca = m.id_marca and id_municipio =1054) as Tame,
            (select isnull(SUM(valor),0) from #ConjuntosDatos where id_marca = m.id_marca and id_municipio =1125) as PtoJordan,
            (select isnull(SUM(valor),0) from #ConjuntosDatos where id_marca = m.id_marca) Total
         FROM marca m
         DROP TABLE #ConjuntosDatos
END

de mi query anterior obtengo los siguientes registros

lo que pretendo realizar es que las filas cuyos campo total sea igual a cero no se muestren. Que puedo hacer para lograr esto
Ejemplo: El item: 6, 7, 17, 18, 19, 20 no se mostrarian ya que el total es cero

A: Básicamente tienes dos formas:
1. Usando una subconsulta
SELECT  *
        FROM (SELECT    m.nombre as marca,
                        (select isnull(SUM(valor),0) from #ConjuntosDatos where id_marca = m.id_marca and id_municipio =1048) as Arauca,
                        (select isnull(SUM(valor),0) from #ConjuntosDatos where id_marca = m.id_marca and id_municipio =1049) as Arauquita,
                        (select isnull(SUM(valor),0) from #ConjuntosDatos where id_marca = m.id_marca and id_municipio =1051) as Fortul,
                        (select isnull(SUM(valor),0) from #ConjuntosDatos where id_marca = m.id_marca and id_municipio =1052) as PtoRondon,
                        (select isnull(SUM(valor),0) from #ConjuntosDatos where id_marca = m.id_marca and id_municipio =1053) as Saravena,
                        (select isnull(SUM(valor),0) from #ConjuntosDatos where id_marca = m.id_marca and id_municipio =1054) as Tame,
                        (select isnull(SUM(valor),0) from #ConjuntosDatos where id_marca = m.id_marca and id_municipio =1125) as PtoJordan,
                        (select isnull(SUM(valor),0) from #ConjuntosDatos where id_marca = m.id_marca) Total
                    FROM marca m
            ) T
            WHERE T.Total <> 0

Tu consulta final la puedes escribir dentro de otro FROM por lo que puedes acceder a las columnas calculadas como Total de forma transparente.
2. Usando un GROUP BY
SELECT  m.nombre as marca,
        SUM(ISNULL(CASE WHEN id_municipio = 1048 THEN d.valor ELSE 0 END, 0))   AS  Arauca,
        SUM(ISNULL(CASE WHEN id_municipio = 1049 THEN d.valor ELSE 0 END, 0))   AS  Arauquita,
        SUM(ISNULL(CASE WHEN id_municipio = 1051 THEN d.valor ELSE 0 END, 0))   AS  Fortul,
        SUM(ISNULL(CASE WHEN id_municipio = 1052 THEN d.valor ELSE 0 END, 0))   AS  PtoRondon,
        SUM(ISNULL(CASE WHEN id_municipio = 1053 THEN d.valor ELSE 0 END, 0))   AS  Saravena,
        SUM(ISNULL(CASE WHEN id_municipio = 1054 THEN d.valor ELSE 0 END, 0))   AS  Tame,
        SUM(ISNULL(CASE WHEN id_municipio = 1125 THEN d.valor ELSE 0 END, 0))   AS  PtoJordan,
        SUM(ISNULL(d.valor,0))                                                  AS  Total

        FROM marca m
        LEFT JOIN #ConjuntosDatos d
            on d.id_marca = m.id_marca
        GROUP BY m.nombre
        HAVING SUM(ISNULL(d.valor,0)) <> 0

Esta solución es mucho más óptima, por que dejamos de usar subconsultas a nivel de columnas, algo que no suele ser del todo óptimo. La diferencia con tu consulta es que usamos una suma condicional de acuerdo al municipio y el filtro final hay que implementarlo mediante el HAVING ya que el total es un SUM del GROUP BY.

A: Has probado algo así como:
where total<>0


text:
Q: Changing package content in batch I would like to know if it's safe to do batch operations in a list of package files, applying a function like this:
SetAttributes[packStringReplace,HoldRest]
packStringReplace[packPath_String,{replaceRule__}]:=Module[{pack},
    pack=Import[packPath,"Text"];
    pack=StringReplace[pack,{replaceRule}];
    Export[packPath,pack,"Text"]
]

packs=FileNames["*.m","/packageDirectory",∞];
packStringReplace[#,{"text1"->"text2","text3"->"text4"}]&/@packs

Can Import and Export change something inside pack in some unexpected way? It's safe? Or should I use ImportString or another Import equivalent? If yes, why?
Update
As pointed by @AlbertRetey in the comments, it's safer do use:
Export[packname,pack,"Text",CharacterEncoding->"ASCII"]
instead of
Export[packPath,pack,"Text"]

redpajama_set_name: RedPajamaStackExchange


text:
Q: How can I detect if camera is restricted by user I'm doing an ios app with a button that launch the camera.
I want to enable/disable the button if the device has a camera available or not.
I want to detect if the device has a camera and also when the device has camera but it's restricted (with this) so you can't use it.
How can I detect these two options?
Thanks

A: To check whether camera restricted AVAuthorizationStatus is not enough. As said in documentation:

This status is normally not visible—the AVCaptureDevice class methods for discovering devices do not return devices the user is restricted from accessing.

So for proper check you need to create some capture device, for example, as I did:
AVAuthorizationStatus authStatus = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo];
if (authStatus == AVAuthorizationStatusAuthorized) {
    BOOL atLeastOne = NO;
    NSArray *devices = [AVCaptureDevice devicesWithMediaType:AVMediaTypeVideo];
    for (AVCaptureDevice *device in devices) {
        if (device) {
            atLeastOne = YES;
        }
    }
    if (!atLeastOne) {
        authStatus = AVAuthorizationStatusRestricted;
    }
}

A: The first time the user tries to use to camera on ios 6 he/she is automatically asked for permission. You don't have to add extra code (before that the authorisationstatus is ALAuthorizationStatusNotDetermined ).
So if user denies the first time you cannot ask again.
You can use ALAssetsLibrary to check this.
Check this answer for this solutions :
ask-permission-to-access-camera
Hope it helps you.

A: To check camera permission status in app use following snippet.
@import AVFoundation;

if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera])
 {
  AVAuthorizationStatus status = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo];

  if(status == AVAuthorizationStatusAuthorized) {
    // authorized
  } else if(status == AVAuthorizationStatusDenied){
    // denied
  } else if(status == AVAuthorizationStatusRestricted){
    // restricted
  } else if(status == AVAuthorizationStatusNotDetermined){
      // not determined
      [AVCaptureDevice requestAccessForMediaType:AVMediaTypeVideo completionHandler:^(BOOL granted) {
          if(granted){
            NSLog(@"Granted access");
          } else {
            NSLog(@"Not granted access");
          }
      }];
   }
}

A: To decide if the camera button should even be enabled (or hidden)You should check the:
    if UIImagePickerController.isSourceTypeAvailable(.Camera){ }

But then I would check to see if the user allowed access to camera as apple suggests in their PhotoPicker example (PhotoPicker example Objective-C):
*please note you have to import AVFoundation
SWIFT 5
    let authStatus = AVCaptureDevice.authorizationStatus(for: AVMediaType.video)
    switch authStatus {
        /*
         Status Restricted -
         The client is not authorized to access the hardware for the media type. The user cannot change the client's status, possibly due to active restrictions such as parental controls being in place.
         */
    case .denied, .restricted:
        // Denied access to camera
        // Explain that we need camera access and how to change it.
        let dialog = UIAlertController(title: "Unable to access the Camera", message: "To enable access, go to Settings > Privacy > Camera and turn on Camera access for this app.", preferredStyle: UIAlertController.Style.alert)

        let okAction = UIAlertAction(title: "OK", style: UIAlertAction.Style.default, handler: nil)

        dialog.addAction(okAction)
        self.present(dialog, animated:true, completion:nil)
    case .notDetermined:
        // The user has not yet been presented with the option to grant access to the camera hardware.
        // Ask for it.
        AVCaptureDevice.requestAccess(for: AVMediaType.video, completionHandler: { (grantd) in
        // If access was denied, we do not set the setup error message since access was just denied.
           if grantd {
           // Allowed access to camera, go ahead and present the UIImagePickerController.
            self.showImagePickerForSourceType(sourceType: UIImagePickerController.SourceType.camera)
            }
        })
    case .authorized:
        // Allowed access to camera, go ahead and present the UIImagePickerController.
        self.showImagePickerForSourceType(sourceType: UIImagePickerController.SourceType.camera)
    @unknown default:
        break; //handle other status
    }

SWIFT 3
let authStatus = AVCaptureDevice.authorizationStatus(forMediaType: AVMediaTypeVideo)

if authStatus == AVAuthorizationStatus.denied {
    // Denied access to camera
    // Explain that we need camera access and how to change it.
    let dialog = UIAlertController(title: "Unable to access the Camera", message: "To enable access, go to Settings > Privacy > Camera and turn on Camera access for this app.", preferredStyle: UIAlertControllerStyle.alert)

    let okAction = UIAlertAction(title: "OK", style: UIAlertActionStyle.default, handler: nil)

    dialog.addAction(okAction)
    self.present(dialog, animated:true, completion:nil)

} else if authStatus == AVAuthorizationStatus.notDetermined {     // The user has not yet been presented with the option to grant access to the camera hardware.
    // Ask for it.
    AVCaptureDevice.requestAccess(forMediaType: AVMediaTypeVideo, completionHandler: { (grantd) in
    // If access was denied, we do not set the setup error message since access was just denied.
       if grantd {
       // Allowed access to camera, go ahead and present the UIImagePickerController.
            self.showImagePickerForSourceType(sourceType: UIImagePickerControllerSourceType.camera)
        }
    })
} else {

    // Allowed access to camera, go ahead and present the UIImagePickerController.
    self.showImagePickerForSourceType(sourceType: UIImagePickerControllerSourceType.camera)

}

func showImagePickerForSourceType(sourceType: UIImagePickerControllerSourceType) {

    let myPickerController = UIImagePickerController()
    myPickerController.delegate = self;
    myPickerController.sourceType = sourceType
    self.present(myPickerController, animated: true, completion: nil)
}

A: As stated elsewhere, checking the AVAuthorizationStatus won't actually tell you if it's restricted, despite the presence of a "restricted" value in the enum.
Instead, I have found that checking if source is enabled to be helpful:
BOOL isCameraAvailable = [UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera];

If isCameraAvailable is NO then the user has most likely disabled camera in Restrictions. See Detect existence of camera in iPhone app?


text:
Q: Save Pandas or Pyspark dataframe from Databricks to Azure Blob Storage Is there a way I can save a Pyspark or Pandas dataframe from Databricks to a blob storage without mounting or installing libraries?
I was able to achieve this after mounting the storage container into Databricks and using the library com.crealytics.spark.excel, but I was wondering if I can do the same without the library or without mounting because I will be working on clusters without these 2 permissions.

A: Here the code for saving the dataframe locally to dbfs.
# export
from os import path

folder = "export"
name = "export"
file_path_name_on_dbfs = path.join("/tmp", folder, name)

# Writing to DBFS
# .coalesce(1) used to generate only 1 file, if the dataframe is too big this won't work so you'll have multiple files qnd you need to copy them later one by one
sampleDF \
  .coalesce(1) \
      .write \
      .mode("overwrite") \
      .option("header", "true") \
      .option("delimiter", ";") \
      .option("encoding", "UTF-8") \
      .csv(file_path_name_on_dbfs)

# path of destination, which will be sent to az storage
dest = file_path_name_on_dbfs + ".csv"

# Renaming part-000...csv to our file name
target_file = list(filter(lambda file: file.name.startswith("part-00000"), dbutils.fs.ls(file_path_name_on_dbfs)))
if len(target_file) > 0:
  dbutils.fs.mv(target_file[0].path, dest)
  dbutils.fs.cp(dest, f"file://{dest}") # this line is added for community edition only cause /dbfs is not recognized, so we copy the file locally
  dbutils.fs.rm(file_path_name_on_dbfs,True)

The code that will send the file into az storage :
import requests

sas="YOUR_SAS_TOKEN_PREVIOUSLY_CREATED" # follow the link below to create SAS token (using sas is slightly more secure than raw key storage)
blob_account_name = "YOUR_BLOB_ACCOUNT_NAME"
container = "YOUR_CONTAINER_NAME"
destination_path_w_name = "export/export.csv"
url = f"https://{blob_account_name}.blob.core.windows.net/{container}/{destination_path_w_name}?{sas}"

# here we read the content of our previously exported df -> csv
# if you are not on community edition you might want to use /dbfs + dest
payload=open(dest).read()

headers = {
  'x-ms-blob-type': 'BlockBlob',
  'Content-Type': 'text/csv' # you can change the content type according to your needs
}

response = requests.request("PUT", url, headers=headers, data=payload)

# if response.status_code is 201 it means your file was created successfully
print(response.status_code)

Follow this link to setup a SAS token
Remember that anyone who got the sas token can access your storage depending on permissions you set while creating the sas token
Code for Excel export version (using com.crealytics:spark-excel_2.12:0.14.0)
Saving the dataframe :
data = [
 ('a',25,'ast'),
 ('b',15,'phone'),
 ('c',32,'dlp'),
 ('d',45,'rare'),
 ('e',60,'phq' )
      ]
colums = ["column1" ,"column2" ,"column3"]
sampleDF = spark.createDataFrame(data=data, schema = colums)
sampleDF.show()

# export
from os import path
folder = "export"
name = "export"
file_path_name_on_dbfs = path.join("/tmp", folder, name)

# Writing to DBFS
sampleDF.write.format("com.crealytics.spark.excel")\
  .option("header", "true")\
  .mode("overwrite")\
  .save(file_path_name_on_dbfs + ".xlsx")

# excel
dest = file_path_name_on_dbfs + ".xlsx"
dbutils.fs.cp(dest, f"file://{dest}") # this line is added for community edition only cause /dbfs is not recognized, so we copy the file locally

Uploading the file to azure storage :
import requests

sas="YOUR_SAS_TOKEN_PREVIOUSLY_CREATED" # follow the link below to create SAS token (using sas is slightly more secure than raw key storage)
blob_account_name = "YOUR_BLOB_ACCOUNT_NAME"
container = "YOUR_CONTAINER_NAME"
destination_path_w_name = "export/export.xlsx"
# destination_path_w_name = "export/export.csv"
url = f"https://{blob_account_name}.blob.core.windows.net/{container}/{destination_path_w_name}?{sas}"

# here we read the content of our previously exported df -> csv
# if you are not on community edition you might want to use /dbfs + dest
# payload=open(dest).read()
payload=open(dest, 'rb').read()

headers = {
  'x-ms-blob-type': 'BlockBlob',
#   'Content-Type': 'text/csv'
   'Content-Type': 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
}

response = requests.request("PUT", url, headers=headers, data=payload)

# if response.status_code is 201 it means your file was created successfully
print(response.status_code)


text:
Q: Arithmetic with short and byte primitives and compilation While I have been studying for my OCA exam I came across something in Java that got me thinking "Why is this acceptable?".
This is not acceptable for the compiler.
short shortX = 1;
short shortY = 1;
short shortZ = shortX + shortY; //Compiler error

Although this is.
short shortZ = (short)1 + (short)1;

To me, they both seem exactly the same. My theory is that shortX and shortY are literals defined as an int just stored in a short variable, while casting directly tells the compiler the literal is a short, making it acceptable.
I would understand if the equation result was casted but it isn't, just the literals are. Does anyone have some clarification to soothe my inner curiosity?

A: Here any direct arithmetic summation of variable will result in integer because compiler will not be 100% sure that it will fit in short size because variable assignment will be done at run times so it will not allowed you to assign to your short variable so your first case will give compilation error, while in your second case you are directly using 1 which is like fixed and sure to have range of short , so even if you not cast it will work fine


text:
Q: Proving $\int_{-\infty}^{\infty} f = \lim_{a\to\infty}\int_{-a}^a f$ I have to show that

Let $f$ be locally integrable and nonnegative on $(-\infty, \infty)$. Then $$\int_{-\infty}^{\infty} f = \lim_{a\to\infty}\int_{-a}^a f$$

The integral here is improper Riemman integral.
I think the fact that $\int_{-a}^a$ is monotone increasing as $a$ goes to infinity could be a key to solution.
However, I have trouble defining what $\int_{-\infty}^{\infty} f$ is. (It was just given in the problem.)
Could anyone help please?


text:
Q: Index error in code to show image random without repetion I am trying to display a series of images randomly but I want to avoid repeating the images.
The code below works on startup but there comes a time when the following error simply appears:
pop index out of range
sufijos_png = list(range(1, 10+1))

def vars_for_template(self):
    n_img = random.choice(sufijos_png)
    self.player.n_loteria = n_img
    sufijos_png.pop(n_img-1)
    return dict(
        image_path='dict/G{}.png'.format(n_img)
    )´

Anyone have any idea how to fix this error?

A: .pop() actually returns and removes the last element of the list sufijos_png, so with the logic above, it's possible that at some point it will try to remove the element at index n_img-1 from the list sufijos_png, which doesn't exist anymore. To demonstrate, let's take the example you gave:
sufijos_png = list(range(1, 10+1))
sufijos_png

[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

Notice that len(sufijos_png) = 10. Now, the first time we randomly choose a value from sufijos_png. Let's say that value is 9, so
n_img = random.choice(sufijos_png)
n_img
9

Then we pop (+ return) the value at position n_img-1 = 9-1 = 8 of sufijos_png.
sufijos_png.pop(n_img-1) # pops value at index position 8
sufijos_png
[1, 2, 3, 4, 5, 6, 7, 8, 10]

Now, imagine the next random draw from sufijos_png is equal to 10 (it's one of the values still remaining there). However, the length of sufijos_png is now 9, so the index range is 0-8. Therefore the following will raise an IndexError:
n_img = random.choice(sufijos_png)
n_img
10 # one of the remaining possible values in sufijos_png

sufijos_png.pop(n_img-1) # pops value at index position 10, which doesn't exist

IndexError: pop index out of range

One way to overcome this problem, assuming that you just need a random number that doesn't repeat itself to assign to self.player.n_loteria = n_img, is to generate a list of digits/values, then shuffle them, and then keep popping from this randomly ordered list. For example:
import random
sufijos_png = list(range(1, 10+1))
random.shuffle(sufijos_png) # just need to shuffle once

def vars_for_template(self):
    n_img = sufijos_png.pop() # every time you accessing, you're depleting the list
    self.player.n_loteria = n_img
    return dict(
        image_path='dict/G{}.png'.format(n_img)
    )


text:
Q: Can $e^{k \cdot \pi}$ be algebraic for any real algebraic number $k \neq 0$? Specifically, I am trying to solve for t in the following system of constraints :

*

*$e^{(a + \iota b) t} = r$, and

*$e^{(a - \iota b) t} = s$, and

*$t > 0$

where $a$ and $b$ are known to be real algebraic numbers, and $r$ and $s$ are known to be rational numbers.
One can conclude (by dividing the LHS and RHS of 1. and 2., and because $r\cdot s > 0$).
that $r = s$, and that $2bt = 2n\pi$ for some integer $n$.
This means that $e^{\frac{a}{b}n\pi} = r$.
I wish to characterize the cases when this can happen.
EDIT : I see that $a = 0$ (and hence $r = 1$) is one possibility (in which case there are many possible values of $t$, one for each $n \in \mathbb{Z}$).
Are there other possibilities ?

A: $e^{\pi}$ is a trascendental number by the Gelfond-Schneider theorem, and $e^{k\pi}=(e^{i\pi})^{-ik}$ is a trascendental number for any algebraic $k\neq 0$.


text:
Q: Inducitve Proximity Sensor - Safety Gate Latch Codes? If I am using an inductive proximity sensors as a safety gate latch, what codes and standards do I need to abide by?
Some safety sensors I research have:
 - Category 3 (EN ISO 13849)
 - Safety integrity level (SIL2, SILCL2)
 - EN ISO 14119
How do I figure out for a given application, what safety integrity level, category, performance level..etc I require for my application?
Edit: We are trying to follow NFPA70, 33, and CSA

A:
If I am using an inductive proximity sensors as a safety gate latch ...
... when the metal door opens the inductive proximity sensor will trigger.

I'm concerned that you may not understand the potential failure modes.

Safety integrity level (SIL) is defined as a relative level of risk-reduction provided by a safety function, or to specify a target level of risk reduction. In simple terms, SIL is a measurement of performance required for a safety instrumented function (SIF). Source: Safety integrity level.

You need to perform a risk analysis based on

*

*Severity of possible injury.

*Frequency of exposure.

*Likelihood of avoidance.

That will determine the SIL required.
In general, an inductive proximity switch would not be suitable. You can't predict its failure mode - open-circuit or short-circuit and therefore you can't guarantee that it will switch off the hazard when "triggered" - whatever that means.
Instead, the SIL will require that the switch output turns off when the guard is opened - either by forced disconnection of the switch contacts or by some other means. If there is a risk of permanent or "non-reversible" injury or death the system will require redundant or dual-channel safety with a safety controller that will guarantee that a fault on one channel is detected and will not reset until the fault is cleared.
Your question and comments suggest that you are going to use a prox switch to detect opening of the gate. Instead your safety must prove that the safety gate is closed before energising the circuit.


text:
Q: Low quality with Glide When I use Glide to put and image inside an ImageView and then I "zoom in" (with a function that I bound to my ImageView), I see that the image has a low quality.
I already read Glide documentation but I'm not able to solve the problem.
Note: I use Glide inside a ViewPager.
This is what I did following the documentation
  Glide
        .with(context)
        .loadFromMediaStore(uri)
        .dontAnimate()
        .diskCacheStrategy(DiskCacheStrategy.SOURCE)
        .into(imageView);

This is the Manifest.xml
<manifest ...>
    <application...>
        <meta-data android:name="come.package.glide.MyGlideConfiguration"
            android:value="GlideModule"/>
    </application>
</manifest >

This is my GlideConfiguration
public class GlideConfiguration implements GlideModule {
    @Override
    public void applyOptions(Context context, GlideBuilder builder) {
        // Apply options to the builder here.
        builder.setDecodeFormat(DecodeFormat.PREFER_ARGB_8888);
    }

    @Override
    public void registerComponents(Context context, Glide glide) {
        // register ModelLoaders here.
    }
}

I also tried doing just
Glide
    .with(context)
    .loadFromMediaStore(uri).asBitmap().format(DecodeFormat.ALWAYS_ARGB_8888)

But the quality is always low.
Does anybody see where is my error??

A: Instead of calling
.diskCacheStrategy(DiskCacheStrategy.SOURCE)
try
.diskCacheStrategy(DiskCacheStrategy.RESOURCE)


text:
Q: Настройка SVN и виртуального хоста под Ubuntu 14.04 Проблема с настройкой SVN и хоста
Репозиторий лежит в /var/svn/arm и подтягивается с удаленного
Настройка хоста:
<VirtualHost *:80>

  ServerName svn.example.com

  <Location />
    DAV svn
    SVNPathAuthz off
    SVNPath /var/svn/arm
  </Location>

</VirtualHost>

Содержимое директории:

Вот что отображается при обращению к хосту:

Почему пустота, как правильно настроить, что бы отобразилось хоть что-то, а не чистый экран с непонятной надписью?
Новый конфиг:
<VirtualHost *:80>

    ServerName arm.local

    DocumentRoot "/var/svn"

    <Location />
        DAV svn
        SVNPathAuthz off
        SVNParentPath "/var/svn"
    </Location>

</VirtualHost>

http://localhost/arm - Not Found
http://arm.local/ - Forbidden

A: во-первых, надо включить соответствующий модуль (после чего надо перезапустить apache):
$ sudo a2enmod dav_svn

во-вторых, я думаю, сто́ит указать и documentroot. примерно так:
...
  ServerName svn.example.com

  documentroot /var/svn

  <Location />
...

и я бы порекомендовал изменить svnpath на svnparentpath (эти директивы нельзя использовать одновременно). тогда можно будет размещать несколько репозиториев в каталоге /var/svn:
svnparentpath /var/svn

A: Проблема в том, что /var/svn/arm в том виде, как на скриншоте - не чистый репозиторий, а нормальное дерево репозитория + куча мусора, к репо отношения не имеющая и оттого не показываемая. А репозиторий (который физически вовсе не копия дерева в рабочей копии) - свежесозданный пустой

подтягивается с удаленного

вообще не комментирую - я не переводчик и не доктор. Жаргон профессиональный знать надо, а не изобретать свой
На будущее, с опережением: крайне не рекомендуется <Location /> для SVN во избежание массы проблем в процессе - чистый HTTP отдельным деревом и SVN отдельно живет гораздо увереннее (только если у тебя хост не выделен весь полностью под SVN)


text:
Q: Update duplicate rows for logical deletion in MYSQL I've seen a few other posts about deleting/updating duplicate rows, but I was a little confused about how to correctly apply it to my specific predicament.
Was hoping someone could give me a push in the right direction.
I have a table with some duplicate rows on it and would like to logically delete them for each user by setting the isdeleted column to 1.
My table has a primary key called Id that is an unsigned bigint, and it has a column called cid which represents another id that is duplicated. cid is not unique from user to user, but it should be unique for a specific user.
For example you could see this in my table:
id | cid | userid | is_deleted
1  | 1   | 100    | 0
2  | 2   | 101    | 0
3  | 1   | 102    | 0
4  | 1   | 100    | 0
5  | 2   | 101    | 0

So in this case, user#100 has two CIDs that are the same - on record #1 and record #4. Similarly, user#101 has two CID's that are the same - on record #2 and record #5
What I'd like to do is just take the duplicate CIDs for a given user and set is_deleted to 1, rather than purge the actual row.  I'd want to preserve one record as is_deleted = 0 so this way something is retained.
So an output I'd be hoping for is:
id | cid | userid | is_deleted
1  | 1   | 100    | 0
2  | 2   | 101    | 0
3  | 1   | 102    | 0
4  | 1   | 100    | 1
5  | 2   | 101    | 1

I can do this in code but it would be rather involved, and I've seen some amazing responses for pure SQL statements; would anyone be able to give some advice or offer a solution?
Thanks so much!

A: You can use following query to update 1 row out of N repeated entries,
Update table t
inner join
(select id from table group by userid,cid having count(1)>1) t1
on t1.id = t.id
set t.is_deleted=1;


text:
Q: UIView-layer addAnimation:forKey: Since the value of forKey is a NSString, where do I find a complete list of all possible value in the Apple documentation? Thanks

A: The method addAnimation:forKey: doesn't do what you think it does.
The second string parameter is an arbitrary user-defined string to associate with the animation object. The purpose of this parameter is for accessing the animation object at a later time with the animationForKey: method.
The list of animatable properties provided above/below is pertinent to the keyPath property of a CABasicAnimation instance.

A: List of animatable properties of CALayer:
http://developer.apple.com/library/ios/#DOCUMENTATION/Cocoa/Conceptual/CoreAnimation_guide/Articles/AnimProps.html#//apple_ref/doc/uid/TP40005942-SW1
and/or here
http://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/CoreAnimation_guide/Articles/AnimProps.html#//apple_ref/doc/uid/TP40005942-SW1


text:
Q: Add empty string to first argument of parseInt I'm just trying to understand how JS currying works. While I was looking for it I found a related example:
var add = function (orig) {
  var inner = function (val) {
    return add(parseInt(val+'', 10) == val ? inner.captured+val : inner.captured);
  };
  inner.captured = orig;
  inner.valueOf = function () {return inner.captured;};

  return inner;
};

What the point to add an empty string to the first argument in a parseInt
method?
I think it also can be related to the valueOf

A: val+'' converts expression to string.
Quick test to show what's going on:
typeof(1)
"number" // value is 1 (number)
typeof(1+'')
"string" // now value is "1" (a string)

what is the purpose of making it a string?

The purpose could be to avoid native code to call abstract ToString method to convert first argument of parseInt to string.
We can read in MDN that first argument to parseInt is string with following description:

The value to parse. If string is not a string, then it is converted to
  a string (using the ToString abstract operation). Leading whitespace
  in the string is ignored.

A: To explain we can re-write part of the code:
return add(parseInt(val+'', 10) == val ? inner.captured+val : inner.captured);

// could be written like:

if ( parseInt(val+'', 10) == val ) {
    return inner.captured+val
}
else {
    return inner.captured;
}

// Looking at:
parseInt(val+'', 10) == val
// we're checking if the number at base 10 is equal to itself
// parseInt takes a string as it's first parameter, hence
// the type-casting with +''.
// This step could probably be ignored as the docs say that the number is
// cast to a string automatically, however for completeness we might
// choose to manually cast it.

parseInt docs


text:
Q: adding ad to app deletee its content-android I added adsense to my app. Tha problem is that I only see the ad without the original content of the activity. What could be the reason?
This is the activity:
package com.example.newpingpong;
import com.google.ads.*;

import com.google.ads.AdRequest;
import com.google.ads.AdSize;
import com.google.ads.AdView;

import android.os.Bundle;

import android.preference.PreferenceManager;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.view.Menu;
import android.view.MenuItem;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.TableLayout;
import android.widget.TextView;
import android.widget.Toast;
import android.support.v4.app.NavUtils;
import android.view.View;

public class Grid extends Activity {

    private AdView adView;
    public Intent intent;

    SharedPreferences preferences;
    int level_int;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_grid);

        //for ad: + manifest + above import and change in properties+lib +java class or in the layout
        // Look up the AdView as a resource and load a request.
        AdView adView = (AdView)this.findViewById(R.id.adView);
        adView.loadAd(new AdRequest());

        Const.isLevelEVERCompleted = new boolean[Const.LevelsAmount];
        for(int i=0 ; i< Const.LevelsAmount ; i++){
            Const.isLevelEVERCompleted[i] = false;
        }

    }

    @Override
    public void onResume()
    {
        preferences=PreferenceManager.getDefaultSharedPreferences(this);

         Const.isAllLevelsComplete = true;
        for(int i=0 ; i< Const.LevelsAmount ; i++){
            //int j=i+1;
            if(preferences.getInt("level"+i, Const.NOT_STARTED) == Const.NOT_STARTED){
                Const.isLevelEVERCompleted[i] = false;
                Const.isAllLevelsComplete = false;
            }
            else
                Const.isLevelEVERCompleted[i] = true;
        }

        TextView editText3 = (TextView) findViewById(R.id.win);
        if( Const.isAllLevelsComplete == true)
            editText3.setText("WIN!");
        else
            editText3.setText("");

        GridView gridview = (GridView) findViewById(R.id.gridview);
        gridview.setAdapter(new ImageAdapter(this));

        gridview.setOnItemClickListener(new GridView.OnItemClickListener()
        {
            public void onItemClick(AdapterView parent, View v, int position, long id)
            {

            }
        });

        super.onResume();
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
        case android.R.id.home:
            NavUtils.navigateUpFromSameTask(this);
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

}

And this is the layout
<?xml version="1.0" encoding="UTF-8"?>
<TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/tableLayout_delek"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:background="@color/aliceblue"
    android:layout_gravity="right" >

    <com.google.ads.AdView
xmlns:ads="http://schemas.android.com/apk/lib/com.google.ads"
android:id="@+id/adView"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
ads:adSize="BANNER"
ads:adUnitId="a1524d50e6097be"
/>

    <TextView
        android:fontFamily="monospace"
        android:freezesText="true"
        android:text= "@string/app_name"
        android:textSize="35sp"
         android:gravity="center"
        android:textColor="#800000"
          android:paddingTop="15dp"
        android:paddingBottom="20dp"
        android:textStyle="bold" />

        <TextView
            android:id="@+id/win"
        android:fontFamily="monospace"
        android:freezesText="true"
        android:text= ""
        android:textSize="35sp"
         android:gravity="center"
        android:textColor="#600000"
          android:paddingTop="15dp"
        android:paddingBottom="20dp"
        android:textStyle="bold" />

    <GridView
        android:id="@+id/gridview"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:columnWidth="90dp"
        android:gravity="center"
        android:horizontalSpacing="10dp"
        android:numColumns="auto_fit"
        android:stretchMode="columnWidth"
        android:background="@color/aliceblue"
        android:verticalSpacing="10dp" />

    <TableRow
        android:id="@+id/tableRow1_delek1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginRight="14.5sp"
        android:layout_marginTop="20sp"
        android:gravity="center"
        android:padding="5dip" >
    </TableRow>

</TableLayout>

A: Try this..
because admob hight android:layout_height="fill_parent" it will fill the parent so that it happen
<?xml version="1.0" encoding="UTF-8"?>
<TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/tableLayout_delek"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:background="@color/aliceblue"
    android:layout_gravity="right" >

    <com.google.ads.AdView
xmlns:ads="http://schemas.android.com/apk/lib/com.google.ads"
android:id="@+id/adView"
android:layout_width="fill_parent"
android:layout_height="wrap_content"        //correction here
ads:adSize="BANNER"
ads:adUnitId="a1524d50e6097be"
/>

    <TextView
        android:fontFamily="monospace"
        android:freezesText="true"
        android:text= "@string/app_name"
        android:textSize="35sp"
         android:gravity="center"
        android:textColor="#800000"
          android:paddingTop="15dp"
        android:paddingBottom="20dp"
        android:textStyle="bold" />

        <TextView
            android:id="@+id/win"
        android:fontFamily="monospace"
        android:freezesText="true"
        android:text= ""
        android:textSize="35sp"
         android:gravity="center"
        android:textColor="#600000"
          android:paddingTop="15dp"
        android:paddingBottom="20dp"
        android:textStyle="bold" />

    <GridView
        android:id="@+id/gridview"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:columnWidth="90dp"
        android:gravity="center"
        android:horizontalSpacing="10dp"
        android:numColumns="auto_fit"
        android:stretchMode="columnWidth"
        android:background="@color/aliceblue"
        android:verticalSpacing="10dp" />

    <TableRow
        android:id="@+id/tableRow1_delek1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginRight="14.5sp"
        android:layout_marginTop="20sp"
        android:gravity="center"
        android:padding="5dip" >
    </TableRow>

</TableLayout>


text:
Q: JS equivalent to Ruby's return if In Ruby i can use return if variable != 1
as example to not run the code comming after the return. I need to do the same in JS but i dont want to use a full if (variable != 1) { My code here } statement.
Is that possible?

A: Put the return after the if statement:
if (variable != 1) return;
// more code here

A: Put return after a one-line if:
if (variable !== 1) return;

Demonstration:

function test() {
  if (variable != 1) return;
  console.log("Variable equals one"); //Will never be run
}

var variable = 2;
test();

A: 1.
if (i !== 1) return 'True';

2.
return (i !== 1) ? 'True' : 'False';

3.
if (i !== 1) { console.log('Not equal'); } // else { }

Example

function test() {
    let i = 1;
    if (i !== 1) {
        console.log('Not equal to 1');
        return false;
    } else {
        return true;
    }
}

console.log(test());

Single

function test() {
    let i = 1;
    if (i !== 1) return 'True';
}

console.log(test());

Ternary operator

function test() {
    let i = 1;
    return (i !== 1) ? 'True' : 'False';
}

console.log(test());


text:
Q: Horizontal scroll appears on website when using iPhone I have a problem with mobile version of my website http://dsmedvednikov2.zzz.com.ua/. A horizontal scroll appears when using iPhone or iPad, no matter whether using Safari or Google Chrome browser. Everything works fine on Android devices. Could someone give me an advice?

A: you can restrict user to stop zoom/pinch on your website by adding this meta tag :
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">

or if its a very minute x-scroll effect you can use the following little hack:
body    {
    overflow: hidden;
    overflow-y: auto;
    }

it will stop any horizontal scroll effect.

A: It seems like the page css is making this mess. Even in safari on my Mac getting the same issue. Please make sure your CSS.
As of my knowledge I gone through the CSS properties of your page
which is causing the issue. It will be better if you use % instead of 'px' will resolve your issue.
Thanks!
Keep Coding.

A: If you are using fixed width, then it might lead to problems. Use **

width:100%

**


text:
Q: Is Model a better place to set HTTP status code? In MVC usually the controller sets whatever needs to be sent back to the client/View, including HTTP status code, e.g.:
class Controller {

    public function get(Request req, Response resp) {

        if (this.model.get(req.getId()) {
            resp.setStatusCode(Response::HTTP_OK)

        } else {
            resp.setStatusCode(Response::HTTP_NOT_FOUND)
        }
    }
}

There are a few problems in doing it this way:

*

*all controller methods become littered with if/else for setting different HTTP status code

*I've encountered a problem where someone has a Model::createOrGet(), which just return Model. The controller doesn't know if one has been created or fetch from store.

*setting HTTP status code code becomes duplicated between controllers.

Would it be better to make Model pass HTTP status code back to the controller, e.g.:
class Controller {

    public function get(Request req, Response resp) {
        cart := this.model.getOrCreate(req.getCustomerId()
        resp.setStatusCode(this.model.getStatusCode())

        if (cart) {
            return cart
        }
    }

    public function create(Request req, Response resp) {
        cart := this.model.getOrCreate(req.getCustomerId()
        resp.setStatusCode(this.model.getStatusCode())

        if (cart) {
            return cart
        }
    }

    public function put(Customer c, array data) {
        // this can result different success/error status codes
        this.model.processPutDataForCustomer(c, data)
        resp.setStatusCode(this.model.getStatusCode())
    }
}

Basically this.model sets the last status to the appropriate HTTP status code which can be one of the success, client error or server error codes and the controller can just get that status code.
Is this good or is there a better way for this common problem? Isn't it logical for web application to know HTTP status code deeper than the controller?
I'd really like to see example for multiple possible HTTP status code to be returned by the controller, something like a PUT request that can be one of "Bad Request", "Conflict", "Not Found", "Created" and "No Content".

A: The Controller is responsible for handling the HTTP request and knowing what to do. Setting the HTTP status code in the Controller is the right place to do this.

There are a few problems in doing it this way:

*

*all controller methods become littered with if/else for setting different HTTP status code

That's where this code was meant to go.

*

*I've encountered a problem where someone has a Model::createOrGet(), which just return Model. The controller doesn't know if one has been created or fetch from store.

If the Controller needs to know whether or not something was created, then the Controller shouldn't be calling Model::getOrCreate(...).

*

*setting HTTP status code code becomes duplicated between controllers.

If the model set the HTTP status code then it's duplicated between models, so this doesn't really buy you anything either.
This next suggestion will largely depend on the framework you are using, but most frameworks default to a 200 OK response, leaving you to just deal with the negative cases (404 NOT FOUND, etc).
But again, this is precisely what the Controller is meant to do.
Yes, it seems like you are duplicating code, but you are not duplicating business logic. That's the kind of duplication you want to avoid. Duplicating HTTP status codes isn't really what I'd call "duplication." It's part of the Controller's job.
imel96 commented:

I know setting some status code is Controller's job. But a lot of HTTP status codes are part of business logic and business logic should go in Model, right?

HTTP status codes are only a part of Business Logic if the application you are writing is a web server. If not, an HTTP status code is an artifact of your application being implemented as a web application. Imagine if you needed to take your business logic and reuse it in the context of an installed GUI application. Do HTTP status codes make sense then? They don't. An HTTP status code is not business logic. It is application flow control. The Controller is responsible for flow control.
Business Logic is Why and your Controller should know What to do when something happens. Controllers don't know Why something happens, because that's the responsibility of Business Logic.

I also find some Model throwing exceptions with HTTP status code in it and then Controller copy that to Response object. That also indicates to me that Model really wants to return HTTP status code, and without exception (like when using Go), it'd be just like returning status code.

If the model is throwing exceptions containing HTTP status codes, the model was built wrong. An exception is an exceptional condition that cannot be handled by the code being called, and so must be handled by the caller. Validations, as a separate entity from Models (although validators should be calling methods on Models while performing validation) and Controllers should take care of checking the data before exceptions can be thrown by the model or data access layer

When using many status codes, isn't it too much of business logic to be put in Controller?

No. Again, HTTP status codes have nothing to do with Business Logic. The very fact that you've asked this question should show you how confusing it becomes when you mix up two completely different concerns: Business Logic (Models) and Flow Control (Controllers).

A: The controller's job is to mediate between the model and the view. It tells the model what, in the abstract sense, the user wants it to do and tells the view how it should look based on the state of the model. Importantly, it is not the controller's job to decide what the state of the model should be.
The server call and the data it returns are parts of the model and should therefore be handled by the model. The controller should not even tell the model to make a server request, much less directly observe the result of that request.
In a well designed system, the controller should not know where the data is coming from or what the model must do to get it. The model should be free to change its source of truth, for example from the server to a cache, without any changes in the controller.
In essence, I am saying that function get(Request req, Response rest) shouldn't be in the controller in the first place. Instead there should be some sort of "userWantsX" function in the model and how the model responds to that request for X is it's own business.
So the controller's job is to convert UI gestures (user tapped button X) into model requests, (user wants X). Then after the model changes state, to convert that state information into UI view state changes. That's all the controller should be doing.

A: I recommend you to use proper error handling and/or validation system for mitigating code duplication and violation of single responsibility principle.
Every MVC framework has some central error management hooks like these on ASP.NET 6. All you need to do is throw the appropriate exception, catch back on your central error handling mechanism, finally set the appropriate status code to the response.
Your controller shouldn't do the job of validation and error handling.


text:
Q: Is the shrinkage techique all about finite samples? With the right choice of the penalty, the ridge estimator in the linear regression model
$$y=X \beta +\varepsilon, \quad E[X
\varepsilon]=0, \quad \beta \in \mathbb{R}^k$$
will have a smaller MSE that the OLS estimator. The asymptotic distributions of the ridge estimator and the OLS estimator (that is, the distribution limits of $\sqrt{n}(\widehat{\beta}_{OLS}-\beta)$ and $\sqrt{n}(\widehat{\beta}_{ridge}-\beta)$) are the same.
Is shrinkage always just improving the properties of the estimator in a finite sample?
Does it make sense to use  shrinkage in large samples (in the case of a finite-dimensional parameter of interest)?

A: Shrinkage is all about improving finite sample behavior. That's pretty important: I've never analyzed a data set that is not finite.
But more seriously, shrinkage methods are not just useful for data sets with relatively small samples sizes. They are very useful for data sets in which many of the variables have relatively little information about them. For example, you may have 1,000,000 rows of data, which I would say is a lot. But if you have 100,000 covariates, you don't have that much data relative to the number of parameters you are estimating. Or suppose you only have 10 variables, but one of them is 0 in all but a single case. Then all your inference about that single variable is essentially based on a single observation!
These are the types of cases that shrinkage methods can be useful for.
It can be helpful to realize that most penalized methods can be seen as simply putting a prior on the penalized variables and using MAP estimates. In the Bayesian setting, we know that priors can be helpful when the data is not informative, but (thankfully) gets drowned out when the data is very informative.


text:
Q: Retrieve all forms on Webpage How can I retrieve all the forms that are present on the given website. Specifically the id and name of a form.
Thanks

A: Simply with something like that
var page = require('webpage').create();
 page.open('yoursitehere', function (status) {
    if (status !== 'success') {
         console.log('unable to access network');
     } else {
        var forms = page.evaluate(function(){
            //best way here
            return document.forms;
        });
           //some stuff here
        console.log(forms.length);
        console.log(forms[0].name);
    }
   phantom.exit();
});

also, note that can't pass a non-primitive object through evaluate. You will have to do your work in the evaluate.
Note: The arguments and the return value to the evaluate function must be a simple primitive object. The rule of thumb: if it can be serialized via JSON, then it is fine. Closures, functions, DOM nodes, etc. will not work!


text:
Q: Website always flags it using an outdated browser I am trying to scrape the site https://anichart.net/ in order to use the information to build a schedule from the information.  The problem is that the site is always detecting an outdated browser (shows http://outdatedbrowser.com).

We\'re sorry but AniChart requires Javascript.

Please enable Javascript or upgrade to a modern web browser.

Sorry, AniChart requires a modern browser.
Please upgrade to a newer web browser.

I have tried a regular request and have also tried forcing the user agent, shown below.
    import requests

    self.url = 'https://anichart.net/Winter-2019'

    headers = {'User-agent': 'Chrome/72.0.3626.109'}

    self.page = requests.get(self.url, headers=headers)

    print(self.page.content)

I understand that the site uses javascript and the Requests module won't reference the javascript generated portion of the site unless I use other tools with it or potentially Selenium.  My browsers are up-to-date so this should not be returning an outdated browser result.
This was working just fine a few days ago but it looks like they did just update their site so they may have added something that prevents automated requests on the site.
Edit:
Selenium Code below:
    from selenium import webdriver

    url = 'https://anichart.net/Winter-2019'

    website = webdriver.Chrome()

    website.get(url)

    print(website.page_source)

    html_after_JS = website.execute_script("return document.body.innerHTML")

    print(html_after_JS)

A: The problem is not the browser detection.
requests simply does render JavaScript (as you seem to know already), and most sites nowadays uses front-end Javascript libraries to render content. And some more sites use Javascript detection to prevent bots from scraping the pages...
You instead will need to use a tool like Selenium, which will open a headless, "modern" browser, of your choice, and you can scrape the page from there. But you have not shown that code, so it might make sense to ask about that instead?
Or, better yet, they have an API - https://github.com/AniList/ApiV2-GraphQL-Docs

The AniList & AniChart websites themselves run on the Api, so everything you can do on the sites, you can do via the Api.


text:
Q: Tomcat 6 Javax.mail session envCtx.lookup("mail/Session") not returning I am using Tomcat 6 to send a email client with Javax.mail APIs , i set up my configurations in server.xml as below
<Resource name="mail/Session" auth="Container"
            type="javax.mail.Session"
            mail.smtp.host="localhost"/>

And in my web.xml as below
<resource-ref>
    <description>Resource reference to a container-managed JNDI JavaMail factory for sending e-mails.</description>
    <res-ref-name>mail/Session</res-ref-name>
    <res-type>javax.mail.Session</res-type>
    <res-auth>Container</res-auth>
</resource-ref>

But when i tried to create a mail Session ...using context.lookup
ontext initCtx = new InitialContext();
            Context envCtx = (Context) initCtx.lookup("java:comp/env");
            *mailSession = (Session)envCtx.lookup("mail/Session");*

The call nvCtx.lookup("mail/Session"); is not returning....it goes and break in org/springframework/jms/listener/DefaultMessageListenerContainer ...
Any Clues ....
I appreciate any help.
Thanks
Vijay

A: As you don't use spring use this:
Source: Apache Tomcat 6.0 Documentation - JDNI Resources
Context initCtx = new InitialContext();
Context envCtx = (Context) initCtx.lookup("java:comp/env");
Session session = (Session) envCtx.lookup("mail/Session");

Message message = new MimeMessage(session);
message.setFrom(new InternetAddress(request.getParameter("from")));
InternetAddress to[] = new InternetAddress[1];
to[0] = new InternetAddress(request.getParameter("to"));
message.setRecipients(Message.RecipientType.TO, to);
message.setSubject(request.getParameter("subject"));
message.setContent(request.getParameter("content"), "text/plain");
Transport.send(message);

A: Your configuration looks ok, may you need to clean the server first (if you use eclipse).
Anyway: If you use spring then you can use the spring Framwork to access the JNDI ressource:
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:jee="http://www.springframework.org/schema/jee"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
    http://www.springframework.org/schema/jee
    http://www.springframework.org/schema/jee/spring-jee-3.0.xsd">

    <jee:jndi-lookup id="jndiEmailSession"
         jndi-name="java:comp/env/email/Session" />
</beans>


text:
Q: Error when trying to execute Qt app from shared library I am trying to execute simple Qt app from other languages (target is Java).
My app looks like this:
  //HelloWorld.pro
  TEMPLATE= lib
  TARGET = HelloWorld
  QT = core gui widgets
  SOURCES += main.cpp

c++ source
   //main.cpp
   #include <QApplication>

   int main(int argc, char **argv)
   {
       QApplication app (argc, argv);
       return app.exec();
   }

I compiled it with qmake and make but everytime I try to load shared library I get Segmentation fault 11.
 //PS: simplest code in python to load shared library
 from ctypes import *
 cdll.LoadLibrary('libHelloWorld.dylib').main()

I don't know where's the problem.
PS: My goal is to interact with Qt5 in Java through JNI/JNA


text:
Q: Slick-slider заужает блоки-слайды Использую на страничке slick-slider. Присвоение блокам слайдам ширины конкретной ничего не дает. Все равно слик их сам масштабирует. Даже если стиль инлайново присваиваю. Чем меньше слайдов отображаю тем уже он их делает.

'use strict';
$(function () {
  $('.slider').slick({
    arrows: true,
    dots: true,
    adaptiveHeight: true,
    slidesToShow: 3,
    slidesToScroll: 3,
    speed: 600,
    infinite: false,
  });
});

let previousOpen = 0;

//ХОВАЄМО ВСІ БЛОКИ З ПІДМЕНЮ
$('.main__menu-content.vogneva').hide();
$('.main__menu-content.individual').hide();
$('.main__menu-content.topography').hide();

//функція приховує попередньо відкритий блок підменюшек
function hideMenuItem(num) {
  switch (num) {
    case 1: //VOGNEVA
      $('.main__menu-content.vogneva').hide();
      $('.main__menu-content.vogneva').toggleClass('active');
      break;

    case 2: //INDIVIDUAL
      $('.main__menu-content.individual').hide();
      break;

    case 3: //TOPOGRAPHY
      $('.main__menu-content.topography').hide();
      break;
  }
}

//функція відображає відповідний блок підменю
function showSlideItem(number) {
  switch (number) {
    case 1: //VOGNEVA
      $('.main__menu-content.vogneva').show();
      break;

    case 2: //INDIVIDUAL
      $('.main__menu-content.individual').show();

      break;

    case 3: //TOPOGRAPHY
      $('.main__menu-content.topography').show();
      break;
  }
}
function menuItemClick(num) {
  if (previousOpen == 0) {
    previousOpen = num;
    showSlideItem(num);
  } else if (previousOpen != num) {
    hideMenuItem(previousOpen);
    previousOpen = num;
    showSlideItem(num);
  } else {
    hideMenuItem(num);
    previousOpen = 0;
  }
}

/*  MOBILE LOGO CLICK */
$('.mobile__logo').click(function (event) {
  $('.mobile__logo, .mobile__menu').toggleClass('active');
});
/*  MOBILE LOGO CLICK */

/* MINI MENU BTN CLICK*/
let miniLogoClicked = true;
$('.mini__btn').click(function (event) {
  $('.mini__btn,.mini__menu').toggleClass('active');
  if (miniLogoClicked == false) {
    $('.mini__btn').attr('src', 'img/compass.png');
    miniLogoClicked = true;
  } else {
    $('.mini__btn').attr('src', 'img/compass_closed.png');
    miniLogoClicked = false;
  }
});
/* MINI MENU BTN CLICK*/
* {
  box-sizing: border-box;
}

body {
  background-color: #444c38; /*OLIVE*/
  margin: 0;
  list-style-position: inside;
}

body h1 {
  color: #a1a188; /*MILITARY LIGHT*/
  font-size: 30px;
  text-align: center;
  font-family: 'Neucha', sans-serif;
  margin-top: 20px;
  margin-bottom: 20px;
}
body h2 {
  color: #a1a188; /*MILITARY LIGHT*/
  font-size: 24px;
  text-align: center;
  font-family: 'Neucha', sans-serif;
  margin-top: 20px;
  margin-bottom: 20px;
}

h3 {
  font-size: 20px;
  font-family: 'Neucha', sans-serif;
  margin-top: 10px;
  margin-bottom: 10px;
  padding-left: 10px;
}

td {
  padding: 0 5px 0;
}

/* *******************HEADER******************** */
.mobile__header {
  display: none;
}
.header {
  background-color: #444c38; /*OLIVE*/

  width: 100%;
  text-align: center;

  color: #cc9a45; /* LETTERS*/

  padding-top: 10px;

  margin-top: 0px;
  border-radius: 5px;
  margin-bottom: 0px;
}

.logo {
  margin: 0;
  padding-bottom: 20px;
}

.logo-label {
  padding-top: 30px;
  font-size: 30px;
  color: #a1a188; /*MILITARY LIGHT*/
  font-family: 'Neucha', sans-serif;
}

/*MENU HORIZONTAL*/
.menu__hor {
  border-top: 2px solid #a1a188; /*MILITARY LIGHT*/
  border-bottom: 2px solid #a1a188; /*MILITARY LIGHT*/
}
.menu__hor__list {
  display: flex;
  justify-content: center;
}
.menu__hor__list-item {
  width: 200px;
}
.menu__hor__list-link {
  font-size: 30px;
  line-height: 30px;
  color: #a1a188; /*MILITARY LIGHT*/
  text-decoration: none;
  font-family: 'Neucha', sans-serif;
  display: block;
  max-width: 300px;
  padding: 10px 10px 10px;
  border-left: 1px solid #a1a188; /*MILITARY LIGHT*/
  border-right: 1px solid #a1a188; /*MILITARY LIGHT*/
  transition: all 0.3s;
}

.menu__hor__list-link.active,
.menu__hor__list-link:hover {
  background-color: #5b6750; /*MILITARY 2*/
  color: white;
}
/*MENU HORIZONTAL*/
/* *******************HEADER******************** */

/* *******************MOBILE HEADER******************** */
@media (max-width: 767px) {
  .header {
    display: none;
  }

  .mobile__header {
    width: 100%;
    height: 70px;
    background-color: #5b6750; /*MILITARY 2*/
    border-bottom: 1px solid #a1a188; /*MILITARY LIGHT*/
    position: fixed;
    top: 0;
    display: flex;
    justify-content: flex-end;
    z-index: 5;
  }
  .mobile__header-title {
    font-size: 36px;

    padding: 20px 30px 10px 0;
    color: #fafaf6; /*MILITARY LIGHT*/
    font-family: 'Neucha', sans-serif;
    text-align: center;
  }
  .mobile__logo {
    max-height: 50px;
    padding-right: 20px;
    cursor: pointer;
    z-index: 3;
  }

  .mobile__logo-image {
    height: 70px;
  }
  .mobile__menu {
    border-top: 1px solid #a1a188; /*MILITARY LIGHT*/
    border-bottom: 1px solid #a1a188; /*MILITARY LIGHT*/
    position: fixed;
    width: 100%;

    background-color: #5b6750; /*MILITARY 2*/
    top: -100%;
    z-index: 6;
    transition: all 0.3s;
  }
  .mobile__menu.active {
    top: 70px;
  }
  .mobile__menu__hor__list {
    display: flex;
    flex-direction: column;
    list-style-type: none;
  }
  .mobile__menu__hor__list-link {
    display: block;
    text-decoration: none;
    font-size: 40px;
    line-height: 40px;
    padding: 10px 10px 10px;
    color: #a1a188; /*MILITARY LIGHT*/
    font-family: 'Neucha', sans-serif;
    text-align: center;
  }
  .mobile__menu__hor__list-link:hover {
    background-color: #c4c4c4;
  }
  .main {
    margin-top: 80px;
  }
  .main__menu__list-link {
    border-top: 1px solid #a1a188; /*MILITARY LIGHT*/
  }

  #mini {
    display: none;
  }
  .mobile__mini {
    position: fixed;
    left: -100%;
    top: 70px;
    background-color: #5b6750; /*MILITARY 2*/
    z-index: 4;
    border-bottom-right-radius: 5px;
    border-right: 2px solid #a1a188; /*MILITARY LIGHT*/
    border-bottom: 2px solid #a1a188; /*MILITARY LIGHT*/
    transition: all 0.3s;
  }
  .mobile__mini__menu__list {
    list-style-type: none;
  }
  .mobile__mini__menu-link {
    display: block;
    text-decoration: none;
    font-size: 40px;
    line-height: 40px;
    padding: 10px 10px 10px;
    color: #a1a188; /*MILITARY LIGHT*/
    font-family: 'Neucha', sans-serif;
    text-align: center;
  }
  .mobile__mini.active {
    left: 0;
  }
}
/* *******************MOBILE HEADER******************** */

/*MAIN - MENU*/
.main {
  width: 100%;
}
.main__menu-item {
  border: 2px solid #a1a188; /*MILITARY LIGHT*/
  border-radius: 5px;
  margin: 15px 50px 15px;
}
.main__menu-topic {
  text-align: center;
  border-bottom: 1px solid #a1a188; /*MILITARY LIGHT*/
  cursor: pointer;
}
.main__menu-item-link {
  display: block;
  padding: 5px 0 5px;
  text-decoration: none;
  color: #a1a188; /*MILITARY LIGHT*/
  font-family: 'Neucha', sans-serif;
  font-size: 30px;
  outline: none;
  transition: all 0.2s;
}
.main__menu-item-link:hover {
  background-color: #5b6750; /*MILITARY 2*/
  color: white;
}

/*MAIN - MENU*/

/*MAIN - CONTENT*/
.content {
  min-width: 0;
  width: 100%;
}
.menu__content {
  padding: 5px 5px 5px;
  width: 100%;
}
.menu__table {
  width: 100%;
}
.menu__table td {
  background-color: #5b6750; /*MILITARY 2*/
}
.content__menu-item {
  text-align: center;
  margin: 15px 0 20px;
  list-style-type: circle;
  list-style-type: none;
}

.content__menu-link {
  text-decoration: none;
  color: #a1a188; /*MILITARY LIGHT*/
  font-family: 'Neucha', sans-serif;
  font-size: 24px;
  padding: 5px 10px 5px;
  border: 2px solid #5b6750; /*MILITARY 2*/
}

.content__menu-link:hover {
  border: 2px solid #a1a188; /*MILITARY LIGHT*/
  border-radius: 5px;
  color: white;
  background-color: #444c38; /*OLIVE*/
}

/*MAIN - CONTENT*/

.paragraph {
  text-align: justify;
  padding: 15px;
  text-indent: 20px;
  background-color: #a1a188; /*MILITARY LIGHT*/
  border: 1px dotted;
  border-radius: 5px;
  line-height: 1.5;
  font-size: 20px;
  margin: 10px 10px 10px;

  font-family: 'Neucha', sans-serif;
}
.paragraph p {
}
.paragraph img {
  border: 1px solid;
}
.paragraph a {
  text-decoration: none;
  color: black;
  font-weight: bold;
}
.paragraph a:hover {
  color: white;
}
.paragraph li {
  list-style-position: inside;
}

.my {
  color: green;
  font-weight: bold;
}

.linko {
  list-style-type: none;
  margin-left: 20px;
}

/* VIDEO ELEMENT*/
.video__block {
  margin: 10px 5px 10px;
  width: 20%;
  background-color: #5b6750; /*MILITARY 2*/
  height: 250px;
  border: 1px solid #a1a188; /*MILITARY LIGHT*/
  border-radius: 10px;
}

.video__block-frame {
  border: none;
  border-radius: 10px;
  width: 100%;
}

.video__block hr {
  margin: 0;
}

.video__block-descript {
  color: #a1a188; /*MILITARY LIGHT*/
  font-size: 24px;
  text-align: center;
  font-family: 'Neucha', sans-serif;
}
/* VIDEO ELEMENT*/

/* SLIDER */

/* Слайдер */
.slick-slider {
}
/* Слайдер запущен */
.slick-slider.slick-initialized {
}
/* Слайдер с точками */
.slick-slider.slick-dotted {
}
/* Ограничивающая оболочка */
.slick-list {
}
/* Лента слайдов */
.slick-track {
}
/* Слайд */
.slick-slide {
}
/* Слайд активный (показывается) */
.slick-slide.slick-active {
}
/* Слайд основной */
.slick-slide.slick-current {
}
/* Слайд по центру */
.slick-slide.slick-center {
}
/* Клонированный слайд */
.slick-slide.slick-cloned {
}
/* Стрелка */
.slick-arrow {
}
/* Стрелка влево */
.slick-arrow.slick-prev {
}
/* Стрелка вправо */
.slick-arrow.slick-next {
}
/* Стрелка не активная */
.slick-arrow.slick-disabled {
}
/* Точки (булиты) */
.slick-dots {
}
.slick-dots li {
}
/* Активная точка */
.slick-dots li.slick-active {
}
/* Элемент точки */
.slick-dots li button {
} /* Слайдер */
.slick-slider {
}
/* Слайдер запущен */
.slick-slider.slick-initialized {
}
/* Слайдер с точками */
.slick-slider.slick-dotted {
}
/* Ограничивающая оболочка */
.slick-list {
  overflow: hidden;
}
/* Лента слайдов */
.slick-track {
  display: flex;
  align-items: center;
}
/* Слайд */
.slick-slide {
}
/* Слайд активный (показывается) */
.slick-slide.slick-active {
}
/* Слайд основной */
.slick-slide.slick-current {
}
/* Слайд по центру */
.slick-slide.slick-center {
}
/* Клонированный слайд */
.slick-slide.slick-cloned {
}
/* Стрелка */
.slick-arrow {
}
/* Стрелка влево */
.slick-arrow.slick-prev {
}
/* Стрелка вправо */
.slick-arrow.slick-next {
}
/* Стрелка не активная */
.slick-arrow.slick-disabled {
}
/* Точки (булиты) */
.slick-dots {
}
.slick-dots li {
}
/* Активная точка */
.slick-dots li.slick-active {
}
/* Элемент точки */
.slick-dots li button {
}
/* OUR SLIDER*/
.slider {
  position: relative;
  padding: 0 70px;
}
.slider .slick-arrow {
  position: absolute;
  top: 50%;
  font-size: 0;
  width: 50px;
  height: 50px;
  z-index: 2;
  border-radius: 50%;
  outline: none;
  border: 1px solid #a1a188; /*MILITARY LIGHT*/
  cursor: pointer;
}
.slider .slick-arrow.slick-prev {
  left: 10px;
  background: url('../img/prev.png') 0 0 / 100% no-repeat;
}
.slider .slick-arrow.slick-next {
  right: 10px;
  background: url('../img/next.png') 0 0 / 100% no-repeat;
}
.slider__item {
  max-width: 25%;
}

.slider .slick-dots {
  display: flex;
  align-items: center;
  justify-content: center;
}
.slider .slick-dots li {
  list-style: none;
  margin: 0 10px;
}
/* Активная точка */
.slider .slick-dots li.slick-active {
}
/* Элемент точки */
.slider .slick-dots li button {
  font-size: 0;
  height: 10px;
  width: 10px;
  background-color: transparent;
  border: 1px solid #a1a188; /*MILITARY LIGHT*/
  border-radius: 50%;
  cursor: pointer;
  outline: none;
}
.slider .slick-dots li.slick-active button {
  background-color: #a1a188; /*MILITARY LIGHT*/
  outline: none;
}

/* SLIDER */

/* FOOTER MINI  */
.mini {
  position: fixed;
  bottom: 10px;
  right: 10px;
  z-index: 5;
}
.mini__btn {
  cursor: pointer;
  border: 2px solid black;
  border-radius: 50%;
  outline: none;
  background-color: #5b6750; /*MILITARY 2*/
}
.mini__btn.active {
  src: url(../img/eye.png);
}

.mini__menu {
  position: fixed;
  background-color: #5b6750; /*MILITARY 2*/
  bottom: 130px;
  right: -100%;
  border: 2px solid black;
  border-top-left-radius: 10px;
  border-bottom-left-radius: 10px;
}
.mini__menu.active {
  right: -2px;
}
.mini__menu__list {
  list-style-type: none;
  padding: 10px 10px 10px;
}
.mini__menu__list-link {
  display: block;
  padding: 5px 5px 10px;
  color: black;
  text-decoration: none;
  font-size: 24px;
  font-family: 'Neucha', sans-serif;
}
.mini__menu__list-link:hover {
  color: white;
}
/* FOOTER MINI  */

/* FOOTER LOGO */
.footer__logo {
  min-height: 40px;
  padding: 0 20px 0;
  display: flex;
  justify-content: flex-start;
}

.footer__logo-bottom {
  background-color: #5b6750; /*MILITARY 2*/
  margin-top: 20px;
  border-top: 1px solid #a1a188; /*MILITARY LIGHT*/
}

.footer__logo-link {
  display: block;
  padding: 5px 5px 5px;
}
/* FOOTER LOGO */
<!DOCTYPE html>

 <meta charset="utf-8">
 <meta name="viewport" content="width=device-width, initial-scale=0.5">
 <meta name="description" content="Довідкова інформація військової тематики для піхотних підрозділів">
 <title>Infantry Handbook</title>
 <link rel="stylesheet" type="text/css" href="css/reset.css">

 <link rel="stylesheet" type="text/css" href="css/style.css">
 <link href="https://fonts.googleapis.com/css2?family=Neucha&display=swap" rel="stylesheet">

ГОЛОВНА

ДОВІДНИК

БІБЛІОТЕКА

ВІДЕОТЕКА

ПОСИЛАННЯ

ДОВІДНИК ПІХОТИНЦЯ

ДОВІДНИК ПІХОТИНЦЯ

ГОЛОВНА

ДОВІДНИК

БІБЛІОТЕКА

ВІДЕОТЕКА

ПОСИЛАННЯ

ВОГНЕВА ПІДГОТОВКА

Зброя

3D модель роботи АК-47

3D модель роботи АК-47

3D модель роботи M-16, AR-15

3D модель роботи 12,7 х 105 ДШК

Високоточна стрільба

Балістичний калькулятор Strelok Pro, ч.1

Балістичний калькулятор Strelok Pro, ч.2

Стрільба з нестабільних положень. Частина 1

Стрільба з нестабільних положень. Частина 2

Стрільба з нестабільних положень. Частина 3

Стрільба з нестабільних положень. Частина 4

Читання вітру армійськими снайперами, базові навички
      (USAMU)

ІНДИВІДУАЛЬНА ПІДГОТОВКА

Тренінг індивідуальної підготовки з автоматом АК-74

Габріель Суарез "Бій з автоматом Калашнікова"

 ВІЙСЬКОВА ТОПОГРАФІЯ

Теорія

Топографічні карти

ЗАДАЧІ

Комплексна задача. Цілевказання за допомогою оберненого
      азимуту

Комплексна задача

ВОГНЕВА

ІНДИВІДУАЛКА

ТОПОГРАФІЯ

A: Попробуй команду       variableWidth: true, для слайдера. Тогда он будет брать размеры элементов слайдера из стилей, прописанных в css


text:
Q: How to make JS parse 12 hour input format into 24 or Hope to get some help with this. I am total novice to JS. I have to write a script that asks user for the current hour. That's easy. If the hour is between 6am and 9 am, it will give certain prompt. If the hour is between 11 am and 1 pm, another prompt. If between 5 pm and 8 pm, prompt. My issue is how to have JS understand when user enters let's say number 5, that it is 5 pm (time for dinner) and not 5 am (go get snack). Please, help me. What would be solution to my problem? No one in the US really uses 24 hour format so numbers 13 (1pm), 17(5pm) or 20(8pm) in my script wont work. I can only have inputs in 12 hour time format.
var hour=prompt("What is the current hour? ","");

  if( hour >= 6 && hour <= 9 ){
    alert("Breakfast is served.");
  }
  else if( hour >=11  && hour <= 13 ){
    alert("Time for lunch.");
  }
  else if( hour >=17  && hour <= 20 ){
    alert("It's dinner time.");
  }
  else {
    alert("Sorry, you'll have to wait, or go get snack.");
  }

A: I would use JavaScript's String.match() to compare the string to a RegExp that describes the hour format such as /^(\d{1,2})\s*(am|pm)?$/i.  This RegExp means:

*

*^ match the start of the string

*(\d{1,2}) match and capture 1 or 2 digits (ie, 0-9)

*\s* match 0 or more whitespace characters

*(am|pm)? optionally match and capture 'am' or 'pm'

*$ match the end of the string

*i at the end means ignore the upper/lowercasing for the matches (ie match 'am' or 'AM')

Also, I'd throw a loop around the prompt in case the user didn't enter the correct format.
Here's a complete sample.
var hour;
var done = false;

while (!done) {
  var answer = prompt("What is the current hour?","");
  var result = answer.match(/^(\d+)\s*(am|pm)?$/i);
  if (result) {
    hour = +result[1];
    if (result[2] && result[2].match(/pm/)) {
      // If pm was specified, add 12
      hour += 12;
    }
    if (hour < 24) {
      done = true;
    }
  }
}

... Your code as before

A: Well make a parser to parse 12 > 24 hour
You could do this:
var hour   = prompt("What is the current hour? ","");
var apm    = hour.replace(/[0-9]/g, '');
var thour  = ""
if(apm = "am"){
  thour = parseInt(hour);
  out(thour);
}
else{
  thour = parseInt(hour) + 12;
  out(thour);
}
out = function(hour) {
(Your Code Here)
}

That is all I worked out and the output is a int.
So leave the code alone.
Output is in 24 hour.


text:
Q: Changing style of overlay container I use a git project for a virtual keyboard (https://ngx-material-keyboard.github.io/demo/). And I have some issues to get it running on a small device with 450*250 pixel.
At the end I found the necessary changes in the css if I modify it directly at the web browser with dev tools.
Now I have to find the right position to change the sources.
There will be used the overlay component from angular2-material to visualize the keyboard.
If I comment out the position in the cdk-overlay-container, it works:
.cdk-overlay-container {
/* position: fixed; */
z-index: 1000;

}
But I cant overwrite these from my angular application.
Any suggestions?
Screenshot of changes

A:
UPDATED ANSWER

From the official documentation:

Styling overlay components
Overlay-based components have a panelClass
property (or similar) that can be used to target the overlay pane.

You can override the default dialog container styles by adding a css class in your global styles.css. For example:
.custom-dialog-container .mat-dialog-container {
    /* add your styles */
}

After that, you'll need to providies you css class as a panelClass parameter to your dialog:
this.dialog.open(MyDialogComponent, { panelClass: 'custom-dialog-container' })

Read this official documentation for more information.

ORIGINAL ANSWER

Use ::ng-deep in your component.css to override the default styles.
::ng-deep .cdk-overlay-container {
    /* Do you changes here */
    position: fixed;
    z-index: 1000;
}

A: To be able to override the Material CSS classes from your component styles, you will need to set the View Encapsulation to None on your component:
@Component({
    templateUrl: './my.component.html' ,
    styleUrls: ['./my.component.scss'], //or .css, depending what you use
    encapsulation: ViewEncapsulation.None,
})

A: If you want to change the styling of mat-dialogue-container adding a panel class and giving style is enough, but in case if you want to change the styling of cdk-overlay-container then adding a backdropClass will help
const dialogRef = this.dialog.open(PopupComponent, {
  backdropClass: 'popupBackdropClass',
  panelClass: 'custom-dialog-container',
  data: { data: data }
});

in css add
.popupBackdropClass {
   background-color:yellow
 }

A: Overriding cdk-overlay-containeris not good since it is gonna affect all other components. You can create custom OverlayContainer. See example.

A: I found that by using the main/default "Styles.css". Styling changes for the CDK (as well as Material and Animations) are picked-up properly. (caveat) I am using Angular 4 .

A: I sort it out myself by using two stylessheet one Global and other component's stylesheet, In global i set z-index to to lower value(1000) so that it goes behind the header and in popup component styles sheet i set that to high value(2000) with !important so that header goes behind my overlay.
That's how i manage to solve it.
Thank me later

A: Avoid using encapsulation: ViewEncapsulation.None, because the css classes inside the component's css file, will influence the whole app.
The best way is the one suggested by @Faisal


text:
Q: What kind of neural network model to build to identify that the algo is n*n? I'm working with @tensorflow/tfjs-node to play with neural networks. I'm a beginner and don't yet fully grasp how they work, nor do I understand the mathematics behind it. But I like to play with them for fun.
So, what I'm playing with right now is I create a sequence: [1, 2, ..., n], and a function, for example n => n + 4 or n => n * 2, and I map it to the labels. Then my goal is to predict n+1, n+2, etc with the neural network without knowing the function.
Played with different kind of dense layers and different activations and optimizers, and usually after 1000 epochs on, for n = 1000, I get a very low loss. Which is perfect!
But here comes to bomb. I can't seem to get a low loss for n => n * n.
The code I'm playing with is here: https://pastebin.com/KSjAraF0

A: I found the following snippet. That helped me achieve function detection.
https://github.com/CodingTrain/website/blob/master/CodingChallenges/CC_105_tf_polynomial_regression/P5/sketch.js
However, it's not really the same, because here you know that some things get multiplied. But I believe that's how I need to think about AI, learn to model the problem, that's where 99% of effort is.


text:
Q: !ls in Jupyter notebook (Python 3) If I use:
!ls '/Users/martyn/Documents/rawData'

it gives me a list of the files in the required directory.
But I want to paramterize this. I tried:
pathData = '/Users/martyn/Documents/rawData'
!ls pathData

But this gives the error:
ls: pathData: No such file or directory

I can see the problem ... but can't see how to fix it. Any help would be greatly appreciated.

A: You probably need
!ls {pathData}

or
!ls $pathData

A: Using only %ls gives you the list in your current directory.

A: Maybe you can also use:
from glob import glob

#path_list=glob("put your file path here.extension")
path_list=glob("C:/Users/..../PYTHON/module1/data.jpg")

A: You can also use:
import subprocess
print(subprocess.check_output(['ls', '-lhS']).decode('utf-8'))


text:
Q: MSbuild batching -- recursive folder copy to multiple destination folders I am running into a situation. I am trying to use MSBuild batching to copy a folder (subdirectories as well as files) to mutilple dest folders.
but when i run the below script, it dumps every content from the src (contents from sub directories too) in root target directory, whereas what i was looking was to get the exact same structure as in src in the target dirs.
<PropertyGroup>
        <Srcfldr>C:\helloworld\REService</Srcfldr>
    <DestFldr>C:\Projects\desire\Examples</DestFldr>
  </PropertyGroup>

  <ItemGroup>
    <SrcToCopy Include="$(Srcfldr)\*.*"/>
  </ItemGroup>

  <ItemGroup>
    <DestToCopy Include="$(DestFldr)/destfldr1"/>
    <DestToCopy Include="$(DestFldr)/destfldr2"/>
    <DestToCopy Include="$(DestFldr)/destfldr3"/>

  </ItemGroup>

   <Target Name="DeployBatching">
    <RemoveDir Directories="@(DestToCopy)"/>
    <MakeDir Directories="@(DestToCopy)"/>

    <Copy SourceFiles="@(SrcToCopy)" DestinationFolder="%(DestToCopy.FullPath)" />

Can you please tell me what am i doing wrong ...
SK

A: Vanilla copy task is better suited for copying files rather than directories, in any case to preserve structure you need to remap destination using %(RecursiveDir) and %(Filename)%(Extension) metadata. See second example on MSDN.
Edit:
<Project xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
    <PropertyGroup>
        <Srcfldr>C:\helloworld\REService</Srcfldr>
        <DestFldr>C:\Projects\desire\Examples</DestFldr>
    </PropertyGroup>

    <ItemGroup>
        <SrcToCopy Include="$(Srcfldr)\**\*"/>
    </ItemGroup>

    <ItemGroup>
        <DestToCopy Include="$(DestFldr)\destfldr1"/>
        <DestToCopy Include="$(DestFldr)\destfldr2"/>
        <DestToCopy Include="$(DestFldr)\destfldr3"/>
    </ItemGroup>

    <Target Name="DeployBatching" Outputs="%(DestToCopy.FullPath)">
        <PropertyGroup>
            <DestToCopy>%(DestToCopy.FullPath)</DestToCopy>
        </PropertyGroup>
        <RemoveDir Directories="@(DestToCopy)"/>
        <MakeDir Directories="@(DestToCopy)"/>
        <Copy
            SourceFiles="@(SrcToCopy)"
            DestinationFiles="@(SrcToCopy->'$(DestToCopy)\%(RecursiveDir)\%(Filename)%(Extension)')"
        />
    </Target>
</Project>

A: Doesn't look like it's working the way i wanted it to  ...  I tried the below code
<PropertyGroup>
        <Srcfldr>C:\helloworld\REService</Srcfldr>
    <DestFldr>C:\Projects\desire\Examples</DestFldr>
  </PropertyGroup>

  <ItemGroup>
    <SrcToCopy Include="$(Srcfldr)\*.*"/>
  </ItemGroup>

  <ItemGroup>
    <DestToCopy Include="$(DestFldr)/destfldr1"/>
    <DestToCopy Include="$(DestFldr)/destfldr2"/>
    <DestToCopy Include="$(DestFldr)/destfldr3"/>

  </ItemGroup>

<PropertyGroup>
        <DestToCopyvar>%(DestToCopy)</DestToCopyvar>
      </PropertyGroup>

        <Target Name="DeployBatching">

          <Copy SourceFiles="@(SrcToCopy)" DestinationFiles="@(SrcToCopy->'$(DestToCopyvar)\%(RecursiveDir)%(Filename)%(Extension)')" />

It's copying just the root files in the root directory, it is missing the directories and sub directories al together ...

A: This seems to be working for me now ...
<PropertyGroup>
<Srcfldr>C:\Msbuild\exproj\Rebinaries</Srcfldr>
<copyfldr>c$\component1</copyfldr>
</PropertyGroup>

<ItemGroup>
<SrcToCopy Include="$(Srcfldr)\**\*"/>
</ItemGroup>

 <ItemGroup>
 <DestToCopy Include="\\devsvr1\$(copyfldr);\\devsvr2\$(copyfldr)"/>
 </ItemGroup>

 <Target Name="DeployBatching" Outputs="%(DestToCopy.FullPath)">
    <PropertyGroup>
        <DestToCopy>%(DestToCopy.FullPath)</DestToCopy>
    </PropertyGroup>
    <RemoveDir Directories="@(DestToCopy)"/>
    <MakeDir Directories="@(DestToCopy)"/>
    <Copy
        SourceFiles="@(SrcToCopy)"
        DestinationFiles="@(SrcToCopy->'$(DestToCopy)\%(RecursiveDir)\%(Filename)%(Extension)')"
    />
</Target>


text:
Q: Power Query: How to assemble list of files from multiple directories (Folder.Files, Table.Combine) I'd like to load a list of files from multiple different folders and merge them all into one table.
Just going by the documentation, I thought this code should work:
let
    Source1 = Folder.Files("folder path 1"),
    Source2 = Folder.Files("folder path 2"),
    Appended = Table.Combine(Source1,Source2)
in
    Appended

...but this is giving me the error: "2 arguments were passed to a function which expects 1"
That would make it seem like I am very close, but I have been trying to get this syntax right for quite a while and google isn't doing much for me.

A: Minor typo (note the braces around tables in combine statement):
let
    Source1 = Folder.Files("folder path 1"),
    Source2 = Folder.Files("folder path 2"),
    Appended = Table.Combine({Source1,Source2})
in
    Appended

https://msdn.microsoft.com/en-us/library/mt260748.aspx


text:
Q: Java: Modifying System Properties for a Java App I am using a Java JMS GUI utility (HermesJMS), and in its runtime, I need to invoke:

System.setProperty("user.name", "s24park");

Is there a properties file within JDK(1.6.0.18) that stores system properties?

A: You can use -D flag when launching your application.
java -Duser.name=s24park YourClass

See this post for more information. There is no file for System properties.

A: An interesting link I had come upon recently:
http://leepoint.net/notes-java/io/30properties_and_preferences/40sysprops/10sysprop.html
You can also use the Properties class - but this has nothing to do with "system" properties.
Any properties can be saved and loaded via this class

A: It is possible that your JVM may have one or more configuration files in which it is possible to create permanent system properties. That said, you really should be using java.util.prefs.Preferences.


text:
Q: How do I output a folder that I have created without accessing the previously created folders? I have created a folder and this folder has about 60 subfolders. How can I access this folder, which I have created to a another Python file? For this Method im using tkinter, because i would like to show these in a GUI.
Now I have created a folders with subfolders. This is what my folder looks like now: main_folder -> testOne, testTwo, testThree. testThree is the newly created folder and and the others were created before that.
Each single folder has 60 subfolders with numbers from 1 to 60. There is data/content in all 60 subfolders in testOne and testTwo. Only the newly created folder testThree contains 60 subfolders, but there is no data or content in the 60 subfolders.
Now to my current problem. I need the folder testThree in my other Python file or rather, I need the folder that I previously created with my entry. How do I do that?
It must only output the one folder I created. So here only the folder testThree should show and the others are to be ignored. To do this, I tried to access the folders:
# second.py
my_folder= [item for item in os.listdir('main_folder') if os.path.isdir(os.path.join('main_folder', item))]
print(my_folder)

But unfortunately, it prints all the folder from the main_folder. how can i get just the one folder which I have just created.

A: OK, given a directory dirx, here's how you find the most recent directory in dirx.  I list all the entries of the directory that are themselves directories.  I construct a list of each directory with its creation time, but with the creation time first.  That way, I can sort that list, grab the last element, and print the name.
import os
dirs = [(os.stat(dirx+'/'+d).st_ctime,d) for d in os.listdir(dirx) if os.path.isdir(dirx+'/'+d)]
dirs.sort()
print( dirs[-1][1] )


text:
Q: ServiceName not reflected in web services I have serviceName in my webservice as MYService. But in the wsdl I am not getting this name. I am still getting http://localhost:8080/rpc/soap/getResult?wsdl=Info.wsdl
@WebService(portName="portname", serviceName = "MYService", targetNamespace="http://test.com/webservices")
@SOAPBinding(style = SOAPBinding.Style.RPC, use= SOAPBinding.Use.LITERAL, parameterStyle= SOAPBinding.ParameterStyle.WRAPPED)
public interface Info {

    ........
}

Can some one tell how to rectify it.
Thanks.


text:
Q: Activity Label Text Alignment I want to know whether there is a way to change the alignment of activiy label, like other views can be aligned by android:gravity attribute..
NOTE: Except  android:label="  Header "
Thanks in advance..

A: You  have to customize Title Bar for that.
See the Examples Here :
http://www.londatiga.net/it/how-to-create-custom-window-title-in-android/
http://coderzheaven.com/2011/06/16/custom-title-bar-in-android/
You can customize according to your need.


text:
Q: Rake task for scraping with rails I'm starting to write scrapers to get data from different websites. I built the first scraper in a rake file and am now starting to write a second rake file to get data from a second site. For now, I am writing a scraper specific to each site I'm interested in (not trying to build a generic scraper).
I have 3 questions:

*

*Is writing rake tasks a good choice for me? Are there alternatives I should consider?

*How can I add functions/methods to my rake files? (sorry, very silly questions, but I can't figure out how to structure my code... so for now it's just 500 lines of uninterrupted code in a long method) for instance, I'd like a "get_description(section)" method that returns the description from the page. The method could be different depending on which site I'm scraping.

*How can I test my task with RSpec? I'd like to give a link and make sure the output of my tasks matches what I expect to get
Thanks for your help!

A: As a general principle, rake tasks should be very minimal. Refer the actual behavior to real classes. These classes can then be easily tested.
Example:
task :scrape do
  Scraper.scrape!
end

class Scraper
   def self.scrape!
     # do something
   end
end

describe Scraper do
  # your tests
end

You could, as @brad indicated, use thor, which has a regular class structure by itself, so in theory it should be easier to test the tasks themselves. I haven't done that though.
You can define methods in rake, but I don't know where they end up. You shouldn't do that, so don't bother. Keep task bodies minimal, write normal code to do the dirty work.

A: *

*Sure rake is fine if you want to use it, you can also check out thor which uses more standard ruby-like syntax rather than the dsl rake provides you.

*Rake is just another ruby library so you can include whatever you like in there.  As such you can write your own library and load it in your rake file.  Check out how Bundler does it for instance.  They've just defined their own classes, then created tasks inside of it.  It uses thor by the way, which, from what I can gather somehow proxies those tasks on to rake, haven't really looked through it thoroughly though so i could be wrong.

*If you're defining things in your own library, just use rspec as you normally would for any other project, then hook that library into rake or thor with whatever means and you're off to the races


text:
Q: Heroku Website with Google API - Need IP? I have a website that I wrote with react and pushed to heroku to host it while in development. The website uses the Google API -
When I get the API Key I need to specify the IP address that can get access to the api key. It was easy to put my own ip address in for my local server... but Idk what to put in for a website hosted on heroku. Can you help?


text:
Q: Join three text files based on multiple columns I want to join three text files based on multiple columns in Unix
I want to use in Perl script though
File1
A|B|C|MIKE
D|E|F|BIKE
G|H|I|HELLO

File2
A|B|C|123
D|E|F|456
G|H|I|789
A|A|A|121
B|B|B|221

File 3
G|H|I|ABC
A|A|A|BCA
B|B|B|CBA

Final ouput
A|B|C|MIKE|123|
D|E|F|BIKE|456|
G|H|I|HELLO|789|ABC
A|A|A|121|BCA
B|B|B|221|CBA.

I don't want to use a script which creates some temp text files since each of my text file size is very big. Can I achieve this using join in Unix?

A: perl solution from command line,
perl -F'\|' -lane'
  BEGIN { $" = "|" }
  $v = pop @F;
  $h{"@F"} or push @r, "@F";
  $h{"@F"}[$i] = $v;
  $i++ if eof;
}{
  print "@$_" for map [ $_, @{$h{$_}}[0..$i-1] ], @r
' file1 file2 file3

output
A|B|C|MIKE|123|
D|E|F|BIKE|456|
G|H|I|HELLO|789|ABC
A|A|A||121|BCA
B|B|B||221|CBA

EXPLANATION:
Before printing output, script generates following %h hash structure,
$VAR1 = {
      'G|H|I' => [
                   'HELLO',
                   '789',
                   'ABC'
                 ],
      'D|E|F' => [
                   'BIKE',
                   '456'
                 ],
      'B|B|B' => [
                   undef,
                   '221',
                   'CBA'
                 ],
      'A|A|A' => [
                   undef,
                   '121',
                   'BCA'
                 ],
      'A|B|C' => [
                   'MIKE',
                   '123'
                 ]
    };

A: Here's a basic program that does what you ask, but if your files are truly huge then it may die from lack of memory.
The names of the three files are expected on the command line, so it should be run as
perl program.pl file1.txt file2.txt file3.txt > merge.txt

use strict;
use warnings;

my @keys;
my %data;

my $i = 0;
while (<>) {
  next unless /\S/;
  my ($key, $val) = /(.+)\|(.+)/;
  push @keys, $key unless $data{$key};
  $data{$key}[$i] = $val;
}
continue {
  ++$i if eof;
}

for my $key (@keys) {
  print join('|', $key, map $_ // '', @{ $data{$key} }), "\n";
}

output
A|B|C|MIKE|123
D|E|F|BIKE|456
G|H|I|HELLO|789|ABC
A|A|A||121|BCA
B|B|B||221|CBA