text:
Q: oracle sql how to select specific distinct set in group by function Table

--------------------------------------------------
| Col1               | Col2                      |
--------------------------------------------------
| A                  | 1                         |
--------------------------------------------------
| A                  | 2                         |
--------------------------------------------------
| A                  | 3                         |
--------------------------------------------------
| B                  | 3                         |
--------------------------------------------------
| B                  | 4                         |
--------------------------------------------------
| B                  | 5                         |
--------------------------------------------------
| C                  | 4                         |
--------------------------------------------------
| C                  | 6                         |
--------------------------------------------------
| C                  | 3                         |
--------------------------------------------------

how to select distinct col1 that has 3 and 4 (answer is B, C)
Thanks in advance

A: You can use two IN clauses (or EXISTS):
SELECT DISTINCT col1
FROM Table
WHERE
COL1 IN (SELECT Col1 FROM Table WHERE Col2 = 3)
AND
COL1 IN (SELECT Col1 FROM Table WHERE Col2 = 4)

Or this GROUP BY
SELECT Col1 FROM Table
WHERE Col2 IN (3,4)
GROUP BY Col1
HAVNG COUNT(DISTINCT Col2) = 2

A: SQL Fiddle
Oracle 11g R2 Schema Setup:
CREATE TABLE tbl (Col1, Col2 ) AS
          SELECT 'A', 1 FROM DUAL
UNION ALL SELECT 'A', 2 FROM DUAL
UNION ALL SELECT 'A', 3 FROM DUAL
UNION ALL SELECT 'B', 3 FROM DUAL
UNION ALL SELECT 'B', 4 FROM DUAL
UNION ALL SELECT 'B', 5 FROM DUAL
UNION ALL SELECT 'C', 4 FROM DUAL
UNION ALL SELECT 'C', 6 FROM DUAL
UNION ALL SELECT 'C', 3 FROM DUAL;

CREATE OR REPLACE TYPE NUMBERs_Table AS TABLE OF NUMBER(1);

Query 1:
SELECT   Col1
FROM     tbl
GROUP BY Col1
HAVING   NUMBERs_Table(3,4) SUBMULTISET OF CAST( COLLECT( Col2 ) AS NUMBERs_Table )

Results:
| COL1 |
|------|
|    B |
|    C |


text:
Q: How to sort a category list array alphabetically in Magento In Magento, I've created a phtml template file with the code below. I got this from this tutorial. Me and others are wondering how to sort this category list alphabetically. The first lines of code create an array with Category IDs. Further down, we can get the Category Name using the ID within the foreach section. But to sort by Name, we need to get the Names in an array before the foreach and then sort by name. How?
<?php
$cats = Mage::getModel('catalog/category')->load(319)->getChildren();
$catIds = explode(',',$cats);
?>

<?php foreach($catIds as $catId): ?>

        <?php
            $category = Mage::getModel('catalog/category')->load($catId);
            echo 'getUrl() . '">';
            echo $category->getName() . '';
        ?>

<?php endforeach; ?>

Note: 319 is the category id of the parent category for which I want to list subcategories. Also, I'm not putting this is a category page template. I'm inserting as a block in a CMS page (that part is already working).

A: You can call
Mage::getModel('catalog/category')->getCollection()->addFieldToFilter('parent_id', '319')->addAttributeToSort('name', 'ASC');

and you'll get the whole bunch sorted right away, rest is just iteration over typical Varien collection. It's a pseudo sample and i don't know if the parent_id is the actual field name in db so you might check that out before you get the right results.
Great read about collections in Magento is written by Alan Storm

A: You could build a list of category names first.
<?php
$cats = Mage::getModel('catalog/category')->load(319)->getChildren();
$catIds = explode(',',$cats);

$categories = array();
foreach($catIds as $catId) {
       $category = Mage::getModel('catalog/category')->load($catId);
       $categories[$category->getName()] = $category->getUrl();
}

ksort($categories, SORT_STRING);
?>

<?php foreach($categories as $name => $url): ?>

    <a href="<?php echo $url; ?>"><?php echo $name; ?>

<?php endforeach; ?>

I wrote this answer without knowing too much about Magento and just wanting something quickly that worked. Anton's answer is better and more Magentic(?)

A: Hi I am using magento 1.4.1.1 and this worked to sort the child categories:
use
$cats = Mage::getModel('catalog/category')->load(319)->getChildrenCategories();

to get the children categories of category with id 319
and edit the file at code/core/Mage/catalog/Model/Resource/Eav/Mysql4/category.php at line 582 under the function getChildrenCategories() to change
->setOrder('position','ASC');

to
->setOrder('name','ASC);

hope this works for you too.

A: There's a much easier way to do this in the latest Magento (CE 1.7.0.2)+
$children = Mage::getModel('catalog/category')->getCategories(319, 1, true, true);

// iterate through the results
foreach ($children as $category):
    echo '<option value="' . $category->getUrl() . '">' . $category->getName() . '</option>';
endforeach;

The function getChildren() resides at...
app/code/core/Mage/Catalog/Model/Category.php around line 817
There are loads of options. Hope it saves you some time!

A: First backup your topmenu.phtml then replace the following code in your new topmenu.phtml file
<?php $_helper = Mage::helper('catalog/category') ?>
<?php $_categories = $_helper->getStoreCategories() ?>
<?php

function array_sort($array, $on, $order=SORT_ASC){
    $new_array = array();
    $sortable_array = array();

    if (count($array) > 0) {
        foreach ($array as $k => $v) {
            if (is_array($v)) {
                foreach ($v as $k2 => $v2) {
                    if ($k2 == $on) {
                        $sortable_array[$k] = $v2;
                    }
                }
            } else {
                $sortable_array[$k] = $v;
            }
        }

        switch ($order) {
            case SORT_ASC:
            asort($sortable_array);
            break;
            case SORT_DESC:
            arsort($sortable_array);
            break;
        }

        foreach ($sortable_array as $k => $v) {
            $new_array[$k] = $array[$k];
        }
    }

    return $new_array;
}

?>
<?php
$layer = Mage::getSingleton('catalog/layer');
$_category = $layer->getCurrentCategory();
$currentCategoryId= $_category->getId();
?>

    <?php $_helper = Mage::helper('catalog/category') ?>
    <?php $_categories = $_helper->getStoreCategories() ?>
    <?php $currentCategory = Mage::registry('current_category') ?>
    <?php if (count($_categories) > 0){ ?>
        <?php foreach($_categories as $_category){ ?>
            <?php $_category = Mage::getModel('catalog/category')->load($_category->getId()) ?>

<a href="<?php echo $_helper->getCategoryUrl($_category) ?>"><?php echo $_category->getName(); ?>
            <?php $catList = array();?>
            <?php $_subcategories = $_category->getChildrenCategories() ?>
            <?php foreach($_subcategories as $_subCategory){ ?>
                <?php $catList[] = array('name' => $_subCategory->getName(), 'url' => $_subCategory->getUrl(), 'id' => $_subCategory->getId());?>
            <?php } ?>
            <?php $catList = array_sort($catList, 'name', SORT_ASC);?>

            <?php if (count($catList) > 0){ ?>
                <?php $subcat=0?>
                <?php foreach($catList as $_subCategory){ ?>

<a href="<?php echo $_subCategory['url'] ?>"><?php echo $_subCategory['name'] ?>
                    <?php $subCatList = array();?>
                    <?php $_subSubCat = Mage::getModel('catalog/category')->load($_subCategory['id']);
                    $_subSubCategories = $_subSubCat->getChildrenCategories();?>
                    <?php foreach($_subSubCategories as $_subSubCategory){ ?>
                        <?php $subCatList[] = array('name' => $_subSubCategory['name'], 'url' => $_subSubCategory['url']);?>
                    <?php } ?>
                    <?php $subCatList = array_sort($subCatList, 'name', SORT_ASC);?>
                    <?php if (count($subCatList) > 0){ ?>

                            <?php foreach($subCatList as $_subSubCat){ ?>

<a href="<?php echo $_subSubCat['url'] ?>"><?php echo $_subSubCat['name'] ?>
                            <?php } ?>

                    <?php } ?>

                <?php } ?>

                <?php } ?>

        <?php } ?>
    <?php } ?>

redpajama_set_name: RedPajamaStackExchange


text:
Q: When i use nativescript-uuid plugin a get a error I get an error that says:
"TypeError: SSKeychain.passwordForServiceAccount is not a function. (In 'SSKeychain.passwordForServiceAccount(appName, "incoding")', 'SSKeychain.passwordForServiceAccount' is undefined)"

When i do this:
const uid = require("nativescript-uuid");
var uuid = uid.getUUID();
console.log("The device UUID is " + uuid);
I just want to get the device ID of the user device so i can store it.

A: 1) Install: tns plugin add nativescript-uuid
2) This code works:
<script>
var plugin = require("nativescript-uuid");

export default {
  data: () => {
    return {
      message: "<!-- testpage -->"
    };
  },
  methods: {
    uuid() { // called from a button @tap
      var uuid = plugin.getUUID();
      console.log("The device UUID is " + uuid);
    }
  }
};
</script>

3) console output: *CONSOLE LOG file:///app/components/Search.vue:32:0: 'The device UUID is B62CFD5E-C012-49E7-80CA-5DD9D0AC8F10'
4) you can do this in mounted: too


text:
Q: Why MongoDB Class doesn't work in Laravel? I want to use MongoDB in Laravel. This is my code inside of the controller:
public function create (Request $request) {
    $m = new MongoClient();
    $db = $m->selectDB("Laravel");
    $collection = $db->selectCollection("Posts");
    $document = array(
       "Title" => $request->input('Title'),
       "Publisher" => $request->input('Publisher')
    );
    $collection->insert($document);
}

But when I click "Submit", it gives me an error :

Fatal error: Class 'App\Http\Controllers\MongoClient' not found

I have run MongoDB Server and also Wamp and I have installed MongoDB and it's driver for PHP …
What is my mistake ?
(I should say that I haven't done any config for Laravel by using MongoDB. Is it needed ?)

A: Laravel doesn't come with a driver for MongoDB.
If you want to use mongo with laravel you'll have to create your own class to deal with it or use this one:
laravel-mongodb


text:
Q: two directories in git submodule I have few repos that requre same files in each. I discovered that I can use git submodules to do it but I got stuck.
Let's say this is a file structure in each of my projects:
MainCatalog/

*

*CatalogA (contains some files)

*CatalogB (contains some files)

*CatalogC (contains some files)

*File1

*File2

*...

And with that structure I'd like to use a submodule for two catalogs (CatalogA and CatalogB)
Is it possible? Or should I use two submodules for each catalog?

A: Yes, you can use git submodules. You just have to see/decide if CatalogA and CatalogB should be in separate repositories.
Since you want these two catalogues to be a submodule, they have to either have separate or one joint git repo.
After that, you only need to add them as a submodule to your projects, like so:
git submodule add https://github.com/<you>/CatalogAandCatalogB

# or if they are in separate repos

git submodule add https://github.com/<you>/CatalogA
git submodule add https://github.com/<you>/CatalogB

Note: if in your project you already have CatalogA and CatalogB, then you can transform your subfolders into submodules easily. This SO answer covers the topic nicely!


text:
Q: How to parse strings from a file in multiple other files? I am trying to grep a list of strings listed in 7253.txt which looks like this:
rs11078372
rs1124961
rs11651880
rs11659047
rs1736209

using:
grep -o -f 7253.txt *.logistic > result.txt

from multiple files *.logistic. The files are on larger size and this grep command takes forever.
.logistic files look like this:
#CHROM  POS  ID REF ALT A1  TEST    OBS_CT  OR  LOG(OR)_SE  Z_STAT  P
17  16933404    rs11867934  T   C   T   ADD 32232   0.974082    0.0279353   -0.940008   0.347213

so the strings from 7253.txt are matched from ID column in .logistic. And they should be the exact match.
Do you have more efficient way to parse those *.logistic files?
There is 22 of these files, and they are named like:FINchr1.pheno.glm.logistic, FINchr2.pheno.glm.logistic...
It would be great if I can have in result.txt extracted columns from .logistic for ID and P (3rd and 12th column)
To extract only ID from .logistic I could do this:
awk 'FNR!=1 {print $3}' *.logistic | grep -o -w -F -f 7253.txt > result.txt

But how to extract ID and P column, which are 3rd and 12th column in .logistic
Thanks
Ana

A: Perhaps you want
awk '
    NR == FNR {ids[$1]=1; next}
    $3 in ids {print $3, $12}
' 7253.txt *.logistic > result.txt


text:
Q: Spring boot mongodb connection time out error I am learning mongodb and basically I have a simple spring boot application which connects to a mongo db to save information.
My application properties is as follows:
spring.data.mongodb.port=27017
spring.data.mongodb.database=emailDb
spring.data.mongodb.username=admin-user123
spring.data.mongodb.password=admin-password123
spring.data.mongodb.authentication-database=admin

So I have created a docker-compose file to link the db with my spring boot app:
version: '3.2'

volumes:
  mongodb_data:     #creates mount point on docker for mongodb
    driver: local

# config postgres, Keycloak & Mongodb
services:
  servicel-component:
    image: servicel-component
    networks:
      test:
        aliases:
          - email
    environment:
      SPRING_PROFILES_ACTIVE: message
      SPRING_RABBITMQ_HOST: rabbitmq
    ports:
      - 8080:8080       # port for postgres
    depends_on:
      - rabbitmq

  rabbitmq:
    image: rabbitmq:3-management
    environment:
      RABBITMQ_DEFAULT_USER: guest
      RABBITMQ_DEFAULT_PASS: guest
    ports:
      - "5672:5672"
      - "15672:15672"
    networks:
      test:
        aliases:
          - rabbitmq
  mongodb:
    image: mongo:latest
    networks:
      test:
        aliases:
          - mongodb
    environment:
      MONGO_INITDB_ROOT_USERNAME: admin-user123
      MONGO_INITDB_ROOT_PASSWORD: admin-password123
    restart: always
    ports:
      - 27017:27017
    volumes:
      - mongodb_data:/data/db
networks:
  test:
    external: true

When u execute docker-compose up the following exception is triggered:
2020-08-07 09:35:23.063 INFO 1 --- [ main] org.mongodb.driver.cluster : Adding discovered server localhost:27017 to client view of cluster

2020-08-07 09:35:23.143 INFO 1 --- [localhost:27017] org.mongodb.driver.cluster : Exception in monitor thread while connecting to server localhost:27017

com.mongodb.MongoSocketOpenException: Exception opening socket

at com.mongodb.internal.connection.SocketStream.open(SocketStream.java:70) ~[mongodb-driver-core-3.11.2.jar!/:na]

at com.mongodb.internal.connection.InternalStreamConnection.open(InternalStreamConnection.java:128) ~[mongodb-driver-core-3.11.2.jar!/:na]

at com.mongodb.internal.connection.DefaultServerMonitor$ServerMonitorRunnable.run(DefaultServerMonitor.java:117) ~[mongodb-driver-core-3.11.2.jar!/:na]

at java.base/java.lang.Thread.run(Thread.java:832) ~[na:na]

Caused by: java.net.ConnectException: Connection refused

at java.base/sun.nio.ch.Net.pollConnect(Native Method) ~[na:na]

at java.base/sun.nio.ch.Net.pollConnectNow(Net.java:589) ~[na:na]

at java.base/sun.nio.ch.NioSocketImpl.timedFinishConnect(NioSocketImpl.java:542) ~[na:na]

at java.base/sun.nio.ch.NioSocketImpl.connect(NioSocketImpl.java:597) ~[na:na]

at java.base/java.net.SocksSocketImpl.connect(SocksSocketImpl.java:333) ~[na:na]

at java.base/java.net.Socket.connect(Socket.java:648) ~[na:na]

at com.mongodb.internal.connection.SocketStreamHelper.initialize(SocketStreamHelper.java:64) ~[mongodb-driver-core-3.11.2.jar!/:na]

at com.mongodb.internal.connection.SocketStream.initializeSocket(SocketStream.java:79) ~[mongodb-driver-core-3.11.2.jar!/:na]

at com.mongodb.internal.connection.SocketStream.open(SocketStream.java:65) ~[mongodb-driver-core-3.11.2.jar!/:na]

... 3 common frames omitted

When I don't run servicel-component on docker, just run it as mvn spring-boot:run and run mongodb on docker it works fine.
Any idea what i am missing here please?

A: You can't use localhost, this refer to the container itself. You need use host IP or use docker DNS if the containers are in the same network (not your case).
2020-08-07 09:35:23.143 INFO 1 --- [localhost:27017] org.mongodb.driver.cluster : Exception in monitor thread while connecting to server localhost:27017


text:
Q: Numpy: Negative Execution Time for exponentiation operation I am multiplying two large matrices, and it turns out the operation is faster when I first perform exponentiation on the first input:
import time
import numpy as np

a = np.asarray(np.random.uniform(-1,1, (100,40000)), dtype=np.float32)
b = np.asarray(np.random.uniform(-1,1, (40000,20000)), dtype=np.float32)

start = time.time()
d0 = np.dot(a,b)
print "\nA.B           - {:.2f} seconds".format((time.time()-start))

start = time.time()
d1 = np.dot(np.exp(a), b)
print "exp(A).B      - {:.2f} seconds".format((time.time()-start))

start = time.time()
d2 = np.dot(a, np.exp(b))
print "A.exp(B)      - {:.2f} seconds".format((time.time()-start))

start = time.time()
d3 = np.dot(np.exp(a), np.exp(b))
print "exp(A).exp(B) - {:.2f} seconds".format((time.time()-start))

Here are the results:
A.B            1.27 seconds
exp(A).B       1.15 seconds
A.exp(B)       7.31 seconds
exp(A).exp(B)  7.38 seconds

Can anyone explain what am I doing wrong, or how is this possible?

A: What you are seeing is the reason why you would never run an operation only once when you are benchmarking, which is kind of what you are attempting here. Many things will affect the result you are seeing when you're only doing it once. In this case, probably some caching-effect. Also, the b array is so much bigger than the a array that you cannot draw any conclusions with a vs np.exp(a) when doing np.exp(b) unless you're running in a very controlled environment.
To more properly benchmark this, we can cut the two last benchmarks and focus on a vs exp(a). Also, we repeat the operation 10,000 times and reduce the size of the arrays to avoid having to wait for several minutes:
import time
import numpy as np

a = np.asarray(np.random.uniform(-1,1, (100,400)), dtype=np.float32)
b = np.asarray(np.random.uniform(-1,1, (400,2000)), dtype=np.float32)

start = time.time()
for i in xrange(10000):
    d0 = np.dot(a,b)
print "\nA.B           - {:.2f} seconds".format((time.time()-start))

start = time.time()
for i in xrange(10000):
    d0 = np.dot(np.exp(a), b)
print "exp(A).B      - {:.2f} seconds".format((time.time()-start))

This yields the following result on my computer:
A.B           - 7.87 seconds
exp(A).B      - 13.24 seconds

As you see, doing np.exp(a) now takes more time than just accessing a, as expected.

A: I suspect this to be a matter of memory-caching, since inverting the order of the executions
import time
import numpy as np

a = np.asarray(np.random.uniform(-1,1, (100,4000)), dtype=np.float32)
b = np.asarray(np.random.uniform(-1,1, (4000,20000)), dtype=np.float32)

start = time.time()
d1 = np.dot(np.exp(a), b)
print "exp(A).B      - {:.2f} seconds".format((time.time()-start))

start = time.time()
d0 = np.dot(a,b)
print "A.B           - {:.2f} seconds".format((time.time()-start))

start = time.time()
d1 = np.dot(np.exp(a), b)
print "exp(A).B      - {:.2f} seconds".format((time.time()-start))

start = time.time()
d0 = np.dot(a,b)
print "A.B           - {:.2f} seconds".format((time.time()-start))

will still cause the second statement to be quicker than the first, but second executions of the same statements run also quicker the second time.
exp(A).B      - 0.72 seconds
A.B           - 0.70 seconds
exp(A).B      - 0.70 seconds
A.B           - 0.69 seconds

(I had to reduce the size of the arrays to avoid memory-issues.)


text:
Q: Resize image and place in a byte array for CrystalReports BlobField I've tried to search for this and have code that should work as far as I can see, but the resulting image in my Crystal Report is 5 pages instead of 1 for some reason!
Basically, I have a Crystal Report with a full page image taken from a BlobField that works perfectly when the source image is 2409 pixels wide and 3436 pixels high @ 300 dpi.
When I try to use a source image that is 1700 wide by 2436 high @ 200 dpi, the image height is too great and hangs off the report onto the next page a bit
I thought "no problem, I will just resize the image and the report will display correctly" but I'm having major difficulty in doing so.. Here's the code I'm using at the moment- when using the "normal" image size and this code, everything displays fine in the report but if I need to resize, it stretches massively wide and over FIVE pages which is even worse than leaving it alone! :(
Dim fs As System.IO.FileStream = New System.IO.FileStream(FilePath, System.IO.FileMode.Open, System.IO.FileAccess.Read)
Dim Image() As Byte = New Byte(fs.Length - 1) {}
fs.Read(Image, 0, CType(fs.Length, Integer))
fs.Close()

'Byte[] to image
Dim imgMemoryStream = New IO.MemoryStream(Image)
Dim myImage = Drawing.Image.FromStream(imgMemoryStream)

' Check if image is 2409 wide, if it's not then resize to 2409 while preserving aspect ratio. WIN.
If myImage.Width <> 2409 Then
    MsgBox("myimage before: " & myImage.Width & " by " & myImage.Height)
    myImage = ImageResize(myImage, 3436, 2409)
    MsgBox("myimage after: " & myImage.Width & " by " & myImage.Height)
Else
    MsgBox("myimage (already correct for printing): " & myImage.Width & " by " & myImage.Height)
End If

Dim imgMemoryStream2 As IO.MemoryStream = New IO.MemoryStream()
myImage.Save(imgMemoryStream2, System.Drawing.Imaging.ImageFormat.Jpeg)
Image = imgMemoryStream2.ToArray

objDataRow(strImageField) = Image

So I'm grabbing the original image into a byte array (as I assume the image size is "normal" by default and will just insert it straight into the BlobField) and then converting it back into an image to check the image size. If the size isn't "normal" then I'm resizing the image then converting it back into a byte array to feed to the BlobField in the report.
This is the image resize code:
Public Shared Function ImageResize(ByVal image As System.Drawing.Image, _
ByVal height As Int32, ByVal width As Int32) As System.Drawing.Image
Dim bitmap As System.Drawing.Bitmap = New System.Drawing.Bitmap(width, height, image.PixelFormat)
If bitmap.PixelFormat = Drawing.Imaging.PixelFormat.Format1bppIndexed Or _
bitmap.PixelFormat = Drawing.Imaging.PixelFormat.Format4bppIndexed Or _
bitmap.PixelFormat = Drawing.Imaging.PixelFormat.Format8bppIndexed Or _
bitmap.PixelFormat = Drawing.Imaging.PixelFormat.Undefined Or _
bitmap.PixelFormat = Drawing.Imaging.PixelFormat.DontCare Or _
bitmap.PixelFormat = Drawing.Imaging.PixelFormat.Format16bppArgb1555 Or _
bitmap.PixelFormat = Drawing.Imaging.PixelFormat.Format16bppGrayScale Then
Throw New NotSupportedException("Pixel format of the image is not supported.")
End If
Dim graphicsImage As System.Drawing.Graphics = System.Drawing.Graphics.FromImage(bitmap)
graphicsImage.SmoothingMode = Drawing.Drawing2D.SmoothingMode.HighQuality
graphicsImage.InterpolationMode = Drawing.Drawing2D.InterpolationMode.HighQualityBicubic
graphicsImage.DrawImage(image, 0, 0, bitmap.Width, bitmap.Height)
graphicsImage.Dispose()
Return bitmap
End Function

Maybe I'm addressing the problem incorrectly but basically I'm trying to find a way to allow images of any size to be dropped into the Crystal Reports BlobField and have them take up one full A4 page.

A: You should have your image (as byte[]) stored somewhere already, pass it to this ResizeBytes function, along with the new dimensions you'd like your returned image to be.
private byte[] ResizeBytes(byte[] byteImageIn, int NewWidth, int NewHeight)
{
    //Convert Bytes to Image
    MemoryStream ms1 = new MemoryStream(byteImageIn);
    Image img = Image.FromStream(ms1);

    //Convert Image in to new image with new dimensions, padding with a white background
    img = FixedSize(img, NewWidth, NewHeight);

    //Convert image back to a byte array
    MemoryStream ms2 = new MemoryStream();
    img.Save(ms2, System.Drawing.Imaging.ImageFormat.Jpeg);
    byte[] imageBytes = ms2.ToArray();
    return imageBytes;
}

The FixedSize function:
private Image FixedSize(Image imgPhoto, int Width, int Height)
{
    int sourceWidth = imgPhoto.Width;
    int sourceHeight = imgPhoto.Height;
    int sourceX = 0;
    int sourceY = 0;
    int destX = 0;
    int destY = 0;

    float nPercent = 0;
    float nPercentW = 0;
    float nPercentH = 0;

    nPercentW = ((float)Width / (float)sourceWidth);
    nPercentH = ((float)Height / (float)sourceHeight);
    if (nPercentH < nPercentW)
    {
        nPercent = nPercentH;
        destX = System.Convert.ToInt16((Width -
                      (sourceWidth * nPercent)) / 2);
    }
    else
    {
        nPercent = nPercentW;
        destY = System.Convert.ToInt16((Height -
                      (sourceHeight * nPercent)) / 2);
    }

    int destWidth = (int)(sourceWidth * nPercent);
    int destHeight = (int)(sourceHeight * nPercent);

    Bitmap bmPhoto = new Bitmap(Width, Height,
                      PixelFormat.Format48bppRgb); //Format24bppRgb
    bmPhoto.SetResolution(imgPhoto.HorizontalResolution,
                     imgPhoto.VerticalResolution);

    Graphics grPhoto = Graphics.FromImage(bmPhoto);
    grPhoto.Clear(Color.White);
    grPhoto.InterpolationMode =
            InterpolationMode.HighQualityBicubic;

    grPhoto.DrawImage(imgPhoto,
        new Rectangle(destX, destY, destWidth, destHeight),
        new Rectangle(sourceX, sourceY, sourceWidth, sourceHeight),
        GraphicsUnit.Pixel);

    grPhoto.Dispose();
    return bmPhoto;
}


text:
Q: How can I define two structs, each one used in the second one ? C language Can i define two struct and use each one in the other one?
my code below .
I try to use typedef, but not working.
struct Book{
int isbn;
char title[21];
//This is Auther struct usage;
struct Auther bauther[21];
int numofauth;
char section[21];
int copies;
};

struct Auther{
char auth_name[21];
//This is Book struct usage;
struct Book auth_books[21];
};

J:\Collage_Library\main.c|23|error: redefinition of 'struct Auther'|

A: A struct cannot be inside another struct that is inside the first struct, for the same reason that in the real world you cannot put an object inside another object inside the first object.
An object can refer to another object using a pointer.
For example, a struct Book could have a member that is a pointer to a struct Author or that is an array of pointers to struct Author. That could be declared like this:
struct Book
{
    int isbn;
    char title[21];
    struct Author *bauthor[21]; // Array of pointers to struct Author.
    int numofauth;
    char section[21];
    int copies;
};

Similarly, the struct Author could contain pointers to struct Book:
struct Author
{
    char auth_name[21];
    struct Book *auth_books[21]; // Array of pointers to struct Book.
};

When you create struct Book or struct Author objects, you will have to fill in the pointers. To do this, you will have to create each of the structures and then assign values to the pointers. For example:
struct Book *b = malloc(sizeof *b);
if (b == NULL) ReportErrorAndExit();
struct Author *a = malloc(sizeof *a);
if (a == NULL) ReportErrorAndExit();

b->isbn = 1234;
strcpy(b->title, "Forward Declarations");
b->bauthor[0] = a; // List a as one of b's authors.
b->numofauth = 1;
strcpy(b->section, "Structures");
b->copies = 1;

strcpy(a->auth_name, "C committee");
a->auth_books[0] = b; // List b as one of a's books.

A: Here is a simple example with a one-by-one reference.
#include  <stdio.h>

struct Book {
    char title[21];
    struct Auth *auth;
};

struct Auth {
    char name[21];
    struct Book *book;
};

int main(void)
{
    struct Auth a = { "People of God" , NULL };
    struct Book b = { "42-line Bible", &a };
    a.book = &b;

    printf("book title:  %s\r\n", b.title);
    printf("book author: %s\r\n", b.auth->name);

    printf("auth name:   %s\r\n", a.name);
    printf("auth book:   %s\r\n", a.book->title);

    return 0;
}


text:
Q: Uncaught TypeError with bootstrap-table and angular with sever-side pagination I am getting Uncaught TypeError: bsTable.$s.$applyAsync is not a function.
HTML page code:

the Javascript part:

i have imported the dependencies as:

and my bower.json:
"bootstrap-table": "1.9.0",
"angular": "~1.2.28",
"angular-route": "~1.2.28",
"angular-resource": "~1.2.28",

also tasks api returns result as:
{"rows": [{"status": "SUCCESS", "_id": "db672f91-cf56-4cf1-add2-216e7b069bbb", "date_done": "March 22, 2015 07:17:19 AM"}, {"status": "SUCCESS", "_id": "a44b670c-83c4-49ad-bbe4-11403c1b736e", "date_done": "March 22, 2015 07:17:29 AM"}, {"status": "SUCCESS", "_id": "ac60726e-edf7-4222-9cbb-88cfed5be69b", "date_done": "March 22, 2015 07:17:29 AM"}, {"status": "SUCCESS", "_id": "d3668982-bb3f-42b5-82eb-9b09ead36766", "date_done": "March 22, 2015 07:17:31 AM"}, {"status": "SUCCESS", "_id": "f97f89c1-53ff-4959-a2ad-2e7cfad37f48", "date_done": "March 22, 2015 07:17:41 AM"}, {"status": "SUCCESS", "_id": "84048949-ded1-4fe9-b699-d904c69d9d6c", "date_done": "March 22, 2015 07:17:42 AM"}, {"status": "SUCCESS", "_id": "3e06d66b-ba64-4d27-af8d-852356cd0063", "date_done": "March 22, 2015 07:17:44 AM"}, {"status": "SUCCESS", "_id": "82546768-461c-4474-9acb-0954e161e83c", "date_done": "March 22, 2015 07:17:52 AM"}, {"status": "SUCCESS", "_id": "92109e36-d27d-474a-a3e2-f34b743e3fbc", "date_done": "March 22, 2015 07:17:54 AM"}, {"status": "SUCCESS", "_id": "c4d6c39b-facc-4a88-8aa6-15753d7297ab", "date_done": "March 22, 2015 07:17:54 AM"}], "total": 109}

where i am making mistake??

A: I Just got the same error and I resolved with the below change
Open your bootstrap-table-angular.js file and replace $applyAsync with $evalAsync
It solves the error because as this is the preferred method in Angular ^1.4.


text:
Q: Redirection or pipe inside `find -exec` Any "find -exec" guru's around.
I have a folder of files I need to send to sendmail (they appear in there when something bad has happened).

*

*The command
find . -type f -exec sendmail -t < {} \;

gives me
-bash: {}: No such file or directory

It doesn't seem to like the <.

*And this
find . type -f -exec cat {} |sendmail -t \;

gives me
find: missing argument to `-exec'

It doesn't seem to like the |.
What is wrong?

A: It looks like you'd like this redirection (<) or pipe (|) to belong to the inside of the -exec … ; statement. This doesn't work because they are handled by your shell before find even runs.
To make them work you need another shell inside -exec … ;. This other shell will handle < or |. Respectively:
find . -type f -exec sh -c 'sendmail -t < "$1"' sh {} \;
find . -type f -exec sh -c 'cat "$1" | sendmail -t' sh {} \;

Note: find . -type f -exec sh -c 'sendmail -t < "{}"' \; is less complicated but wrong. This is explained here: Is it possible to use find -exec sh -c safely?

A: In both cases your redirection is parsed by the shell, not by find, so you need to escape it:
find . -type f -exec sendmail -f \< {} \;

works as expected.


text:
Q: Append data to a cell in a datatable? is there a way to append data to an existing cell of a datatable in asp net C# ?
I have a 4 columns as below that forms a gridview that is being sourced by a datatable - dt.
Data is being sourced by reading a txt file. So at the "Result" column the idea is to validate if the parts exists at a Database, so I made a validation for the ChildPartNumber column and then for the ParentParts column. The thing is that at the validation of ParentParts it overwrites the result that I did at the ChildPartNumber column validation and I am looking to append both results so I can have something like this:
How the datatable should look like
Some of the code:
String errorLocation = "Child not found";
dt.Rows[i]["Result"] = errorLocation;

GridView1.DataSource = (DataTable)ViewState["partnumbers"];
GridView1.DataBind();

Any help will be appreciated
Thanks

A: If you want to update the datatable row value, then
 dt.Rows[i]["Result"] += errorLocation;

If you want to edit the gridview cell value then you can do it in gridview rowdatabound event. ex: http://www.dotnetlearners.com/blogs/view/120/aspnet-gridview-rowdatabound-example-using-c-.aspx

A: Here you go:
dt.Rows[i]["Result"] += errorLocation;

Hope this helps!


text:
Q: Foreach loop for three List I want to loop through three List<string>. I'm sending ajax request containing 3 parameter as Array.
This is my WebMethod.
 public string saveEachTask(string imageData, string desc, string tid)
    {
            var imglist = imageData.Split(',').ToList();
            var desclist = desc.Split(',').ToList();
            var idlist = tid.Split(',').ToList();
           // here i want a foreach loop for above three list
            return "Saved Succesfully";
    }

Edit: in loop how can I identity which string is for img, desc and id
Any Help appreciated.

A: Perhaps something like this:
foreach (var list in new[] {imglist, desclist, idlist})
{
  foreach (var s in list)
  {
  }
}

A: If you need to handle everything the same way in your loop, you could try:
foreach(var s in imglist.Union(desclist.Union(idlist)))
{
    // do something with the string
}

A: Use one loop and each iteration process each list.
public string saveEachTask(string imageData, string desc, string tid)
{
  var imglist = imageData.Split(',').ToList();
  var desclist = desc.Split(',').ToList();
  var idlist = tid.Split(',').ToList();

  int maxLength = Math.Max(imglist.Count, Math.Max(desclist.Count, idlist.Count));

  for (int i = 0; i < maxLength; ++i)
  {
    string imgItem = (i < imglist.Count ? imglist[i] : null);
    string descItem = (i < desclist.Count ? desclist[i] : null);
    string idItem = (i < idlist.Count ? idlist[i] : null);

    // TODO: Process imgItem, descItem, idItem
  }

  return "Saved Succesfully";
}


text:
Q: C#: Windows Form creating table and and retrieve data from database by each dynamic button click
*

*I am trying  to develop a restaurant billing application in windows form.

*so I created dynamic buttons.

*now I need a table which will retrieve data from database for each button click.

How can it possible?
 private void newb_Click(object sender, EventArgs e)
 {
     Button btn = (Button)sender;
     //  textBox1.Text = btn.Text;
     connection con = new connection();
     con.connecting();
     // Button b = new Button();
     int i = 0;
     var query = "select itemname,itemcode,price from item_master                     where itemcode =" + btn.Name;
     MySqlCommand cmd = new MySqlCommand(query, con.con);
     while (i < 10)
     {

         MySqlDataAdapter sda = new MySqlDataAdapter();
         DataTable dt = new DataTable();
         sda.SelectCommand = cmd;
         DataTable dbdataset = new DataTable();
         sda.Fill(dbdataset);
         BindingSource bsource = new BindingSource();
         bsource.DataSource = dbdataset;

         dataGridView1.DataSource = bsource;
      //  MessageBox.Show(btn.Name);
         i++;
     }
    // sda.Update(dbdataset);
 //  =dataGridView1.Rows[0]

//// MySqlDataReader mdr;
//// mdr = cmd.ExecuteReader();
// while (mdr.Read())
// {
////  textBox1.Text = (mdr["itemname"].ToString());
// }
}

 private void textBox1_TextChanged(object sender, EventArgs e)
 {

 }

 private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
 {

 }


text:
Q: Passing colors through a pixel shader in HLSL I have have a pixel shader that should simply pass the input color through, but instead I am getting a constant result. I think my syntax might be the problem. Here is the shader:
struct PixelShaderInput
{
    float3 color : COLOR;
};

struct PixelShaderOutput
{
    float4 color : SV_TARGET0;
};

PixelShaderOutput main(PixelShaderInput input)
{
    PixelShaderOutput output;
    output.color.rgba = float4(input.color, 1.0f); // input.color is 0.5, 0.5, 0.5; output is black
    // output.color.rgba = float4(0.5f, 0.5f, 0.5f, 1); // output is gray
    return output;
}

For testing, I have the vertex shader that precedes this in the pipleline passing a COLOR parameter of 0.5, 0.5, 0.5. Stepping through the pixel shader in VisualStudio, input.color has the correct values, and these are being assinged to output.color correctly. However when rendered, the vertices that use this shader are all black.
Here is the vertex shader element description:
const D3D11_INPUT_ELEMENT_DESC vertexDesc[] =
{
    { "POSITION",   0, DXGI_FORMAT_R32G32B32_FLOAT, 0, D3D11_APPEND_ALIGNED_ELEMENT, D3D11_INPUT_PER_VERTEX_DATA, 0 },
    { "COLOR",      0, DXGI_FORMAT_R32G32B32_FLOAT, 0, D3D11_APPEND_ALIGNED_ELEMENT, D3D11_INPUT_PER_VERTEX_DATA, 0 },
    { "TEXCOORD",   0, DXGI_FORMAT_R32G32_FLOAT,    0, D3D11_APPEND_ALIGNED_ELEMENT, D3D11_INPUT_PER_VERTEX_DATA, 0 },
};

I'm not sure if it's important that the vertex shader takes colors as RGB outputs the same, but the pixel shader outputs RGBA. The alpha layer is working correctly at least.
If I comment out that first assignment, the one using input.color, and uncomment the other assignment, with the explicit values, then the rendered pixels are gray (as expected).
Any ideas on what I'm doing wrong here?
I'm using shader model 4 level 9_1, with optimizations disabled and debug info enabled.

A: output.color.rgba = float4(input.color, 1.0f);

your input.color is a float4 and you are passing it into another float4, i think this should work
output.color.rgba = float4(input.color.rgb, 1.0f);

this is all you need to pass it thru simply
 return input.color;

if you want to change the colour to red then do something like
input.color = float4(1.0f, 0.0f, 0.0f, 1.0f);
return input.color;

A: *Are you sure that your vertices are in the place they are supposed to be? You are starting to make me doubt my D3D knowledge. :P
I believe your problem is that you are only passing a color,
BOTH parts of the shader NEED a position in order to work.
Your PixelShaderInput layout should be:
    struct PixelShaderInput
    {
        float4 position :SV_POSITION;
        float3 color : COLOR;
    };*
Could you maybe try this as your pixel shader?:
float4 main(float3 color : COLOR) : SV_TARGET
{
    return float4(color, 1.0f);
}

A: I have never seen this kind of constructor
float4(input.color, 1.0f);

this might be the problem, but I could be wrong. Try passing the float values one by one like this:
float4(input.color[0], input.color[1], input.color[2], 1.0f);

Edit:
Actually you might have to use float4 as type for COLOR (http://msdn.microsoft.com/en-us/library/windows/desktop/bb509647(v=vs.85).aspx)


text:
Q: If $H \unlhd G$ is CC-closed, then $H$ is a Hall subgroup I'm stuck with this problem.
Let $H$ be a normal subgroup of a finite group $G$ such that $C_G(x)\subseteq H$ for every non-identity element $x\in H$ (that is, $H$ is a normal CC-subgroup of $G$).
Then $\textrm{gcd}(|H|,|G/H|)=1$ (i.e. $H$ is a Hall-subgroup of $G$).
I think that Sylow's Theorems would be helpful here.
I spent hours thinking and I couldn't solve it.
Thanks in advance.

A: Hint: Consider a p-element of H and an element of the center of a Sylow p-subgroup containing it.  Centers and centralizers unite!

 If p divides H, then let Q be a Sylow p-subgroup of H, and let P be a Sylow p-subgroup of G containing Q.  Let z be an element of the center of P, and let x be a non-identity element of Q.  Since x and z commute, $z \in C_G(x) \leq H$, and so z in H.  However, z is in the center of P, and so $P \leq C_G(z) \leq H$ and P is actually a Sylow p-subgroup of H as well.  Hence $[G:H]$ is not divisible by p.


text:
Q: What is the recommended way to decorate request and response object with custom helpers in marblejs? As the title of the question, what are the guidelines for decorating request and response object with custom data or helpers in marble.js or Node.js in general?
This situation arises when there is a middleware that wishes to inject or decorate request with additional data, ex. authorization middleware adding auth data or helper functions added by middleware to help with streaming large files.
As I currently understand, marblejs exposes HTTPRequest and HTTPResponse objects. They are simply extending native Node.js request and response object as:
export interface HttpRequest extends http.IncomingMessage {}
export interface HttpResponse extends http.ServerResponse {}


text:
Q: heroku migrations silently failing Note: this is my first time configuring a rails application, deploying a rails app and setting up a database. I very well might be doing something obviously stupid.
I have a working rails application setup with postgres 9.3. I can run migrations, run my server locally and get a running application locally.
I pushed my code up to heroku and at one point it ran. Now when I run the heroku console it shows that my database is totally empty and I cannot figure out how to recreate it.
I am using v 0.17.1 of the pg gem.
Here are the steps I have taken.
1) Created my database.yml
development:
  adapter: postgresql
  encoding: unicode
  database: fr_development
  pool: 5
  username: user
  password: password

test:
  adapter: postgresql
  encoding: unicode
  database: fr_test
  pool: 5
  username: user
  password: password

production:
  url: <%= ENV['DATABASE_URL'] %>

1.5) setup my heroku account and installed papertrail
2) Made sure my schema.rb and all migrations are under source control.
3) ran "git push heroku master"
4) ran "heroku run db:drop db:setup --app app" or alternately sometime "heroku pg:reset DATABASE_URL"
5)  ran "heroku run rake db:migrate --app app"
6) ran "heroku restart --app app"
Basically no matter what I run, all i get in papertrail is:
Nov 09 11:19:50 app heroku/api:  Starting process with command `bundle exec rake db:drop db:create db:migrate RAILS_ENV=production` by email@gmail.com
Nov 09 11:19:53 app heroku/run.3003:  Awaiting client
Nov 09 11:19:53 app heroku/run.3003:  Starting process with command `bundle exec rake db:drop db:create db:migrate RAILS_ENV=production`
Nov 09 11:19:53 app heroku/run.3003:  State changed from starting to up
Nov 09 11:19:54 app heroku/run.3003:  Process exited with status 0
Nov 09 11:19:54 app heroku/run.3003:  State changed from up to complete

And then if I hit my server Ill get an error that one of my relations doesnt exist.
If I "heroku run console" and try to run any of my tables it will say they dont exist.
One thing I no nothing about and am having a hard time finding resources to learn about is proper configurations for bin directory stuff. I have not touched
my bin/bundle is totally empty
#!bin/rails

begin
  load File.expand_path("../spring", __FILE__)
rescue LoadError
end
APP_PATH = File.expand_path('../../config/application',  __FILE__)
require_relative '../config/boot'
require 'rails/commands'

.
#bin/rake
begin
  load File.expand_path("../spring", __FILE__)
rescue LoadError
end
require_relative '../config/boot'
require 'rake'
Rake.application.run

.
#bin/spring
unless defined?(Spring)
  require "rubygems"
  require "bundler"

  if match = Bundler.default_lockfile.read.match(/^GEM$.*?^    spring \((.*?)\)$.*?^$/m)
    ENV["GEM_PATH"] = ([Bundler.bundle_path.to_s] + Gem.path).join(File::PATH_SEPARATOR)
    ENV["GEM_HOME"] = ""
    Gem.paths = ENV

    gem "spring", match[1]
    require "spring/binstub"
  end
end

if I run heroku pg:info i get
HEROKU_POSTGRESQL_ONYX_URL (DATABASE_URL)
Plan:        Hobby-dev
Status:      Available
Connections: 1/20
PG Version:  9.3.3
Created:     2014-11-06 04:08 UTC
Data Size:   6.5 MB
Tables:      0
Rows:        0/10000 (In compliance)
Fork/Follow: Unsupported
Rollback:    Unsupported

One last thing that may be relevant I keep seeing this stack trace in paper trail although I'm not sure if it is just what happens when I reset the app:
[2014-11-10 03:39:58] FATAL SignalException: SIGTERM
Nov 09 19:39:58 app app/web.1:      /app/vendor/ruby-2.1.4/lib/ruby/2.1.0/webrick/server.rb:170:in `select'
Nov 09 19:39:58 app app/web.1:      /app/vendor/ruby-2.1.4/lib/ruby/2.1.0/webrick/server.rb:170:in `block in start'
Nov 09 19:39:58 app app/web.1:      /app/vendor/ruby-2.1.4/lib/ruby/2.1.0/webrick/server.rb:32:in `start'
Nov 09 19:39:58 app app/web.1:      /app/vendor/ruby-2.1.4/lib/ruby/2.1.0/webrick/server.rb:160:in `start'
Nov 09 19:39:58 app app/web.1:      /app/vendor/bundle/ruby/2.1.0/gems/rack-1.5.2/lib/rack/handler/webrick.rb:14:in `run'
Nov 09 19:39:58 app app/web.1:      /app/vendor/bundle/ruby/2.1.0/gems/rack-1.5.2/lib/rack/server.rb:264:in `start'
Nov 09 19:39:58 app app/web.1:      /app/vendor/bundle/ruby/2.1.0/gems/railties-4.1.5/lib/rails/commands/server.rb:69:in `start'

I have really tried to debug this one but I am out of ideas. Any help would be greatly appreciated.
other note: I setup postgres for the first time right before this. I was mucking around with it alot destorying and creating users and destroying and creating tables but I got everything back to a functional state locally. Don't know if that could somehow play into this.

A: Just to make sure, if you haven't already, first run:
heroku run rake db:migrate

And if then if that doesn't work:
heroku pg:reset

Followed by the heroku run rake db:migrate again.
By the way, I don't think Heroku gives you permission to to drop or create. Thus they've implemented pg:reset.
I found the devcenter doc that mentions permissions for dropping and creating and on using pg:reset here:
https://devcenter.heroku.com/articles/rake


text:
Q: Adding 'selected' attribute to user's selected option after 'change' with jQuery I have a select element that I am adding options to dynamically using data from a variable called 'results':
HTML:
<select id="categories">
    <option selected disabled>Select your category</option>
</select>

jQuery:
$.each(results.Subcategories, function(index,category) {
    var category = '<option value="'+category.Name+'" data-index="'+index+'">'+category.Name+'</option>';
    $('#categories').append(category);
});

This works correctly and I am able to choose between the dynamically added options in the select element.
What I need to do now is get the 'value' attribute of the currently selected AFTER the user has chosen it from the added options. This is where I am getting stuck. I thought that something like this would work:
$('#categories').on('change', function() {
    var optionSelected = $("#categories option:selected", this);
    console.log($(optionSelected).data("value"))
});

But the selected attribute does not move on the options when I choose a new one, so I am unable to target that attribute to get the value.
Assuming the approach above is solid, how do I get my newly selected option to have the selected attribute so I can target it and get the value? Or is there a better approach that I'm missing? Thanks in advance.

A: Selected attribute will select an option from load. What you need is this.val() or you could use plain javascript and use getElementById(id of your option element).value() and get the value that way.


text:
Q: Nginx access log shows authenticated user "admin" I came across a line in my Nginx access log:
218.201.121.99 - admin [12/Dec/2012:18:33:18 +0800] "GET /manager/html HTTP/1.1" 444 0 "-" "-"

Let me stress that there is only 1 record with this IP.
Notice the authenticated user admin.
After some googling, I was able to find out only that this is authenticated user (http://wiki.nginx.org/HttpCoreModule#.24remote_user), which was authenticated by the Auth Basic Module (http://wiki.nginx.org/HttpAuthBasicModule).
However, nowhere in my site (configuration) do I use HTTP basic authentication.
What is going on? How did it get there? Was the user authenticated?

A: The fact that a username was given in the log means only that the client passed a username (and presumably a password). It does not necessarily mean that it authenticated successfully. In fact, we can see from your log entry that it did not; nginx returned a 444, an internal error which means nginx dropped the connection without sending anything.


text:
Q: Remove initial silence from recorded audio file of wave type Can anyone help me out removing the initial silence in recorded audio file?
I am fetching the data bytes of wav file and after ignoring first 44 header bytes getting the end range of 0 bytes which are silent in wave file.
After that from total data bytes, end range of silent audio bytes and total duration of file, I am calculating the silence time of audio file and trimming that much time from audio file.
But the issue is still there is some silent part remaining in audio file.
So not sure if I missed something?
- (double)processAudio:(float)totalFileDuration withFilePathURL:(NSURL *)filePathURL{
    NSMutableData *data = [NSMutableData dataWithContentsOfURL:filePathURL];
    NSMutableData *Wave1= [NSMutableData dataWithData:[data subdataWithRange:NSMakeRange(44, [data length] - 44)]];
    uint8_t * bytePtr = (uint8_t  * )[Wave1 bytes] ;
    NSInteger totalData = [Wave1 length] / sizeof(uint8_t);
    int endRange = 0;
    for (int i = 0 ; i < totalData; i ++){
           /
        if (bytePtr[i] == 0) {
            endRange = i;
        }else
            break;
    }

    double silentAudioDuration =(((float)endRange/(float)totalData)*totalFileDuration);
    return silentAudioDuration;
}
- (void)trimAudioFileWithInputFilePath :(NSString *)inputPath toOutputFilePath : (NSString *)outputPath{
    /
    NSString *strInputFilePath = inputPath;
    NSURL *audioFileInput = [NSURL fileURLWithPath:strInputFilePath];

    /
    NSString *strOutputFilePath = [outputPath stringByDeletingPathExtension];
    strOutputFilePath = [strOutputFilePath stringByAppendingString:@".m4a"];
    NSURL *audioFileOutput = [NSURL fileURLWithPath:strOutputFilePath];
    newPath = strOutputFilePath;

    if (!audioFileInput || !audioFileOutput){
        /
    }

    [[NSFileManager defaultManager] removeItemAtURL:audioFileOutput error:NULL];
    AVAsset *asset = [AVAsset assetWithURL:audioFileInput];
    CMTime audioDuration = asset.duration;
    float audioDurationSeconds = CMTimeGetSeconds(audioDuration);

    AVAssetExportSession *exportSession = [AVAssetExportSession exportSessionWithAsset:asset presetName:AVAssetExportPresetAppleM4A];

    if (exportSession == nil){
        /
    }

    /
    float startTrimTime = [self processAudio:audioDurationSeconds withFilePathURL:audioFileInput];
    /
    /
    float endTrimTime = audioDurationSeconds;

    recordingDuration = audioDurationSeconds - startTrimTime;

    CMTime startTime = CMTimeMake((int)(floor(startTrimTime * 100)), 100);
    CMTime stopTime = CMTimeMake((int)(ceil(endTrimTime * 100)), 100);
    CMTimeRange exportTimeRange = CMTimeRangeFromTimeToTime(startTime, stopTime);

    exportSession.outputURL = audioFileOutput;
    exportSession.outputFileType = AVFileTypeAppleM4A;
    exportSession.timeRange = exportTimeRange;

    [exportSession exportAsynchronouslyWithCompletionHandler:^{
         if (AVAssetExportSessionStatusCompleted == exportSession.status){
         }
         else if (AVAssetExportSessionStatusFailed == exportSession.status){
         }
     }];
}

What am I doing wrong here?

A: It is possible that you don't have complete silence in your files?  Perhaps your sample has a value of 1 or 2 or 3 which technically is not silent but it is very quiet.
Wave files are stored as signed numbers if 16 bits and unsigned if 8 bits.  You are processing and casting your data to be an unsigned byte:
    uint8_t * bytePtr = (uint8_t  * )[Wave1 bytes] ;
You need to know the format of your wave file which can be obtained from the header.  (It might use sample sizes of say  8 bit, 16 bit, 24 bit, etc.)
If it is 16 bits and mono, you need to use:
int16_t * ptr = (int16_t) [Wave1 bytes];

Your loop counts one byte at a time so you would need to adjust it to increment by the size of your frame size.
You also don't consider mono/stereo.
In general, your processAudio function needs more details and should consider the number of channels per frame (stereo/mono) and the size of the sample size.
Here is a wave header with iOS types.  You can cast the first 44 bytes and get the header data so you know what you are dealing with.
typedef struct waveHeader_t
{
    //RIFF
    char        chunkID[4];             ///< Should always contain "RIFF" BigEndian    //4
    uint32_t    chunkSize;              ///< total file length minus 8  (little endian!!!)    //4
    char        format[4];              ///< should be "WAVE"  Big Endian

    // fmt
    char        subChunk1ID[4];         ///< "fmt " Big Endian                //4
    uint32_t    subChunk1Size;          ///< 16 for PCM format                        //2
    uint16_t    audioFormat;            ///< 1 for PCM format                       //2
    uint16_t    numChannels;            ///< channels                                     //2
    uint32_t    sampleRate;             ///< sampling frequency                           //4
    uint32_t    byteRate;               ///< samplerate * numchannels * bitsperSample/8
    uint16_t    blockAlign;             ///< frame size
    uint16_t    bitsPerSample;          ///< bits per Sample

    char        subChunk2ID[4];         ///< should always contain "data"
    uint32_t    subChunk2Size;          ///<

    ///< sample data follows this.....
} waveHeader_t;

So your todo list is

*

*Extract the fields from the header

*Specifically get number of channels and bits per channel  (note **BITS per channel)

*Point to the data with the appropriate size pointer and loop through one frame at a time.  (A mono frame has one sample that is could be 8, 16, 24 etc bits.  A stereo frame has two samples that could be 8, 16, or 24 bits per sample.  e.g.  LR LR LR LR LR LR would be 6 frames)

A: The header of an Apple generated wave file is usually not 44 bytes in length.  Some Apple generated headers are 4k bytes in length.  You have to inspect the wave RIFF header for extra 'FFLR' bytes.  If you don't skip past this extra filler padding, you will end up with about an extra tenth of a second in silence (or potentially even bad data).


text: Q: Sending the same notification for multiple times in GCM Push Notifications I am implement the GCM push notification. I have added the registration id for the device in database along with invalid registration id. I am sending auto-generated message from my server to GCM, each message is unique. The problem is I am just getting same notification for 3 or 4 times from GCM. This is due to invalid registration id ?


text:
Q: How to open an .exe through the Command Line in Sikuli? I have PL/SQL Developer installed, and I am trying to get Sikuli to open it through the Command Line.
If I do it manually I do:
1) Open CMD
2) "C:\Program Files (x86)\PLSQL Developer\plsqldev.exe"
3) [Enter]
This is my code:
vcCMD = '"C:\Program Files (x86)\PLSQL Developer\plsqldev.exe"'
App.open('CMD ' + vcCMD)

It did log that the App.open() has runned, but the .exe does not open.
[log] App.open CMD "C:\Program Files (x86)\PLSQL Developer\plsqldev.exe"

Does anyone know how to do this?

A: Found the answer, I needed /C
vcCMD = '"C:\Program Files (x86)\PLSQL Developer\plsqldev.exe"'
App.open('CMD /C ' + vcCMD)

Or even more simple:
run(vcCMD)

A: import os

def firstline(x):
    wait(2)
    os.popen("@echo off")
    t="echo "+x+">log.csv"
    os.popen(t)

def append(x,y):
    wait(2)
    os.popen("@echo off")
    for i in range (0,y):
        x=","+x
        wait(1)
    t="echo "+x+">>log.csv"
    os.popen(t)

firstline("Invalid,test,test1")
append("test1",0)
append("test2",1)
append("test3",2)


text:
Q: Multiple page size and orientation setting in power bi report builder I am working on a report project using Power Bi Report Builder version 15.7.1740.1 (latest).
And I have a request from the customer to create only the first page as portrait as cover page and the remaining pages orientation will be landscape.
The problem is that the builder has only one canvas page and the orientation for this canvas will ignore the size of each page even I use the subreport is not working correctly.
The customer uses this report to an export pdf version, So any idea or workaround how to fix it?
This is the example of the request


text:
Q: Magento Varien_Data_Collection returns wrong size after removing items I'm running on Magento 1.4, but also have verified the problem in 1.7.
Working with an instance of Varien_Data_Collection provides the use of Varien_Data_Collection::removeItemByKey. In my case, I'm removing items from the collection, and later trying to get the updated size of that collection, like so:
$body=$this->getTable()->getBody();

echo $body->getHeight(); // Outputs 25

$body->deleteRow(1);

echo $body->getHeight(); // Still outputs 25

...

My_Model_Body_Class extends Mage_Core_Model_Abstract {

  /* @var $_rows Varien_Data_Collection */
  protected $_rows;

  public function deleteRow($index) {
    $this->_rows->removeItemByKey($index);

    return $this;
  }

  public function getHeight() {
    return $this->_rows->getSize();
  }

}

...

Code limited for brevity.
So if you call my deleteRow method, the item will in fact be removed from the collection, but subsequent calls to get the size of that collection will always return the original count. Therefore, if I have 25 items in the collection, and remove 1, then a call to getSize on the collection returns 25.
I traced this back to the parent class, in Varien_Data_Collection::getSize:
/**
 * Retrieve collection all items count
 *
 * @return int
 */
public function getSize()
{
    $this->load();
    if (is_null($this->_totalRecords)) {
        $this->_totalRecords = count($this->getItems());
    }
    return intval($this->_totalRecords);
}

We see that the count hinges on the NULL status of the _totalRecords property. So it looks like a bug in core code. Am I reading this correctly? Should I just rely on a call to count on the items?

A:
We see that the count hinges on the NULL status of the _totalRecords
  property. So it looks like a bug in core code. Am I reading this
  correctly?

Whether to interpret said behaviour as bug or feature, lies in the eyes of the beholder.
This behaviour is not 1.4 specific, btw; it works the same way up to the current CE version (1.8.1).
public function getSize()
{
    $this->load();
    if (is_null($this->_totalRecords)) {
        $this->_totalRecords = count($this->getItems());
    }
    return intval($this->_totalRecords);
}

Most people for sure expect a method named getSize() to always return the current size, so they may call it a bug, perhaps.
But if you take a closer look at the Varien_Data_Collection class, you'll notice, that getSize() is not the only method that looks somewhat.. "weird".
Take the addItem() and removeItemByKey() methods, for example.
Why don't they increment/decrement the _totalRecords property, when getSize() uses it?
Lazy Loading
The reason for these "weird" behaviours is, that Varien_Data_Collection basically is designed for the usage of the Lazy Loading pattern. That means, it allows to delay loading of the collection, until the data is really needed.
To accomplish this, Varien_Data_Collection implements the IteratorAggregate and Countable interfaces. Their implementation points are the getIterator() and count() methods:
public function getIterator()
{
    $this->load();
    return new ArrayIterator($this->_items);
}

public function count()
{
    $this->load();
    return count($this->_items);
}

As you can see, both of these methods call load() first.
The result of this is, that whenever you use foreach or the PHP function count() on the collection, the load() method automatically will be called first.
Now, for a default Varien_Data_Collection nothing special will happen, when load() is called, because load() only calls loadData() and loadData() only returns $this.
But when it comes to its heavily used child class Varien_Data_Collection_Db, then the call to load() will result in loading the collection and setting _totalRecords to the SQL count of loaded records.
For performance reasons the collection usually will be loaded once only (if it hasn't been loaded yet).
So you see, depending on which context you use Varien_Data_Collection in, it perfectly makes sense, why getSize() behaves this way.

Should I just rely on a call to count on the items?

If your collection is not bound to complex or slow I/O, I'd say: yes.
You can simply use:
$n = count($this->_rows->getItems());

Or even this way:
$n = count($this->_rows->getIterator());


text:
Q: Plot bars next to each of subplots in matplotlib? I'd like to visualize 2D data with bar charts where I want to show totals per X and also ratios of Y's within each X. My idea was a nested bar plot. So I started with the ratio's of Y within each X:
import pandas as pd
import random
import itertools as itoo
import matplotlib.pyplot as plt

random.seed(0)
s=pd.Series([random.randint(1,10) for _ in range(100)],
             index=pd.MultiIndex.from_tuples([(x,y) for x,y in itoo.product(range(10), repeat=2)], names=list("xy")))
fig, axes=plt.subplots(10, sharex=True) # no sharey since only ratios important
for x, ax in zip(range(10), reversed(axes)):
    sx=s[x]
    ax.bar(sx.index, sx, align="center")
    ax.set_xticks(range(10))
    ax.yaxis.set_ticks([])
    ax.set_ylabel(x)
    tot=sx.sum()
    #plot label `x` and a single hbar(width=tot) right next to plot?;

How can I add horizontal bars for totals on the right of each bar plot?
Basically it will look like a full hbar plot of totals for each X on the right of the whole bar plot set (it should also have a labeled xaxis). It's just important to align these bars with the corresponding bar subplots. I'd also like labels per "row" between the subplot and the horizontal bar. I'd also like to make the given subplots (and thus bar) much more narrow.

A: As others said, using gridspec can do it for you. Here's an example of how to do it:
import pandas as pd
import random
import itertools as itoo
import matplotlib.pyplot as plt
import matplotlib.gridspec as gridspec
from numpy import arange,array

random.seed(0)
s=pd.Series([random.randint(1,10) for _ in range(100)],
             index=pd.MultiIndex.from_tuples([(x,y) for x,y in itoo.product(range(10), repeat=2)], names=list("xy")))

fig=plt.figure()
fig.subplots_adjust(hspace=0,wspace=0.5)
gs=gridspec.GridSpec(10,8)

axes=[fig.add_subplot(gs[0,:6])]
[axes.append(fig.add_subplot(gs[i,:6],sharex=axes[0])) for i in range(1,10)]

tot=[] # Keep track of totals

for x, ax in zip(range(10), reversed(axes)):
    sx=s[x]
    ax.bar(sx.index, sx, align="center")
    ax.set_xticks(range(10))
    ax.yaxis.set_ticks([])
    ax.set_ylabel(x)
    tot.append(sx.sum())

#plot label `x` and a single hbar(width=tot) right next to plot
axh=fig.add_subplot(gs[:,6:])
axh.barh(arange(10)-0.4,array(tot))
axh.set_yticks(range(10))
axh.set_ylim(-0.5,9.5)
fig.savefig('test.pdf')

And here's what the output looks like:


text:
Q: how to generate constructors in eclipse I have a class A and B.M extends A. Now I want a create a constructor of B using code generation option of eclipse which accepts parameters and set values of all fields of B (I mean it should also set fields inherited from A).
Is there any shortcut to generate such code in eclipse?

A: Eclipse (3.5) has no built in option for that particular case, but I would anyway suggest that you have a separate constructor in the super class, which the sub-class invokes through super(...) in its constructor.
This would be easier to maintain. If you for instance add a filed in the super class, you would need to remember to update the sub-class as well.
class A {
    int i;
    public A(int i) { this.i = i; }
}

class B extends A {
    int j;
    public B(int i, int j) {
        super(i);
        this.j = j;
    }
}

A: Right click in the editor and click "Source -> Generate Constructor using Fields".  You can select the super constructor to use and also select instance variables to add to the constructor.

A: There is no automatic way to do it and I'm close to believe that the eclipse team did this on purpose as it would lead to bad design.
Constructing a class is about initializing the objects own fields only. If you need to set (init) fields on the superclass, call the superclasses constructor, if you need to change superclass fields, call the superclasses getter and setter methods.
To me it's bad design to init superclass fields and can be avoided easily.


text:
Q: Call a script for another script, but don't exit the parent if the child calls exit first.sh:
#! /bin/ksh
echo "prova"
. ./second.sh
echo "ho lanciato il secondo"
. ./third.sh
echo "ho lanciato il terzo"

second.sh:
echo "sono nel secondo script"
dosomething1
exit $?

If second.sh detects an error and exits with status -9, first.sh exits always.
How I can do avoid exiting from the first shell if the child shell exits?
I can't edit second.sh.

A: Instead of sourcing the second and third shell, just run them as you would any other command. The exit code can be stored and used if you need, like so:
#! /bin/ksh
echo "prova"

# execute and capture stdout ... output of second is not seen ...
OUTPUT1=$(./second.sh)

# find out exit status of second.sh
STATUS1=$?

# ... until now
echo $OUTPUT1

# do something based on the result
if [ $STATUS1 -eq 0 ]; then
  echo "second.sh ran successfully"
else
  echo "second.sh crapped out"
fi

# and so on...

A: What you're doing here is including second.sh and third.sh as sub-scripts running in the same process, which is called "sourcing" in shell programming. . ./second.sh is basically equivalent to including the text of second.sh at that point. The exit command exits the process, it doesn't matter whether you call it in the original script or in a sourced script.
If all you want to do is run the commands in second.sh and third.sh and they don't need to access or modify variables and functions from the original script, call these scripts as child processes.
#! /bin/ksh
echo "prova"
./second.sh
echo "ho lanciato il secondo"
./third.sh
echo "ho lanciato il terzo"

If you need the other scripts to access variables and functions from the original script, but not modify them, then call these scripts in subshells. Subshells are separate processes, so exit exits only them.
#! /bin/ksh
echo "prova"
(. ./second.sh)
echo "ho lanciato il secondo"
(. ./third.sh)
echo "ho lanciato il terzo"

If you need to use variables or functions defined in second.sh and third.sh in the parent script, then you'll need to keep sourcing them.
The return builtin exits only the sourced script and not the whole process — that's one of the few differences between including another script with the . command and including its text in the parent script. If the sourced scripts only call exit at the toplevel, as opposed to inside functions, then you can change exit into return. You can do that without modifying the script by using an alias.
#! /bin/ksh
echo "prova"
alias exit=return
. ./second.sh
echo "ho lanciato il secondo"
. ./third.sh
unalias exit
echo "ho lanciato il terzo"

If exit is also called inside functions, I don't think there's a non-cumbersome way. A cumbersome way is to set an exit trap and put your code there.
#!/bin/ksh
do_first () {
  echo "prova"
  trap "after_second" EXIT
  . ./second.sh
  after_second
}
after_second () {
  echo "ho lanciato il secondo"
  trap "after_third" EXIT
  . ./third.sh
  after_third
}
after_third () {
  trap - EXIT
  echo "ho lanciato il terzo"
}
do_first

A: Try it this way (remove first . on calling second.sh):
first.sh:
#! /bin/ksh
echo "prova"
./second.sh
echo "ho lanciato il secondo"
./third.sh
echo "ho lanciato il terzo"

second.sh:
echo "sono nel secondo script"
dosomething1
exit $?

This is because . is shortcode for source which cause the second script to be included as a part of first one.

A: script1.sh
  1 PWD="/scratch/currdir"
  2 echo "Hello from scrpt 1"
  3
  4 sh $PWD/script2.sh # We will exit in script2.sh and see if line 6 gets printed
  5
  6 echo "From script 1: After scrpt2 call"
  7 exit 0

script2.sh
  1 echo "Hello from script 2"
  2
  3 exit 1
  4 echo "This should not get printed"

Output:
-bash-4.1$ sh script1.sh
Hello from scrpt 1
Hello from script 2
From script 1: After scrpt2 call

(Note: Although we exited script2 (line number 3 with exit 1), but still in script1.sh the line no 6 gets executed post calling script2.sh
Hope this helps.


text:
Q: MySQL - Filtering table based on most current dates My first post on stackoverflow please be gentle!
I have a MySQL (5.5.24) Database (WAMP Setup) with a table with records like this
Person_ID     R_Date

137           2013-01-01
137           2013-02-01
137           2013-03-15
168           2013-01-01
168           2013-02-01
168           2013-03-21
172           2013-01-01
172           2013-02-01
172           2013-03-27

However I would like to just have 1 record for each Person_ID using the most recent/current R_Date.
So the results would look like this:
Person_ID    R_Date

137          2013-03-15
168          2013-03-21
172          2013-02-27

I have had difficulty searching for answers as I'm not sure of the terminology, it is possibly something really simple.  It is possible to get this result using PHP While loops combined with multiple MySQL queries but I'm after a pure MySQL solution if it's possible.
Maybe the results I am after are achievable with subqueries? Thanks

A: SELECT Person_ID, MAX(R_Date) as 'R_Date' FROM TableName GROUP BY Person_ID

A: SELECT *
FROM PERSONTABLE a
WHERE R_Date = ( SELECT MAX(R_Date)
                 FROM PERSONTABLE b
                 WHERE a.Person_ID = b.Person_ID
               )

A: SELECT Person_ID, MAX(R_Date) FROM <YourTable> GROUP BY Person_ID


text:
Q: Regex to Locate Carriage Return Line Feed Followed by anything except an 8 digit number and a | All.
I have some data with some improper line breaks. I would like to search and replace any  CR LF that is not followed by an 8 digit number and a pipe.
For example:
12345678|Text|Text CRLF
123.4567|Text|Text CRLF
Text|4567890|Text

This text above should change to:
12345678|Text|Text 123.4567|Text|Text Text|4567890|Text

I have tried the following:
\r\n([^[0-9]{8}\|])

Any help is very appreciated.

A: *

*Ctrl+H

*Find what: \R(?!\d{8}\|)

*Replace with: LEAVE EMPTY

*CHECK Wrap around

*CHECK Regular expression

*Replace all
Explanation:
\R              # any kind of linebreak, you can use \r\n if you want to replace ONLY \r\n
(?!             # negative lookahead, make we haven't after:
    \d{8}           # 8 digit
    \|              # a pipe
)               # endd lookahead

Screenshot (before):

Screenshot (after):


text:
Q: Query JavaScript Object group by I have a JavaScript object like this:
[{"a":1,"b":2},{"a":1,"b":3},{"a":2,"b":4},{"a":2,"b":5}]

I want to group this object field 'a' and want something like this:
[{"a":1,"values":[{"a":1,"b":2},{"a":1,"b":3}]},{"a":2,"values":[{"a":2,"b":4},{"a":2,"b":5}]}]

I have a JavaScript array of more than few thousands elements. What is the most efficient way to achieve this?

A: Underscore JS provides nice methods for structuring your models and grouping/filtering them.
http://underscorejs.org/#groupBy

A: Try this code:
var data = [{"a":1,"b":2},{"a":1,"b":3},{"a":2,"b":4},{"a":2,"b":5}];

var res = alasql('SELECT a, ARRAY(_) AS [values] FROM ? GROUP BY a',[data]);

Here ARRAY(_) is a special aggregation function which saves current record(_) into the array with name values.
You can play with this example in jsFiddle.


text: Q: Read json file written by Chrome Extension stdout the chrome extension outputs json file to stdout. I want to read this json file from my python application. my application is using selenium and load this extension to the chrome browser. my environment is windows 7.


text:
Q: Using C++/WinRT dll in WPF with elevated rights application I have got WPF c# server application (WCF) and want to use c++/WinRT dynamic library inside it. I can simply do this by using UWP desktop bridge with WPF app and UWP empty app that includes my dll. This works fine for applications without elevated rights but WCF service require to run it as admin. I can achieve this by starting my application as admin or adding tags in projects manifest files (requireAdministrator for WPF and allowElevation for UWP).
My problem starts here as I get exception System.TypeLoadException with inner exception  System.Runtime.InteropServices.COMException with code 0x80040154 (REGDB_E_CLASSNOTREG)) from System.StubHelpers.StubHelpers.GetWinRTFactoryObject(IntPtr pCPCMD) if I run app as admin.
This behavior is similar to what I get when I use c++/WinRT library without desktop bridge project. Is there any solution for such problem?
I compiled all projects against Windows 10 1809 (17763) build.
Edit:
I do not care about desktop bridge but it was only way that I could find to connect c# with c++/WinRT. What I want is to use classes exported through MSIDL to c# application.
Instruction to recreate this issue in VS 2017 (requirement is to have Windows 10 1809 or later):
1. To do so first install  C++/WinRT projects templates from nuget.
2. Next create new project of Windows Runtime Component (C++/WinRT), chose target and minimum version of windows to 1809. You should get project with single class Class.
3. Now in same solution create C# WPF App project (Framework 4.7.2). In it add reference to runtime component project and set Copy Local to False for this reference. Use Class inside WPF project (ex. create field inside MainWindow class RuntimeComponent1.Class c = new RuntimeComponent1.Class();)
 At this point both projects should be compilable but WPF project will throw an exception (TypeLoadException may be inner exception or root exception) at runtime. Also this step is what I want to achieved and all next steps are redundant for me but are necessary to create working application.
4. Next create Windows Universal Blank App (set platform versions to 1809) and as previous with WPF add reference to runtime component project and set Copy Local to False.
5. After that create Windows Application Packaging Project (target and minimum platform versions set to 1809), inside it to applications add both UWP and WPF Apps (it should be not possible to add library project). Set WPF app as Entry Point.
6. At this point Packaging project should be compilable and runnable without an error. Also it should be possible to run Packaging application as administrator from menu start but it will produce a runtime exception (TypeLoadException).
7. Finally to make application run by default with elevated rights add to WPF project Application Manifest File and change requestedExecutionLevel tag to <requestedExecutionLevel level="requireAdministrator" uiAccess="false" />. Also inside Packaging project in Package.appxmanifest add <rescap:Capability Name="allowElevation" /> after <rescap:Capability Name="runFullTrust" />. This step require to build against 1809 as a minimum version.
After thous steps application will throw TypeLoadException (as root or inner exception depends how Class is used). To actually show it throwing something instead of just dying change WPF project type to console and then it will print exception for a brief moment before dying.


text:
Q: Datetime in yyyy-mm-dd-hh.mm.ss.fff format My webservice requires an input parameter of datetime of this format : yyyy-mm-dd-hh.mm.ss.fff. I tried this:
Datetime myDT = Datetime.now();
String myDate = myDT.format('yyyy-mm-dd-hh.mm.ss.fff');

says the format is not recognized. How do I create a date time in this format?
Thanks.

A: Your format template does not match the valid strings.
As BarCotter said, yyyy-MM-dd-hh.mm.ss.SSS will work since it uses the formatting as described here: http://docs.oracle.com/javase/7/docs/api/java/text/SimpleDateFormat.html


text:
Q: React admin login using customRoute not rerendering resources/drawer I am using react-admin for a dashboard. Everything works fine, but using login on a custom page (using customRoutes) is not rererendering the drawer after the redirect.
Those are my custom routes:
export default [
    <Route exact path="/signup" component={SignUp} noLayout />,
];

Part of the SignUp component (the values contain phone and password, where phone is the username):
    const login = useLogin();
    const notify = useNotify();
    const classes = useStyles();
    const formik = useFormik({
        initialValues: {
            phone: '',
            password: '',
            role: '',
            first_name: '',
            last_name: ''
        },
        onSubmit: async (values, { setStatus }) => {
            try {
                const response = await httpClient('/api/auth/users/', {
                    method: 'POST',
                    body: JSON.stringify(values),
                })
                login({ phone: values.phone, password: values.password })
                    .catch(() => notify('Invalid phone number or password'));
            } catch (e) {
                notify(e.message, 'error');
            }
        }
    });

my Admin component:
  <Admin layout={Layout} dataProvider={drfProvider('/api', httpClient)} authProvider={authProvider} loginPage={LoginPage} customRoutes={customRoutes}>
    {role => {
      return [
        <Resource name="checkins" list={CheckInList} create={CheckInCreate} show={CheckInShow} icon={PersonPinCircleIcon} options={{ label: 'Check Ins' }} />,
        <Resource name="myplaces" list={role === ROLES.HOST ? PlaceList : null} edit={PlaceEdit} create={PlaceCreate} show={PlaceShow} icon={StoreIcon} options={{ label: 'My Places' }} />,
        <Resource name="myrooms" list={role === ROLES.HOST ? RoomList : null} edit={RoomEdit} create={RoomCreate} show={RoomShow} icon={RoomIcon} options={{ label: 'My Rooms' }} />,
        <Resource name="guests" list={role === ROLES.HOST ? GuestList : null} create={GuestCreate} show={GuestShow} icon={PeopleIcon} />,
        <Resource name="places" />,
        <Resource name="rooms" />,
      ]
    }}
  </Admin>

As you can see depending on the role, some routes won't be rendered. The problem is, the Admin component is only rendered in the background when I go to /signup page, and after the login redirect, it's not rerendered, so I don't see the correct resources.
Here is also my authProvider:
import jwtDecode from 'jwt-decode';

export default {
    // called when the user attempts to log in
    login: ({ phone, password }) =>  {
        console.log('login start')
        const request = new Request('/api/auth/jwt/create/', {
            method: 'POST',
            body: JSON.stringify({ phone, password }),
            headers: new Headers({ 'Content-Type': 'application/json' }),
        });
        return fetch(request)
            .then(response => {
                if (response.status < 200 || response.status >= 300) {
                    throw new Error(response.statusText);
                }
                return response.json();
            })
            .then(({ access }) => {
                localStorage.setItem('token', access);
            });
    },
    // called when the user clicks on the logout button
    logout: () => {
        localStorage.removeItem('token');
        return Promise.resolve();
    },
    // called when the API returns an error
    checkError: ({ status }) => {
        if (status === 401 || status === 403) {
            localStorage.removeItem('token');
            return Promise.reject();
        }
        return Promise.resolve();
    },
    // called when the user navigates to a new location, to check for authentication
    checkAuth: () => {
        return localStorage.getItem('token')
            ? Promise.resolve()
            : Promise.reject();
    },
    // called when the user navigates to a new location, to check for permissions / roles
    getPermissions: () => {
        console.log('getPermissions start')
        const token = localStorage.getItem('token');
        let role = null;
        try {
            const decodedToken = jwtDecode(token);
            role = decodedToken.role;
        } catch (e) {
            role = '';
        }
        console.log('role ' + role)
        return Promise.resolve(role);
    }
};

A custom login page, however works correctly, so probably because we don't need a customRoute for it. I think it's about how react-admin manages the customRoutes.


text:
Q: magento custom module block not calling I Created module i try to call my category page but it not showing
layout.xml
<reference name="content">
      <block type="gallery/index" name="gallery_index" template="gallery/index.phtml"/>
    </reference>

in static block i call this way
{{block type="gallery/index" name="gallery" template="gallery/index.phtml"}}

then i call this static block my category but it not working
config.xml
<?xml version="1.0"?>
<config>
  <modules>
    <MPS_Gallery>
      <version>0.1.0</version>
    </MPS_Gallery>
  </modules>
  <frontend>
    <routers>
      <gallery>
        <use>standard</use>
          <args>
            <module>MPS_Gallery</module>
            <frontName>gallery</frontName>
          </args>
      </gallery>
    </routers>
        <layout>
          <updates>
            <gallery>
              <file>gallery.xml</file>
            </gallery>
          </updates>
        </layout>
  </frontend>
  <admin>
        <routers>
            <gallery>
                <use>admin</use>
                <args>
                    <module>MPS_Gallery</module>
                    <frontName>gallery</frontName>
                </args>
            </gallery>
        </routers>
    </admin>
    <adminhtml>
        <menu>
            <gallery module="gallery">
                <title>Gallery</title>
                <sort_order>71</sort_order>
                <children>
                    <items module="gallery">
                        <title>Manage Items</title>
                        <sort_order>0</sort_order>
                        <action>gallery/adminhtml_gallery</action>
                    </items>
                </children>
            </gallery>
        </menu>
        <acl>
            <resources>
                <all>
                    <title>Allow Everything</title>
                </all>
                <admin>
                    <children>
                        <gallery>
                            <title>gallery Module</title>
                            <sort_order>200</sort_order>
                        </gallery>
                    </children>
                </admin>
            </resources>
        </acl>
        <layout>
            <updates>
                <gallery>
                    <file>gallery.xml</file>
                </gallery>
            </updates>
        </layout>
    </adminhtml>
  <global>
    <models>
            <gallery>
                <class>MPS_Gallery_Model</class>
                <resourceModel>gallery_mysql4</resourceModel>
            </gallery>
            <gallery_mysql4>
                <class>MPS_Gallery_Model_Mysql4</class>
                <entities>
                    <gallery>

gallery

                    </gallery>
                </entities>
            </gallery_mysql4>
        </models>
        <resources>
            <gallery_setup>
                <setup>
                    <module>MPS_Gallery</module>
                </setup>
                <connection>
                    <use>core_setup</use>
                </connection>
            </gallery_setup>
            <gallery_write>
                <connection>
                    <use>core_write</use>
                </connection>
            </gallery_write>
            <gallery_read>
                <connection>
                    <use>core_read</use>
                </connection>
            </gallery_read>
        </resources>
    <helpers>
      <gallery>
        <class>MPS_Gallery_Helper</class>
      </gallery>
    </helpers>
    <blocks>
      <gallery>
        <class>MPS_Gallery_Block</class>
      </gallery>
    </blocks>
    <resources>
      <gallery_setup>
        <setup>
          <module>MPS_Gallery</module>
        </setup>
        <connection>
          <use>core_setup</use>
        </connection>
      </gallery_setup>
      <gallery_write>
        <connection>
          <use>core_write</use>
        </connection>
      </gallery_write>
      <gallery_read>
        <connection>
          <use>core_read</use>
        </connection>
      </gallery_read>
    </resources>
  </global>
</config>

A: Give permission to that block

system -> permission -> Blocks -> Click add new Block

then Save Block
and Make sure your block name should be unique.


text:
Q: What does the color of player names mean in Monster Hunter World? I just saw this image and was wondering what the meaning of the different name colors is as well as how to unlock change the color.

So the question in total is, what is the meaning of each color and how do I unlock/change the color? Can the color be changed at will?
EDIT:
As it seems that the completion of specific quests changes to name color, I would like to know which quests specifically unlock which color.

A: According to reddit (and partially the official manual):

Green is after story. Orange is for completing HR100, Blue is for entering MR, Purple is for clearing MR story.

MR200 is yellow

It's an indication of progress through quests (not through ranks like the reddit post suggests!). Each of the quests to unlock the colours are optional, and are unlocked once you have passed that point in the game. For example, the MR200 quest:

Apparently you need to do all the optionals that upgrade equipment like the mr 150 and mr 175 quests to upgrade mantles, to unlock it.

I've searched various forums in an attempt to find the relevant quests for each rank, and will link the source for each one in format: [Color](source) - Description
Green - Beat the final story quest, Land of Convergence

Orange - Beat The Sapphire Star's Guidance

Blue - Buy the Iceborne DLC

Purple - Beat the final story quest of the DLC, Paean of Guidance

Gold/Yellow - Beat Master Hunter of the New World, unlocked by completing all the MR optionals
There is no indication that you can change this colour anywhere on the internet, though if you get two, please try, and tell me.


text:
Q: Error using installing MSSQL Server2014 using chef I have window 2012 R2 based two VM machines.
One is using for Chef-workstation and other is for  Chef-client.
I am trying to install MSSQL Server 2014 using chef-cmd from chef-workstation on chef-client.
Sometimes I am getting below error on chef-client while installing MSSQL Server.

check for instance name, got: 'MSSQLSERVER' Error: Action
  "Microsoft.SqlServer.Configuration.SetupExtension.FinalCalculateSettingsAction"
  threw an exception during execution.
  Microsoft.SqlServer.Setup.Chainer.Workflow.ActionExecutionException:
  There was an error generating the XML document. --->
  Microsoft.SqlServer.Chainer.Infrastructure.ChainerInfrastructureException:
  There was an error generating the XML document. --->
  System.InvalidOperationException: There was an error generating the
  XML document. --->
  System.Security.Cryptography.CryptographicException: Access is denied.
  at System.Security.Cryptography.ProtectedData.Protect(Byte[] userData,
  Byte[] optionalEntropy, DataProtectionScope scope)    at
  Microsoft.SqlServer.Common.SqlSecureString.WriteXml(XmlWriter writer)
  at
  System.Xml.Serialization.XmlSerializationWriter.WriteSerializable(IXmlSerializable
  serializable, String name, String ns, Boolean isNullable, Boolean
  wrapped)    at
  Microsoft.Xml.Serialization.GeneratedAssembly.XmlSerializationWriterAgentConfigurationPublic.Write6_AgentConfigurationPublic(String
  n, String ns, AgentConfigurationPublic o, Boolean isNullable, Boolean
  needType)    at
  Microsoft.Xml.Serialization.GeneratedAssembly.XmlSerializationWriterAgentConfigurationPublic.Write7_AgentConfigurationPublic(Object
  o)    at
  Microsoft.SqlServer.Setup.Chainer.Workflow.ActionEngine.RunActionQueue()
  Error: Action
  "Microsoft.SqlServer.Configuration.BootstrapExtension.ExecuteWorkflowAction"
  threw an exception during execution.
  Microsoft.SqlServer.Setup.Chainer.Workflow.ActionExecutionException:
  There was an error generating the XML document. --->
  Microsoft.SqlServer.Chainer.Infrastructure.ChainerInfrastructureException:
  There was an error generating the XML document. --->
  System.InvalidOperationException: There was an error generating the
  XML document. --->
  System.Security.Cryptography.CryptographicException: Access is denied.
  at System.Security.Cryptography.ProtectedData.Protect(Byte[] userData,
  Byte[] optionalEntropy, DataProtectionScope scope)    at
  Microsoft.SqlServer.Common.SqlSecureString.WriteXml(XmlWriter writer)

For more information:
https://discourse.chef.io/t/error-action-microsoft-sqlserver-configuration-setupextension-finalcalculatesettingsaction-threw-an-exception-during-execution/13778


text:
Q: Open local file with click on a Button on Java form New to Java. Creating a button on a Java form and want button click to open a jnlp file located on a local drive.
How will that be possible? Double clicking on the button takes me
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
    // TODO add your handling code here:

}

A: The class to help you open files with the default program is called "Desktop". See http://docs.oracle.com/javase/7/docs/api/java/awt/Desktop.html, especially Desktop.open( File );


text:
Q: Can no longer view Jetpack Compose Previews. Failed to instantiate one or more classes (ComposeViewAdapter) I've recently got an error preventing any Jetpack Compose previews from being displayed as follows:
Failed to instantiate one or more classes
The following classes could not be instantiated:
     -androidx.compose.ui.tooling.ComposeViewAdapter(Open Class, Show Exception, Clear Cache)

if this is an unexpected error you can also try to build the project, then manually refresh the layout

java.lang.NoClassDefFoundError: Could not initialize class androidx.customview.poolingcontainer.PoolingContainer
    at androidx.compose.ui.platform.ViewCompositionStrategy$DisposeOnDetachedFromWindowIfNotInPoolingContainer.installFor(ViewCompositionStrategy.android.kt:97)
    at androidx.compose.ui.platform.AbstractComposeView.<init>(ComposeView.android.kt:123)
    at androidx.compose.ui.platform.ComposeView.<init>(ComposeView.android.kt:392)
    at androidx.compose.ui.platform.ComposeView.<init>(ComposeView.android.kt:388)
    at androidx.compose.ui.tooling.ComposeViewAdapter.<init>(ComposeViewAdapter.kt:131)
    at java.base/jdk.internal.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at java.base/jdk.internal.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
    at java.base/jdk.internal.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
    at java.base/java.lang.reflect.Constructor.newInstance(Constructor.java:490)
    at org.jetbrains.android.uipreview.ViewLoader.createNewInstance(ViewLoader.java:339)
    at org.jetbrains.android.uipreview.ViewLoader.loadClass(ViewLoader.java:176)
    at org.jetbrains.android.uipreview.ViewLoader.loadView(ViewLoader.java:136)
    at com.android.tools.idea.rendering.LayoutlibCallbackImpl.loadView(LayoutlibCallbackImpl.java:301)
    at android.view.BridgeInflater.loadCustomView(BridgeInflater.java:417)
    at android.view.BridgeInflater.loadCustomView(BridgeInflater.java:428)
    at android.view.BridgeInflater.createViewFromTag(BridgeInflater.java:332)
    at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:965)
    at android.view.LayoutInflater.inflate(LayoutInflater.java:663)
    at android.view.LayoutInflater.inflate(LayoutInflater.java:505)
    at com.android.layoutlib.bridge.impl.RenderSessionImpl.inflate(RenderSessionImpl.java:363)
    at com.android.layoutlib.bridge.Bridge.createSession(Bridge.java:436)
    at com.android.tools.idea.layoutlib.LayoutLibrary.createSession(LayoutLibrary.java:121)
    at com.android.tools.idea.rendering.RenderTask.createRenderSession(RenderTask.java:739)
    at com.android.tools.idea.rendering.RenderTask.lambda$inflate$8(RenderTask.java:895)
    at com.android.tools.idea.rendering.RenderExecutor$runAsyncActionWithTimeout$2.run(RenderExecutor.kt:187)
    at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1128)
    at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:628)
    at java.base/java.lang.Thread.run(Thread.java:829)

I have tried clearing the cache, rebuilding my project, cleaning my project as suggested but nothing has helped. I have had the same issue on both Android Studio Bumblebee 2021.2.1 Patch 3 as well as Chipmunk 2021.2.1 beta 4.
I am currently using version 1.1.1 for all my Compose related dependencies, but have tried downgrading and using newer versions but nothing helps.
implementation 'androidx.core:core-ktx:1.7.0'
implementation "androidx.compose.ui:ui:1.1.1"
implementation "androidx.compose.material:material:1.1.1"
implementation "androidx.compose.ui:ui-tooling-preview:1.1.1"
implementation 'androidx.lifecycle:lifecycle-runtime-ktx:2.3.1'
implementation 'androidx.activity:activity-compose:1.1.1'

I think there are a couple of questions on here asking similar things, but they are all very old and use long outdated versions of Compose and Android Studio, so they are not very helpful.

A: I was migrating one of my simple projects to compose and I faced this issue. Then I realised I forgot adding "androidx.compose.ui:ui-tooling:1.1.1"
These are all of my dependencies for jetpack compose. Adding the last line did the trick. It took 20 min to realize this...
implementation("androidx.compose.ui:ui:1.1.1")
implementation("androidx.compose.material:material:1.1.1")
implementation("androidx.compose.ui:ui-tooling-preview:1.1.1")
debugImplementation("androidx.compose.ui:ui-tooling:1.1.1")

A: It is a known bug: https://issuetracker.google.com/issues/227767363
Google is currently working on a fix but there is already a workaround: add these dependencies to every module where you use the Compose preview:
debugImplementation "androidx.customview:customview:1.2.0-alpha01"
debugImplementation "androidx.customview:customview-poolingcontainer:1.0.0-alpha01"

If you have a common core/base/ui module, you can add it there and use Api instead of Implementation to avoid adding it to every module:
debugApi "androidx.customview:customview:1.2.0-alpha01"
debugApi "androidx.customview:customview-poolingcontainer:1.0.0-alpha01"

Artifacts release reference


text:
Q: How to use $resource in AngularJS properly for building a client app? I've been following this tutorial http://draptik.github.io/blog/2013/07/28/restful-crud-with-angularjs/. I implemented a Grails backend with it instead of the Java one in the tutorial.
I've got the data coming back and forth, with one issue. If I create/update/delete a user, I don't see the changes reflected on my user list when I am redirected back. I have to refresh the page to see the updates.
Looking at the network traffic for an edit, it looks like it does a PUT and fires off the GET before the PUT is complete. Assuming this is because $resource returns a promise so things can be done asynchronously. So how do I handle this so that when $location redirects me, my list is up to date?
I'm guessing the options are to wait for the PUT to complete before redirecting/querying for the list, or to somehow manually manage the $scope.users to match the request?
Or maybe this tutorial is just a bad example? Maybe there is a better way to do it (still using $resource)?
Note: I've seen Restangular out there, and I've seen $http with success callbacks, but I would like to understand the situation above.

A: One way to overcome this issue would be to not redirect to the list page, till you get a callback, and then do a redirect. You can show some busy indicator till that time. The resource call looks like this.
resource.update(config,data,function() { //gets called on success},
                             function(error) { //gets called on failure});
In real life scenario waiting for the response of update makes sense as you want to handle the error and success scenarios on the same page.

A: I don't see your code anywhere so i'm just assuming (based on what you wrote and your current problem)
You are probably doing a full (or partial) get each time you changed a user and (re)binding the result to your scope. Doing this in the callback of the resource should actually start the digest cycle angular does to update modified objects. If you had been doing the fetching outside $resource - for example with custom/jquery ajax you would need to execute $scope.$apply()
What i really don't understand you would need to wait for the callback. You already know you added/modified a user. Instead of 'detaching' that user from your scope, modify it, post it to your rest server, then wait for callback, and reinserting it into the scope - why not modify it directly in the list/array you put on your scope?
var users = Users.get(function () {
  $scope.users = users.record; // bind the resulting records to the scope
});

$scope.updateUser = function (user) {
  resource.update(...); //pseudo
};

Then in your html, you will keep a reference to the currentUser and the div-list will update automaticly.

{{user.Name}}

<input ng-model="currentUser.Name">
<button ng-click="updateUser(currentUser);">Update</button>

If you don't want to see the update in the list while you type, but only once your callback fires or when you hit the button, would would instead use another ng-model for your input like this:
<input ng-model="tempUser.Name">

And you would then copy the value other in either the updateUser method or in the resource callback like this:
$scope.updateUser = function (user) {
  user.Name = $scope.tempUser.Name; // should update automaticly
  resource.update(...) // pseudo
}

Hope it helped!


text:
Q: Root shell keyboard repeat rate I am not talking about the Ubuntu Desktop here, it is the "bare bones" server, pretty much any version of Ubuntu you could name, there is a very annoying keyboard "bounce" or as I refer to it "psycho uncommanded keyboard repeat." No GUI involved, just a root shell that often looks like "sudooo apttttt inssssstall" or "cd /////etc///deffffault" etc. Is there anything I can do to stop the repeat, and get the keyboard responding like it does in a remote terminal/ssh?

A: Although This Link is a hundred years old, it led me to what looks like a working solution.
I added atkbd.nosoftrepeat=[1] to the kernel command line in /etc/default/grub, ran update-grub, and presto! Bounce is all gone!