text:
Q: Installing Yeoman generator globally using npm and Github fork for development I currently have quite a few Yeoman generators installed globally (e.g., generator-angular and generator-meanjs). I'd like to fork one or two and try to contribute back to the community. However, I'm confused as to how I can install and utilize both the forked version as well as the  globally installed generator.

*

*Can I install a Yeoman generator globally (e.g., npm install -g generator-meanjs) and install a Github fork for development?

*When developing a forked Yeoman generator, do I need to uninstall the global npm package (e.g., npm uninstall -g generator-meanjs) and then follow the Yeoman Contributing Quick Start instructions?

A: You should clone your fork and then use npm link (from within it) to have it globally available, so that it can be used from yo.
See http://yeoman.io/authoring/ .

A: Based on my research, the answers are:

*

*No. I was not able to find a way to have the Yeoman generator installed globally (e.g., npm install -g generator-meansjs) and installed using a local repository containing a clone of the Github fork.

*No. If the Yeoman generator was previously installed globally, you don't need to uninstall the package prior to linking the local repository. The previously installed package will be replaced with a link to your local repository whenever, you run npm link <dir>.

More Information
I installed Node on OS X 10.9.2 using nvm so my global modules are installed at:
/Users/matthew/.nvm/v0.10.28/lib/node_modules

Then I followed these steps:
$ npm install -g generator-meanjs
$ cd ~/.nvm/v0.10.28/lib/node_modules/
$ ls -l generator-meanjs      --> Shows this is a directory
$ cd ~/development/foss-projects/
$ git clone https://github.com/matthewrankin/generator-meanjs
$ cd generator-meanjs
$ npm link .
$ cd ~/.nvm/v0.10.28/lib/node_modules/
$ ls -l generator-meanjs      --> Shows this is a link

As can be seen, when I npm link . the globally installed package generator-meanjs was replaced with a link to ~/development/foss-projects/generator-meanjs.


text:
Q: safely terminating a thread in Meyers Singleton I have a boost thread running inside a Meyers' Singleton. It happily runs for the duration of my program.
When my Singleton's destructor is called (when the program is loaded out of memory) I set a flag so that the thread should exit it's loop and fire off a call to thread.join().
Now, on Windows, calling thread.join() causes a bad access exception. But on Mac, not calling thread.join() throws a bad access exception!
Can anyone shed any light on this difference in behaviour between these 2 operating systems, and/or provide instructions on how to safely terminate my thread?
edit: this code works on both Mac and Windows if I run it in a simple command line application. It doesn't matter if I call myThread.join() or not!
Running as shared library exhibits the issue... the memory exception on Mac happens when I try and reload the dylib a second time and I omit the call to myThread.join(),
example:
#include "boost/thread.hpp"

class MeyersSingleton
{
public:
    MeyersSingleton()
    :   threadShouldExit(false),
        myThread(boost::ref(*this) ) {
    }

    ~MeyersSingleton() {
        threadShouldExit = true;
        myThread.join();
    }

    static MeyersSingleton& getInstance() {
        static MeyersSingleton singletonInstance;
        return singletonInstance;
    }

    void operator()() {
        while(!threadShouldExit) {
            // my busy worker thread...
            sleep(1);
        }
    }
private:
    bool threadShouldExit;
    boost::thread myThread;
};

A: Couple of points:

*

*sleep() is not safe in multi-threaded applications because it uses SIGALRM. Use nanosleep() instead.

*threadShouldExit is changed with no locks held, so it should be a C++11 atomic, or use atomic functions to read and set its value.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Looking for Windows script to delete files older than 1 year I need a Windows script to delete files older than 1 year with:
forfiles  /S /P "E:\" /M *.* /D -365 /C "cmd /c echo @path" >> "xxx_log"

I am not familiar with Windows scripting.
Can anyone please help me?

A: If you plan on using windows scripts/batch file, but you are not familiar with them, I really recommend you familiarize yourself first, otherwise it may be dangerous to play with, especially when deleting in bulk...
Fist of all open a Command Prompt and type FORFILES /? to read through the help for the FORFILES command and DEL /? for the DEL (delete) command.
The complete command you are looking for is something like this:
FORFILES /S /P "E:\" /M "*" /D -365 /C "CMD /C DEL @path"

Where E:\ is the top level directory, * is the wildcard you want to match (e.g. change to *.bak to delete only files with the extension .bak) and 365 is the number of days (the minus sign means delete anything older than 365 days).

A: As well as the invalid /Q option you had used (now corrected), I would also advise that there is no need to use the /M option, as it's default is already *. Also, you may also wish to include some other options for your DEL command, such as its /A and /F options. Additionally, since the intention is to delete files, you should omit possible directory paths, using @ISDIR too. Example: FORFILES /P "E:" /S /D -365 /C "CMD /C IF @ISDIR==FALSE DEL /A /F @PATH". – Compo yesterday
Thank you for your answer. Can I use the day to replace 365 ?
FORFILES /P "E:" /S /D -"01/01/2020" /C "CMD /C IF @ISDIR==FALSE DEL /A /F @PATH"  ? Thank you.

A: I have a script to delete .zip files more than 30 days:
 @echo off
 FORFILES /p "c:\respaldos" /M *.zip /D -30 /C "cmd /c del @file"

I hope this help you, for more information write in CMD FORFILES /?


text:
Q: UnboundLocalError when trying to use decorator function arguments I've been trying to use Python's decorator functions to make a completely stupid project, but I've been getting this error
UnboundLocalError: local variable 'mana_cost' referenced before assignment

and I'm not really sure what's wrong. Here's the code so far (not even sure if it's functional yet, WIP obvs):
from stuff.mana_pool import ManaPool

def spell(mana_cost):
    def decorator(func):
        def wrap(*args, **kwargs):
            print(mana_cost)
            mana_pool = kwargs['mana_pool']
            cost = {}
            for mana_type in ['W', 'U', 'B', 'R', 'G']:
                cost[mana_type] = mana_cost.count(mana_type)
                mana_cost = mana_cost.replace(mana_type, '')
            cost['generic'] = int(mana_cost)
            func(*args, **kwargs)
        return wrap
    return decorator

my_pool = ManaPool()

@spell("2BB")
def func(thingy):
    print(thingy)

func('boop', mana_pool=my_pool)

Any ideas?


text:
Q: Exception writing ByteBuffer field into Cassandra We have an apache beam dataflow job that reads the data from Big Query converts them into POJO before writing into Cassandra using Datastax driver. I recently added a new blob column to the table and added a ByteBuffer field to the POJO.
How I am creating the ByteBuffer
String str = objectMapper.writeValueAsString(installSkuAttributes);
byte[] bytes = str.getBytes( StandardCharsets.UTF_8 );
pojo.setInstallAttributes(ByteBuffer.wrap(bytes));

here is the pipeline snippet
    public void executePipeline() throws Exception {
Pipeline pipeline =
Pipeline.create(jobMetaDataBean.getDataflowPipelineOptions());

....
    writeDataToCassandra(installSkuData);
pipeline.run();

After making the necessary changes in the DAO writer I am getting the following exception When I ran the job. I am using Datastax driver
Exception in thread "main" org.apache.beam.sdk.Pipeline$PipelineExecutionException: java.lang.IllegalArgumentException: Forbidden IOException when writing to OutputStream
    at org.apache.beam.runners.direct.DirectRunner$DirectPipelineResult.waitUntilFinish(DirectRunner.java:349)
    at org.apache.beam.runners.direct.DirectRunner$DirectPipelineResult.waitUntilFinish(DirectRunner.java:319)
    at org.apache.beam.runners.direct.DirectRunner.run(DirectRunner.java:210)
    at org.apache.beam.runners.direct.DirectRunner.run(DirectRunner.java:66)
    at org.apache.beam.sdk.Pipeline.run(Pipeline.java:311)
    at org.apache.beam.sdk.Pipeline.run(Pipeline.java:297)
    at com.homedepot.productassortment.fullfeed.dataflow.InstallSkusFullFeed.executePipeline(InstallSkusFullFeed.java:216)
    at com.homedepot.productassortment.fullfeed.dataflow.InstallSkusFullFeed.main(InstallSkusFullFeed.java:221)
Caused by: java.lang.IllegalArgumentException: Forbidden IOException when writing to OutputStream
    at org.apache.beam.sdk.util.CoderUtils.encodeToSafeStream(CoderUtils.java:88)
    at org.apache.beam.sdk.util.CoderUtils.encodeToByteArray(CoderUtils.java:69)
    at org.apache.beam.sdk.util.CoderUtils.encodeToByteArray(CoderUtils.java:54)
    at org.apache.beam.sdk.util.CoderUtils.clone(CoderUtils.java:148)
    at org.apache.beam.sdk.util.MutationDetectors$CodedValueMutationDetector.<init>(MutationDetectors.java:117)
    at org.apache.beam.sdk.util.MutationDetectors.forValueWithCoder(MutationDetectors.java:46)
    at org.apache.beam.runners.direct.ImmutabilityCheckingBundleFactory$ImmutabilityEnforcingBundle.add(ImmutabilityCheckingBundleFactory.java:112)
    at org.apache.beam.runners.direct.ParDoEvaluator$BundleOutputManager.output(ParDoEvaluator.java:242)
    at org.apache.beam.repackaged.beam_runners_direct_java.runners.core.SimpleDoFnRunner.outputWindowedValue(SimpleDoFnRunner.java:219)
    at org.apache.beam.repackaged.beam_runners_direct_java.runners.core.SimpleDoFnRunner.access$700(SimpleDoFnRunner.java:69)
    at org.apache.beam.repackaged.beam_runners_direct_java.runners.core.SimpleDoFnRunner$DoFnProcessContext.output(SimpleDoFnRunner.java:517)
    at org.apache.beam.repackaged.beam_runners_direct_java.runners.core.SimpleDoFnRunner$DoFnProcessContext.output(SimpleDoFnRunner.java:505)
    at com.homedepot.productassortment.fullfeed.dataflow.InstallSkusFullFeed$PrepareDataForCassandraWrite.processElement(InstallSkusFullFeed.java:160)
Caused by: java.io.NotSerializableException: java.nio.HeapByteBuffer
    at java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java:1184)
    at java.io.ObjectOutputStream.defaultWriteFields(ObjectOutputStream.java:1548)
    at java.io.ObjectOutputStream.writeSerialData(ObjectOutputStream.java:1509)
    at java.io.ObjectOutputStream.writeOrdinaryObject(ObjectOutputStream.java:1432)
    at java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java:1178)
    at java.io.ObjectOutputStream.writeObject(ObjectOutputStream.java:348)
    at org.apache.beam.sdk.coders.SerializableCoder.encode(SerializableCoder.java:166)
    at org.apache.beam.sdk.coders.SerializableCoder.encode(SerializableCoder.java:52)
    at org.apache.beam.sdk.coders.IterableLikeCoder.encode(IterableLikeCoder.java:99)
    at org.apache.beam.sdk.coders.IterableLikeCoder.encode(IterableLikeCoder.java:60)
    at org.apache.beam.sdk.coders.Coder.encode(Coder.java:143)
    at org.apache.beam.sdk.util.CoderUtils.encodeToSafeStream(CoderUtils.java:85)
    at org.apache.beam.sdk.util.CoderUtils.encodeToByteArray(CoderUtils.java:69)
    at org.apache.beam.sdk.util.CoderUtils.encodeToByteArray(CoderUtils.java:54)
    at org.apache.beam.sdk.util.CoderUtils.clone(CoderUtils.java:148)
    at org.apache.beam.sdk.util.MutationDetectors$CodedValueMutationDetector.<init>(MutationDetectors.java:117)
    at org.apache.beam.sdk.util.MutationDetectors.forValueWithCoder(MutationDetectors.java:46)
    at org.apache.beam.runners.direct.ImmutabilityCheckingBundleFactory$ImmutabilityEnforcingBundle.add(ImmutabilityCheckingBundleFactory.java:112)
    at org.apache.beam.runners.direct.ParDoEvaluator$BundleOutputManager.output(ParDoEvaluator.java:242)
    at org.apache.beam.repackaged.beam_runners_direct_java.runners.core.SimpleDoFnRunner.outputWindowedValue(SimpleDoFnRunner.java:219)
    at org.apache.beam.repackaged.beam_runners_direct_java.runners.core.SimpleDoFnRunner.access$700(SimpleDoFnRunner.java:69)
    at org.apache.beam.repackaged.beam_runners_direct_java.runners.core.SimpleDoFnRunner$DoFnProcessContext.output(SimpleDoFnRunner.java:517)
    at org.apache.beam.repackaged.beam_runners_direct_java.runners.core.SimpleDoFnRunner$DoFnProcessContext.output(SimpleDoFnRunner.java:505)
    at com.homedepot.productassortment.fullfeed.dataflow.InstallSkusFullFeed$PrepareDataForCassandraWrite.processElement(InstallSkusFullFeed.java:160)
    at com.homedepot.productassortment.fullfeed.dataflow.InstallSkusFullFeed$PrepareDataForCassandraWrite$DoFnInvoker.invokeProcessElement(Unknown Source)
    at org.apache.beam.repackaged.beam_runners_direct_java.runners.core.SimpleDoFnRunner.invokeProcessElement(SimpleDoFnRunner.java:185)
    at org.apache.beam.repackaged.beam_runners_direct_java.runners.core.SimpleDoFnRunner.processElement(SimpleDoFnRunner.java:149)
    at org.apache.beam.repackaged.beam_runners_direct_java.runners.core.SimplePushbackSideInputDoFnRunner.processElementInReadyWindows(SimplePushbackSideInputDoFnRunner.java:78)
    at org.apache.beam.runners.direct.ParDoEvaluator.processElement(ParDoEvaluator.java:189)
    at org.apache.beam.runners.direct.DoFnLifecycleManagerRemovingTransformEvaluator.processElement(DoFnLifecycleManagerRemovingTransformEvaluator.java:55)
    at org.apache.beam.runners.direct.DirectTransformExecutor.processElements(DirectTransformExecutor.java:161)
    at org.apache.beam.runners.direct.DirectTransformExecutor.run(DirectTransformExecutor.java:125)
    at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511)
    at java.util.concurrent.FutureTask.run(FutureTask.java:266)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
    at java.lang.Thread.run(Thread.java:748)

A: The real problem is here:

java.io.NotSerializableException: java.nio.HeapByteBuffer

It's caused by the fact that ByteBuffer isn't serializable, so it couldn't be used for distributed work. You can avoid this by using byte[] directly as your attribute, or implement a wrapper around ByteBuffer that will be serializable.


text:
Q: Как улучшить код и избавиться от множества if Вопросы по оформлению кода...
Есть такой метод:
/**
 * Activate module from ZIP archive
 * @param $archiveFilePath
 * @return bool
 */
public function activate($archiveFilePath)
{
    if( file_exists($archiveFilePath) ) {
        $moduleDirectory = $this->extractArchive($archiveFilePath);
        if( $moduleDirectory ) {
            $moduleConfig = $this->getConfig($moduleDirectory);
            if( $moduleConfig ) {

            } else {
                \Yii::$app->session->setFlash(self::ERRORS_KEY, self::ERROR_INSTALL_CONFIG_NOT_EXIST);
                return false;
            }
        } else {
            \Yii::$app->session->setFlash(self::ERRORS_KEY, self::ERROR_ARCHIVE_EXTRACT);
            return false;
        }
    } else {
        \Yii::$app->session->setFlash(self::ERRORS_KEY, self::ERROR_ARCHIVE_NOT_EXIST);
        return false;
    }
}

Видим множество if. Мне постоянно необходимо проверять значения, которые возвращают другие методы класса и выводить ошибки, если что-то не так.
Вопрос 1. Код получается ужасный (это я только начал, там много таких проверок должно еще быть). Как в таких случаях поступать правильно?
Вопрос 2. Например, у меня есть проверка if( $moduleDirectory ). В $moduleDirectory может быть string или false. Стоит ли так писать? Или лучше делать так: if( $moduleDirectory !== false )?

A:
Вопрос 1. Код получается ужасный (это я только начал, там много таких проверок должно еще быть). Как в таких случаях поступать правильно?

Придерживаться правила: сначала обрабатывать простые случаи, а потом, ниже по коду - сложные.

Вопрос 2. Например, у меня есть проверка if( $moduleDirectory ). В $moduleDirectory может быть string или false. Стоит ли так писать? Или лучше делать так: if( $moduleDirectory !== false )?

Всегда, конечно, лучше чтобы переменная имела всего 1 тип данных и все. Но если уж так, то:
если строка не может быть пустой(пустая строка преобразуется в false) - то так вполне нормально, если может - проверять уже на равенство/не равенство.
Я бы код переписал так:
public function activate($archiveFilePath) {
    if( !file_exists($archiveFilePath) ) {
        \Yii::$app->session->setFlash(self::ERRORS_KEY, self::ERROR_ARCHIVE_NOT_EXIST);
        return false;
    }

    $moduleDirectory = $this->extractArchive($archiveFilePath);
    if( !$moduleDirectory ) {
        \Yii::$app->session->setFlash(self::ERRORS_KEY, self::ERROR_ARCHIVE_EXTRACT);
        return false;
    }

    $moduleConfig = $this->getConfig($moduleDirectory);
    if( !$moduleConfig ) {
        \Yii::$app->session->setFlash(self::ERRORS_KEY, self::ERROR_INSTALL_CONFIG_NOT_EXIST);
        return false;
    }

    // тут основной код - тот что внутри if( $moduleConfig ) ...
}

A: Сделать классы исключений:
class ArchiveNotFoundException extends Exception;
class ArchiveExtractException extends Exception;
class ConfigNotFoundException extends Exception;

Функция, бросающаяся исключениями:
public function activate($archiveFilePath) {
    if (!file_exists($archiveFilePath))
        throw new ArchiveNotFoundException("Архив не найден");

    $moduleDirectory = $this->extractArchive($archiveFilePath);
    if (!$moduleDirectory)
        throw new ArchiveExtractException("Ошибка распаковки архива");

    $moduleConfig = $this->getConfig($moduleDirectory);
    if (!$moduleConfig)
        throw new ConfigNotFoundException("Конфигурация не найдена");

    // штатное продолжение функции
}

Применение функции, бросающейся исключениями:
try {
    // начало
    activate($archiveFilePath);
    // штатное продолжение программы
} catch (ArchiveNotFoundException $e) {
    \Yii::$app->session->setFlash(self::ERRORS_KEY, self::ERROR_ARCHIVE_NOT_EXIST);
} catch (ArchiveExtractException $e) {
    \Yii::$app->session->setFlash(self::ERRORS_KEY, self::ERROR_ARCHIVE_EXTRACT);
} catch (ConfigNotFoundException $e) {
    \Yii::$app->session->setFlash(self::ERRORS_KEY, self::ERROR_INSTALL_CONFIG_NOT_EXIST);
}

Кроме того функция теперь не привязана к YII (по крайней мере в части ошибок), сама не занимается их обработкой. Таким образом появляется возможность повторного использования кода в самых разных ситуациях и полная свобода действий по обработке ошибок.


text:
Q: Can't find variable addproduct error in while using redux in react native I have the following code inside flatlist for adding product into cart using redux

<View style={styles.priceContainer}>
  <Text style={styles.gridItemTitle}>${item.price}</Text>
  <Button size="small" onPress={()=> addproduct(item)} style={styles.addBtn} accessoryLeft={PlusIcon} />
</View>

and this is how i am using map Dispatch to props in the bottom of functional component

const mapStateToProps = (state) => {
    console.log(state);
    return {
        products: state.groceryReducer.productList
    }
}

const mapDispatchToProps = (dispatch) => {
    return {
        addproduct: (product) => dispatch(addToCart(product))
    }
}
export default connect(mapStateToProps, mapDispatchToProps)(Products)

but it is showing an error can't find variable addproduct
can you tell why i am getting this error or what i am doing wrong any solution or suggestions?
Thanks in advance

A: if you are using class component you should find use this.props:
<View style={styles.priceContainer}>
  <Text style={styles.gridItemTitle}>${item.price}</Text>
  <Button size="small" onPress={()=> this.props.addproduct(item)} style={styles.addBtn} accessoryLeft={PlusIcon} />
</View>

if you are using a functional component you have to pass the props an the argument of function like this:
const ProductPage(props) => {
  return (
    <View style={styles.priceContainer}>
      <Text style={styles.gridItemTitle}>${item.price}</Text>
      <Button size="small" onPress={()=> props.addproduct(item)} style={styles.addBtn} accessoryLeft={PlusIcon} />
    </View>
  )
}

or just pass just the function from the props like this:
const ProductPage({addproduct}) => {

}


text:
Q: Rebuilding Qt application does not change the string Kindly consider me as a fresher in Qt. I have written the following code for the button click event.
void dbCheck ()
{
    db = QSqlDatabase::addDatabase("QSQLITE");

    QString dbPath(QDir::home().path());

    dbPath.append("/Desktop/jk/sample.sqlite");
    qDebug () <<"Path Name is "<<dbPath;
    .......
}

And after some time, I have changed the following line into
dbPath.append("/Desktop/jk/Newsample.sqlite");

When I ran the code,  still it prints the previous path i.e. sample.sqlite.
I cleaned the project, and rebuild the same, but no use, still I'm getting the same result. Really weird.
Did I miss something here? How can I rectify this problem? Anything related to do with cache? Kindly advise.

A: Be careful about mixing in-source builds and "shadow builds". You get in-source build if you go to the source directory, and run qmake and make. On the other hand, Qt Creator by default uses separate build dir, AKA "shadow building", and you can of course do that yourself too. In practice this is done with qmake by creating build dir as sibling of source dir, going there and doing qmake ../myproject to generate makefiles in the shadow build dir.
Now the thing is, make program does not really have this concept of separate build dir, and if you have performed in-source build, then those built files are accessible to make too. Then when you think you're doing shadow build, make finds those built files under source directory and uses those instead of creating new ones.
In case this is the problem, following should help:
Go to the source dir at Qt SDK command prompt, and run
make clean distclean

Note: order is important, distclean will remove any makefiles too so it must be done last. Also replace make with nmake or mingw32-make or whatever you actually use. If that command does not find a makefile, then you probably have not run qmake there and issue is something else, but you can verify this by running qmake to generate the makefiles, and make clean distclean will work.
Alternative to remove extra files, if you use version control (and have not accidentally checked in generated files...) is to use the version control tool to remove all extra files from the version-controlled directory.

A: Please, recheck your environment: do you really clears all? Insure, that you have no *.o, moc_*.cpp, ui_*.h from previous builds. Try to delete .user file and reconfigure your project to make builds to different folder.
Also, you can use concatenations of strings this way:
QString dbPath = QString("%1%2")
        .arg( QDir::home().path() )
        .arg( "/Desktop/jk/Newsample.sqlite" ) );

Offtop, but don't forget about native separators (http://qt-project.org/doc/qt-4.8/qdir.html#separator and http://qt-project.org/doc/qt-4.8/qdir.html#toNativeSeparators) - if you write crossplatform software.


text:
Q: renderInContext with iPhoto images working for PDFs but not thumbnails I seem to have a curious bug involving renderInContext.
I am working on a "scrapbook" app which allows people to freely arrange text, colored squares and photos within a scrapbookView.  Note that users can add both photos from a built-in collection of photos (loaded via imageNamed:) and photos from their asset library.
My code creates both PDFs and thumbnails as needed from the scrapbook view and all its subviews by first creating a PDFContext (for PDFs) or an ImageContext (for thumbnail images), then calling renderInContext on scrapBookView.layer.
In general, the code works, with one exception which I will describe.  When I am creating a PDF, both built-in images and asset library images are correctly included in the rendered PDF. However, when I am creating a thumbnail, the built-in images appear, but the asset library images don't correctly appear.  I know the imageView is there because elsewhere I set its background color to light gray but the image itself is absent.
I suspect that there may be an asynchronous element to loading the images into image views, and the image doesn't get there fast enough when its an asset library image being rendered into an ImageContext.
Is this possible?  If not, why would renderInContext work fine in a PDFContext but not so well in an ImageContext?
And more to the point, how can I get my asset library images included in my thumbnails.
Both the pdf representation and the thumbnail are created via methods in scrapbookView.  The code is as follows:
To create pdfs:
-(NSData*) pdfRepresentation
{
     //== create a pdf context
     NSMutableData* result = [[NSMutableData alloc] init];
     UIGraphicsBeginPDFContextToData(result, self.bounds, nil);
     UIGraphicsBeginPDFPage();

     //== draw this view into it
     [self.layer renderInContext: UIGraphicsGetCurrentContext()];  // works for asset library images

     //== add a rectangular frame also
     CGContextRef pdf = UIGraphicsGetCurrentContext();
     CGContextAddRect(pdf, self.bounds);
     [[UIColor lightGrayColor] setStroke];
     CGContextStrokePath(pdf);

     //== clean up and return the results
     UIGraphicsEndPDFContext();
     return [result copy];
}

To create the thumbnail:
-(UIImage*) thumbnailRepresentation
{
     //== create a large bitmapped image context
     CGFloat minSpan = MIN(self.bounds.size.height, self.bounds.size.width);
     CGSize imageSize = CGSizeMake(minSpan, minSpan);
     UIGraphicsBeginImageContextWithOptions(imageSize, YES, 0.0);

     //== draw the current view into the bitmap context
     self.backgroundColor = [UIColor whiteColor];
     [self.layer renderInContext: UIGraphicsGetCurrentContext()];  // doesn't work for asset library images
     self.backgroundColor = [UIColor clearColor];

     //== get the preliminary results
     UIImage* image = UIGraphicsGetImageFromCurrentImageContext();
     UIGraphicsEndImageContext();

     //== create a smaller image from this image
     CGFloat thumbnailWidth = 40.0;
     CGFloat scaleFactor = thumbnailWidth / minSpan;
     UIImage* result = [UIImage imageWithCGImage:[image CGImage] scale:scaleFactor orientation:UIImageOrientationUp];

     return result;
}
// btw - seems wasteful to create such a large intermediate image

Any help would be appreciated.


text:
Q: Android - OKHttp: how to enable gzip for POST In our Android App, I'm sending pretty large files to our (NGINX) server so I was hoping to use gzip for my Retrofit POST message.
There are many documentations about OkHttp using gzip transparently or changing the headers in order to accept gzip (i.e. in a GET message).
But how can I enable this feature for sending gzip http POST messages from my device?
Do I have to write a custom Intercepter or something? Or simply add something to the headers?

A: According to the following recipe:
The correct flow for gzip would be something like this:
OkHttpClient client = new OkHttpClient.Builder()
      .addInterceptor(new GzipRequestInterceptor())
      .build();

/** This interceptor compresses the HTTP request body. Many webservers can't handle this! */
  static class GzipRequestInterceptor implements Interceptor {
    @Override public Response intercept(Chain chain) throws IOException {
      Request originalRequest = chain.request();
      if (originalRequest.body() == null || originalRequest.header("Content-Encoding") != null) {
        return chain.proceed(originalRequest);
      }

      Request compressedRequest = originalRequest.newBuilder()
          .header("Content-Encoding", "gzip")
          .method(originalRequest.method(), gzip(originalRequest.body()))
          .build();
      return chain.proceed(compressedRequest);
    }

    private RequestBody gzip(final RequestBody body) {
      return new RequestBody() {
        @Override public MediaType contentType() {
          return body.contentType();
        }

        @Override public long contentLength() {
          return -1; // We don't know the compressed length in advance!
        }

        @Override public void writeTo(BufferedSink sink) throws IOException {
          BufferedSink gzipSink = Okio.buffer(new GzipSink(sink));
          body.writeTo(gzipSink);
          gzipSink.close();
        }
      };
    }
  }

A: in addition to the accepted answer: First, declare this class (from @Jason)
// to compress the body of request which is injected as interceptor.
public class GzipInterceptor implements Interceptor {
    @Override public okhttp3.Response intercept(Chain chain) throws IOException {
        Request originalRequest = chain.request();

        // do not set content encoding in negative use case

        if (originalRequest.body() == null || originalRequest.header("Content-Encoding") != null) {
            return chain.proceed(originalRequest);
        }

        Request compressedRequest = originalRequest.newBuilder()
                .header("Content-Encoding", "gzip")
                .method(originalRequest.method(), gzip(originalRequest.body()))
                .build();
        return chain.proceed(compressedRequest);
    }

    private RequestBody gzip(final RequestBody body) {
        return new RequestBody() {
            @Override public MediaType contentType() {
                return body.contentType();
            }

            @Override public long contentLength() {
                return -1; // We don't know the compressed length in advance!
            }

            @Override public void writeTo(BufferedSink sink) throws IOException {
                BufferedSink gzipSink = Okio.buffer(new GzipSink(sink));
                body.writeTo(gzipSink);
                gzipSink.close();
            }
        };
    }
}

then :
 //Encryption Interceptor
GzipInterceptor gzipInterceptor = new GzipInterceptor();

// OkHttpClient. Be conscious with the order
OkHttpClient okHttpClient = new OkHttpClient()
        .newBuilder()
        //httpLogging interceptor for logging network requests
        .addInterceptor(gzipInterceptor)
        .build();

Finally add it to your retrofit as a client: (No need for further changes!)
 Retrofit retrofit = new Retrofit.Builder()
        .client(okHttpClient)
        .baseUrl(Constants.serveraddress)
        .addConverterFactory(GsonConverterFactory.create())
        .build();
Serverinterface serverinterface = retrofit.create(Serverinterface.class);


text:
Q: Understanding excel formula I have a excel formual. =IF(SUMIFS(G:G,D:D,D2)>0,"YES","NO")
I searched on net but found any suitable answer to understand this.
http://office.microsoft.com/en-in/excel-help/sumifs-function-HA010047504.aspx
http://www.myonlinetraininghub.com/excel-2007-sumif-and-sumifs-formulas-explained
I did not find any help from the above link. Could any one please help what this formula actully mean?

A: You first need to understand how the SUMIFS(G:G,D:D,D2) works. It returns the sum of rows within G:G where the corresponding D:D is equal to D2, as explained by the Microsoft link you have already. E.g.
  | D    G
--+-----------
1 | H1   H2
2 | A    1
3 | B    2
4 | C    3
5 | D    4
6 | A    5
7 | B    6
8 | C    7
9 | D    8

Here, D2 is A. SUMIFS(G:G,D:D,D2) will return the sum of values from G where the ones in D are equal to A, which is 1 + 5 = 6
So, if this sum is above 0 in
=IF(SUMIFS(G:G,D:D,D2)>0,"YES","NO")

Then, put YES, otherwise NO.

A: The SUMIFS function takes at least three arguments:

*

*the range to be summed

*the range to be tested

*the condition that the second range is tested for (e.g. ">0")

In your example this function is evaluated; if the result is greater than zero, the outermost IF returns the string "YES", otherwise it returns "NO".
In other words - your expressions tells us whether (the sum of all elements in the first range for which the second range meets the condition in the third range), is greater than zero or not.


text:
Q: Сделать из массивов 1 массив с объектами Есть первый массив:
const arr1 = [
  { id: 1, name: "Группа 1" },
  { id: 3, name: "Группа 2" },
  { id: 2, name: "Группа 3" },
];

Есть второй массив:
const arr2 = [
  {
    groupId: 1,
    title: "Test Title 1",
  },
  {
    groupId: 2,
    title: "Test Title 2",
  },
  {
    groupId: 2,
    title: "Test Title 2",
  },
  {
    groupId: 3,
    title: "Test Title 3",
  },
];

Нужно получить массив с объектами вида:
const arr3 = [
  {
    title: "Группа 1",
    docs: [
      {
        groupId: 1,
        title: "Test Title",
      },
    ],
  },
  {
    title: "Группа 2",
    docs: [
      {
        groupId: 2,
        title: "Test Title",
      },
      {
        groupId: 2,
        title: "Test Title",
      },
    ],
  },
  {
    title: "Группа 3",
    docs: [
      {
        groupId: 3,
        title: "Test Title",
      },
    ],
  },
];

A: Всё довольно просто. Пример решения ниже. Используя flatMap сводим к единому массиву два других.

const arr1 = [
  { id: 1, name: "Группа 1" },
  { id: 3, name: "Группа 2" },
  { id: 2, name: "Группа 3" },
];

const arr2 = [
  {
    groupId: 1,
    title: "Test Title 1",
  },
  {
    groupId: 2,
    title: "Test Title 2",
  },
  {
    groupId: 2,
    title: "Test Title 2",
  },
  {
    groupId: 3,
    title: "Test Title 3",
  },
];

const arr3 = arr1.flatMap(item => {
  const tempObj = {
    title: item.name,
    docs: []
  }
  tempObj.docs = arr2.filter(({groupId}) => groupId === item.id);
  return [tempObj]
})

console.log(arr3)

A: Так сделал. Спасибо всё равно.
const items =
    arr1.map((itema) => ({
      title: itema.name,
      docs: arr2.filter((itemb) => itemb.groupId === itema.id),
    }));


text:
Q: Exporting data frame columns into separate txt files I chunked several novels into a data frame called documents. I want to export each chunk as a separate .txt file.
The data frame that consists of two columns. The first column has the file names for each chunk, and the second column has the actual text that would go into the file.
documents[1,1]
[1] "Beloved.txt_1"

documents[1,2]
[1] "124 was spiteful full of a baby's venom the women......"

class(documents)
[1] "data.frame"

I'm trying to write a for loop that would take each row, make the second column into a .txt file, and make the first column the name of the file. And then to iterate for each row. I've been working with something like this:
for (i in 1:ncol(documents)) {
  write(tagged_text, paste("data/taggedCorpus/",
                     documents[i], ".txt", sep=""))

I've also been reading that maybe the cat function would work well here?

A: I'm not positive this will work for you (a little more of an example of your input and desired output would help), but one issue you've got is that your for loop is by column rather than by row. If you want to do this once for every row, then it needs to be for (i in 1:nrow(documents) rather than ncol.
Assuming that "documents" is the name of your data.frame and that the column containing the text you want to save is called "tagged_text" and the column with the file name is called "file", try this:
 for (i in 1:nrow(documents)) {
      write(documents$tagged_text[i], paste0("data/taggedCorpus/",
                 documents$file[i], ".txt"))
 }

Note that you don't need to specify the path every time if you already set it before you start the loop.


text:
Q: Drag items to canvas from menu in Android Studio I was trying to do a simple application that, from a menu where you have simple geometric figures, you could drag those figures to a canvas (i suppose it has to be a canvas) and those figures appeared on said canvas.
I realized that I have no idea how to begin and I'm having trouble searching for solutions. I could further explain what i want to do if it is needed. Thank you in advance.


text:
Q: is there a way to add a tuple of both str and int to a dict and how to delete a key of a dict python so I have this code right here I want to make a dict of roll num is key and a tuple of name and marks is the value. So I cant do it so I'm using dict of roll num is key and list as value not tuple but I have encounter some error .
lst=[]
lst2=['English','Math','Physic','Chemistry','CS']
n=int(input("Enter roll number: "))
name=str(input("Enter Name: "))
lst.append(name)
for i in range (0,len(lst2)):
    print("Enter Marks in ", lst2[i], end='')
    mark=input(": ")
    lst.append(mark)
    dicta.setdefault(n,lst)

this is what I'm currently having but if I want to delete a key I encounter unhashable type list error when I use del dicta[key] and key error when I use dicta.pop[key]
my input is like this
12 John 8 9 3 4
the first one is roll number so i want to make it as a key in a dictionary and john 8 9 3 4 (name and grades) as value but if I append his name and grades to a list and put like tuple(list) it appear the (match generic type got '_KT') got list[str/int] instead so im using key:list for now and my other question is how can i delete a key of a dictionary of key:list or key:tuple


text:
Q: How to use substring for comparison in mongo db Below is my aggregation
db.customers.aggregate([{
    $match: {
        "CDF.UTILITYTYPE.D1.G1" : "12387835"
    }
},  {
        $project: {
         _id:0,
         "CDF.UTILITYTYPE.D1.G22.NAME":1,
         "CDF.UTILITYTYPE.D1.G1":1,
         "CDF.UTILITYTYPE.D5.EVENT": {
            $filter: {
               input: "$CDF.UTILITYTYPE.D5.EVENT",
               as: "item",
               cond: { $eq: [ "$$item.TIME", "12-04-2018 15:46:02" ] }
            }
         }
      }
    }
]).pretty();

i am comparing TIME field here i actually want to compare "06-2022" as a substring instead of "12-04-2018 15:46:02" this whole date and time format

A: You never store date/time values as string, it's a design flaw. Store always proper Date objects.
Once you corrected the data type, e.g. with
{
   $set: {
      TIME: {
         $dateFromString: {
            dateString: "$TIME",
            format: "%d-%m-%Y %H:%M:%S"
         }
      }
   }
}

you can filter by using for example
cond: {
   $eq: [
      { $dateTrunc: { date: "$TIME" unit: "month" } },
      ISODate("2022-06-01")
   ]
}

or supposingly
cond: {
   $eq: [
      { $dateTrunc: { date: "$TIME" unit: "month" } },
      { $dateTrunc: { date: "$$NOW" unit: "month" } }
   ]
}

A: db.customers.aggregate([{
    $match: {
        "CDF.UTILITYTYPE.D1.G1" : "12387835"
    }
},  {
        $project: {
         _id:0,
         "CDF.UTILITYTYPE.D1.G22.NAME":1,
         "CDF.UTILITYTYPE.D1.G1":1,
         "CDF.UTILITYTYPE.D5.EVENT": {
            $filter: {
               input: "$CDF.UTILITYTYPE.D5.EVENT",
               as: "item",
               cond: { $regexMatch: { input:"$$item.TIME", regex: "05-2022"}}
            }
         }
      }
    }
]).pretty();


text:
Q: intent to install apk on android N I'm trying to Intent to install APK on android N.
I use the following code:
File toInstall = new File(appDirectory, appName + ".apk");
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
    Uri apkUri = FileProvider.getUriForFile(activity, BuildConfig.APPLICATION_ID + ".provider", toInstall);
    Intent intent = new Intent(Intent.ACTION_INSTALL_PACKAGE);
    intent.setData(apkUri);
    intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
    activity.startActivity(intent)
} else {
    Uri apkUri = Uri.fromFile(toInstall);
    Intent intent = new Intent(Intent.ACTION_VIEW);
    intent.setDataAndType(apkUri, "application/vnd.android.package-archive");
    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    activity.startActivity(intent);
}

but I face the following error:
    FATAL EXCEPTION: Thread-5
Process: com.myapp.myapp, PID: 16557
java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.res.XmlResourceParser android.content.pm.ProviderInfo.loadXmlMetaData(android.content.pm.PackageManager, java.lang.String)' on a null object reference
at android.support.v4.content.FileProvider.parsePathStrategy(FileProvider.java:583)
at android.support.v4.content.FileProvider.getPathStrategy(FileProvider.java:557)
at android.support.v4.content.FileProvider.getUriForFile(FileProvider.java:399)
at ir.myapp.picwriter.service.MyService$1.run(MyService.java:57)
at java.lang.Thread.run(Thread.java:761)

Which the error is in this line:
Uri apkUri = FileProvider.getUriForFile(activity, BuildConfig.APPLICATION_ID + ".provider", toInstall);

A: If the File Provider is not being found in the manifest file you have to do something like this to define it:
<provider
    android:name="android.support.v4.content.FileProvider"
    android:authorities="com.mydomain.fileprovider"
    android:exported="false"
    android:grantUriPermissions="true">
    ...
</provider>

Here is a link to the documentation on setting up FileProviders.
https://developer.android.com/reference/android/support/v4/content/FileProvider.html

A: I had many problems with it finally I found the answer. here is the answer hope its useful for you.
    File toInstall = new File(url);
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
        File newFile = new File(new File(Environment.getExternalStorageDirectory(), "apps"), getImageNameByUrl(appUrl));
        Uri apkUri = getUriForFile(context, BuildConfig.APPLICATION_ID+".provider", newFile);
        Intent intent = new Intent(Intent.ACTION_INSTALL_PACKAGE);
        intent.setData(apkUri);
        intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
        context.startActivity(intent);
    } else {
        Uri apkUri = Uri.fromFile(toInstall);
        Intent intent = new Intent(Intent.ACTION_VIEW);
        intent.setDataAndType(apkUri, "application/vnd.android.package-archive");
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        context.startActivity(intent);
    }

manifest:
    <provider
        android:name="android.support.v4.content.FileProvider"
        android:authorities="${applicationId}.provider"
        android:exported="false"
        android:grantUriPermissions="true">
        <meta-data
            android:name="android.support.FILE_PROVIDER_PATHS"
            android:resource="@xml/file_paths" />
    </provider>

and file_paths:
<paths xmlns:android="http://schemas.android.com/apk/res/android">
    <external-path name="." path="." />
</paths>

and permission for API>25
<uses-permissionandroid:name="android.permission.REQUEST_INSTALL_PACKAGES" />


text:
Q: What does try_files do in this nginx configuration? I copied this config when setting up a basic  Nginx / PHP-FPM webserver
server {
    listen 80 default_server;
    listen [::]:80 default_server ipv6only=on;

    root /usr/share/nginx/html;
    index index.php index.html index.htm;

    server_name server_domain_name_or_IP;

    location / {
        try_files $uri $uri/ =404;
    }

    location ~ \.php$ {
        try_files $uri =404;
        fastcgi_split_path_info ^(.+\.php)(/.+)$;
        fastcgi_pass unix:/var/run/php5-fpm.sock;
        fastcgi_index index.php;
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
        include fastcgi_params;
    }
}

It works as it should, but I dont understand how the try_files in location ~ \.php$ { .... } block works when serving a request for a php file, e.g. domain.com/test.php.
I thought this line
try_files $uri =404;

tells nginx to just go ahead and try serving the static file - i.e. append $uri to root directory, if the file exists - nginx would simply send the static file and the request would be over wouldn't it?
And therefore the fastcgi_pass wouldn't occur? but php-fpm does get it and execute the script.
Why doesn't the try_files prevent the fastcgi_pass?

A: Why do you think it should? Nginx documentation doesn't say anything like that.

Checks the existence of files in the specified order and uses the
  first found file for request processing; the processing is performed in the current context. [...] If none of the files were found, an internal redirect to the uri specified in the last parameter is made.

As long as the file is found, the request is processed normally, i.e. passed to fastcgi. Otherwise a 404 will be sent.

A: try_files does not tell nginx to serve the static file. Reaching the closing brace in the absence of any other operation causes it to serve the static file. try_files tests for the existence of the file in the local file system and may rewrite the URL.
So try_files $uri =404; is one of a number of common tricks to overcome a particular script injection exploit by ensuring the the PHP file is a real  file before sending the URL to the upstream interpreter.


text:
Q: Get-Content file reading issues I am trying to push a set of software to multiple machines on a domain using Powershell. I am able to only get the first line in the machinegroup.txt to behave as I expected it to. Every machine listed beyond the first line in the text file Just does not register. How do I get the script to read beyond the first line in the text file?
enter code here

#Variables for Software Local Machine Push
$computername = Get-Content 'C:\Users\Public\testdeploy\machinegroup.txt'
$sourcefile = "C:\Users\Public\testdeploy\file1.msi",
"C:\users\public\testdeploy\file2.msi",
"C:\users\public\testdeploy\file_push_2.ps1","C:\users\public\testdeploy\OrgInfo.json"

#This section will push the software
foreach ($computer in $computername)
{}
$destinationFolder = "\\$computer\c$\users\Public\Downloads\Cisco"
#This section will copy the $sourcefile to the $destinationfolder. If the Folder does not exist it
will create it.
if (!(Test-Path -path $destinationFolder))
{
    New-Item $destinationFolder -Type Directory
}
Copy-Item -Path $sourcefile -Destination $destinationFolder

A: You are passing in an array with this $computername and this $sourcefile. Thus you cannot pass it the way you are doing. You have to enumerate/loop thru them.
So, something like this, keeping all comments in the comment block. Avoid commenting on the obvious. Your code should be written to be in plain English, Full cmdlet use, no aliases in scripts (they are fine in throw-away code, interactive stuff), self-explanatory, and self-documenting as possible.
<#
.Synopsis
    Remote application deployment
.DESCRIPTION
    Copy required apps from source to destination
.EXAMPLE
    Example of how to use this function/script/cmdlet
.EXAMPLE
    Another example of how to use this function/script/cmdlet
.NOTE
    More notes here
#>

$computernames = Get-Content -Path 'C:\Users\Public\testdeploy\machinegroup.txt'

$sourcefile   = @(
                    'C:\Users\Public\testdeploy\file1.msi',
                    'C:\users\public\testdeploy\file2.msi',
                    'C:\users\public\testdeploy\file_push_2.ps1',
                    'C:\users\public\testdeploy\OrgInfo.json'
                 )

$computernames |
ForEach {
    $destinationFolder = "\\$PSItem\c$\users\Public\Downloads\Cisco"

    if (-Not(Test-Path -path $destinationFolder))
    {New-Item -Path $destinationFolder -Type Directory}

    $sourcefile |
    ForEach {Copy-Item -Path $PSItem -Destination $destinationFolder}
}


text:
Q: How much memory is used for function references in a Java object? Is it 32-bit / 64-bit depending on the JVM, or is it less as do we really need that many possibilities for addresses when addressing functions?
Surely we would never need that many possibilities as the number of types, and resulting number of functions would never reach these numbers?

A: The by far simplest implementation uses the "real"/full address of the function, whatever that may be on the architecture in question (e.g. the virtual address of the first instruction of the function prologue). So yeah, such a function pointer will probably be a word large. And this is a good thing!
Size is not anywhere as important as for object references or object headers, because there is only one such pointer in the whole process per method, regardless of how many instances there are. Moreover, any scheme for shrinking the address means you need additional operations to call the function pointed to (either some indirection, or some arithmetic). That would be bad, because it has to happen every time a virtual method (which is all of them prior to optimizations, and still quite a few afterwards) is called.


text:
Q: A yielded value of type 'Stream' must be assignable to 'LocationData' I was trying to make a stream function that returns LocationData as stream.
But I got this error saying
A yielded value of type 'Stream<LocationData>' must be assignable to 'LocationData'
Stream<LocationData>  getCoordinates() async* {
      yield Location.instance.onLocationChanged;//error shows here
}

A: According to your error message, you are missing a * after your yield to actually yield each item in your stream:
Stream<LocationData>  getCoordinates() async* {
      yield* Location.instance.onLocationChanged;
}

Please note that this is an educated guess, next time it would really help to have more code.

A: Maybe This helps anyone who needs to return a stream of data so I think you have to provide something like this
If you want to return a stream of data inside a listener which return another stream of data maybe you can do something like this.
  Stream<LocationData> getUserLiveLocation() async* {
   yield* location.onLocationChanged;

}


text:
Q: JS / Coffee + HTML, simpler way to set conditional class So, when I'm rendering html templates from javascript (or coffeescript, I use both depending on the circumstances), I find I have a really common case that seems unnecessarily clunky. For example:
I have a JS object like this:
var thingy = {
  name: 'Some Thing',
  category: 'widget',
  active: true
};

I might want to render this into html like so:

Some Thing

The bit that always feels clunky is turning a boolean check in javascript into a css class string. What I normally end up doing is something like this:
function renderThing(thing) {
  var klass = thing.active ? thing.category + " active" : thing.category
  return '
'+thing.name+'
';
}

In coffeescript this feels longer since the ternary is more verbose:
renderThing = (thing) ->
  klass = if thing.active then thing.category + " active" else thing.category
  '
'+thing.name+'
'

This isn't too terrible when there's only one such property but if you end up in a situation with three or four the code quickly gets very verbose.
So, I was wondering, does anyone have ideas/suggestions on a more concise and/or readable way to do this?

A: If I was doing a lot of these then I'd write a simple function to, more or less, provide my own "cast boolean to string":
if_true = (f, s) ->
    return s if(f)
    return ''

Then a bit of string interpolation to build the class string:
klass = "#{if_true(o.active, 'active')} #{o.category}"

If you don't like the stray space when !o.active then you could move that space into the if_true argument:
klass = "#{if_true(o.active, 'active ')}#{o.category}"

And if you have a whole bunch of flags, toss their names in an array and use a loop comprehension to build an array of class names:
o =
    first: true
    second: true
    third: false
    fourth: undefined
    fifth: 'element'
    category: 'pancakes'

flags = [ 'first', 'second', 'third', 'fourth', 'fifth' ]

klasses = (if_true(o[f], f) for f in flags)
klasses.push(o.category)
klass = klasses.join(' ')

Demo: http://jsfiddle.net/ambiguous/eGDaa/

A:
This isn't too terrible when there's only one such property but if you
  end up in a situation with three or four the code quickly gets very
  verbose.

Indeed it will. Looks like a perfect place to use assign from switch -- that is, if there will only be one "add-on" class:
score = 76
grade = switch
  when score < 60 then 'F'
  when score < 70 then 'D'
  when score < 80 then 'C'
  when score < 90 then 'B'
  else 'A'

But that would be 1 input equals 1 output, which might not be what you want. Maybe you need:
renderThing = (thing) ->
  cssClass = thing.category
  keysToCss = ["active", "disabled", "delta", "gamma", "epsilon"]

  for k,v of thing
   if lodash.contains(keysToCss, k) # I'm using lodash here, same as Underscore
     cssClass += " #{k}"

  "

"

Also, I think once you start mixing markup and code like this you need to start investigating a tool like Angular.

A: Check coffeescripts loop comprehensions to iterate a bunch of flags and build a list which you can concatenate to the class value:
renderThing = (thing) ->
  flags = ["selected", "current", "active", "disabled", "bookmarked"];
  klasses = (f for f in flags when thing[f])
  klasses.push thing.category
  "
#{thing.name}
"


text:
Q: Get a route frontname by route id I'm currently working with URL rewrites and I'm looking for a way to get the front name of a route from a module.
<router id="standard">
    <route id="support" frontName="faq">
        <module name="" />
    </route>
</router>

This is for a module that I'm customizing, not a new module. I don't want to have to change the id as I would probably need to change quite a bit of code.
I'd like to get the 'faq' front name by supplying the id 'support' (which it does for getUrl(), but that returns the front name appended to the base URL.
If all else fails I could probably just use the getUrl() method and just grab the last fragment I guess, but I'd like to use a better solution if possible.

A: routes.xml
When set the url by routes which id and frontName must be same ( ie, id="support" and frontName="support
")
The routes.xml file maps which module to use for a URL with a specific frontName and area. The location of the routes.xml file in a module, either etc/frontend or etc/adminhtml, specifies where those routes are active.
The content of this file uses the following format:
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:App/etc/routes.xsd">
    <router id="%routerId%">
        <route id="custom" frontName="custom">
            <module name="%moduleName%"/>
        </route>
    </router>
</config>

For more details refer the link https://devdocs.magento.com/guides/v2.3/extension-dev-guide/routing.html

A:
Please use this way

 getUrl("support/index/index");

A: I ended up creating this function in the module's helper class and pulling the helper into whatever class I needed it via di (in the __construct method).
/**
 * Get the frontend url for the given path
 *
 * @param string $route
 * @param string $type base,path,frontname
 */
public function getFrontUrl($route = '', $type = 'base')
{
    if (empty($route)) {
        return false;
    }
    $storeId = $this->_storeManager->getDefaultStoreView()->getStoreId();
    $url = $this->_storeManager->getStore($storeId)->getUrl($route);

    if ($type == 'path' || $type == 'frontname') {
        $parsed = ltrim(parse_url($url, PHP_URL_PATH), '/');
        if ($type == 'path') {
            return $parsed;
        } else {
            $parsedFront = explode('/', $parsed);
            return $parsedFront[0];
        }
    } else {
        return $url;
    }
}

Which basically lets me get the frontend url or some variants of it:
$_helper->getFrontUrl('support')
    // returns 'http://example.com/faq/

$_helper->getFrontUrl('support', 'path')
    // returns 'faq/'

$_helper->getFrontUrl('support/view', 'path')
    // returns 'faq/view'

$_helper->getFrontUrl('support', 'frontname')
    // returns 'faq', even if the route specified was 'support/view'


text:
Q: Meaning of spectral functions for a non-interacting electron system at $T \to 0$ I am doing an exercise on solid state physics. Using Hartree-Fock formalism, and assuming a non-interacting electron system with the following grand canonical hamiltonean: $$\mathcal{H}= \sum_{k,\sigma} (\epsilon_k - \mu) c_{k \sigma}^\dagger  c_{k \sigma}$$
with eigenstates defined as: $E_n = \cal{E} -\mu  N_n$
I calculated the spectral density of this system, defined as: $$\mathcal{S}_\sigma (\omega, k)= \frac{1}{\Omega} \sum_b e^{- \beta K_b} \cdot \sum_a |\langle a | c_{k \sigma}| b\rangle|^2 \delta(E_b - E_a - \hbar w)$$
and  by manupulating the terms, I eventually arrived at the following expression:
$$\mathcal{S}_\sigma (\omega, k)= \frac{1}{\Omega} f(\epsilon_k) \delta(\epsilon_k - \mu- \hbar w)$$
where $f(\epsilon_k)$ represents the fermi function: $$f(\epsilon_k)= \frac{1}{1+ e^{\beta (\epsilon_k - \mu)}}$$
I am having some trouble with the next steps in the exercise.
The next challenge is to analyze the meaning of these results at the limit $T \to 0$. Now, in this limit I know that:

*

*$\mu = E_F$, the fermi energy of the system

*$f(\epsilon_k) = \theta(\epsilon_k - \mu)$, where $\theta$ represents the heaviside step function (meaning all states are occupied up to the fermi level)

Using this, I know that as $T\to 0$, the spectral density of the system is only non-zero as $\epsilon_k \le \mu$, at which the function becomes simply:
$$\mathcal{S}_\sigma (\omega, k)= \frac{1}{\Omega} \delta(\epsilon_k - \mu- \hbar w)$$
But I don't understand what this means for the system and the electron occupation.

A: At T = 0 the system is in its ground state where all energy levels up to the Fermi level have full occupation and all of the energy levels above the Fermi level are completely unoccupied.
The spectral density essentially represents how easy it is for your system to exchange energy with the environment. At T= 0, because all lower energy states are filled, the system can only take energy from the environment (absorb), it cannot give energy (emit). The only excitations you have are electrons near the Fermi level absorbing some quanta of energy, and that is represented in your expression.


text:
Q: what is WIZARD_ID? win32console.vsz
VSWIZARD 7.0
Wizard=VsWizard.VsWizardEngine.10.0
Param="WIZARD_NAME = Application"
Param="RELATIVE_PATH = VCWizards\AppWiz\Generic"
Param="WIZARD_ID = 75"

what is WIZARD_ID? any official document or specification?


text:
Q: angularjs filter of a select with empty value I have a problem with a filter in AngularJS. See my code here: http://jsfiddle.net/sqev9/7/
I have a select that uses a filter in the ng-options field:
ng-options="listitem as listitem.Name for listitem in MyList.Items|filter:FilterList"

I also use an empty option because this select is optional.
As ng-model for the select I use the value "SelectedInList"
The problem is now that when the filter doesn't match anything, the "SelectedInList" variable in my $scope is not null then.
Simulate this by selecting "item1" and pressing "Go": the SelectedInList is now correctly the item1 object. Now the filter changes and the list is "empty": only the "-" item is there, which is also expected. Now pressing "go" again should give me "null" as SelectedInList, but it is still the item1 object, which I don't expect.
Any solutions to this approach?
Best regards,
Tom,

A: Seems that when the list is filtered and the value is no more, there is no update on the ng-model. This seems pretty much like a bug, but I would need more research to understand the reason.
Anyway, a solution is to set SelectedInList to null at the end of Add method.


text:
Q: How safe is it to use PhpStorm's refactoring commands I have some PHP code that is does not have good test coverage and is not easily testable in its current state. If I use commands from the refactor menu of PhpStorm, and make no other changes, how sure can I be that this won't change the behaviour of my application?
How safe are other automatic refactoring tools?
My understanding is that these tools will apply static analysis and could only cause changes to behaviour if the application does something very weird like depending on the output of debug_backtrace()

A: The (overly) simple answer is it's no better or worse than manually refactoring.
If you have good tests then it's safe. If you don't then it's not.
I would say do not do any refactoring without having unit tests for each function being refactored. Refactoring should not break unit tests, if it does then you haven't refactored it, you've changed it.
I have been bitten by PhpStorms refactoring tools in weird ways in the past, even resulting in broken syntax. But, that was a long time ago, the tools have moved on, and it's always easy to go back a step if you're methodically committing changes to your SCM.


text:
Q: QGIS set raster No-Data value I have a raster layer that resulted from a series of calculations with

*

*raster calculator (simple subtraction of two raster layers)

*gdal_translate -ot Int16 -of GTiff ... (convert to Int16, as the result of above is in Float32)

however the gdal_translate command seems to forfeit the No-Data information. It ("correctly") assigns minmal values to the previously no-data cells (−32,768 in case of Int16), however doesn't store the No-Data information in the metadata (as seen in Properties of the raster layer, see picture).
Previous layer, result from raster calculator:

Problematic layer, result from gdal_translate with no No-Data value:

As a result, the values are displayed as regular raster cells by default. I'm aware that I can adjust styling and clip out of range values in styling options to make the "−32,768-No-Data"-cells invisible again. But I'd rather have the raster layer remember, which cell values correspond to "No-Data"!
I tried to assign it with the gdal command:
gdal_translate -a_nodata -32.768 -ot Int16 -of GTiff ...
however that shows no effect.
Can I manually set a No-Data-Value via Properties or some other tool?

A: When saving a raster layer (Right click on layer > Export > Save as ...) you have the option to set No-Data values (see yellow circle in picture). This will have the desired effect.
As an additional hint since we're talking about conversion from Float32 to Int16: Don't forget to check Compression options, since they are not always on by default (see red arrow in picture).


text:
Q: Is there an exception that would rollback an Django atomic transaction without being propagated? I created an exception
class MyOwnRollBack(Exception):
    pass

only to be able to rollback a transaction without it being raised beyond the transaction:
try:
    with transaction.atomic():
         # do stuff
         raise MyOwnRollBack
except MyOwnRollBack:
    pass

Is there an exception that transaction.atomic() won't let propagate, similar to this code I wrote?

A:
Is there an exception that transaction.atomic() won't let propagate, similar to this code I wrote?

Technically, yes, but for all practical purposes, no.
IntegrityErrors will escape
try:
    with transaction.atomic():
        generate_relationships()
except IntegrityError:
    handle_exception()

but once you get to handle_exception() the transaction has already been rolled back. Even if it wasn't rolled back, you're not allowed to run database statements before the rollback is finished (a TransactionManagmentError will be raised).
You might find a solution handling transactions manually, check the docs https://docs.djangoproject.com/en/2.1/topics/db/transactions/#transactions


text:
Q: PHP Array parent/child display/inherit I have an piece of my array here:
   [0] => stdClass Object
    (
        [id] => 8005
        [parentid] => 8004
        [name] => a, b
        [level] => 1
        [prodtypename] => 1, 2, 3, 4
    )

[1] => stdClass Object
    (
        [id] => 8006
        [parentid] => 8005
        [name] => c
        [level] => 2
        [prodtypename] =>
    )

[2] => stdClass Object
    (
        [id] => 8007
        [parentid] => 8005
        [name] => d
        [level] => 2
        [prodtypename] =>
    )

In my form I display them like:
 <?php foreach ($this->myArray as $item): ?>
 <?php echo $item->prodtypename ?>

it displays me current category and its current type. I need to display parent "prodtypename" next to child type, so we can know, what is parents types for current child category. Im trying to make display look something like this:
 [1] => stdClass Object
    (
        [id] => 8006
        [parentid] => 8005
        [name] => c
        [level] => 2
        [prodtypename] => 1,2,3,4
    )

Because parents "prodtypename" have 1.2.3.4, so the child inherits it. Thanks.

A: Based on the array you have already something like this might work assuming that you can rely on parents always appearing in the array before their children:
$prodTypeNames = array();
foreach ($this->myArray as $item) {
    $prodTypeName = $item->prodtypename;
    if( is_null( $item->prodtypename ) && isset( $prodTypeNames[$item->parentid] ) ) {
        $prodTypeName = $prodTypeNames[$item->parentid];
    }
    $prodTypeNames[$item->id] = $prodTypeName;
    echo $prodTypeName;
}

But you're probably better off getting the data in a better format to begin with.


text:
Q: Como recuperar todos os dados de uma coluna datatable após uma busca feita? Preciso recuperar os dados de uma coluna, mas quero somente os que estão visíveis na tela após digitar uma busca filtrando a quantidade de linhas.
Já conseguir recuperar uma coluna com todas as linhas da tabela assim:
var coluna = $('#tabela').DataTable().column().data();
console.log(coluna);

Mas preciso dos dados somente de algumas linhas que atendem a minha busca no campo "search" do datatables.
Tentei filtrar antes sem sucesso:
var palavra = $('div.dataTables_filter input').val(); //palavra buscada
var filtro = $('#tabela').DataTable().search(palavra).draw(); //filtrando as linhas que contem a palavra
var nomes = filtro.column().data(); //pegando os dados da coluna apos o filtro
console.log(nomes); //imprime os dados da coluna toda - todas as linhas da tabela

Agradeço desde já qualquer ajuda!

A: Um comanndo no SQL que eu sei que funciona é o LIKE
SELECT nome_da_coluna FROM nome_da_tabela WHERE nome_da_coluna LIKE '%MINHA CHAVE DE BUSCA%'

Se seu script imprime o resultado em tempo real, então o resultado vai sendo impresso gradativamente assim que você escrever o M ... vai aparecer a fraze que esta na sua coluna, se você preencher MN, por exemplo, nao vai imprimir nada, se você colocar CHAVE vai aparecer a frase completa novamente... e por ai vai, espero ter te dado um norte.
Obs.: nao conselho usar * entre o SELECT e o FROM , tente sempre buscar a coluna que voce precisa.

A: Você pode usar um .each() do jQuery e pegar os dados de uma determinada coluna da tabela:
var dados = [];
$('#tabela tbody tr').each(function(){
   dados.push(this.cells[0].textContent.trim());
});

Isso irá adicionar na array dados[] somente o texto de cada célula da primeira coluna da tabela (o índice [0] significa a primeira coluna).
Por exemplo, se você procurar pela letra "b" e a tabela mostrar:
-----------------------------
|   Nome        |   Idade   |
-----------------------------
|  Beatriz      |    25     |
-----------------------------
|  Bianca       |    21     |
-----------------------------

O resultado será dados = ["Beatriz", "Bianca"].


text:
Q: Scala object oriented design suggestion I have two kinds of reviews for a product:

*

*Works as suggested (1 to 5).

*Price okay. (1 to 5).

I'd like WorksFineRating instances to be stored in WorksFine table in SQL. I'd like PriceOkayRating instances to be stored in PriceOkay table in SQL.
I am looking at something like the following modal that has both the rating types: (Question marks deliberate to indicate that this is not the final design)
trait? ProductRating( rating: Int, productId: Int, userId: Int )
{
   val sqlTable
   def getRatings: ProductRating = doMagicSql( s"SELECT * FROM $sqlTable" )
}

case Class? WorksFineRating(rating, productId, userId) extends Rating( rating, productId, userId){ val sqlTable = "WorksFineRating" }

case Class? PriceOkayRating(rating, productId, userId) extends Rating( rating, productId, userId){ val sqlTable = "PriceOkayRating" }

Here's how I'm actually modelling it in Scala:
trait ProductRating[ PR <: ProductRating[ PR ] ]{
  val reviewId: Int
  val userId: Int
  val rating: Int
}

case class WorksFineRating(
  reviewId: Int,
  userId: Int,
  rating: Int
) extends ProductRating[ WorksFineRating ]

case class PriceOkayRating(
  reviewId: Int,
  userId: Int,
  rating: Int
) extends ProductRating[ PriceOkayRating ]

trait ProductRatingCompanion[ PR <: ProductRating[ PR ] ]
{
  val sqlTable: String
  def factory( reviewId: Int, userId:Int, rating:Int ): PR

  def getAllFromSqlTable = {
    Seq( factory( 1, 2, 3 ), factory( 4, 5, 6 ) )
  }
}

object WorksFineRating
  extends ProductRatingCompanion[ WorksFineRating ]
{
  val sqlTable = "WorksFineRating"
  def factory( reviewId: Int, userId:Int, rating:Int )
  : WorksFineRating =
    WorksFineRating( reviewId, userId, rating )
}

object PriceOkayRating
  extends ProductRatingCompanion[ PriceOkayRating ]
{
  val sqlTable = "PriceOkayRating"
  def factory( reviewId: Int, userId:Int, rating:Int ): PriceOkayRating =
    PriceOkayRating( reviewId, userId, rating )
}

object T extends App{
  println( WorksFineRating.getAllFromSqlTable )
}

Explanations:
1) I was not very comfortable putting sqlTable inside the class as I showed in the first code outline. I think not every instance should have to know this.
(I guess rest seems straightforward to me).
Questions:
1) Am I overcomplicating by adding FBounded polymorphism to the ProductRating trait? It's not required there. It is indeed required in the ProductRatingCompanion object because factory's return type is known to be PR. Is it not?
2) Can I somehow get rid of the 'factory'? The code is almost identical. I don't understand JVM all that much, but if an external library were to use this class, it would see only the generic version of the companions, which means that at runtime, there would be no way to create an instance of that class. Is that correct? Can I somehow store the type in the object? Like type T = RR.type? (It doesn't work)
3) How does one create a function that can handle both types? Like a function that takes a param "PriceOrFunctionality" and decides to create an instance of appropriate class. If you do an if-else, then the type of this instance would actually be a mixed type of the two types. So any further operations using companion object would require asInstanceOf calls.
Any suggestions would be great. I'd like for this question to be a good reference for design- so I'm willing to make a lot of modifications and make it community wiki (I'm not looking to gain points here) so that people can use this as an example of good OO design. So I'd appreciate if you guys could help. (I'll find out how to make community wiki)
EDIT: I can't make this question a community wiki. If any mods could do that, that would be great. Thanks in advance.


text:
Q: draggable div without jquery UI cant drag well I have this code:
jQuery:
var mouseDown=false;
var lastPositionX;
var lastPositionY;
var newX;
var newY;
var lastPositionLeft;
var lastPositionTop;
var newLeft;
var newTop;
    $("#insideMap").on("mousedown",function(){
        mouseDown=true;
        lastPositionX=e.pageX;
        lastPositionY=e.pageY;
    });
    $("#insideMap").on("mouseup",function(u){
        mouseDown=false;
    });
    $("#insideMap").on("mouseleave",function(){
        mouseDown=false;
    });
    $("#insideMap").on("mousemove",function(n){
        if (mouseDown){
            mouseDown = true; // mantain the boolean to prevent mouseleave trigger
            newX=n.pageX-lastPositionX;
            newY=n.pageY-lastPositionY;
            lastPositionLeft=$("#insideMap").position().left;
            lastPositionTop=$("#insideMap").position().top;
            newLeft=newX+lastPositionLeft;
            newTop=newY+lastPositionTop;
            $("#insideMap").css({"left":newLeft,"top":newTop});
            lastPositionX=n.pageX;
            lastPositionY=n.pageY;
        }
    });

Demo: http://jsfiddle.net/SkWeX/3/
but something is still bad :( it doesnt work well, it is still lagging,
 can you help me with it?

A: :) the browser wants sometimes to drag your image (bg), you need to prevent this!
jsFiddle demo
Just add this to your #insideMap element's CSS:
-webkit-touch-callout: none;
-webkit-user-select: none;
-khtml-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
user-select: none;

And this code is all you need:
var mouseDown=false,
    posX   = 0,
    posY   = 0,
    innerX = 0,
    innerY = 0;

$("#insideMap").on("mousedown",function(e){
    innerX = e.pageX - $(this).offset().left;
    innerY = e.pageY - $(this).offset().top;
    mouseDown= true;
}).on("mouseup",function(){
    mouseDown=false;
});

$(document).on("mousemove",function(e){
    if (mouseDown){
        var m = {  x: e.pageX-innerX,  y: e.pageY-innerY };
        $('#insideMap').css({ left: m.x, top: m.y });
    }
});

Some explanation:
Your code is slow cause on any registered mousemovement (and there are many) you are recalculating the element position. Wrong.

*

*I grab the mouse position inside the element on click vars innerX and innerX

*On mousemove I just move the CSS element position to the actual mouse position (you guess right: ) but minus the position where the element was clicked (innerX, innerY) (to prevent the element jump to mouse position)  .


text:
Q: is there a better way to get the data form beautiful soup query? I am trying to extract the m/z data for different ions from "https://www.lipidmaps.org/databases/lmsd/LMFA08040013".
I can get access to the ions and thier data, however to extract the formula and m/z, I am thinking to convert it to a string and the use striping tool to extract it. Is thier another way using beautifulsoup?

from bs4 import BeautifulSoup #used to interact with the website
import requests
soup = BeautifulSoup(requests.get("https://www.lipidmaps.org/databases/lmsd/LMFA08040013").text, "html.parser")

for option in soup.find_all('option'):
    ion = option.text
    option = str(option)
    m_z = ion
    ion_formula =
    return ([m_z,ion-formula,ion]

example of option data:
<option data-display-formula="C18H38NO2" data-formula="C18H38NO2" data-mass-z-ratio="300.2897" value="MplusH">
                                    [M+H]+
                                </option>

Example of output data:

m_z = 300.2897
ion-formula = C18H38NO2
ion = \[M+H\]+

A: Not sure what you mean by more elegant but if all you want is the first option with the given ion value you can get the output you want this way:
import requests
from bs4 import BeautifulSoup

url = "https://www.lipidmaps.org/databases/lmsd/LMFA08040013"
soup = (
    BeautifulSoup(requests.get(url).text, "lxml")
    .select_one(".change\:calculate-mz > option:nth-child(2)")
)

mz = soup["data-mass-z-ratio"]
formula = soup["data-formula"]
ion = soup.getText(strip=True)

print(f"{mz} {formula} {ion}")

Output:
300.2897 C18H38NO2 [M+H]+

To list them all, try this:
import requests
from bs4 import BeautifulSoup

url = "https://www.lipidmaps.org/databases/lmsd/LMFA08040013"
options = (
    BeautifulSoup(requests.get(url).text, "lxml")
    .select(".change\:calculate-mz > option")[1:]
)

for option in options:
    mz = option["data-mass-z-ratio"]
    formula = option["data-formula"]
    ion = option.getText(strip=True)
    print(f"m_z = {mz}\nion-formula = {formula}\nion = {ion}")
    print("-" * 30)

Output:
m_z = 300.2897
ion-formula = C18H38NO2
ion = [M+H]+
------------------------------
m_z = 282.2791
ion-formula = C18H36NO
ion = [M+H-H2O]+
------------------------------
m_z = 299.2819
ion-formula = C18H37NO2
ion = [M.]+
------------------------------
m_z = 150.6485
ion-formula = C18H39NO2
ion = [M+2H]2+
------------------------------
m_z = 100.7681
ion-formula = C18H40NO2
ion = [M+3H]3+
------------------------------
m_z = 75.8279
ion-formula = C18H41NO2
ion = [M+4H]4+
------------------------------
m_z = 338.2456
ion-formula = C18H37KNO2
ion = [M+K]+
------------------------------
m_z = 188.6044
ion-formula = C18H37K2NO2
ion = [M+2K]2+
------------------------------
m_z = 376.2015
ion-formula = C18H36K2NO2
ion = [M+2K-H]+
------------------------------
m_z = 322.2716
ion-formula = C18H37NNaO2
ion = [M+Na]+
------------------------------
m_z = 172.6304
ion-formula = C18H37NNa2O2
ion = [M+2Na]2+
------------------------------
m_z = 344.2536
ion-formula = C18H36NNa2O2
ion = [M+2Na-H]+
------------------------------
m_z = 306.2979
ion-formula = C18H37LiNO2
ion = [M+Li]+
------------------------------
m_z = 156.6567
ion-formula = C18H37Li2NO2
ion = [M+2Li]2+
------------------------------
m_z = 317.3162
ion-formula = C18H41N2O2
ion = [M+NH4]+
------------------------------
m_z = 298.2752
ion-formula = C18H36NO2
ion = [M-H]-
------------------------------
m_z = 148.6339
ion-formula = C18H35NO2
ion = [M-2H]2-
------------------------------
m_z = 98.7535
ion-formula = C18H34NO2
ion = [M-3H]3-
------------------------------
m_z = 73.8133
ion-formula = C18H33NO2
ion = [M-4H]4-
------------------------------
m_z = 334.2518
ion-formula = C18H37ClNO2
ion = [M+Cl]-
------------------------------
m_z = 358.2963
ion-formula = C20H40NO4
ion = [M+OAc]-
------------------------------
m_z = 344.2806
ion-formula = C19H38NO4
ion = [M+HCOO]-
------------------------------
m_z = 299.2824
ion-formula = C18H37NO2
ion = M(neutral)
------------------------------

A: I can't say what could be considered elegant, but I usually get data like this using .get and list comprehension
ionOptions = [{
    'ion': option.get_text(' ').strip(),
    'ion-formula': option.get('data-formula'),
    'm_z': option.get('data-mass-z-ratio')
} for option in soup.select('option[data-mass-z-ratio][data-formula]')]

and ionOptions would look like
[{'ion': '[M+H]+', 'ion-formula': 'C18H38NO2', 'm_z': '300.2897'},
 {'ion': '[M+H-H2O]+', 'ion-formula': 'C18H36NO', 'm_z': '282.2791'},
 {'ion': '[M.]+', 'ion-formula': 'C18H37NO2', 'm_z': '299.2819'},
 {'ion': '[M+2H]2+', 'ion-formula': 'C18H39NO2', 'm_z': '150.6485'},
 {'ion': '[M+3H]3+', 'ion-formula': 'C18H40NO2', 'm_z': '100.7681'},
 {'ion': '[M+4H]4+', 'ion-formula': 'C18H41NO2', 'm_z': '75.8279'},
 {'ion': '[M+K]+', 'ion-formula': 'C18H37KNO2', 'm_z': '338.2456'},
 {'ion': '[M+2K]2+', 'ion-formula': 'C18H37K2NO2', 'm_z': '188.6044'},
 {'ion': '[M+2K-H]+', 'ion-formula': 'C18H36K2NO2', 'm_z': '376.2015'},
 {'ion': '[M+Na]+', 'ion-formula': 'C18H37NNaO2', 'm_z': '322.2716'},
 {'ion': '[M+2Na]2+', 'ion-formula': 'C18H37NNa2O2', 'm_z': '172.6304'},
 {'ion': '[M+2Na-H]+', 'ion-formula': 'C18H36NNa2O2', 'm_z': '344.2536'},
 {'ion': '[M+Li]+', 'ion-formula': 'C18H37LiNO2', 'm_z': '306.2979'},
 {'ion': '[M+2Li]2+', 'ion-formula': 'C18H37Li2NO2', 'm_z': '156.6567'},
 {'ion': '[M+NH4]+', 'ion-formula': 'C18H41N2O2', 'm_z': '317.3162'},
 {'ion': '[M-H]-', 'ion-formula': 'C18H36NO2', 'm_z': '298.2752'},
 {'ion': '[M-2H]2-', 'ion-formula': 'C18H35NO2', 'm_z': '148.6339'},
 {'ion': '[M-3H]3-', 'ion-formula': 'C18H34NO2', 'm_z': '98.7535'},
 {'ion': '[M-4H]4-', 'ion-formula': 'C18H33NO2', 'm_z': '73.8133'},
 {'ion': '[M+Cl]-', 'ion-formula': 'C18H37ClNO2', 'm_z': '334.2518'},
 {'ion': '[M+OAc]-', 'ion-formula': 'C20H40NO4', 'm_z': '358.2963'},
 {'ion': '[M+HCOO]-', 'ion-formula': 'C19H38NO4', 'm_z': '344.2806'},
 {'ion': 'M(neutral)', 'ion-formula': 'C18H37NO2', 'm_z': '299.2824'}]

Note: You can use .find_all('option') or .select('option') instead of .select('option[data-mass-z-ratio][data-formula]'), but then the first option tag would also get included:
{'ion': '(Select m/z)', 'ion-formula': None, 'm_z': None}

You could print it in sections
for o in ionOptions:
    for k, v in o.items(): print(f'{k:>15} = {v}')
    print('-'*40)

output:
            ion = [M+H]+
    ion-formula = C18H38NO2
            m_z = 300.2897
----------------------------------------
            ion = [M+H-H2O]+
    ion-formula = C18H36NO
            m_z = 282.2791
----------------------------------------
            ion = [M.]+
    ion-formula = C18H37NO2
            m_z = 299.2819
----------------------------------------
            ion = [M+2H]2+
    ion-formula = C18H39NO2
            m_z = 150.6485
----------------------------------------
            ion = [M+3H]3+
    ion-formula = C18H40NO2
            m_z = 100.7681
----------------------------------------
            ion = [M+4H]4+
    ion-formula = C18H41NO2
            m_z = 75.8279
----------------------------------------
            ion = [M+K]+
    ion-formula = C18H37KNO2
            m_z = 338.2456
----------------------------------------
            ion = [M+2K]2+
    ion-formula = C18H37K2NO2
            m_z = 188.6044
----------------------------------------
            ion = [M+2K-H]+
    ion-formula = C18H36K2NO2
            m_z = 376.2015
----------------------------------------
            ion = [M+Na]+
    ion-formula = C18H37NNaO2
            m_z = 322.2716
----------------------------------------
            ion = [M+2Na]2+
    ion-formula = C18H37NNa2O2
            m_z = 172.6304
----------------------------------------
            ion = [M+2Na-H]+
    ion-formula = C18H36NNa2O2
            m_z = 344.2536
----------------------------------------
            ion = [M+Li]+
    ion-formula = C18H37LiNO2
            m_z = 306.2979
----------------------------------------
            ion = [M+2Li]2+
    ion-formula = C18H37Li2NO2
            m_z = 156.6567
----------------------------------------
            ion = [M+NH4]+
    ion-formula = C18H41N2O2
            m_z = 317.3162
----------------------------------------
            ion = [M-H]-
    ion-formula = C18H36NO2
            m_z = 298.2752
----------------------------------------
            ion = [M-2H]2-
    ion-formula = C18H35NO2
            m_z = 148.6339
----------------------------------------
            ion = [M-3H]3-
    ion-formula = C18H34NO2
            m_z = 98.7535
----------------------------------------
            ion = [M-4H]4-
    ion-formula = C18H33NO2
            m_z = 73.8133
----------------------------------------
            ion = [M+Cl]-
    ion-formula = C18H37ClNO2
            m_z = 334.2518
----------------------------------------
            ion = [M+OAc]-
    ion-formula = C20H40NO4
            m_z = 358.2963
----------------------------------------
            ion = [M+HCOO]-
    ion-formula = C19H38NO4
            m_z = 344.2806
----------------------------------------
            ion = M(neutral)
    ion-formula = C18H37NO2
            m_z = 299.2824
----------------------------------------

I personally prefer to use pandas to get a tabular format:
# import pandas

print(pandas.DataFrame(ionOptions).to_markdown(index=False))

output:
| ion        | ion-formula   |      m_z |
|:-----------|:--------------|---------:|
| [M+H]+     | C18H38NO2     | 300.29   |
| [M+H-H2O]+ | C18H36NO      | 282.279  |
| [M.]+      | C18H37NO2     | 299.282  |
| [M+2H]2+   | C18H39NO2     | 150.649  |
| [M+3H]3+   | C18H40NO2     | 100.768  |
| [M+4H]4+   | C18H41NO2     |  75.8279 |
| [M+K]+     | C18H37KNO2    | 338.246  |
| [M+2K]2+   | C18H37K2NO2   | 188.604  |
| [M+2K-H]+  | C18H36K2NO2   | 376.202  |
| [M+Na]+    | C18H37NNaO2   | 322.272  |
| [M+2Na]2+  | C18H37NNa2O2  | 172.63   |
| [M+2Na-H]+ | C18H36NNa2O2  | 344.254  |
| [M+Li]+    | C18H37LiNO2   | 306.298  |
| [M+2Li]2+  | C18H37Li2NO2  | 156.657  |
| [M+NH4]+   | C18H41N2O2    | 317.316  |
| [M-H]-     | C18H36NO2     | 298.275  |
| [M-2H]2-   | C18H35NO2     | 148.634  |
| [M-3H]3-   | C18H34NO2     |  98.7535 |
| [M-4H]4-   | C18H33NO2     |  73.8133 |
| [M+Cl]-    | C18H37ClNO2   | 334.252  |
| [M+OAc]-   | C20H40NO4     | 358.296  |
| [M+HCOO]-  | C19H38NO4     | 344.281  |
| M(neutral) | C18H37NO2     | 299.282  |


text:
Q: How to access html controls in code behind I'm trying to follow this example on how to validate credentials. However, it uses asp: controls for the login form.
If I were to use html controls instead so CSS styles can be applied, eg

        <form action="#" runat="server">
            <fieldset>

Login

                    Sign in to your account.

                    <input type="text" value="Username" class="input-text autoclear" />
                    <input type="password" value="Password" class="input-text autoclear"/>

                <input type="submit" value="Sign in" class="input-submit float-right" runat="server" onserverclick="LoginButton_Click"/>
                Forgot your password?

            </fieldset>
        </form>

How do I access the Username & Password in code behind similar to?
protected void LoginButton_Click(object sender, EventArgs e)
{
    // Validate the user against the Membership framework user store
    if (Membership.ValidateUser(UserName.Text, Password.Text))
    {
        // Log the user into the site
        FormsAuthentication.RedirectFromLoginPage(UserName.Text, RememberMe.Checked);
    }
    // If we reach here, the user's credentials were invalid
    InvalidCredentialsMessage.Visible = true;
}

What is the correct syntax instead of UserName.Text, Password.Text?

A: Add runat="server" and id="your_id" and you should have access to them.  For example:
<input type="text" value="Username" class="input-text autoclear"
   runat="server" id="UserName" />
<input type="password" value="Password" class="input-text autoclear"
   runat="server" id="Password"/>

Then you can access the values like this:
Membership.ValidateUser(UserName.Value, Password.Value)

A: You can access them from code behind by adding runat="server" on the html elements.
http://www.w3schools.com/aspnet/aspnet_refhtmlcontrols.asp
The below link has an example of how you can do this
http://msdn.microsoft.com/en-us/library/aa478973.aspx

A: Add id and runat server attributes to the input tag (see below)
<input type="text" value="Username" class="input-text autoclear"  id="Username" runat="server"/>
<input type="password" value="Password" class="input-text autoclear" id="Password" runat="server"/>

You also need to change Text to Value in your code:
protected void LoginButton_Click(object sender, EventArgs e)
{
    // Validate the user against the Membership framework user store
    if (Membership.ValidateUser(Username.Value, Password.Value))
    {
        // Log the user into the site
        FormsAuthentication.RedirectFromLoginPage(UserName.Value, RememberMe.Checked);
    }
    // If we reach here, the user's credentials were invalid
    InvalidCredentialsMessage.Visible = true;
}

You can also add a html checkbox for RememberMe
<input id="RememberMe" type="checkbox" runat="server" value ="RememberMe"/>

Now you can check the checked states by calling RememberMe.Checked


text:
Q: get values from ANY type Object I'm having issues trying to extract values from object list, this is the flow:

*

*button gets clicked

*click calls a callout function

*get response from response.getBody()
at this point, I have two options:

*

*Use JSON2Apex, that for some reason always return: "Apex Type unsupported in JSON: Object

if (response.getStatusCode() == 200) {
       //Where, TicketJson is JSON2Apex class
       TicketJson ticketResponse = TicketJson.parse(response.getBody());
       System.debug(ticketResponse);

*Use JSON.deserializeUntyped(), this my favorite approach, but when I manage to reach the Object List that I need, I'm unable to get it's Object values as MAP

if (response.getStatusCode() == 200) {
    Map<String, Object> obj = (Map<String, Object>) JSON.deserializeUntyped(response.getBody());
    Object ticketTypeData = obj.get('ticket_group');
    Map<String, Object> TicketData = (Map<String, Object>)ticketTypeData;
    List<Object> Data = (List<Object>) TicketData.get('_data');

Any help is welcome.
Best regards.
JSON2Apex class
public class TicketJson {

public Integer x_total {get;set;} // in json: _total
public Event_template event_template {get;set;}
public Ticket_group ticket_group {get;set;}
public Ticket_type ticket_type {get;set;}

public class Ticket_group {
    public Integer x_count {get;set;} // in json: _count
    public List<Data_Z> x_data {get;set;} // in json: _data
    public Integer x_total {get;set;} // in json: _total

    public Ticket_group(JSONParser parser) {
        while (parser.nextToken() != System.JSONToken.END_OBJECT) {
            if (parser.getCurrentToken() == System.JSONToken.FIELD_NAME) {
                String text = parser.getText();
                if (parser.nextToken() != System.JSONToken.VALUE_NULL) {
                    if (text == '_count') {
                        x_count = parser.getIntegerValue();
                    } else if (text == '_data') {
                        x_data = arrayOfData_Z(parser);
                    } else if (text == '_total') {
                        x_total = parser.getIntegerValue();
                    } else {
                        System.debug(LoggingLevel.WARN, 'Ticket_group consuming unrecognized property: '+text);
                        consumeObject(parser);
                    }
                }
            }
        }
    }
}

JSON Example
{
"ticket_group": {
    "_count": 21,
    "_data": [
      {
        "_rank": 1,
        "additional_info_spec": null,
        "admission_end_offset": "2h",
        "admission_start_offset": "-10m",
        "capacity": -1,
        "description": "",
        "duration": null,
        "duration_new": null,
        "event_template_id": "4549294f-bc7a-1679-7797-90c5a9180c90",
        "exclude_from_event_capacity": false,
        "handler": "tickets",
        "hidden_type": "public_browsable",
        "id": "0e038e0e-24f2-5186-3c6c-adae2727d29d",
        "max_redemptions": 1,
        "max_tickets_per_order": 15,
        "member_role_id": null,
        "min_tickets_per_order": 1,
        "name": "Free Admission by PNC",
        "oversell_capacity": 0,
        "portal_id": "605f5cc3-3892-4c6f-bed0-4910cecd82b0",
        "sales_end_offset": null,
        "sales_start_offset": null,
        "sells_out_event": false,
        "start_policy": "immediate"
      },
}


text:
Q: Access information from Byte Array using its index I am using  a byte array to store Nsdata of(4840 bytes) and nnow i have to access the data at index of byte array.here is my code .
[Bufferdata appendBytes:&data length:len];
Byte *byteArray = (Byte *)[data bytes];

for(int i=0;i< sizeof(byteArray);i++)
**NSLog(@"BYTES %@",[byteArray objectAtIndex:i])**;

but it is giving BAD ACCESS

A: The byteArray pointer you get back from [data bytes] is a pointer to raw bytes, not an object pointer. Since it doesn't point to an object, you can't use it to send messages like [byteArray objectAtIndex:i]. Instead, you should do something like:
for(int i=0;i< sizeof(byteArray);i++)
    NSLog(@"BYTES %c", byteArray[i]);


text:
Q: Wrap an image into a parent Before-hand I apologize for any doublets, I've searched a little but haven't found a script that fits my needs. (BTW: Javascript isn't my strong side)
What I need, is a script that wraps up every image inside the div class "post" with the div class "parent".
What I have is the following:

What I want the outcome to be:

I want the script to be pure, vanilla Javascript, no jQuery or extra external http requests for script languages.  I tried:
var parent = element.parentNode;
var wrapper = document.createElement('.parent'); // set the wrapper as child (instead of the element)
parent.replaceChild(img, .parent); // set element as child of wrapper
wrapper.appendChild(element);

EDIT:
Found this snippet
// create the container div
var dv = document.createElement('div');
// get all divs
var divs = document.getElementsByTagName('div');
// get the body element
var body = document.getElementsByTagName('body')[0];

// apply class to container div
dv.setAttribute('class', 'container');

// find out all those divs having class C
for(var i = 0; i < divs.length; i++)
{
   if (divs[i].getAttribute('class') === 'C')
   {
      // put the divs having class C inside container div
      dv.appendChild(divs[i]);
   }
}

// finally append the container div to body
body.appendChild(dv);

Would someone be kind an elaborate this into what I'm requesting?

A: I'd suggest:
function imgWrap(parent) {
    if (!parent || parent.nodeType !== 1) {
        return false;
    }
    else {
        var images = parent.getElementsByTagName('img'),
            newDiv = document.createElement('div'),
            tmp;
        newDiv.className = 'parent';
        for (var i = 0, len = images.length; i < len; i++) {
            tmp = newDiv.cloneNode(true);
            parent.insertBefore(tmp, images[i])
            tmp.appendChild(images[i]);
        }
    }
}

JS Fiddle demo.


text:
Q: Is it possible to roll a significantly faster version of modf In an app I'm profiling, I found that in some scenarios this function is able to take over 10% of total execution time.
MSVC++ 2008 compiler is being used, for reference... I don't recall if modf maps to a single instruction or if there is likely any way to make it faster.
see also here for similar question on sqrt function
Unlike sqrt, I don't really know how modf works. Is there an assembly operation? For instance you could do:
modf(float input,int &intPart, float &floatPart)
{
 intPart= (int)input;
 floatPart= input - intPart;
}

But I assume this incurs penalties from casting/conversion, etc. how does a fast implementation work?

A: You're getting good answers here, but where does the other 90% of time go?
Don't look at exclusive % time per routine.
Look at inclusive % time per line of code, and if possible, have it include blocked time, not just CPU time.
That way, you may well find out that part of the time, you don't even need to be in the modf function, or other functions.
An easy way to get that information is this technique.
Added: As you find optimizations that you can do, expect total execution time to decrease, but don't expect the percentages to necessarily go down. Your % time in modf and / or sqrt may actually go up if you get rid of other stuff, or they may go down if you find that you can memoize them (and therefore call them less), for example.
In this approach to optimization, you can think of the program's execution history as a big call tree, and what you are looking for is whole branches that you can prune off. What's more, since a line of code can appear in multiple branches of the call tree, pruning it in one prunes it in all.

A: A good implementation of modf can be quite fast (on the order of 10 cycles on current hardware).  A bad implementation can be quite slow (on the order of 100 cycles).  A really poorly conceived implementation could conceivably take 1000 cycles.  I don't know what the state of Microsoft's implementation is, but there are a number of good implementations in various open source C libraries that you might look at.
Your proposed implementation takes some shortcuts and wouldn't comply with the C standard; in particular, it will misbehave rather severely in the case where input is too large to be successfully converted to integer.  It also gets the sign of zero wrong in some cases, but you might not care about that.
Note also that you would be well served to use a compiler / C library that supports the C99 standard, as you could then take advantage of the modff function and avoid the overhead of converting to and from double precision.  I know that Intel's math library (which comes with their compilers) has an excellent modf and modff implementations.  GCC also supports the C99 single-precision variants.
FWIW, I benchmarked your proposed implementation, and (assuming excellent compiler codegen), it's about 50% faster than the Intel library modff (Intel's implementation however, delivers the correct result for all inputs).  The fastest correct implementation that I've benchmarked is only about 15% slower than your implementation (but again, gives the correct result for all inputs, and even sets the floating-point state flags correctly to boot).

A: modf should be a very fast function indeed, so the problem might be that it is still a function (ie, not being inlined). You could try using exactly the same code from the library but in an inline static function in a header to allow the compiler to inline it.
When the function is inlined, if you're always only using one of the mantissa/exponent, the compiler ought to be clever enough to only emit code to calculate that part, further speeding things up.
If you're still interested in rolling your own have a look at wikipedia on the floating point format

A: Note that the library has to do the fastest possible solution that works in all of the corner cases -- which, for something like this, adds quite a bit of complexity.
If your version with the casts works fine for your program, meaning that you're not having any floats that are outside of the range of an int, and either you've confirmed that it works correctly for negative numbers or that you don't care about them, then it's probably going to be a fair bit faster.

A: I have also seen cases where small routines when called within a DLL (as is the case with the CRT) incur quite a hit from the glue code in getting in and out of the DLL. In such a case, then, rolling your own and altering how it is compiled (e.g., inlining it) could give you a performance boost even if the implementation itself is identical. YMMV, POITROAE, etc.

A: Your implementation is probably the fastest possible on x86. Though keep in mind that you limited the supported range of the input to the range of int!
You would probably want to set your compiler to use SSE(2) for floating-point math, as this gets rid of (possibly slow) control-word changes for truncation.


text:
Q: Users table in Postgres DB not synced while using LDAP in Hyperledger Fabric I am trying to register users, client and peers in Hyperledger Fabric network using Postgres as database and using LDAP for authentication.
Although I'm able to generate certificates successfully and everything is working well but still while i check into the Postgres database then the users table is empty and there is no entry in that table, while certificates table is propagated properly and have all the certificates that I have generated.
I have checked postgres database without integrating it with LDAP and then the users table is updating successfully and I can see user entries there.
Is it a normal behavior or I'm missing something?