text:
Q: OOM exception while loading large bitmaps in android I tried to display large Bitmaps in the application,I continuesly getting OOM exception,
Here is the Imageloader class I used
 public class ImageLoader {

    MemoryCache memoryCache=new MemoryCache();
    FileCache fileCache;
    private Map<ImageView, String> imageViews=Collections.synchronizedMap(new WeakHashMap<ImageView, String>());

    public ImageLoader(Context context){
        //Make the background thead low priority. This way it will not affect the UI performance
        photoLoaderThread.setPriority(Thread.NORM_PRIORITY-1);

        fileCache=new FileCache(context);
    }

//    final int stub_id=R.drawable.stub;
    public void DisplayImage(String url,ImageView imageView)
    {
        imageViews.put(imageView, url);

//        Bitmap bitmap=createScaledBitmap(memoryCache.get(url), 100,100,0);
        Bitmap bitmap=memoryCache.get(url);
      //  Bitmap bitmaps=bitmap.createScaledBitmap(bitmap, 0, 100, 100);

        if(bitmap!=null)
        {
            imageView.setBackgroundDrawable(new BitmapDrawable(bitmap));

            System.gc();
//            bitmap.recycle();
//            bitmap=null;
//            imageView.setImageBitmap(getRoundedCornerBitmap( bitmap, 10,70,70));
//            imageView.setImageBitmap(bitmap);
//            Log.v("first", "first");
        }
        else
        {
            queuePhoto(url, imageView);
//            Log.v("second", "second");

        }
    }

    private Bitmap createScaledBitmap(Bitmap bitmap, int i, int j, int k) {
        // TODO Auto-generated method stub
        return null;
    }

    private void queuePhoto(String url, ImageView imageView)
    {
        //This ImageView may be used for other images before. So there may be some old tasks in the queue. We need to discard them.
        photosQueue.Clean(imageView);
        PhotoToLoad p=new PhotoToLoad(url, imageView);
        synchronized(photosQueue.photosToLoad){
            photosQueue.photosToLoad.push(p);
            photosQueue.photosToLoad.notifyAll();
        }

        //start thread if it's not started yet
        if(photoLoaderThread.getState()==Thread.State.NEW)
            photoLoaderThread.start();
    }

   public Bitmap getBitmap(String url)
    {
        File f=fileCache.getFile(url);

        //from SD cache
        Bitmap b = decodeFile(f);
        if(b!=null)
            return b;

        //from web
        try {
            Bitmap bitmap=null;
            URL imageUrl = new URL(url);
            HttpURLConnection conn = (HttpURLConnection)imageUrl.openConnection();
            conn.setConnectTimeout(30000);
            conn.setReadTimeout(30000);
            InputStream is=conn.getInputStream();
            OutputStream os = new FileOutputStream(f);
            Utils.CopyStream(is, os);
            os.close();
            bitmap = decodeFile(f);
            return bitmap;
        } catch (Exception ex){
           ex.printStackTrace();
           return null;
        }
    }//Lalit

    private Bitmap decodeFile(File f){
        try {
            //decode image size
            BitmapFactory.Options o = new BitmapFactory.Options();
            o.inJustDecodeBounds = true;
            FileInputStream stream1=new FileInputStream(f);
            BitmapFactory.decodeStream(stream1,null,o);
            stream1.close();

            //Find the correct scale value. It should be the power of 2.
            final int REQUIRED_SIZE=Wall.width;
            final int REQUIRED_SIZE1=Wall.height;
            int width_tmp=o.outWidth, height_tmp=o.outHeight;
            int scale=1;
            while(true){
                if(width_tmp/2<REQUIRED_SIZE || height_tmp/2<REQUIRED_SIZE)
                    break;
                width_tmp/=2;
                height_tmp/=2;
                scale*=2;
            }

            //decode with inSampleSize
            BitmapFactory.Options o2 = new BitmapFactory.Options();
            o2.inSampleSize=scale;
            FileInputStream stream2=new FileInputStream(f);
            Bitmap bitmap=BitmapFactory.decodeStream(stream2, null, o2);
            stream2.close();
            return bitmap;
        } catch (FileNotFoundException e) {
        }
        catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    //Task for the queue
    private class PhotoToLoad
    {
        public String url;
        public ImageView imageView;
        public PhotoToLoad(String u, ImageView i){
            url=u;
            imageView=i;
        }
    }

    PhotosQueue photosQueue=new PhotosQueue();

    public void stopThread()
    {
        photoLoaderThread.interrupt();
    }

    //stores list of photos to download
    class PhotosQueue
    {
        private Stack<PhotoToLoad> photosToLoad=new Stack<PhotoToLoad>();

        //removes all instances of this ImageView
        public void Clean(ImageView image)
        {
            for(int j=0 ;j<photosToLoad.size();){
                if(photosToLoad.get(j).imageView==image)
                    photosToLoad.remove(j);
                else
                    ++j;
            }
        }
    }

    class PhotosLoader extends Thread {
        public void run() {
            try {
                while(true)
                {
                    //thread waits until there are any images to load in the queue
                    if(photosQueue.photosToLoad.size()==0)
                        synchronized(photosQueue.photosToLoad){
                            photosQueue.photosToLoad.wait();
                        }
                    if(photosQueue.photosToLoad.size()!=0)
                    {
                        PhotoToLoad photoToLoad;
                        synchronized(photosQueue.photosToLoad){
                            photoToLoad=photosQueue.photosToLoad.pop();
                        }
                        Bitmap bmp=getBitmap(photoToLoad.url);
                        memoryCache.put(photoToLoad.url, bmp);
                        String tag=imageViews.get(photoToLoad.imageView);
                        if(tag!=null && tag.equals(photoToLoad.url)){
                            BitmapDisplayer bd=new BitmapDisplayer(bmp, photoToLoad.imageView);
                            Activity a=(Activity)photoToLoad.imageView.getContext();
                            a.runOnUiThread(bd);
                        }
                    }
                    if(Thread.interrupted())
                        break;
                }
            } catch (InterruptedException e) {
                //allow thread to exit
            }
        }
    }

    PhotosLoader photoLoaderThread=new PhotosLoader();

    //Used to display bitmap in the UI thread
    class BitmapDisplayer implements Runnable
    {
        Bitmap bitmap;
        ImageView imageView;
        public BitmapDisplayer(Bitmap b, ImageView i){bitmap=b;imageView=i;}
        public void run()
        {
            if(bitmap!=null)
                imageView.setBackgroundDrawable(new BitmapDrawable(bitmap));

        }
    }

    public void clearCache() {
        memoryCache.clear();
        fileCache.clear();
    }
    public static Bitmap getRoundedCornerBitmap(Bitmap bitmap, int pixels,int width,int height) {

        Bitmap output = Bitmap.createBitmap(width,height, Config.ARGB_8888);
        Canvas canvas = new Canvas(output);

        final int color = 0xff424242;
        final Paint paint = new Paint();
        final Rect rect = new Rect(0, 0, bitmap.getWidth(), bitmap.getHeight());
        final RectF rectF = new RectF(rect);
        final float roundPx = pixels;

        paint.setAntiAlias(true);
        canvas.drawARGB(0, 0, 0, 0);
        paint.setColor(color);
        canvas.drawRoundRect(rectF, roundPx, roundPx, paint);

        paint.setXfermode(new PorterDuffXfermode(Mode.SRC_IN));
        canvas.drawBitmap(bitmap, rect, rect, paint);

        return output;
    }
}

And my Memorycache class
public class MemoryCache {

    private static final String TAG = "MemoryCache";
    private Map<String, Bitmap> cache=Collections.synchronizedMap(
            new LinkedHashMap<String, Bitmap>(10,1.5f,true));//Last argument true for LRU ordering
    private long size=0;//current allocated size
    private long limit=1000000;//max memory in bytes

    public MemoryCache(){
        //use 25% of available heap size
        setLimit(Runtime.getRuntime().maxMemory()/4);
    }

    public void setLimit(long new_limit){
        limit=new_limit;
        Log.i(TAG, "MemoryCache will use up to "+limit/1024./1024.+"MB");
    }

    public Bitmap get(String id){
        try{
            if(!cache.containsKey(id))
                return null;
            //NullPointerException sometimes happen here http://code.google.com/p/osmdroid/issues/detail?id=78
            return cache.get(id);
        }catch(NullPointerException ex){
            ex.printStackTrace();
            return null;
        }
    }

    public void put(String id, Bitmap bitmap){
        try{
            if(cache.containsKey(id))
                size-=getSizeInBytes(cache.get(id));
            cache.put(id, bitmap);
            size+=getSizeInBytes(bitmap);
            checkSize();
        }catch(Throwable th){
            th.printStackTrace();
        }
    }

    private void checkSize() {
        Log.i(TAG, "cache size="+size+" length="+cache.size());
        if(size>limit){
            Iterator<Entry<String, Bitmap>> iter=cache.entrySet().iterator();//least recently accessed item will be the first one iterated
            while(iter.hasNext()){
                Entry<String, Bitmap> entry=iter.next();
                size-=getSizeInBytes(entry.getValue());
                iter.remove();
                if(size<=limit)
                    break;
            }
            Log.i(TAG, "Clean cache. New size "+cache.size());
        }
    }

    public void clear() {
        try{
            //NullPointerException sometimes happen here http://code.google.com/p/osmdroid/issues/detail?id=78
            cache.clear();
            size=0;
        }catch(NullPointerException ex){
            ex.printStackTrace();
        }
    }

    long getSizeInBytes(Bitmap bitmap) {
        if(bitmap==null)
            return 0;
        return bitmap.getRowBytes() * bitmap.getHeight();
    }
}

Here is the logcat Output ------------>
01-09 12:40:38.940: E/dalvikvm-heap(18736): 1123536-byte external allocation too large for this process.
    01-09 12:40:38.979: D/GraphicsJNI(18736): Waiting for heap walker to free more memory
    01-09 12:40:38.979: D/dalvikvm(18736): GC_FOR_MALLOC freed <1K, 53% free 4297K/8967K, external 22504K/23758K, paused 29ms
    01-09 12:40:38.979: D/GraphicsJNI(18736): Heap walker done, retry to allocate
    01-09 12:40:39.002: I/MemoryCache(18736): cache size=5691144 length=7
    01-09 12:40:39.112: D/dalvikvm(18736): GC_EXTERNAL_ALLOC freed 89K, 53% free 4272K/8967K, external 21905K/22856K, paused 42ms
    01-09 12:40:39.127: E/dalvikvm-heap(18736): 2457600-byte external allocation too large for this process.
    01-09 12:40:39.167: D/GraphicsJNI(18736): Waiting for heap walker to free more memory
    01-09 12:40:39.167: D/dalvikvm(18736): GC_FOR_MALLOC freed <1K, 53% free 4272K/8967K, external 21905K/22856K, paused 28ms
    01-09 12:40:39.167: D/GraphicsJNI(18736): Heap walker done, retry to allocate
    01-09 12:40:39.206: D/dalvikvm(18736): GC_EXTERNAL_ALLOC freed 2K, 53% free 4270K/8967K, external 20808K/22856K, paused 38ms
    01-09 12:40:39.252: I/MemoryCache(18736): cache size=8148744 length=8
    01-09 12:40:39.323: D/dalvikvm(18736): GC_EXTERNAL_ALLOC freed 148K, 53% free 4253K/8967K, external 23218K/25256K, paused 42ms
    01-09 12:40:39.331: E/dalvikvm-heap(18736): 960000-byte external allocation too large for this process.
    01-09 12:40:39.370: D/GraphicsJNI(18736): Waiting for heap walker to free more memory
    01-09 12:40:39.370: D/dalvikvm(18736): GC_FOR_MALLOC freed <1K, 53% free 4253K/8967K, external 23218K/25256K, paused 28ms
    01-09 12:40:39.377: D/GraphicsJNI(18736): Heap walker done, retry to allocate
    01-09 12:40:39.409: D/dalvikvm(18736): GC_EXTERNAL_ALLOC freed 1K, 53% free 4251K/8967K, external 23208K/25256K, paused 38ms
    01-09 12:40:39.424: E/dalvikvm-heap(18736): 960000-byte external allocation too large for this process.
    01-09 12:40:39.463: E/GraphicsJNI(18736): VM won't let us allocate 960000 bytes
    01-09 12:40:39.463: D/dalvikvm(18736): GC_FOR_MALLOC freed 0K, 53% free 4251K/8967K, external 23208K/25256K, paused 28ms
    01-09 12:40:39.463: D/skia(18736): --- decoder->decode returned false
    01-09 12:40:39.463: W/dalvikvm(18736): threadid=16: thread exiting with uncaught exception (group=0x40018560)
    01-09 12:40:39.471: E/AndroidRuntime(18736): FATAL EXCEPTION: Thread-26
    01-09 12:40:39.471: E/AndroidRuntime(18736): java.lang.OutOfMemoryError: bitmap size exceeds VM budget
    01-09 12:40:39.471: E/AndroidRuntime(18736):    at android.graphics.BitmapFactory.nativeDecodeStream(Native Method)
    01-09 12:40:39.471: E/AndroidRuntime(18736):    at android.graphics.BitmapFactory.decodeStream(BitmapFactory.java:470)
    01-09 12:40:39.471: E/AndroidRuntime(18736):    at com.beerbro.utils.ImageLoader.decodeFile(ImageLoader.java:190)
    01-09 12:40:39.471: E/AndroidRuntime(18736):    at com.beerbro.utils.ImageLoader.getBitmap(ImageLoader.java:100)
    01-09 12:40:39.471: E/AndroidRuntime(18736):    at com.beerbro.utils.ImageLoader$PhotosLoader.run(ImageLoader.java:257)
    01-09 12:40:39.471: W/ActivityManager(1320):   Force finishing activity com.stellent.beerbro/.Wall

I am loading the data from the Facebook graph api,I am getting Firstpage data and I am displaying the whole data at a time.I think this is making the memory to increase a lot.
So, how to handle that large amount of data.
please help

A: You should use inJustDecodeBounds to decode the bitmap' size without loading it into memory. ATM, if you try to load a large bitmap, you create it before checking if it it within the size range of the cache.
You should not force the GC, especially as it is run asynchronously and the system.gc forces it to be synchronous. The Bitmaps are not loaded on the java heap directly so anything that comes out of the cache should be recycled. Finally don't keep references to the bitmap.
Overall, I would use LRUCache rather then your own cache.
Finally, being bias, I would suggest the likes of enter link description here which caches the images to disk and uses LRUCache for performances.


text:
Q: Magento 2 Braintree declined orders not sending Payment Failed emails I'm using Braintree as default payment method for my Magento 2.2.3 store.
Sometimes, It happens that customer cannot finish checkout as his CC gets declined, when this happens I would like to get notified on email with information like what customer experienced this problem, what did he have in cart and what was order total.
As far as I understand, Magento 2 has this feature built-in but looks like it's not working properly with Braintree payment method. How could I fix this? I see that function sendPaymentFailedEmail is called from module checkout controller named SaveOrder.php in case of 2 errors (in 2 catch blocks), but it does not seem that Braintree error ever gets there.

A: I was able to solve this when I manually applied this patch , I hope this will be merged soon :)

redpajama_set_name: RedPajamaStackExchange


text:
Q: Images & Buttons I have assigned a button (holdCardOne) an image in the interface builder. What I want to do is change the image when a card is selected from a picker. I have the picker working and selecting the card but I need to change the image on the original selected button to resemble the selection.
Can I do this using code?
Does it matter I assigned the image in the interface builder or does it have to be all done by code?

A: You should be able to change the button image using the setImage:forState: method of the UIButton class. See the UIButton class reference for more info.
In terms of using the Interface Builder, it would be safe to set the initial image in that, but you'll need to handle things yourself from that point onwards. (e.g.: If a user can un-associate an image with a button, you'll need to set an appropriate image programatically as above.)

A: It doesn't matter that it was assigned in Interface Builder. All you need to do is this:
[yourButtonName setImage:yourNewImageName forState:UIControlStateNormal];

You'll also likely want to set an image for
UIControlStateHighlighted

and possibly for
UIControlStateDisabled

and
UIControlStateSelected

A: You can do it either in code or in the interface builder or both!
InterfaceBuilder lets you assign images for each button state (normal, highlighted, selected) -- so it could be as easy as assigning images for each state, and then simply changing the state in your code.
Alternatively, you can set the image directly, simply by saying:
[myButton setImage: (someImage) forState: UIControlStateNormal];

You might want to also set this image for the other buttons states (highlighted, selected), it all depends on how you want the interface to behave.


text:
Q: Replace function in prototype attributes iteration I am trying to replace a hyphen in all attributes
North Dakota

like so:
var el = document.getElementById('someId');
Array.prototype.slice.call(el.attributes).forEach(function(item) {
   item.value.replace('-','_');
   console.log(item.value);
});

Can't quite figure out why it's not actually replacing the hyphen with an underscore. Am I missing something?

A: String.prototype.replace() returns a new String, it does not alter the original String. Just assing the new value and you're done.
item.value = item.value.replace('-','_');

Quoted from the MDN documentation:

This method does not change the String object it is called on. It simply returns a new string.


text:
Q: SQL. Как сделать поиск с несколькими значениями? При таком запросе: И при поиске одного значения
SELECT *
FROM resources
LEFT JOIN users ON users.id=resources.author_id
LEFT JOIN categories ON categories.categories_id=resources.categories_id
LEFT JOIN specialty ON specialty.specialty_id=resources.specialty_id
WHERE
    categories.categories LIKE '%$_GET[categories]%' AND title LIKE '%$_POST[search]%'
    OR
    categories.categories LIKE '%$_GET[categories]%' AND description LIKE '%$_POST[search]%'
    OR .......

все нормально, но если искать более одного значения то ничего не находит.
ВОПРОС: Как сделать так чтобы при запросе Например: СЛОВО СЛОВО все находилось ?)


text:
Q: Properly implementing a Delegate & Protocol I created this test case as a simple example of my problem.

*

*The AppDelegate initializes the TestViewController and adds it to the window

*The TestViewController initializes the TestView and makes it the view

*The TestView initializes the TestSubView and adds it as a subview

My goal is to allow TestSubView, through a delegate, access to TestViewController's methods & variables. In this example TestSubView accesses the methods through either a touchesBegan or touchesMoved.
Please Help. Thank you.
EDIT: Still doesn't work, though no more errors. What I did: Moved the protocol definition to a separate file and imported it, retain to assign, and removed the @protocol TestDelegate declaration in the beginning of the header.
I think my problem is that I don't assign the delegate in the TestViewController.m, if that's the problem how would I do that?
TestViewController.h
#import <UIKit/UIKit.h>

@interface TestViewController : UIViewController <TestDelegate> {

    int number;
}

-(void)assignNumber:(int)value;
-(void)displayNumber;

@property int number;

@end

Moved to protocol.h and imported where needed
@protocol TestDelegate

-(void)assignNumber:(int)value;
-(void)displayNumber;

@end

TestViewController.m
#import "TestViewController.h"
#import "TestView.h"

@implementation TestViewController

@synthesize number;

- (void)loadView {
    TestView *myView = [[TestView alloc] initWithFrame:CGRectMake(0,0,320,480)];
    self.view = myView;
    [myView release];
}

-(void)assignNumber:(int)value {
    NSLog(@"Number Assigned");
    number = value;
}

-(void)displayNumber {
    NSLog(@"%i",number);
}

TestSubView.h
#import <UIKit/UIKit.h>
#import "TestViewController.h"

@interface TestSubView : UIView {

    id<TestDelegate> delegate;
}

@property (nonatomic, retain) id<TestDelegate> delegate;

@end

TestSubView.m
#import "TestSubView.h"
#import "TestViewController.h"

@implementation TestSubView

@synthesize delegate;

- (id)initWithFrame:(CGRect)frame {
    if ((self = [super initWithFrame:frame])) {
        // Initialization code
        [self setBackgroundColor:[UIColor redColor]];
        [self setUserInteractionEnabled:YES];
    }
    return self;
}

- (void)dealloc {
    [super dealloc];
}

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {

    [self.delegate assignNumber:5];
}

- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event {

    [self.delegate displayNumber];
}

A: First and foremost, you're declaring a protocol and then assigning the same object as implementing that protocol. What you're probably looking for is to declare the TestDelegate protocol on your TestSubView instead. Additionally when setting up a property for a delegate, be sure to use the 'assign' keyword as opposed to 'retain'.
Finally all of this can be greatly simplified by using UIGestureRecognizer. You can set it up in your controller and add it to your testSubView. This way, when the view recognizes that the corresponding gesture occurred within it's bounds, a message will be sent to your controller allowing you to do what you need to do like assigning or displaying a number.

A: You're referring to TestView when your class is called TestSubView, unless you have 2 classes defined.
TestView *myView = [[TestView alloc] initWithFrame:CGRectMake(0,0,320,480)];
You're correct that you're not assigning the delegate yet.
You would do that on the next line:
myView.delegate = self;
To end up with this:
- (void)loadView {
    TestSubView *myView = [[TestSubView alloc] initWithFrame:CGRectMake(0,0,320,480)];
    myView.delegate = self; // Set Delegate Here
    self.view = myView;
    [myView release];
}


text:
Q: Move or copy SSL certificates from broken windows server Yesterday we had a major problem with our windows 2003 webserver and we had to move all our sites to a new machine. There were a couple of sites that used a SSL certificate and we cannot export these because the we cannot start windows on the broken machine.
Is there a way to get these certificates to work on the other server? I have access to the hard drive of the broken server. I may have to mention that the new server is on windows 2008 r2.


text:
Q: How to compare to home screen in splash screen on flutter Suppose, I have two users on this App (Teacher & Student). Their platform or home screen is different and so is the login, and registration section. Now I want the login status (student or teacher) to compare the splash screen to see who has the login and send it to its home screen. How can do this?enter image description here

A: You need to assign a role each user, and then do the routing based on the role.
2 places where you can store the role information:

*

*In the Firebase Authentication token of that user as a custom claim

*In the database, either as a document associated with that user or in a table if you're using SQL. Please create a different table to store user details and use the user id as a foreign key. Do not mess with the tables generated by the authentication provider.

Always set the role from a trusted environment, otherwise your users will be able to change their own roles.
Once this is done, you can access the role information from your app and do role based authorization (in your case, routing)

A: You can make role-based authorization. Here is an example.


text:
Q: Application of orbits and Sylow Theorems Suppose I have a group $G$ such that $n_p \not \equiv 1 \pmod{p^2}$, where $n_p = |\operatorname{Syl}_p(G)|$. Consider a $P \in \operatorname{Syl}_p(G)$ acting on $ \operatorname{Syl}_p(G)$ by conjugation. I want to show that $\exists Q \in \operatorname{Syl}_p(G) : |\mathcal{O} (Q)| = p$. I was considering how to apply the orbit-stabilizer theorem, but I do not know how to apply the fact that $n_p \not \equiv 1 \pmod{p^2}$.

A: *

*For $P$ acting on $Syl_p(G)$, each orbit has size equal to some power of $p$. (Use orbit-stabilizer.)

*Show that there is only one orbit of size $1$. (Use Sylow's theorems.)

*The sizes of the orbits sum up to $n_p$, so conclude that there is some orbit of size $p$.


text:
Q: Change Default Font in Xcode 8 Swift 3 IOS Is there any way to change the default font of the Application from one place, not each view controller and not each element category??
for example in html and CSS, you can define the global font from CSS with one line of code.
Thanks.

A: I don't know if its what you ask, but you can change all the fonts in your app in appDelegate. Will change all the fonts in the buttons, labels, etc.
you can do it creating a extension form UILabel like this
extension UILabel {

    var substituteFontName : String {
        get { return self.font.fontName }
        set { self.font = UIFont(name: newValue, size: self.font.pointSize) }
    }
}

then in the didFinishLaunchingWithOptions in your appDelegate you can call the variable and pass the name of the font you want, like this:
UILabel.appearance().substituteFontName = "Kyrial Sans Pro"

A: when you add the font to info.plist you already changed the default font of the Xcode , try to leave the UILabel Font as system Font and change only the style and run your app you will have what you want.


text:
Q: Rails sunspot: re-indexing of an associated model does not run as a delayed job I am using sunspot in combination with delayed job to perform re-indexing of my models as an asynchronous background process. For model updates this works fine due to: handle_asynchronously :solr_index, :queue => 'solr_index'.
However, the searchable block within the model (let's call it model A) also references attributes of an associated model (B), where B has many As. When the associated model becomes updated by the user, I trigger re-indexing within an after_save callback in B like so: Sunspot.index(self.my_many_As). While re-indexing is successful, it does not run as a delayed job. How can I accomplish that?
Any suggestions?

A: How about you schedule a job that calls the index on the updated documents? You can log last time index for specific model was updated, and call Sunspot.index(ModelB.updated_after(last_update_time))

A: Instead of calling Sunspot.index(self.my_many_As) I call solr_index for each A directly inside B's after_save callback self.my_many_As.each(&:solr_index). Works for me.


text:
Q: How to show the Chebyshev polynomials in the solution of a differential equation? In the following code I solved a differential equation on Mathematica 11. The solution has two arbitrary constants, which, if set to 0 and 1, in previous versions of Mathematica used to give as the solution the Chebyshev polynomials.
How can I tell to Mathematica that I would like to set the constants in order to keep (and later plot) the part of the solution that represents the Chebyshev polynomials?
sol4[n_] := y[x] /. DSolve[ (1 - x^2) y''[x] - x y'[x] + n^2 y[x] == 0, y[x], x] [[1]] /. {C[1] ->1, C[2]->0}

lista = Table[ sol4[i], {i, 1, 5}];
gra1 = Plot[lista, {x, -1, 1}]

listaorig = Table[ ChebyshevT[i,x], {i, 1, 5}];
gra2 = Plot[ listaorig, {x, -1, 1}]

A: Clear[sol4]

sol4[n_, x_] =
 DSolveValue[(1 - x^2) y''[x] - x y'[x] + n^2 y[x] == 0, y[x],
    x] /. {C[1] -> c1, C[2] -> c2} // FullSimplify[#, -1 < x < 1] &

(* c1 Cosh[n ArcTanh[x/Sqrt[-1 + x^2]]] + c2 Sin[n ArcSin[x]] *)

Solve for the constants such that the sol4[n, x] is equal to ChebyshevT[n,x]. Since there are two unknowns, you need a second equation: equate the derivatives.
Assuming[-1 < x < 1,
 Solve[{sol4[n, x] == ChebyshevT[n, x],
     D[sol4[n, x], x] == D[ChebyshevT[n, x], x]}, {c1, c2}][[1]] //
  FullSimplify]

(* {c1 -> Cos[(n π)/2], c2 -> Sin[(n π)/2]} *)

After clearing the definition, redefine the function with these constants
Clear[sol4]

sol4[n_, x_] =
 DSolveValue[(1 - x^2) y''[x] - x y'[x] + n^2 y[x] == 0, y[x],
    x] /. {C[1] -> Cos[n π/2], C[2] -> Sin[n π/2]} //
  FullSimplify[#, -1 < x < 1] &

(* Cos[n ArcCos[x]] *)

Verify that sol4[n, x] == ChebyshevT[n, x]
sol4[n, x] == ChebyshevT[n, x] // FullSimplify

(* True *)

The plots are as expected
lista = Table[sol4[n, x], {n, 1, 5}];
gra1 = Plot[lista, {x, -1, 1}]

EDIT: Alternatively, looking at the plots for ChebyshevT[n,x],  just include the values for y[0] and y[1] to define the constants.
Clear[sol4]

sol4[n_, x_] =
 DSolveValue[{(1 - x^2) y''[x] - x y'[x] + n^2 y[x] == 0,
    y[0] == Cos[n π/2], y[1] == 1}, y[x], x] //
  FullSimplify[#, -1 < x < 1] &

(* Cos[n ArcCos[x]] *)


text:
Q: How can I trigger an explicit UI update in qml? I have a qml application which performs a rather long action upon a users request. During the time, I want to display an overlay over the whole screen, so the user is aware that the application is working, basically a busy indicator.
My Problem is, that the application starts with the task, before updating the UI component. Here's a minimal example to demonstrate the problem:
import QtQuick 2.9
import QtQuick.Window 2.3

Window {
    visible: true
    width: 640
    height: 480
    title: qsTr("Ui Demo")

    Rectangle {
        id: rectangle
        anchors.fill: parent
        color: "green"
    }

    MouseArea {
        id: action

        anchors.fill: parent
        onClicked: {
            rectangle.color = "red"
            for(var i = 0; i < 10000; i++)
                console.log(i)
        }
    }
}

What I want is, that the Rectangles color turns red while the for loop is running, but the behavior I see is that the color changes only after the loop has finished.
I also tried the following with no difference:
Rectangle {
    id: rectangle
    anchors.fill: parent
    color: "green"

    onColorChanged: {
        for(var i = 0; i < 10000; i++)
            console.log(i)
    }
}

I know, that the cleanest solution would be to perform the heavy work on a different thread to not block the UI thread. But I do not wish to do this, because in my actual application the blocking work is updating a ListModel, which (as noted here for example)

Qt views unfortunately don't know how to deal with [when they are] in foreign threads.

So I would need to implement a new, asynchronous Model class, which is effort and time my customer is currently not willing to pay for.
Therefor my question is: How can I make sure, that the UI is redrawn/updated as soon as I set the property?

A: A possible approach is to use transform the sequential logic of the "for" to an asynchronous logic through a Timer:
import QtQuick 2.9
import QtQuick.Window 2.3

Window {
    visible: true
    width: 640
    height: 480
    title: qsTr("Ui Demo")

    Rectangle {
        id: rectangle
        anchors.fill: parent
        color: "green"
    }

    MouseArea {
        id: action

        anchors.fill: parent
        onClicked: {
            rectangle.color = "red"
            timer.start()
        }
    }
    Timer{
        id: timer
        interval: 1
        property int counter: 0
        repeat: true
        onTriggered: {
            counter += 1
            console.log(counter)
            if(counter > 100000)
                timer.stop()
        }
    }
}

A: Reliable Workaround
Thanks to eyllanesc's answer I figured out a possible solution.
I use a single shot timer, to start my work, because in the actual code I cannot call different steps with a repeating timer - but I do not need to anyway, as I don't want to display any animated UI elements. This code works for my purposes:
import QtQuick 2.9
import QtQuick.Window 2.3

Window {
    visible: true
    width: 640
    height: 480
    title: qsTr("Ui Demo")

    Rectangle {
        id: rectangle
        anchors.fill: parent
        color: "green"
    }

    MouseArea {
        id: action

        anchors.fill: parent
        onClicked: {
            rectangle.color = "red"
            timer.start()
        }
    }

    Timer {
        id: timer

        interval: 1
        repeat: false
        onTriggered: {
            for(var i = 0; i < 10000; i++)
                console.log(i)
            rectangle.color = "green"
        }
    }
}

Adding a Timer - even with only a 1 msec interval - grants the logic with the processing time to change the color, before starting with the actual work. While this looks like a slightly hacky workaround it works just fine.
More elegant though less reliable approach
There is a cleaner, though less reliable solution:
Qts callLater() function seems to be sort of what I was looking for. Even though the official documentation seems incomplete, I found the function documentation in its source code:

Use this function to eliminate redundant calls to a function or signal.
The function passed as the first argument to Qt.callLater()
  will be called later, once the QML engine returns to the event loop.
When this function is called multiple times in quick succession with the
  same function as its first argument, that function will be called only once.
For example:
  \snippet qml/qtLater.qml 0
Any additional arguments passed to Qt.callLater() will
  be passed on to the function invoked. Note that if redundant calls
  are eliminated, then only the last set of arguments will be passed to the
  function.

Using the call later function delayed the call to the working code most of the time for long enough so that the UI would get updated. However about a third of the times, this would fail and show the same behavior as described in the question.
This approach can be implemented like the following:
import QtQuick 2.9
import QtQuick.Window 2.3

Window {
    visible: true
    width: 640
    height: 480
    title: qsTr("Ui Demo")

    Rectangle {
        id: rectangle
        anchors.fill: parent
        color: "green"
    }

    MouseArea {
        id: action

        anchors.fill: parent
        onClicked: {
            rectangle.color = "red"
            Qt.callLater(action.doWork)
        }

        function doWork() {
            for(var i = 0; i < 10000; i++)
                console.log(i)
            rectangle.color = "green"
        }
    }
}


text:
Q: How references are really implemented in C++? I would like to know how references are really implemented in C++.
I mean, initialization of a réference?
Is it more efficient to handle a reference or a pointer?
for example:
int i = 7;
int &j = i;   // how is this ligne compiled?
int *k = &i;  // is it less efficient doing this?

And is the case of objets, is there any diffrence in managing reference?


text:
Q: ASCII Changing Numbers I'm having a problem in my Python ASCII Code where when I am trying to convert a letter to ASCII it will convert the numbers from the ASCII into more ASCII code. How do I fix this?
Choice = input("Now tell us which code language you like to convert this to Binary or ASCII: \n")
Code = input("Insert your code here, it converts letters to Binary/ASCII: \n\n")

Zero = '048'
One = '049'
Two = '050'
Three = '051'
Four = '052'
Five = '053'
Six = '054'
Seven = '055'
Eight = '056'
Nine = '057'

NewCode = Code.replace('0', Zero)
print(NewCode, '\n\n')
time.sleep(0.1)
NewCode = NewCode.replace('1', One)
print(NewCode, '\n\n')
time.sleep(0.1)
NewCode = NewCode.replace('2', Two)
print(NewCode, '\n\n')
time.sleep(0.1)
NewCode = NewCode.replace('3', Three)
print(NewCode, '\n\n')
time.sleep(0.1)
NewCode = NewCode.replace('4', Four)
print(NewCode, '\n\n')
time.sleep(0.1)
NewCode = NewCode.replace('5', Five)
print(NewCode, '\n\n')
time.sleep(0.1)
NewCode = NewCode.replace('6', Six)
print(NewCode, '\n\n')
time.sleep(0.1)
NewCode = NewCode.replace('7', Seven)
print(NewCode, '\n\n')
time.sleep(0.1)
NewCode = NewCode.replace('8', Eight)
print(NewCode, '\n\n')
time.sleep(0.1)
NewCode = NewCode.replace('9', Nine)
print(NewCode, '\n\n')
time.sleep(0.1)

A: What you are trying to do can be accomplished in literally one line without hardcoding the ASCII codes of the characters:
code = '3210' # Do not use initial upper-case letters for variable names!
newCode = ''.join('{:03}'.format(ord(n)) for n in code)
# '051050049048'

However, the purpose of your exercise is still unclear. Also mind that '0XY' typically means that 'XY' is written in the octal number system. Therefore, neither X nor Y can be an 8 or a 9.

A: The problem is that the replacement strings contain characters that will be replaced by later .replace() calls.
One solution is to process the input a character at a time, rather than using .replace() on the entire string.
BTW, Python has an ord() function that returns the code for a character, which is normally ASCII.
NewCode = ''
for char in Code:
    NewCode += str(ord(char)).zfill(3)

A: You're problem is that you are constantly modifying NewCode so that at each step it continues to modify itself, changing the numbers to their ASCII numbers. Instead of re-using NewCode for each replacestatement, use a new variable as a buffer.
Code = '3210'
NewCode = Code.replace('', Zero) #NewCode is now 321048
print(NewCode, '\n\n')
time.sleep(0.1)
NewCode = NewCode.replace('4', Four) #The '4' near the end of '321048' gets replaced with '052' making NewCode = 32100528
print(NewCode, '\n\n')
time.sleep(0.1)

A: I would go about it like this, it ensures you don't change the ascii code twice by using a buffer.
Code = raw_input("Insert your code here, it converts letters to Binary/ASCII: \n\n")

lst_words = ['Zero', 'One', 'Two', 'Three', 'Four', 'Five', 'Six', 'Seven', 'Eight', 'Nine']
lst_numbers = ['048','049','050','051','052','053','054','055','056','057']

for i in range(10):
    Code = Code.replace(str(i), lst_words[i])
print(Code)
for i in range(10):
    Code = Code.replace(lst_words[i], lst_numbers[i])
print(Code)


text:
Q: How does the Safari Javascript console predict properties of nonexistent objects? Please note, I have not been able to reproduce this behavior in Chrome or Firefox, just Safari.
Let's say I have a function with two possible randomly-selected return values: { foo: 'test' } and { bar: 'test' }.
function getObj() {
    console.log('This code has been executed.');
    if (Math.random() > 0.5) {
        return { foo: 'test' };
    } else {
        return { bar: 'test' };
    }
}

When I type an invocation of the function but do not press "enter", Safari's predictions can still make assumptions about the return value. Sometimes it sees one return value, sometimes it sees the other.
Sometimes one:

Sometimes the other:

Obviously, by simply typing the function invocation, I'm not calling the function as I understand it, and I do not see a console.log saying "This code has been executed." How does Safari do this?


text:
Q: How to extend Visual Studio 2012 suggestions with IntelliSence I don't know how to extend VS 2012 to provide this functionality or any 3rd Party tools that provides this but I'd like the ability to have in the intellisense the ability to provide coding suggestions if certain classes perform a certain way. Example, if I write the code:
UsersContext db = new UsersContext(

I'd like the intellisense to include suggestions (or an option to provide them):
UserContext.UserContext()
-------------------------------------------
SUGGESTION: Wrap new reference in Using(){ } statement.
WHY: This class extends IDisposable. This will handles MemoryDisposal of object.

Any help would be appreciated.

A: Resharper and Coderush do this to some extent through their code analysis features.
ReSharper
CodeRush
They both offer free trials and you can see if they fit your need.

A: I suggest to go for Vissual Assist X.It has alot of features and has the ability to do as you requested.


text:
Q: PHP Validation of start date and end date using Javascript/Jquery I am trying to use JavaScript/JQuery to implement a function in which it would detect read the selected date within a form and perform the following validation:

1) Start date can't be before the current date
2) End date can't be before the start date / start date can't be after
  the end date
  If it occurs, the error message would be displayed in my #ErrorBox

Below is the code I have done as of now, it ensures the user to enter their goal, start date, end date and description, otherwise an error text would be displayed below

        <title>Show Me My Money!</title>
        <link rel="stylesheet" href="stylesheet/cmxformTemplate.css"/>

Add Goal

        <fieldset style="width:400;">
            <form  method="post" action="doAddGoal.php" id='Form' enctype="multipart/form-data">

                        Goal($):
                        <input id="id_goal" type="text" name="goal" required />

                        Start Date:
                        <input id="id_startdate" name="startdate" type="date" size="10"/>

                        Target Date:
                        <input id="id_targetdate" name="targetdate" type="date" size="10"/>

                        Description:
                        <input id="id_description" name="goal_description" type="text" required>

                    <input type="submit" value="Submit"/>

            </form>

        </fieldset>


text:
Q: Overheating when using File Roller Every time I try to compress a folder of about 1 Gb with File Roller I have to stop after a few seconds because my laptop overheats. I've checked the temperature in Psensor and it goes over 85 ºC (cpu usage is near 100%).
I've installed tlp, but it seems to do nothing.
I am running Ubuntu 13.10 32-bit on a Dell Latitude D630 Intel Core2 Duo CPU T7500 @ 2.20GHz × 2.
How can I solve this problem?
Thank you for your help.

A: Did you check if your CPU fan is working?  CPU temperature should not be that high even if the CPU is under heavy load.
lm-sensors is required for Psensor to read the fan speed.  Another easy way is to hear if there is a difference in the noise when the CPU is idle and when File Roller is running.  If you cannot tell a difference, that will be the problem of CPU fan.


text:
Q: For (Lebesgue) measurable functions $f$ and $g$, if $f=g$ a.e., then $ \int_{E} f=\int_{E} g. $ Problem

Let $f$ and $g$ be bounded (Lebesgue) measurable functions defined on a set $E$ of finite measure. If $f=g$ a.e., then
  $$
\int_{E} f=\int_{E} g.
$$

Attempt

Let $f,g:E\to \mathbb{R}$ be a (Lebesgue) measurable function with $m(E)<\infty$. Assume $f=g$ a.e. on $E$. It is enough to show that
  $$
\int_{E} f-g=0.
$$
  Let $\varphi$, $\psi$ be simple functions with $\varphi \leq f-g \leq \psi$. Since $f-g=0$ a.e., we have $\psi \geq 0$ a.e. and $\varphi\leq 0$ a.e.. Then,
  $$
0 \leq \int_{E} \psi {\rm ~and~} 0\geq \int_{E} \varphi,
$$
${\it whence} $
$$
\int_{E} f-g \geq 0 {\rm ~and~} \int_{E} f-g \leq 0,
$$
  as required.

Question

*

*The hypothesis that there is a simple function $\varphi$ is vaild?

*What is the exact meaning of 'whence' which is italics?

*For the end of sentence, what did the right expression of the two?: a.e. or a.e..

Thanks!

A: The assertion about the simple functions is not clear neither justified. A simpler approach: let $A:=\{x\in \mathbb{R}:f(x)-g(x)=0\}$, then $A$ is measurable and
$$
\int_{E}(f-g) \mathop{}\!d \lambda =\int_{E \cap A}(f-g) \mathop{}\!d \lambda +\int_{E \cap A^\complement }(f-g) \mathop{}\!d \lambda =\int_{E \cap A}0 \mathop{}\!d \lambda+0=0
$$
where we used the fact that if a set $B$ have measure zero then $\int_B f \mathop{}\!d \lambda =0$ for any measurable function $f$.


text:
Q: Distances between up and down crosses in Gaussian Processes Given a gaussian process $g := \mathcal{GP}\left(\mu, \Sigma \right)$,
where $\mu$ is the mean and $\Sigma$ is the covariance function, I am interested in estimating the mean value $L_m$ of the distances between up and downcrosses with a constant level $u$, i.e. these distances:

In this plot, I use $u=0$, but ideally I would like $u$ to be generic. I suspect that this is related with Rice formula, which estimates the number of upcrosses for a given gaussian process and a given length domain, but I do not know how


text:
Q: Sorting not being applied in a list of objects I am sorting an array of objects and the sorting function seems to do not have any result on the array. So it returns the same list.
I exported the array and the sorting functions to the window and execute them manually then the resulting array is well sorted.
import { connect } from "react-redux"

import DestinationsGallery from "./destinationsGallery"

import DestinationFilter from "./functions/filter"
import WindPoint from "./functions/windPoint"
import {sortCosts,sortWind, sortName} from "./functions/sort"

const getSelectedDestinations = ( catalog, filter ) => {
    let paramCatalog = null
    let paramSorted = null

    if (catalog) {
        paramCatalog =  catalog
            .map(spot => WindPoint(spot,filter))
            .filter( item => DestinationFilter( item,filter ) )
            .sort( ( a,b ) => a.name.localeCompare( b.name ) )

        window.catalog = paramCatalog
        window.sortCosts = sortCosts
        window.sortWind = sortWind
        window.sortName = sortName

        console.log("Unsorted",paramCatalog)
        paramSorted = paramCatalog.sort( sortName )
        console.log( "Sorted name",paraSorted, paramCatalog.sort( sortName ) )

        let paraSorted = paramCatalog.sort( sortWind )
        console.log( "Sorted wind",paraSorted )
    }
    return paramSorted
}

export default connect( store => ({
    destinations: getSelectedDestinations(store.kiteSpots.catalog.list, store.kiteSpots.filter),
    filter: store.kiteSpots.filter,
}),null)(DestinationsGallery)

and my sorting functions are:
export const sortCosts = ( a,b ) => ( a.data.CostsRank > b.data.CostsRank? 1 : -1 )
export const sortWind = ( a,b ) => ( a.windPoint.probability > b.windPoint.probability ? 1 : -1 )
export const sortName = ( a,b ) => { return a.name > b.name ? 1 : -1 }

So I just would like the output list is correct

A: This code does not mutates (sort) the catalog array if it's what you expected, only param catalog will be sorted as the sort is applied to the result of the mapping and filtering of catalog which both return new array instances.
Maybe if you post more code and source data we could find what's wrong.
That said, you shouldn't compare strings this way, using a mathematical operator, as it may not behave as you expect.
This discussion from stackoverflow explains a bit the differences. In short codepoint order (used when comparing with >) is not the same as actual alphabetical order.
Also, the return value of a comparison function should be 1, -1 or 0 because not swaping equal values sometimes matter.
For instance sorting [0,0,1,1,2,2,3,3] by allowing swapping equal comparing value does not matter.
But sorting [{ name: 'foo', value: 0},{ name: 'bar', value: 0},{ name: 'fuu', value: 1},{ name: 'ber', value: 1}] according to value may change the order of the original array when it may not be desirable.
It's true that older implementation of the native sort did not care for equal comparing value and may have the order anyway but now nore implementations respect the contract of not modifying already sorted arrays.
If you care about alphabetical order of unicaode strings, try and use String.prototype.localeCompare.
If you're comparing numbers (say a and b), and if you don't have to deal with NaN or infinity or undefined, it is more correct and requires less native instructions to return a-b for ascending order and b-a for descending order.

A: You can try using String.prototype.localeCompare for comparing strings. See MDN.

const x = [
  { name: "James"},
  { name: "Zeb"},
  { name: "Annie"},
  { name: "Michaèl"},
  { name: "James"},
];

console.log( x.slice(0).sort( (a, b) => a.name.localeCompare(b.name) ) );
// include value equality
console.log( x.slice(0).sort( (a, b) => -(a.name < b.name) || +(a.name > b.name)) );

Or include the possible value equality in comparing:
a.name > b.name ? 1 : a.name < b.name ? -1 : 0) or (see comments)
-(a.name < b.name) || +(a.name > b.name)
Or (for performance) you can use Intl.Collator (see MDN and the next snippet)

const intlCollator = new Intl.Collator("de", {sensitivity: "variant"});
console.log(
  [
    { name: "Anna"},
    { name: "Michiel"},
    { name: "Desiré"},
    { name: "Siënna"},
    { name: "Jøn"},
    { name: "Mariêke"},
    { name: "José"},
    { name: "Anna"},
    { name: "Renée"},
    { name: "Désirée"},
  ].sort( (a, b) =>
      intlCollator.compare(a.name, b.name) )
);
.as-console-wrapper { top: 0; max-height: 100% !important; }


text:
Q: UIButton subview of UITableViewCell unselecting UITableViewCell? I have a subview within UITableViewCell's that contains a UILabel and a UIButton. When I push the button it unselects the UITableViewCell for some reason.
Is there a way to pass the touch event through to its super view? Or is there a different problem all together?
Here is the code for CellForRowAtIndexPath. I plan on creating a custom subclass of UITableViewCell so I can handle cell reuse properly so don't feel the need to mention that.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    CountModel *cellModel = self.viewModel.data[indexPath.row];

    UITableViewCell *cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"RootViewControllerMetricCell"];

    cell.textLabel.text = cellModel.title;

    // Custom background color for selection
    UIView *bgColorView = [[UIView alloc] init];
    bgColorView.backgroundColor = UIColorFromRGB(0xF3F3F3);
    bgColorView.layer.masksToBounds = YES;
    [cell setSelectedBackgroundView:bgColorView];

    // Construct subview and append to bottom (only visible when selected)
    UIView *cellSubView = [[UIView alloc] initWithFrame:CGRectMake(0, 125, cell.frame.size.width, 25)];

    // UILabel for display of current count
    UILabel *lblCount = [[UILabel alloc] initWithFrame:CGRectMake(15, 0, 25, 25)];
    lblCount.text = [NSString stringWithFormat:@"%d", [cellModel.count intValue]];

    // Create UIButton for incrementing
    UIButton *incrementButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    incrementButton.frame = CGRectMake(45, 0, 25, 25);
    [incrementButton setTitle:@"+" forState:UIControlStateNormal];

    // Enable touch event for button view
    [incrementButton addTarget:self action:@selector(countButtonTouchDown:) forControlEvents:UIControlEventTouchDown];

    [cellSubView addSubview:lblCount];
    [cellSubView addSubview:incrementButton];

    [cell addSubview:cellSubView];

    return cell;
}

A: How about you add the [self.tableView cellForRowAtIndePath:] setSelected:] inside the function responding to the button press to reinstate the same selected/ deselected state.
UPDATE:
Shift the code inside the didSelectCellAtIndexPath to another function, say performActionOnSelectionOfCellAtIndexPath and call performActionOnSelectionOfCellAtIndexPath from inside the didSelectCellAtIndexPath with the indexPath and also call performActionOnSelectionOfCellAtIndexPath from the function responding to the button press.


text:
Q: combining row an column marginal distributions to sample a specific cell values It must be the time here (after midnight) as I have a blackout.
I have a matrix with some missing values I want to fill. for a certain cell,
I know that the marginal row probability has mean r (more specifically, the marginal row probability follows the beta distribution with some parameters I know). the marginal column distribution of that cell has mean c (it follows a beta distribution with different known parameters)
what value should I "plug" in that cells (or which probability to sample from, in filling that value?)
EDIT: some further explanations...
The matrix consists values that are sampled from some distribution, with missing values in a few cell. The matrix is large enough so I can estimate the parameters of a the row marginal distribution and column marginal distribution and want to use that information to fill "realistic" values in the blank cell.
for some realistic context: I measure the probability of something to happen, under the combination of two factors. so the rows and columns represent the levels of those factors, and the values in the cells are the empirical measured probabilities of the event. I made many measurements on many combinations of the factors, but not all, and want to estimate the probabilities for the unmeasured combinations.


text:
Q: SQLite C# System.Data.SQLite.SQLiteException I want to insert data into a database via sqlite but each time I got the error below:
Connection Established Successfully...

code = Error (1), message = System.Data.SQLite.SQLiteException
  (0x800007BF): SQL logic error near "hpi_caseid": syntax error    at
  System.Data.SQLite.SQLite3.Prepare(SQLiteConnection cnn, String
  strSql, SQLiteStatement previous, UInt32 timeoutMS, String& strRemain)
  at System.Data.SQLite.SQLiteCommand.BuildNextCommand()    at
  System.Data.SQLite.SQLiteCommand.GetStatement(Int32 index)    at
  System.Data.SQLite.SQLiteDataReader.NextResult()    at
  System.Data.SQLite.SQLiteDataReader..ctor(SQLiteCommand cmd,
  CommandBehavior behave)    at
  System.Data.SQLite.SQLiteCommand.ExecuteReader(CommandBehavior
  behavior)    at
  System.Data.SQLite.SQLiteCommand.ExecuteNonQuery(CommandBehavior
  behavior)    at System.Data.SQLite.SQLiteCommand.ExecuteNonQuery()
  at Dapper.SqlMapper.ExecuteCommand(IDbConnection cnn,
  CommandDefinition& command, Action 2 paramReader)    at
  Dapper.SqlMapper.ExecuteImpl(IDbConnection cnn, CommandDefinition&
  command)    at Dapper.SqlMapper.Execute(IDbConnection cnn, String sql,
  Object param, IDbTransaction transaction, Nullable`1 commandTimeout,
  Nullable 1 commandType)    at
  ConsoleApplication1.SqliteDataAccess.SaveCase(CaseModel CasesData) in
  C:\Users\mansourm\Documents\Visual Studio
  2015\Projects\ConsoleApplication1\ConsoleApplication1\SqliteDataAccess.cs:line
  29    at ConsoleApplication1.Program.test() in
  C:\Users\mansourm\Documents\Visual Studio
  2015\Projects\ConsoleApplication1\ConsoleApplication1\Program.cs:line
  249

namespace ConsoleApplication1
{
    public class SqliteDataAccess
    {
        public static void SaveCase(CaseModel CasesData)
        {
            using (IDbConnection cnn = new SQLiteConnection(LoadConnectionString()))
            {
                cnn.Execute("INSERT INTO CasesData hpi_caseid VALUES @hpi_caseid", CasesData);
            }
        }

        private static string LoadConnectionString(string id = "Default")
        {
            return ConfigurationManager.ConnectionStrings[id].ConnectionString;
        }
    }
}

foreach (var c in ec.Entities)
{

    var newCase = new CaseModel();

    if (c.Attributes.Contains("hpi_caseid")) //Case ID
        newCase.hpi_caseid = Convert.ToInt64(c.Attributes["hpi_caseid"]);

    SqliteDataAccess.SaveCase(newCase);

}

public class CaseModel
{

    public long hpi_caseid;
}

//App.config
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <connectionStrings>
    <add name="Default" connectionString="Data Source=C:\Users\mansourm\Documents\Visual Studio 2015\Projects\ConsoleApplication1\ConsoleApplication1\hptest.db; Version=3;" providerName="System.Data.SqlClient"/>
  </connectionStrings>
    <startup>
        <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.6.1" />
    </startup>
</configuration>

I have tried with a relative path also but I got the same error.
Thank you in advance!

A: It seems you have missed the parenthesis after your table's name and after the Values keyword, i.e around hpi_caseid and @hpi_caseid:
cnn.Execute("INSERT INTO CasesData (hpi_caseid) VALUES (@hpi_caseid)", CasesData);

Also you have declared the parameter but didn't specify it's value, you need to specify a value something like this
yourCommand.Parameters.Add(new SqliteParameter("@hpi_caseid", yourValue));


text:
Q: Relationship between torsion modules and topology I was reviewing my class notes and found the following:
"The name 'torsion' comes from topology and refers to spaces that are twisted, ex. Möbius band"
In our notes we used the following definition for torsion element and torsion module:
An element m of an R-module M is called a torsion element if $rm=0$ for some $r\in R$.
A torsion module is a module which consists solely of torsion elements
What is the relationship between torsion modules and twisted spaces? Was the definition of torsion module somehow motivated from topological considerations of twisted spaces?
I don't really see any obvious connection. I'm taking my first topology class this semester, so I apologize if this is something you learn about later in courses like algebraic topology, but I haven't been able to find any explanation of this.

A: When you compute the homology groups of "twisted" spaces (which are abelian groups), you (sometimes) find that they contain non-zero torsion elements; furthermore, the presence of these particular elements in the homology is due to the twisting (in that, when you compute the homology groups, you see that is the twisting in the space that causes the calculation to give rise to torsion elements).
Since you haven't studied algebraic topology yet, I won't say more here.  Hopefully, while necessarily vague, the above description gives you some feeling for the meaning of the remark in your notes.

A: The definition of torsion in modules is a generalization of the definition of torsion in $\mathbb{Z}$-modules, e.g. abelian groups.  Torsion in abelian groups refers to elements of finite order, and this in turn relates to topology because to any topological space we can associate abelian groups called (integral) homology groups, and torsion in these groups is suggestive of a kind of "twistedness" in the space.  The simplest example of this is in the first integral homology of closed surfaces; the group has torsion if and only if the surface is non-orientable, such as the Klein bottle.


text:
Q: Should stories be usable? I'm new to Agile as a methodology, although I believe a have a basic grasp on its principles.
My team is currently building a framework that will support our client's application in the future. As an input, we have a bunch of requirements and even a suggestion of how the application should be implemented, at a VERY high level.
As an approach, we decided to use some sprints to understand the requirements before actually build the system. Our output is more documents describing the system to be build.
After the first sprint I started to question whether this isn't violating Agile principles, since our output (documents) aren't testable or a goal of the project in itself, only intermediary byproducts.

A: Who says that the output of a sprint is only code?
One of the deliverables of sprints can be documentation:

Once the team gets a business goal, it:

*

*Figures out how to do the work

*Does the work

*Identifies what's getting in its way

*Takes responsibility to resolve all the difficulties within its scope

*Works with other parts of the organization to resolve concerns outside their control

Emphasis above is mine.
While documentation is not one of the preferred outputs, it is an option.

A: The danger is of course that once the documents are complete you then implement them in a waterfall fashion.
I think your approach is probably not a good one. Aglie methodolgies are a response to the problems generated by planning everything in advance and it sounds to me like you are trying to plan everything in advance.
Instead of wtiting the document describing the framework. Write the framework! If it doesnt work as required, do another sprint with the refined requirement

A: When your project goal is to develop a framework to later develop end-user applications, you aren't writing the end-user application. Your users are not the end-users. Your users are future developers, and any user-stories should be written from their perspective.
However, the reasons why your users will use your framework is because they are implementing a user-story of an actual end-user. That means you can have kind of a "story in a story" in form of an end-user story which leads to a developer wanting to use your framework to implement it.

The programmer receives a user-story which reads "the user clicks on a red button to close the window". However, in the current version that button still has the defalut color. So the programmer searches the sourcecode for a call to closeButton = new Button() and adds the line closeButton.SetColor( red ) after it.

This story tells you what kind of requirements your users (the programmers) will have to deal with and how you design your framework in a way that such requirements can be easily implemented.

A: The main point of Agile is to iterate instead of doing the big design up front. However, you still have to have the requirements for the minimally viable product which should be documented in some format: specification, user stories, whatever works for your team.
It's a lot easier/faster to correct problems in the requirements than to rework\throw out already implemented code.
IMHO, if a client asks me to a build a building, I should know if the client wants a shed, a house, a office building, or a shopping mall.  I should also probably know what type of foundation the client wants.  What color the roof should be, and the color of the walls are a decision\requirement that can be nailed down at a later date.


text:
Q: How to get output from shell script on mac? I am looking to run a command in shell script and check its output.If it has certain text, I want to set a global variable to particular string.Below is what I have done so far.
The command ~/Library/Android/sdk/tools/android list | grep 'The "android" command is deprecated. works in terminal however it doesn't seem to work in shell script.
What am I missing here?
#!/bin/bash
Android_Command=''

MKCOMMAND='~/Library/Android/sdk/tools/android list | grep 'The "android" command is deprecated.''
RESP=$($MKCOMMAND)
echo $RESP

if [ '$RESP'=='The "android" command is deprecated.' ]; then
 Android_Command='Version2'
else
 Android_Command='Version1'
fi

Following is the output that I get
 ~/Library/Android/sdk/tools/android: No such file or directory

A: From your last edit, it has become clear that you were not executing the script from your terminal but rather you were just executing a single line from it.
In shell scripts, anything inside a single quote is not subject to shell expansion. Having said that, both ~ and | cannot be quoted.
Redirections are created by the shell before execution. This means MKCOMMAND cannot be executed because the pipe | will be treated as a parameter to the command android.
So how do we deal with this kind of script? Don't quote any redirections.
#!/bin/bash

if ~/Library/Android/sdk/tools/android list | grep -q 'The "android" command is deprecated.'; then
 Android_Command='Version2'
else
 Android_Command='Version1'
fi

The if statement accepts a complex statement. grep -q will return zero if it finds the string and non-zero otherwise.

A: Try running your command directly instead (without using the MKCOMMAND variable):
RESP=$(~/Library/Android/sdk/tools/android list | grep 'The "android" command is deprecated.')
echo $RESP
...

This (quick!) hack might bypass some Bash quoting issues you may be having.


text:
Q: How do I add subscript to a stargazer table covariate label? Within the below covariate labels I'd like to include P, M and C in subscript. Here is my code:
   stargazer(DD1_PT, DD1_MT, DD1_CT,
          type = "text",
          title = "Table 1",
          out = "table1.html",
          dep.var.labels.include = FALSE,
          column.labels = c("Presidential", "Midterm", "Constitutional"),
          model.numbers = FALSE,
          order=c(4, 1, 8, 2, 9, 3, 10, 5, 6, 7),
          covariate.labels=c("TimeP (1 = 2016/0 = 2012)","TimeP*Vote center", "TimeM (1 = 2018/0
          = 2010)", "TimeM*Vote center", "TimeC (1 = 2017/0 = 2009)", "TimeC*Vote center"),
          no.space=TRUE,
          omit.stat=c("LL","ser","f"),
          notes = c("Standard errors given in parentheses ", "Population scaled to 1,000,000 and
          income scaled to 10,000"),
          notes.align = "r"))

Any ideas as to how I do so?
Thanks!

A: Your code has the type = "text". It will be difficult to make subscripted characters in plain text.
If you set your output to html, then you can just use stringr::str_replace() to put in the HTML for a subscript:  <\sub>.
For a reproducible example, let's use mtcars:
Imagine that we want to make the last letter of "Observations" subscripted in the table.
library(stargazer)
library(tidyverse)

fit1 <- lm(mpg ~ cyl, data = mtcars)
output <- stargazer(fit1, type = "HTML") # gives you output

# replace output with the subscripted html
output <- str_replace(output, "Observations", "Observations")

write_lines(output, "subscript_example.html")

which gives the desired subscript, as below:

As a final note, I have read that it is better to edit HTML using xml2 rather than str_replace(). Perhaps someone else can help with that. The above solution does work for me.


text:
Q: Why was this line from "You're a Mean One, Mr. Grinch" removed in Hawkeye? The end credits of Episode 5 of Hawkeye are set to "You're a Mean One, Mr. Grinch", referencing both the show's Christmas setting and

 Wilson Fisk, who was revealed at the end of that episode to be the series' main villain.

The second verse of the song goes like this:

You're a monster, Mr. Grinch
Your heart's an empty hole
Your brain is full of spiders, you've got garlic in your soul,
Mr. Griii~iiinch
I wouldn't touch you with a... thirty-nine-and-a-half-foot pole!

However, the version that plays in Hawkeye omits the last line of the verse, and instead repeats the last line of the first verse:

You're a bad banana with a... greasy black peel!

It felt (and still feels) very weird and arbitrary of Disney to remove that one line and only that one line, but I assume there must have been a reason behind it.
Is there an official explanation for why the lyrics were altered?


text:
Q: access a backend variable in front end using javascript I had Public declared Dictonary in code behind as :
 Public dics As New Dictionary(Of String, String()) From { _
{"picture", New String() {".jpeg", ".jpg", ".png", ".bmp", ".gif", ".tif"}}, _
{"document", New String() {".doc", ".docx", ".txt", ".htm", ".html", ".xml", ".xaml", ".css"}}, _
{"excel", New String() {".xls", ".xlsx", ".xlt", ".xla"}}, _
{"pdf", New String() {".pdf"}}, _
{"zip", New String() {".7z", ".APK", ".BAT", ".rar", ".dll", ".jar", ".zip"}}, _
{"ppt", New String() {".ppt", ".pos", ".pps"}}}

Edit :
if i do like this
function myFunction() {
       var dic = "<%= dics %>";
       var array_keys = new Array();
       var array_values = new Array();
       for (var key in dic) {
           alert(key);
        }
     }

will show alerts as
How can i access this Dictonary in javascript to do some operations

A: For now it looks like you need to serialize dictionary into javascript object and then paste it in your JavaScript. You could use any library for serialization. E.g. Newtosoft.Json. Like this:
function myFunction() {
   var dic = <%= Newtonsoft.Json.JsonConvert.SerializeObject(dics) %>;
   var array_keys = new Array();
   var array_values = new Array();
   for (var key in dic) {
       alert(key);
    }
 }

Note that I removed quotes.
But I suggest you to get rid of this approach and not mix JavaScript and ASP.Net code.
So in my vision you should load this dictionary via AJAX or if it's not possible place ASP.Net in some other place. E.g.:
View:
<input type="hidden" id="dictionaryInput" value="<%=Newtonsoft.Json.JsonConvert.SerializeObject(dics)%> />

JavaScript:
function myFunction() {
   var dicInput = document.getElementById('dictionaryInput');
   var dic = JSON.parse(dicInput.value);
   var array_keys = new Array();
   var array_values = new Array();
   for (var key in dic) {
       alert(key);
    }
 }

Hope it will help.

A: You can create a property(say DictionaryConv) in your code behind, and in page load set that property value.
Dim jsz As New System.Web.Script.Serialization.JavaScriptSerializer
        DictionaryConv = jsz.Serialize(dics)

In javascript you use this function.
function myFunction() {
            var dic = <%= DictionaryConv%>;
            var array_keys = new Array();
            var array_values = new Array();
            for (var key in dic) {
                alert(key);
            }
        }


text:
Q: Is it possible to draw tick marks outside of the X-Axis on Google Charts? I've done quite a bit of research of google charts(specifically combo chart) and I don't think producing this UI is possible:

This is because:

*

*Gridlines in Google Chart only go inward the graph.

*"Ticks" are available, but only as labels.

I don't see any other option to create this effects. Any ideas on how to create this effect?


text:
Q: jQuery: Splash page animation sequence ending with a URL jump I am creating a simple splash page with the following sequence:

*

*Fade in elements

*Wait 5 seconds

*Fade out elements

*Launch new page

I can get steps 1 through 3 to work properly in sequence.
However, as soon as I add a url redirection to my chain (step 4), it runs steps 1 to 3 super quickly and jumps. Here's the code I'm using:

Splash Page!

Is there a proper and better way I should be doing this?

A: you should call go_homebase in the complete callback of fadeOut, e.g.:
$('.splash p').fadeIn('slow').delay(5000).fadeOut('slow', function() { $(this).go_homebase(); });

A: This works perfectly for me.
$(document).ready(function() {
    $('.splash p').fadeIn(1500).delay(5000).fadeOut(2000,
        function() { window.location = "http://google.com"; });
});

A: This should do the trick:
$('.splash p').fadeIn('slow').delay(5000).fadeOut('slow',
  function(){ $(this).go_homebase()}
);

You need to call the redirect function as a callback, when the last animation has finished.


text:
Q: Do I need information_schema, mysql, performance_Schema, phpmyadmin databases? It's my first time using phpmyadmin and databases. I've opened up phpMyAdmin and I already have four databases:

*

*information_schema

*mysql

*performance_schema

*phpmyadmin

which are full of tables.
Reading through https://dev.mysql.com/doc/refman/8.0/en/performance-schema.html never answers the question: Do I need them ? Can I delete them ?

A: Three of the four are used internally by MySQL and if you somehow were successful in removing them, MySQL would no longer work correctly. The phpmyadmin one is not required by either MySQL or phpMyAdmin, but whatever means you used to install phpMyAdmin has configured it and at best you'll confuse that system and at worst you could break logging in through phpMyAdmin (until you manually edit the configuration file) through fiddling with that database. So, as Lelio Faieta said, I would leave them all alone.
What you can do, however, is hide them in phpMyAdmin. There's a configuration directive to hide databases (see https://docs.phpmyadmin.net/en/latest/config.html#cfg_Servers_hide_db). You have to edit the configuration file, config.inc.php, and add a line like $cfg['Servers'][$i]['hide_db'] = '^(information_schema|mysql|performance_schema|phpmyadmin)$';
Strangely, this seems to be broken in the latest phpMyAdmin; there's a bug report about it here https://github.com/phpmyadmin/phpmyadmin/issues/16506, so depending on which phpMyAdmin version you have it might not work at the moment, but will get fixed and you can follow the bug report for more information.


text:
Q: jquery email signup form trying to hide form after submit I am trying to use a simple jquery/php newsletter script. The script works fine. As I enter name and email and hit the submit button, it saves data into a .txt file, and display a success message along with the form. Now, I would like to modify the script. I do not want the form to be seen as I hit the submit, instead it should show the success message only "Thank you." Being very novice to javascript, I have so far figured out that I need to "fadeOut" the form after clicking the submit button.
I think the code might be look like
      $("#submit").on("click", function(e) {
        e.stopImmediatePropagation();
        $("#signup").fadeOut(280, function() {
          // callback method to display new text
          // setup other codes here to store the e-mail address
          $(this).after('
Thank you
');
       });
  });

I have tried to integrate this code, but due to my limited JS experience I cannot do it successfully.
Here is my original jquery script
var error_1 = "Please enter your valid email address";
var error_2 = "Please enter your  name";
var thankyou = "Thank you";

function trim(str) {
    str = str.replace(/^\s*$/, '');
    return str;
}

function $Npro(field) {
    var element = document.getElementById(field);
    return element;
    return false;
}

function emailvalidation(field, errorMessage) {
    var goodEmail = field.value.match(/[a-zA-Z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-zA-Z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-zA-Z0-9](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?\.)+[a-zA-Z0-9](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?/);
    apos = field.value.indexOf("@");
    dotpos = field.value.lastIndexOf(".");
    lastpos = field.value.length - 1;
    tldLen = lastpos - dotpos;
    dmLen = dotpos - apos - 1;
    var badEmail = (tldLen < 2 || dmLen < 2 || apos < 1);
    if (!goodEmail || badEmail) {
        $Npro("Error").innerHTML = errorMessage;
        $Npro("Error").style.display = "inline";
        field.focus();
        field.select();
        return false;
    } else {
        return true;
    }
}

function emptyvalidation(entered, errorMessage) {
    $Npro("Error").innerHTML = "";
    with(entered) {
      if (trim(value) == null || trim(value) == "") { /*alert(errorMessage);*/
         $Npro("Error").innerHTML = errorMessage;
          $Npro("Error").style.display = "inline";
          return false;
      } else {
          return true;
      }
   } //with
} //emptyvalidation

function signup(thisform) {
    with(thisform) {
        if (emailvalidation(email, error_1) == false) {
            email.focus();
            return false;
        };
        if (emptyvalidation(name, error_2) == false) {
            name.focus();
            return false;
        };
    }
    $("#submit, #myResponse").hide(); // Hide the buttom and the message
    $("#loading").show(); // show the loading image.
    params = $("#subform").serialize();
    $.post("optIn.php", params, function(response) {
        //alert(response); //may need to activate this line for debugging.
        $("#loading").hide();
        $("#myResponse").html(thankyou); //Writes the "Thank you" message that comes from optIn.php and styles it.
        $('#myResponse').css({
            display: 'inline',
            color: 'green'
        })
        $("#submit").show();
    })
    return false;
}

Here is the html markup
<form onSubmit="return signup(this);return false;" method="post" name="subform" id="subform" action="

    <?php echo optIn.php ?>">

        Subscribe to our newsletter

           Email:
           <input type="text"  id="email" name="email" value="">

           Name:
           <input type="text"  name="name" id="name"  value="">

        <input type="submit" id="submit" name="submit" value="Sign up">

</form>

Here is my php code:
<?php
//ini_set('display_errors', 0);
header ("Expires: Mon, 26 Jul 1997 05:00:00 GMT");
header("Cache-Control: no-store, no-cache, must-revalidate");
header("Pragma: no-cache");

$email  = trim(htmlspecialchars($_REQUEST["email"]));
$name   = trim(htmlspecialchars($_REQUEST["name"]));

$pfileName  = "mails.txt";
$MyFile     = fopen($pfileName, "a");
$nline="\"".$email."\"" ."," ."\"".$name."\"" ."\r\n";
fwrite($MyFile, $nline);
fclose($MyFile);
die;
?>

A: Try providing a .delay() so that the fadeOut() function has finished before attempting to display the success message:
  $("#submit").on("click", function(e) {
    e.stopImmediatePropagation();
    $("#signup").delay(500).fadeOut(280, function() {
      $(this).after('
Thank you
');
  });

});

A: If I understand you correctly you want the user to submit the information via your html form.  Then you want the form to go away after you hit the submit button.
From reading the JQuery method you have tried I found one mistake that is preventing your form from fading out. You were using the wrong id for your form in your JQuery code(it should be subform according to your html). Note that I removed your PHP code so that I could create an example in jsfiddle for you.  My sample posts to google.com to prevent your from getting an error page displayed in the results sections.
jsfiddle:  fade out form on submission
$("#submit").on("click", function(e) {

       //changed from e.stopImmediatePropogation()
       e.preventDefault();

      //#subform is the actual id of your form, you were using signup
      $("#subform").fadeOut(280, function() {
          // callback method to display new text
          // setup other codes here to store the e-mail address
          $(this).after('
Thank you
');
      });
  });


text:
Q: How to add buttons in an array and loop through them? Got a bunch of letter buttons in code below:
Code:
<?php
    $a = range("A","Z");
?>

<?php
    $i = 1;
    foreach($a as $key => $val){
        if($i%7 == 1) echo"
";
        echo"<input type=\"button\" onclick=\"btnclick(this);\" value=\"$val\" id=\"answer".$val."\" name=\"answer".$val."Name\" class=\"answerBtns answers answerBtnsOff\">";
        if($i%7 == 0) echo"
";
        $i++;
    }
?>

Now the code below is able to turn on an answer button:
Code:
function addwindow(btn) {
$('#answer'+btn).addClass("answerBtnsOn");
}

But the only problem is that the code above is only able to turn on a single answer button on only. For example if the "Answer" is B, then it will look for button "#answerB" and turn on that button which is button B. or if the "Answer" is E, then it will look for button "#answerE" and turn on that button which is button E.
The problem is that if there are multiple answers. If the "Answer" is B E, then it does not turn on buttons B and E. This is because it is trying to find button "#answerBE" which is incorrect, it should be looking for button "#answerB" and button "#answerE" and turn them both on.
Another example is if "Answer" is A D F, it doesn't turn on buttons A D and F because it is trying to find button "#answerADF" which is incorrect, it should be looking for button "#answerA", button "#answerD", and button "#answerF" and turn them all on.
So my question is that how can I turn on multiple buttons if there are multiple Answers? Do I need to put all the buttons in an array and loop through them so that it is able to go through all the buttons and turn on those buttons which should be turn on?
UPDATE:
Below is the "Add" button which calls on the addwindow() function and above the add button is the "Answer" column where it displays rows of Answers
   echo ''.htmlspecialchars($searchNoofAnswers[$key]).'	';
    echo "<button type='button' class='add' onclick=\"parent.addwindow('$searchAnswer[$key]');\">Add</button>
";

A: try this:
function addwindow(btn) {
   var arr = btn.split("");
   $.each(arr, function(i, v) {
      $('#answer' + v).addClass("answerBtnsOn");
   })
}

jQuery.each()

A: I believe,you need this:
function addwindow(btn) {
    var answers = $.map(btn.split(''),function(chr){   return "#answer"+chr;  }).join(', ');
    $(answers).addClass("answerBtnsOn");
}

Explanation:
btn.split('')   //splits btn string into char's array,
                //  e.g. "ADE" will become ["A","D","E"]
$.map           //converts ["A","D","E"]
                //  to ["#answerA","#answerD","#answerE"]
join(',')       //makes "#answerA, #answerD, #answerE" string
                //  from ["#answerA","#answerD","#answerE"] array

A: It sounds like you are passing the 'btn' variable as a string.  This is acceptable if you are able to split() the string and then use a for() loop to loop through the resulting array and assign the appropriate class(es).
function addwindow(btn){
    var answers = btn.split(''); // leave empty if values are not separated by a delimiter
    for(var i=0; i < answers.length; i++){
        $('#answer'+answers[i]).removeClass('answerBtnsOff').addClass('answerBtnsOn');
    }
}

Depending on your delimiter, you would want to modify the following code:
btn.split(''); // no delimiter
btn.split(' '); // space delimiter
btn.split(','); // comma delimiter
btn.split('|'); // pipe delimiter

It also appears that you are escaping your quotes but that is not necessary if you are also using concatenation.

Note: Unlike the double-quoted and heredoc syntaxes, variables and
  escape sequences for special characters will not be expanded when they
  occur in single quoted strings.

<?php
    $i = 1;
    foreach($a as $key => $val){
        echo ($i % 7 == 1 ? "
" : "");
        echo '<input type="button" onclick="btnclick(this);" value="'.$val.'" id="answer'.$val.'" name="answer'.$val.'Name" class="answerBtns answers answerBtnsOff">";
        echo ($i % 7 == 0 ? "
" : "";
        $i++;
    }
?>


text:
Q: How can i capture more then autorized amount On the PayPal developer site they state it is possible to capture 75 US Dollar or 15% percent more than the original authorized amount of a payment. I am currently using the order API because I can't seem to figure out how to create a Payment from the payment API. My question is the following: how can I capture a different amount then the authorized amount(order API). In the capture section of the Order API I can't give up a new amount. I tried to patch the order first but after the amount was authorized the status of the order is COMPLETED, so the value couldn't be updated.
I think the reason I don't understand how to do it is because I don't know the difference between Order and Payment API. I would like to use the payment API but I can not find an PayPal API to create a payment.

A: Use the order API with "intent":"authorize". The completed order will have a payment authorization object in the response.
Use the payment API to capture the authorization object for the desired amount, https://developer.paypal.com/docs/api/payments/v2/#authorizations_capture


text:
Q: What is the most impressive LINQ statement that you have come across? I recently came across this raytracer in LINQ. Just wondering if anyone can top that?
var pixelsQuery =
from y in Enumerable.Range(0, screenHeight)
let recenterY = -(y - (screenHeight / 2.0)) / (2.0 * screenHeight)
select from x in Enumerable.Range(0, screenWidth)
       let recenterX = (x - (screenWidth / 2.0)) / (2.0 * screenWidth)
       let point = Vector.Norm(Vector.Plus(scene.Camera.Forward,
                                           Vector.Plus(Vector.Times(recenterX, scene.Camera.Right),
                                                       Vector.Times(recenterY, scene.Camera.Up))))
       let ray = new Ray { Start = scene.Camera.Pos, Dir = point }
       let computeTraceRay = (Func<Func<TraceRayArgs, Color>, Func<TraceRayArgs, Color>>)
        (f => traceRayArgs =>
         (from isect in
              from thing in traceRayArgs.Scene.Things
              select thing.Intersect(traceRayArgs.Ray)
          where isect != null
          orderby isect.Dist
          let d = isect.Ray.Dir
          let pos = Vector.Plus(Vector.Times(isect.Dist, isect.Ray.Dir), isect.Ray.Start)
          let normal = isect.Thing.Normal(pos)
          let reflectDir = Vector.Minus(d, Vector.Times(2 * Vector.Dot(normal, d), normal))
          let naturalColors =
              from light in traceRayArgs.Scene.Lights
              let ldis = Vector.Minus(light.Pos, pos)
              let livec = Vector.Norm(ldis)
              let testRay = new Ray { Start = pos, Dir = livec }
              let testIsects = from inter in
                                   from thing in traceRayArgs.Scene.Things
                                   select thing.Intersect(testRay)
                               where inter != null
                               orderby inter.Dist
                               select inter
              let testIsect = testIsects.FirstOrDefault()
              let neatIsect = testIsect == null ? 0 : testIsect.Dist
              let isInShadow = !((neatIsect > Vector.Mag(ldis)) || (neatIsect == 0))
              where !isInShadow
              let illum = Vector.Dot(livec, normal)
              let lcolor = illum > 0 ? Color.Times(illum, light.Color) : Color.Make(0, 0, 0)
              let specular = Vector.Dot(livec, Vector.Norm(reflectDir))
              let scolor = specular > 0
                           ? Color.Times(Math.Pow(specular, isect.Thing.Surface.Roughness), light.Color)
                           : Color.Make(0, 0, 0)
              select Color.Plus(Color.Times(isect.Thing.Surface.Diffuse(pos), lcolor),
                                Color.Times(isect.Thing.Surface.Specular(pos), scolor))
          let reflectPos = Vector.Plus(pos, Vector.Times(.001, reflectDir))
          let reflectColor =
              traceRayArgs.Depth >= MaxDepth
              ? Color.Make(.5, .5, .5)
              : Color.Times(isect.Thing.Surface.Reflect(reflectPos),
                            f(new TraceRayArgs(new Ray { Start = reflectPos, Dir = reflectDir },
                                               traceRayArgs.Scene,
                                               traceRayArgs.Depth + 1)))
          select naturalColors.Aggregate(reflectColor, (color, natColor) => Color.Plus(color, natColor)))
                              .DefaultIfEmpty(Color.Background).First())
       let traceRay = Y(computeTraceRay)
       select new { X = x, Y = y, Color = traceRay(new TraceRayArgs(ray, scene, 0)) };

foreach (var row in pixelsQuery)
    foreach (var pixel in row)
        setPixel(pixel.X, pixel.Y, pixel.Color.ToDrawingColor());

A: I doubt that there's anything to top the raytracer. I'm quite fond of my Mandelbrot expression though:
from row in Enumerable.Range(0, ImageHeight)
from col in Enumerable.Range(0, ImageWidth)
// Work out the initial complex value from the row and column
let c = new Complex((col * SampleWidth) / ImageWidth + OffsetX,
                    (row * SampleHeight) / ImageHeight + OffsetY)
// Work out the number of iterations
select Generate(c, x => x * x + c).TakeWhile(x => x.SquareLength < 4)
                                  .Take(MaxIterations)
                                  .Count() into count
// Map that to an appropriate byte value
select (byte)(count == MaxIterations ? 0 : (count % 255) + 1);

A: Mads Torgersen demonstrates how to write a self-contained recursive lambda expression in LINQ to calculate (e.g.) a factorial:
i => new Func<Func<int,int>,Func<int,int>>(fac => x => x == 0 ? 1 : x * fac(x
- 1))(new SelfApplicable<Func<Func<Func<int,int>,Func<int,int>>,Func<int,int>
>>(y => f => x => f(y(y)(f))(x))(y => f => x => f(y(y)(f))(x))(fac => x => x
== 0 ? 1 : x * fac(x - 1)))(i)

Mads notes:

I can't even figure out how to line break it so that it approaches readable, so I haven't.

A: Call me crazy, but I'm a big fan of readability - so I tend to just have a sequence of individually-innocent-looking expressions that I then combine. Of course, it depends how you define LINQ: if you mean query-syntax in C#, then I don't tend to go overboard...  but if you mean meta-programming (i.e. C# code that creates a LINQ expression), I've got a few good examples:

*

*how about some object-construction with DbLinq

*I've got the (LINQ) Expression-based maths interpreter/compiler that I wrote for Finguistics kicking around somewhere...

*the generic operators code I wrote for MiscUtil is all Expression-based

*various object copying examples (like this)

*complex OrderBy construction


text:
Q: TextFormField input text overflow with DropdownButtonFormField, Flutter I have layout issues because the text from the dropdown menu that you choose can't fit inside the TextFormField and I can't seem to fix this issue. I have tried adding the overflow: TextOverflow.ellipsis property but that only changes for the dropdown labels, still when I choose one, they can't fit inside the TextFormField.

When you press the dropdown button, it shows like this:

and with the TextOverflow.elipsis property:

which is fine, but I still have the layout issue because of the chosen text that is now displayed inside the textformfield:

How can I add the same property to the TextFormField, or any sort of solution to this issue?
The code:
Row(
                                    children: [
                                      Expanded(
                                        child: DropdownButtonFormField<String>(
                                          decoration:
                                              kTextFieldDecoration.copyWith(
                                            hintText: 'Legal status',
                                            labelText: 'Legal status',
                                          ),
                                          value: _legalStatus,
                                          items: [
                                            'Sole proprietorship',
                                            'Partnerships',
                                            'Limited Liability Company (LLC)',
                                            'Corporation',
                                            'Small Business Corporation (S-Corporation)'
                                          ]
                                              .map((label) => DropdownMenuItem(
                                                    child: Text(
                                                      label.toString(),
                                                    ),
                                                    value: label,
                                                  ))
                                              .toList(),
                                          onChanged: (value) {
                                            setState(() {
                                              _legalStatus = value;
                                              print(value);
                                            });
                                          },
                                          validator: (thisValue) {
                                            if (thisValue == null) {
                                              return 'Please choose your legal status';
                                            }
                                            return null;
                                          },
                                        ),
                                      ),
                                      SizedBox(
                                        width: 16.0,
                                      ),
                                      Container(
                                        width: 120.0,
                                        child: DropdownButtonFormField<String>(
                                          decoration:
                                              kTextFieldDecoration.copyWith(
                                            hintText: 'Year established',
                                            labelText: 'Year established',
                                          ),
                                          value: _yearEstablished,
                                          items: items // a list of numbers that are Strings
                                              .map((label) => DropdownMenuItem(
                                                    child:
                                                        Text(label.toString()),
                                                    value: label,
                                                  ))
                                              .toList(),
                                          onChanged: (value) {
                                            setState(() {
                                              _yearEstablished = value;
                                              print(value);
                                            });
                                          },
                                          validator: (thisValue) {
                                            if (thisValue == null) {
                                              return 'Please choose your company year of establishment';
                                            }
                                            return null;
                                          },
                                        ),
                                      ),
                                    ],
                                  ),

Thanks in advance for your help!

A: You need to use isExpanded property of DropDownFormField to solve this error.
Row(
                                    children: [
                                      Expanded(
                                        child: DropdownButtonFormField<String>(
                                          isExpanded: true,
                                          decoration:
                                              kTextFieldDecoration.copyWith(
                                            hintText: 'Legal status',
                                            labelText: 'Legal status',
                                          ),
                                          value: _legalStatus,
                                          items: [
                                            'Sole proprietorship',
                                            'Partnerships',
                                            'Limited Liability Company (LLC)',
                                            'Corporation',
                                            'Small Business Corporation (S-Corporation)'
                                          ]
                                              .map((label) => DropdownMenuItem(
                                                    child: Text(
                                                      label.toString(),
                                                    ),
                                                    value: label,
                                                  ))
                                              .toList(),
                                          onChanged: (value) {
                                            setState(() {
                                              _legalStatus = value;
                                              print(value);
                                            });
                                          },
                                          validator: (thisValue) {
                                            if (thisValue == null) {
                                              return 'Please choose your legal status';
                                            }
                                            return null;
                                          },
                                        ),
                                      ),
                                      SizedBox(
                                        width: 16.0,
                                      ),
                                      Container(
                                        width: 120.0,
                                        child: DropdownButtonFormField<String>(
                                          decoration:
                                              kTextFieldDecoration.copyWith(
                                            hintText: 'Year established',
                                            labelText: 'Year established',
                                          ),
                                          value: _yearEstablished,
                                          items: items // a list of numbers that are Strings
                                              .map((label) => DropdownMenuItem(
                                                    child:
                                                        Text(label.toString()),
                                                    value: label,
                                                  ))
                                              .toList(),
                                          onChanged: (value) {
                                            setState(() {
                                              _yearEstablished = value;
                                              print(value);
                                            });
                                          },
                                          validator: (thisValue) {
                                            if (thisValue == null) {
                                              return 'Please choose your company year of establishment';
                                            }
                                            return null;
                                          },
                                        ),
                                      ),
                                    ],
                                  ),

A: You need to use selectedItemBuilder parameter which will control how the selected item will be displayed on the button. Then, TextOverflow.ellipsis will work with you as expected. Here's how to use it:
selectedItemBuilder: (BuildContext context) {
      return items.map<Widget>((String item) {
        return Text(item, overflow: TextOverflow.ellipsis,);
      }).toList();
    },


text:
Q: How to go to the "root" directory of a website? There is a PHP website into a Linux computer webserver. In a particular PHP file , which is located in a deep subdirectory of this site , I want to go to the first directory of the site. How to write the PHP code to achieve that ?

A: $_SERVER['DOCUMENT_ROOT'] will respond the filesystem path to http://your_hostname/

A: Use $_SERVER['DOCUMENT_ROOT']
Documenation

A: $_SERVER['DOCUMENT_ROOT']
this will give the root directory.