text:
Q: State Monad Bind I think I understand how the State Monad works. I've managed to write some code which uses the State Monad.
I understand how the Monad instance of State works:
instance Monad (State s) where
return x = State $ \s -> (x,s)
(State h) >>= f = State $ \s -> let (a, newState) = h s
                                    (State g) = f a
                                in  g newState

This code works perfectly fine:
type PeopleStack = [String]

enterClub :: String -> State PeopleStack String
enterClub name = state $ \xs -> (name ++ " entered club", name:xs)

leaveClub :: State PeopleStack String
leaveClub = state $ \(x:xs) -> ("Someone left the club", xs)

clubAction :: State PeopleStack String
clubAction = do
  enterClub "Jose"
  enterClub "Thais"
  leaveClub
  enterClub "Manuel"

However when I try to write clubAction in a bind function I can't seem to get it working.
this is what I have tried:
let statefulComputation1 = enterClub "Jose"
statefulComputation1 :: State PeopleStack String

runState (statefulComputation1 >>= (enterClub "Manuel") >>= leaveClub) []

I get this error:
<interactive>:13:22:
Couldn't match type 'StateT
                       PeopleStack Data.Functor.Identity.Identity String'
               with 'String
                     -> StateT PeopleStack Data.Functor.Identity.Identity a'
Expected type: String
               -> StateT PeopleStack Data.Functor.Identity.Identity a
  Actual type: State PeopleStack String
Relevant bindings include
  it :: (a, PeopleStack) (bound at <interactive>:13:1)
In the second argument of '(>>=)', namely 'leaveClub'
In the first argument of 'runState', namely
  '(state1 >>= leaveClub)'

My question is how do I translate that do notation to a function using bind.

A: You need to use (>>) instead of (>>=):
runState (statefulComputation1 >> (enterClub "Manuel") >> leaveClub) []

(enterClub "Manuel") has type State PeopleStack String while (>>=) requires a function String -> State PeopleStack a as its second argument. Since you don't use use the result from statefulComputation1 you can combine them with (>>) which ignores the result from the first state computation.

A: Each item on the right side of the bind operator (>>=) needs to be a lambda...., so this would work
runState (statefulComputation1 >>= \_ -> enterClub "Manuel" >>= \_ -> leaveClub) []

or, you can use the shorthand (>>)
runState (statefulComputation1 >> enterClub "Manuel" >> leaveClub) []


text:
Q: Return true or false with preg match instead of echoing out a sentence I am using the following to check to see if the data from a form contains certain words, the problem is though, when it checks I get "a match was found" or "a match was not found" over and over again a million times. How can I just assign a true or false value for the whole sentence that is posted ?. I want to then add something like....if true dump this post, if false process it and put it in the database.
    <?php
    $message = $_POST['message'];
    echo $message;

    $targets = array('viagra', 'prescription', 'drugs', 'zyban', 'zithromax', 'voltaren', 'cilias', 'FDA');

    foreach($targets as $t)
    {
        if (preg_match("/\b" . $t . "\b/i", $message)) {
            echo "A match was found.";
        } else {
            echo "A match was not found.";
        }
    }

    ?>

A: function containsSpam($message) {
    $targets = array('viagra', 'prescription', 'drugs', 'zyban', 'zithromax', 'voltaren', 'cilias', 'FDA');

    foreach($targets as $t)
    {
        if (preg_match("/\b" . $t . "\b/i", $message)) {
            //A match was found.
            return true;
        }
    }
    return false;
}

A: If i get it right you need to set a stop value like this
<?php
function containsSpam($message) {
    $targets = array('viagra', 'prescription', 'drugs', 'zyban', 'zithromax', 'voltaren', 'cilias', 'FDA');
    $stop = false;
    foreach($targets as $t)
    {
        if (preg_match("/\b" . $t . "\b/i", $message)) {
            //A match was found.
            $stop = true;
            break;
        }
    }
    //And you can then do something like this
    if ($check) {
       //Insert it
    } else {
       //Dump it
    }
}
?>

redpajama_set_name: RedPajamaStackExchange


text:
Q: Using function stored in other local files of same directory I've this following code in C++:
//file0.cpp
 #include "file11.cpp"
 #include "file22.cpp"

 #include<iostream>
 #include<conio.h>

 using namespace std;

 extern void func1(int i);
 extern void func2(int i);

 int main(void)
 {
    int i;
    func1(i);
    func2(i);

    cout<<"the value of i is"<<" "<<i;

    getch();
    return 0;
  }

//file11.cpp
 #inluce<iostream>
 #include<conio.h>
 using namespace std;
 void func1(int i)
 {
    cout<<++i;

 }

//file22.cpp
 #inluce<iostream>
 #include<conio.h>
 using namespace std;
 void func2(int i)
 {
    cout<<++i;

 }

I'm using Dev-C++ compiler, on Windows Vista - 32bits.
I'm trying to pass int i from file0.cpp to the function func1(int ) and func2(int). But while i compile this code, it shows error.
the error logs are as follows:
Compiler: Default compiler
Executing  g++.exe...
g++.exe "C:\Users\samurai\Documents\file0.cpp" -o "C:\Users\samurai\Documents\file0.exe"    -I"C:\Dev-Cpp\lib\gcc\mingw32\3.4.2\include"  -I"C:\Dev-Cpp\include\c++\3.4.2\backward"  -I"C:\Dev-Cpp\include\c++\3.4.2\mingw32"  -I"C:\Dev-Cpp\include\c++\3.4.2"  -I"C:\Dev-Cpp\include"   -L"C:\Dev-Cpp\lib"
In file included from C:\Users\samurai\Documents\file0.cpp:1:
C:\Users\samurai\Documents\/file11.cpp:1:2: invalid preprocessing directive #inluce
In file included from C:\Users\samurai\Documents\file0.cpp:1:
C:\Users\samurai\Documents\/file11.cpp: In function `void func1(int)':
C:\Users\samurai\Documents\/file11.cpp:6: error: `cout' undeclared (first use this function)
C:\Users\samurai\Documents\/file11.cpp:6: error: (Each undeclared identifier is reported only once for each function it appears in.)

In file included from C:\Users\samurai\Documents\file0.cpp:2:
C:\Users\samurai\Documents\/file22.cpp:1:2: invalid preprocessing directive #inluce
In file included from C:\Users\samurai\Documents\file0.cpp:2:
C:\Users\samurai\Documents\/file22.cpp: In function `void func2(int)':
C:\Users\samurai\Documents\/file22.cpp:6: error: `cout' undeclared (first use this function)

C:\Users\samurai\Documents\file0.cpp: In function `int main()':
C:\Users\samurai\Documents\file0.cpp:17: error: `cout' undeclared (first use this function)

Execution terminated

I'm unable to debug this code.
Any help would be appreciated.
Thank You.

A: Well, you are typing #inluce and not #include on your source files
When a compiler tells you something, it is usually important :P
EDIT When reading compiler errors, start with the first one, not the last one, and fix it. Do not attempt to correct the second one because most of the time it is a side effect of the first error. Then try to compile it again.
Takes a little practice, just don't be scared of the wall of text it throws at you.

A: You spelled #include wrong.  Fix that and see what errors you get after that.


text:
Q: How to query for rows that have highest column value among rows that have same value for one of the columns v.2 Still a journeyman to SQL here.  I have a temp table named #everything which has the following data.  (headers abbreviated). The temp table has many more columns than this.
hh_key sub_id tier
   1    1234   T1
   2    2345   T2
   3    4567   T4
   3    4568   T3

I want to return the rows with the 'best' tier.  In my case best has the lowest number after the 'T'.  So here are my desired results:
hh_key sub_id tier
   1    1234   T1
   2    2345   T2
   3    4568   T3

I know that this exact issue was asked and resolved here:  previous question
but the syntax provided in the answer does not work for me.  All records are returned, not just the ones with the desired values.
This would be my version of the previous answer and it does not return a subset of values.  Everything is returned.
Select household_key, sm_subscription_id ,mytier
from #everything
where Mytier is not null
and Mytier IN (select MIN(mytier) from #everything group by household_key)
order by household_key

Could the fact that I have more than those 3 columns requested from the table be a factor?

A: You can use ROW_NUMER():
SUBSTRING(tier, 2, LEN(tier) - 1) will extract the numbers after 'T'. You can use the extracted string and CAST it to INT and use it in the ORDER BY clause of your ROW_NUMBER.
SQL Fiddle
WITH Cte AS(
    SELECT *,
        rn = ROW_NUMBER() OVER(
            PARTITION BY hh_key
            ORDER BY CAST(SUBSTRING(tier, 2, LEN(tier) - 1) AS INT)
        )
    FROM #everything
)
SELECT
    hh_key, sub_id, tier
FROM Cte
WHERE rn = 1
DROP TABLE #everything


text:
Q: Bash wait for copy to finish I have the following rename code being run via the OSX cron app Launch Control.
#!bin/bash
find /Volumes/COMMON-LIC-PHOTO/ASPERA/ASPERA_STAGING -mindepth 2 -type f -print0 | xargs -0 /usr/local/bin/rename -v 's/([0-9]*)_LK/$1_standard/' \;
find /Volumes/COMMON-LIC-PHOTO/ASPERA/ASPERA_STAGING -mindepth 2 -type f -print0 | xargs -0 /usr/local/bin/rename -v 's/([0-9]*)_ALT([0-9]*)/$1_alternate$2/' \;
find /Volumes/COMMON-LIC-PHOTO/ASPERA/ASPERA_STAGING -mindepth 2 -type f -print0 | xargs -0 /usr/local/bin/rename -v 's/([0-9]*)_SWATCH/$1_swatch/' \;

It's designed to rename certain files whenever a folder of files is copied to a directory called ASPERA_STAGING. The renaming works, the problem is that as soon as a folder starts copying to ASPERA_STAGING the script renames files before they are done copying. It's causing the computer to get confused and re-copy files. I tried adding Sleep but it's a terrible solution - there could be anywhere from 5-300 files in a folder so the copy times vary dramatically.
Is there something more complex that I could do to force the script to wait until all files in a folder have been copied before attempting the rename?


text:
Q: How to refresh the main frame when the child dialog do someting I want the main frame refresh to update the label When I click the "done" button on MyDialog, But now it doesn't work.
Does there anything wrong? Thanks.
This is the code:
MyDialog: the child dialog where there is a button on it to update the label of the main frame
MainFrame: the main Frame, there is a button on it to start my dialog
# -*- coding: utf-8 -*-

import wx

#Dialog
class MyDialog(wx.Dialog):
    """setting MyDialog."""
    def __init__(self):
        self.dlg_main = wx.Dialog.__init__(self, None, -1, title="setting", size=(300, 300))
        self.btn_ok = wx.Button(self, label="done", pos=(30, 30), size=(50, 26))
        self.Bind(wx.EVT_BUTTON, self.__OnButtonClick_save, self.btn_ok,)

    def __OnButtonClick_save(self, event):
        self.Destroy()
        main = MainFrame()
        **main.set_label_name('test')**
        main.Destroy()

def start_dialog():
    my_dialog = MyDialog()
    my_dialog.ShowModal()
    my_dialog.Destroy()

#Main Frame
class MainFrame(wx.Frame):
    def __init__(self):
        self.main_frame = wx.Frame.__init__(self, None, -1, title='simple', size=(400, 400))
        self.Centre()
        self.label_name = wx.StaticText(self, label="Hello,everyone", pos=(30, 30))
        self.btn_set = wx.Button(self, label="set", pos=(30, 60))
        self.Bind(wx.EVT_BUTTON, self.on_button_click, self.btn_set)

    def set_label_name(self, str):
        print(str)
        self.label_name.SetLabel('hello, Boys')

    def on_button_click(self, event):
        start_dialog()

def show_main():
    main = wx.App()
    main_win = MainFrame()
    main_win.Show()
    main.MainLoop()

if __name__ == '__main__':
    show_main()

A: I have got the method, thanks all!
The point is how to call the parent method, so , use self.parent.xxx to fix the problem.
The code like this:
# -*- coding: utf-8 -*-

import wx

#Dialog
class MyDialog(wx.Dialog):
    """setting MyDialog."""
    def __init__(self, parent, title):
        super(MyDialog, self).__init__(parent, title=title, size=(300, 300))
        self.parent = parent
        panel = wx.Panel(self)
        btn_ok = wx.Button(panel, label="done", pos=(30, 30), size=(50, 26))
        btn_ok.Bind(wx.EVT_BUTTON, self.__OnButtonClick_save)

    def __OnButtonClick_save(self, event):
        #THis is the different
        self.parent.set_label_name('test')
        self.Destroy()

def start_dialog():
    my_dialog = MyDialog()
    my_dialog.ShowModal()
    my_dialog.Destroy()

#Main Frame
class MainFrame(wx.Frame):
    def __init__(self):
        self.main_frame = wx.Frame.__init__(self, None, -1, title='simple', size=(400, 400))
        self.init_ui()

    def init_ui(self):
        self.label_name = wx.StaticText(self, label="Hello,everyone", pos=(30, 30))
        btn_set = wx.Button(self, label="set", pos=(30, 60))
        btn_set.Bind(wx.EVT_BUTTON, self.on_button_click)
        self.Centre()

    def set_label_name(self, str):
        self.label_name.SetLabel('hello, Boys')

    def on_button_click(self, event):
        my_dialog = MyDialog(self, "setting")
        my_dialog.ShowModal()
        my_dialog.Destroy()

def show_main():
    main = wx.App()
    main_win = MainFrame()
    main_win.Show()
    main.MainLoop()

if __name__ == '__main__':
    show_main()

Thanks for the idea in this answer Wxpython show dialog on main frame startup


text:
Q: generics and inheritance question I have three classes:
public abstract class fileHandler<Key extends Object, Value extends Object> {
}

public A extends fileHandler<String, String[]> {
}

public B extends fileHandler<String, String> {
}

Now in my main function i do something like this:
fileHandler file= null;
If (<condition>) {
    fileHandler = new A();
} else
    fileHandler = new B():
}

But this gives 2 compile time errors:

*

*Cannot convert A to fileHandler

*Cannot convert B to fileHandler

How can I get rid of these errors as I don't get this error if base class is not generic.
Update:
My class hierarchy is:

*

*class fileHandler<Key, Value> {     }

*class A extends fileHandler<String, String[]> {     }

*class B extends fileHandler<String, String> {     }

*class C that calls function gen(object of A) or

*class D that calls function gen(object of B).

*both C and D are derived from abstract class E.

Now how should I define these functions in C and D and E:
I gave the following:
E:
public abstract void gen (fileHandler A) throws exception;

C:
void gen (fileHandler A) throws exception;

D:
void gen (fileHandler A) throws exception;

C, D, and E give error fileHandler is raw type. Reference to generic type fileHandler(Key, Value) should be parameterized.

A: When you instantiate a generic type with different type arguments, the two instantiations are not type compatible.  Different instantiations of a generic type are not type-equivalent in the way that a class that inherits from another class is type-equivalent to that class, even when the type arguments themselves may be related by inheritance.  Genericity and polymorphism are two separate language features.
Your code is equivalent to the following:
// Java defaults unspecified type arguments to Object.
fileHandler<Object, Object> file;

if (...) {
   // Error: fileHandler<String, String> is not equivalent to fileHandler<Object, Object>
   file = new fileHandler<String, String>();
} else {
   // Error: fileHandler<String, String[]> is not equivalent to fileHandler<Object, Object>
   file = new fileHandler<String, String[]>();
}

If you truly want to isolate a polymorphic interface that is independent of the types used to instantiate your fileHandler class, then I would suggest you use an interface:
interface IFileHandler
{
    // If this interface needs to talk about keys and values, it
    // does so using only java.lang.Object.
}

public class fileHandler<Key extends Object, Value extends Object>
    implements IFileHandler
{
    // ...
}

public class A extends fileHandler<String, String>
{
    // ...
}

public class B extends fileHandler<String, String[]>
{
    // ...
}

IFileHandler file;

if (...) {
    file = new A();
} else {
    file = new B();
}

A: The problem is that you're trying to assign an instance to the class name. You should instead be saying
if (condition) {
   file = new A();
} else {
   file = new B();
}

"file" is the reference here "fileHandler" is the class name.
Cheers.

A: I get no compile error... if I fix all the error in your provided code
  class fileHandler<Key, Value> {
    }

  class A extends fileHandler<String, String[]> {
    }

  class B extends fileHandler<String, String> {
    }

then
fileHandler file= null;
if (/* condition */)
{
    file = new A();
}
else
{
    file = new B();
}

A: How you decide to fix this warning really depends on what you are trying to do and how strictly you want to restrict the allowed types for the parameter of gen().
Example 1
Very loose
abstract class E {
    public abstract void gen(fileHandler<?,?> A) throws Exception;
}

class C extends E {
    @Override
    public void gen(fileHandler<?,?> A) throws Exception {}
}

Example 2
Restrict Key generic to be a String
abstract class E {
    public abstract void gen(fileHandler<String,?> A) throws Exception;
}

class C extends E {
    @Override
    public void gen(fileHandler<String,?> A) throws Exception {}
}

Example 3
You probably want to name the unrestricted type so you can refer to it.
abstract class E {
    public abstract <Value> void gen(fileHandler<String,Value> A) throws Exception;
}

class C extends E {
    @Override
    public <Value> void gen(fileHandler<String,Value> A) throws Exception {}
}


text:
Q: Youtube iPhone URL shemes How can I launsh my app when there is a YouTube URL opened in Safari?
I searched on the Internet very long, but I didn't see a possibility to do this, because it is an http:// link. But the Google YouTube app does this, can anybody tell me how this works?
Thanks

A: There is no way you can launch your own app with YouTube link in Safari. Unlike Android Intents, iOS has only one way to launch other apps - url schemes. So when you're trying to open YouTube link in Safari it just calls
[[UIApplication sharedApplication] openURL: @"some url scheme"]

Where "some url scheme" is used internally (it is unknown) and only YouTube app can handle it.

A: The only way to do this, is to create your own URL Scheme, as denoted here - Implementing URL Schemes
You can then detect to modify any YouTube URLs so they fit in with your app's URL Scheme with JavaScript [webView stringByEvaluatingJavascriptFromString:yourJavaScript]
Here's the kicker. You can only modify pages from within your own web-browsing instance - i.e. creating a UIWebView inside your app, but then, your already in your app, which will render this entire exercise pointless.
You can however, use this method to communicate from within a suite of apps that you've built, so you could maintain your URL scheme across a web-browsing one, which will launch apps in your video playing one.
You can't do this with Mobile Safari though.
Sorry I couldn't be more help.


text:
Q: Calc for a Background-Position when a Calc is used for Width and Height I have a div, where I will put an icon from a file with a load of icons in it. I also need to scale the icon. So I use the normal width, height, background-position, background-size to sort it all out.
<div style="background: url(images/touchbuttons.png); width: min(10vw, 10vh); height: min(10vw, 10vh); background-position: -min(10vw, 10vh) 0px; background-size: 700% 200%;" >
</div>

The graphic has 7 icons wide and 2 icons high. (Hence the 700% and 200% on background-size.)
I calculate the width and height of the div based on 10% of the minimum of vw or vh.
No worries so far. To get the top left icon in the png file, background-position: 0px 0px; works perfectly.
Question: So how do I get the second icon in the png, ie 2nd to the right on the top row? When I do background-position: -min(10vw, 10vh) 0px;, which is the obvious choice, it gives the same result as background-position: 0px 0px;. It does not seem to be doing the calc. Why?


text:
Q: Shell overlay icon is not displayed I'm trying to implement custom overlay icons for my app. Here's the (simplified) code:
[ComVisible(true)]
[Guid("30BD35BE-D5CE-4751-A3B3-9D601F926E36")]
public abstract class OverlayIconBase : IShellIconOverlayIdentifier
{
    private const string OverlayIdentifiersKeyPath = @"SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\ShellIconOverlayIdentifiers";
    private readonly string _iconFileName;
    protected OverlayIconBase()
    {
        _iconFileName = GetType().Assembly.Location;
    }

    protected static void Register(Type type, string registrationName)
    {
        string guid = type.GUID.ToString("B").ToUpper();

        string keyPath = OverlayIdentifiersKeyPath + "\\" + registrationName;
        using (var key = Registry.LocalMachine.CreateSubKey(keyPath))
        {
            key.SetValue(string.Empty, guid);
        }

        NativeMethods.SHChangeNotify(SHChangeNotifyEvents.AssocChanged, SHChangeNotifyFlags.IdList, IntPtr.Zero, IntPtr.Zero);
    }

    protected static void Unregister(Type type, string registrationName)
    {
        string keyPath = OverlayIdentifiersKeyPath + "\\" + registrationName;
        Registry.LocalMachine.DeleteSubKeyTree(keyPath, false);

        NativeMethods.SHChangeNotify(SHChangeNotifyEvents.AssocChanged, SHChangeNotifyFlags.IdList, IntPtr.Zero, IntPtr.Zero);
    }

    public int IsMemberOf(string path, uint attributes)
    {
        try
        {
            return ShouldDisplay(path) ? WinError.S_OK : WinError.S_FALSE;
        }
        catch
        {
            return WinError.E_FAIL;
        }
    }

    public int GetOverlayInfo(IntPtr pwszIconFile, int cchMax, out int iconIndex, out uint flags)
    {
        iconIndex = 0;
        flags = 0;
        if (string.IsNullOrEmpty(_iconFileName) || fileName.Length + 2 > cchMax)
            return WinError.E_FAIL;

        int count = Encoding.Unicode.GetByteCount(_iconFileName);
        byte[] bytes = new byte[count + 2];
        Encoding.Unicode.GetBytes(_iconFileName, 0, _iconFileName.Length, bytes, 0);
        Marshal.Copy(bytes, 0, pwszIconFile, bytes.Length);
        iconIndex = IconIndex;
        flags = (uint) (ShellIconOverlayIdentifierFlags.ISIOI_ICONFILE | ShellIconOverlayIdentifierFlags.ISIOI_ICONINDEX);
        return WinError.S_OK;
    }

    public int GetPriority(out int priority)
    {
        priority = Priority;
        return WinError.S_OK;
    }

    // 0-100 (0: highest); typically 0
    protected virtual int Priority { get { return 0; } }

    protected abstract bool ShouldDisplay(string path);
    protected abstract int IconIndex { get; }
}

[ComVisible(true)]
[Guid("76344480-04C1-4D15-A0A5-578881CEF415")]
public class MyOverlayIcon1 : OverlayIconBase
{
    private const string RegistrationName = "MyOverlayIcon1";

    [ComRegisterFunction]
    static void Register(Type t)
    {
        Register(t, RegistrationName);
    }

    [ComUnregisterFunction]
    static void Unregister(Type t)
    {
        Unregister(t, RegistrationName);
    }

    protected override bool ShouldDisplay(string path)
    {
        /* some logic to decide if the overlay should be displayed... */
    }

    protected override int IconIndex
    {
        get { return 0; }
    }
}

The icons are embedded in the DLL using Win32Res as explained here.
By attaching to explorer.exe with Debugger.Launch, I was able to confirm that GetOverlayInfo and IsMemberOf work as expected, however the overlay is not displayed in the explorer.
What could be the problem?

A: You are probably running into a similar issue to what is talked about in this thread. Tortoise-svn icons not showing up under windows 7


text:
Q: Fragment vs Activity canvas drawing on android I designed a surfaceview, where it's canvas is drawn using a thread (Game loop). The Game loop draws 300 small images.
If I load this surfaceview on activity, the time to execute a frame is 5- 10 ms lower than if I load it on a fragment (withing an activity).
Test results
300 images loop- activity (24 millsec) , Fragment (32 millsec).
What is the reason behind this? How can I improve the performance in Fragment?
Here is my code. The loop at the end is the bottleneck. clusters  list could have 300 items to draw.
public List<PCluster> clusters = new ArrayList<PCluster>();

    public void doDraw(Canvas canvas) {

    try {
        if (canvas == null) {
            return;
        }
        super.draw(canvas);

        canvas.drawColor(backColor);
        if (waitTillLoad) {
            return;
        }

    } catch (Exception ex) {
    }
    final int savedState = canvas.save();
    try {

        minX = (int) (((viewWidth / mScaleFactor) - Gen.screenSizeWidth) / 2) * Utils.VIEW_SIZE;
        minY = (int) (((viewHeight / mScaleFactor) - Gen.screenSizeHeight) / 2) * Utils.VIEW_SIZE;

        if (mPosX > maxX) {
            mPosX = maxX;
        }
        if (mPosX < minX) {
            mPosX = minX;
        }
        if (mPosY > maxY) {
            mPosY = maxY;
        }
        if (mPosY < minY) {
            mPosY = minY;
        }

        canvas.scale(mScaleFactor, mScaleFactor);
        canvas.translate(mPosX, mPosY);

        long startTime = System.currentTimeMillis();
        if (!showBackground) {

            for (PCluster cluster : clusters) {
                if (cluster.isVisible) {
                    canvas.drawBitmap(cluster.Picture, cluster.BoardLocation.left,
                            cluster.BoardLocation.top, null);
                }
            }
            Log.d("myApp", "   " + (System.currentTimeMillis() - startTime));
        }

    } catch (Exception ex) {
    } finally {
        canvas.restoreToCount(savedState);
    }
}

This is main activity layout.  @+id/fragment is used to load the layout below     which has SurfaceView LinearLayout where the surface view is inserted at run time and where the drawing happens.
Main Layout
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >

<LinearLayout
    android:id="@+id/fragment_fake"
    android:layout_width="0dp"
    android:layout_height="0dp"
    android:gravity="center"
    android:orientation="vertical"
    android:layout_above="@+id/fragment"/>

<LinearLayout
    android:id="@+id/fragment"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:gravity="center"
    android:orientation="vertical"
    android:layout_above="@+id/fragment_ad"/>

 <fragment
    android:id="@+id/fragment_ad"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:layout_alignParentBottom="true"
    class="controllers.AdFragment" />

</RelativeLayout>

Game Layout with surface view
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal">

<LinearLayout
    android:id="@+id/surfaceView"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent"/>

<include
    android:id="@+id/gamesettingpanel"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_alignParentTop="true"
    layout="@layout/gameoption_panel" />

<include
    android:id="@+id/scorepanel"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_gravity="top"
    android:layout_alignParentTop="true"
    android:layout_centerHorizontal="true"
    android:gravity="center_horizontal"
    layout="@layout/scorepanel" />

<include
    android:id="@+id/chaetpanel"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_gravity="bottom"
    layout="@layout/gamecheat_panel" />

<include
    android:id="@+id/finishpanel"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_centerHorizontal="true"
    android:gravity="center_horizontal"
    android:layout_alignParentTop="true"
    layout="@layout/finishedpanel" />


text:
Q: Responsive and split layout I started a project with react-splitter-layout and material ui library.
I would like to find a way to create responsive components, with material ui Grid or Box component
I encounter a problem with responsive, I would like my left panel to be responsive (use of xs / md / lg) with Grid component based on the size of the container (not window size), as you can see in the example below , this is not the case. It's use the viewport size. (I know it's normal because of media queries).
Here the code sample : https://codesandbox.io/s/material-demo-i04rr?file=/demo.js (recommended to open the rendering in a new tab to see the problem)
import React from "react";
import { makeStyles } from "@material-ui/core/styles";
import Paper from "@material-ui/core/Paper";
import Grid from "@material-ui/core/Grid";
import SplitterLayout from "react-splitter-layout";

const useStyles = makeStyles(theme => ({
  root: {
    flexGrow: 1
  },
  paper: {
    padding: theme.spacing(2),
    textAlign: "center",
    color: theme.palette.text.secondary
  }
}));

export default function CenteredGrid() {
  const classes = useStyles();

  return (
    <SplitterLayout>

        <Grid container spacing={3}>
          <Grid item xs={4} md={6} lg={8}>
            <Paper className={classes.paper}>xs=3</Paper>
          </Grid>
          <Grid item xs={4} md={4} lg={2}>
            <Paper className={classes.paper}>xs=3</Paper>
          </Grid>
          <Grid item xs={4} md={2} lg={2}>
            <Paper className={classes.paper}>xs=3</Paper>
          </Grid>
        </Grid>

Panel 2

    </SplitterLayout>
  );
}

Anyone have a solution to this problem ?
Best regards,
EDIT
I also posted in material ui github https://github.com/mui-org/material-ui/issues/25189

A: This is one of my question when I started using material-UI or any CSS framework.
Material-UI currently supports almost cases you need especially for responsive, and I never use any other library/framework for responsive. First, you know that all xs, sm, md are based on screen size, not on their container.
Then, the problem here is how did you called a "container"? When you work with material-UI, you should layout everything based on screen size instead of a specific container. Because your "container" you are think about doesn't have any meaning in responsive. It just help you solve the layout problem.
To be honest, just change your mind, thinking in the way of Material-UI, and everything about responsive become easily.


text:
Q: Python Dictionary: Key with two values possible? For a test program I'm crawling a webpage. I'd like to crawl all activites for specifid ID´s which are associated to the respective cities.
For example, my initial code:
RegionIDArray = {522: "London", 4745: "London", 2718: "London", 3487: "Tokio"}

Im now wondering if its possible to sum up all IDs (values) which are related to e.g. London into one key:
RegionIDArray = {522, 4745, 2718: "London}

If I´m trying this, I get no results
My full code so far
RegionIDArray = {522: "London", 4745: "London", 2718: "London", 3487: "Tokio"}

for reg in RegionIDArray:
    r = requests.get("https://www.getyourguide.de/-l" +str(reg) +"/")
    soup = BeautifulSoup(r.content, "lxml")

    g_data = soup.find_all("span", {"class": "intro-title"})
    for item in g_data:
        POI_final = (str(item.text))

        end_final = ("POI: " + POI_final)
        if end_final not in already_printed:
           print(end_final)
           already_printed.add(end_final)

Is there any smart way.Appreciate any feedback.

A: You can do this in 2 steps:

*

*Create a dictionary mapping locations to list of IDs.

*Reverse this dictionary, taking care to ensure your keys are hashable.

The first step is optimally processed via collections.defaultdict.
For the second step, you can use either tuple or frozenset. I opt for the latter since it is not clear that ordering is relevant.
from collections import defaultdict

RegionIDArray = {522: "London", 4745: "London", 2718: "London", 3487: "Tokio"}

d = defaultdict(list)

for k, v in RegionIDArray.items():
    d[v].append(k)

res = {frozenset(v): k for k, v in d.items()}

print(res)

{frozenset({522, 2718, 4745}): 'London',
 frozenset({3487}): 'Tokio'}

A: You can use itertools.groupby:
import itertools
RegionIDArray = {522: "London", 4745: "London", 2718: "London", 3487: "Tokio"}
new_results = {tuple(c for c, _ in b):a for a, b in itertools.groupby(sorted(RegionIDArray.items(), key=lambda x:x[-1]), key=lambda x:x[-1])}

Output:
{(3487,): 'Tokio', (4745, 522, 2718): 'London'}

A: What you can do is make a reverse lookup table from the values to all working keys, like so:
def reverse(ids):
    table = {}
    for key in ids:
        if ids[key] not in table:
            table[ids[key]] = []
        table[ids[key]].append(key)
    return table


text:
Q: Which and what type indexes should i create to optimize these mysql querys? I'm thinking about creating an hashed index in (1) because it uses equalities and bit map on (2) because the state can only be 'accepted' or 'not accepted'. What else can i use? And also my problem is that i can only try b-tree indexes on mysql oracle..
(1)select R.user_id from rent as R
inner join supervise S on
R.adress = S.adress
and R.space_id = S.space_id
group by R.user_id
having count(distinct S.supervisor_id) = 1

(2) select distinct P.adress, P.code from space as P where (P.adress, P.code) not in (
select P.adress, P.code from space as P
natural join rent as R
natural join state as E where E.state = 'accepted')

A: Since there is no directly limiting criterias in query #1, it will likely be done using a merge join, and no index will improve that.
For query #2, how selective is the criteria E.state = 'accepted'? If very selective (< 5-15% of query result), then index on E.state, indexes for the joins from E to R and from R to P, and index on P.adress, P.code.

A: Composite index on each table:
INDEX(space_id, adress)

Don't use WHERE(a,b) IN ... -- it performs very poorly.
Don't use IN ( SELECT ... ) -- it often performs poorly.
Instead, use a JOIN.
For state, have
INDEX(state)

(or is it already the PRIMARY KEY?)
If you need more help after all that, provide SHOW CREATE TABLE and EXPLAIN SELECT ....


text:
Q: Swagger Gen V3 Not Resolving Internal $ref And Instead has Insane broken Import I am generating via a yaml file
apply plugin: 'java'

import io.swagger.codegen.DefaultGenerator
import io.swagger.codegen.config.CodegenConfigurator

def swaggerInput = "${rootDir}/BundledExports/API/POMOrchestrator.v1-Bundled.json"
def templatedir = "${rootDir}/templates".toString()
def swaggerOutputDir = file('application/')

task generateApi {
    inputs.file(swaggerInput)
    outputs.dir(swaggerOutputDir)
    doLast {
        def config = new CodegenConfigurator()
        config.setInputSpec(swaggerInput)
        config.setOutputDir(swaggerOutputDir.path)
        config.setIgnoreFileOverride(swaggerOutputDir.path)
        config.setLang('spring')
        config.setAdditionalProperties([
                'modelPackage'   : 'com.models.swagger',
                'modelNamePrefix': 'Party',
                'dateLibrary'    : 'java8',
                "fullJavaUtil"   : true,
                "library"        : "spring-boot",
                'templateDir'    : templatedir,
                'interfaceOnly'  : 'true'   // Generating the Controller API interface and the models only

        ])
        config.setImportMappings([
                'hello': 'com.models.Hello'
        ])
        new DefaultGenerator().opts(config.toClientOptInput()).generate()
    }
}

clean.doFirst {
    delete(swaggerOutputDir)
}

configurations {
    swagger
}

sourceSets {
    swagger {
        compileClasspath = configurations.swaggerCompile
    }
}

compileSwaggerJava.dependsOn generateApi
classes.dependsOn swaggerClasses
compileJava.dependsOn compileSwaggerJava

ext {
    swaggerVersion = '3.0.20'
    SwaggerGenerators = '1.0.20'
}

dependencies {

    compile sourceSets.swagger.output
    compile "io.swagger.codegen.v3:swagger-codegen:$swaggerVersion"
    compile "io.swagger.codegen.v3:swagger-codegen-generators:$SwaggerGenerators"

}

And I have a very large json file.  I am unable to share the whole thing.  But here is the problem.  Internal $ref on this line:
                                        "op": {
                                            "$ref": "#/definitions/OnboardingRequest/properties/customers/items/properties/controlPersons/items/properties/op"
                                        }

And here is the definition in the correct path
                                        "op": {
                                            "type": "string",
                                            "title": "FieldOperation",
                                            "enum": [
                                                "ADD",
                                                "UPDATE",
                                                "REMOVE"
                                            ]
                                        }

When I generate, here is what I get:
...
import com.models.swagger.PartyOnboardingRequestpropertiescustomersitemspropertiescontrolPersonsitemspropertiesop;
...

@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class PartyInvestmentExperience   {

  ...

  @JsonProperty("op")
  private PartyOnboardingRequestpropertiescustomersitemspropertiescontrolPersonsitemspropertiesop op;

  ...

Which does not compile because there is no class with that huge name.  I have been searching all over the internet and have not been able to find how to make this resolve.  I was wondering if maybe it is too deep being like 10 levels but there are other references deeper that get resolved correctly.  SO I am at a loss as to how to fix this.
Also, I have had the json validated and it had not errors.


text:
Q: RequestContext.RouteData and Request.UrlReferrer info is lost on FormMethod.Post I am trying to post a form with one of the variables being the Action of the previous URL, however whenever I POST it, the variable becomes null. How can I persist that info at least until it reaches the POST Action?
I've tried using both Url.RequestContext.RouteData.Values["action"] and Request.UrlReferrer to get the Action.
In my View I'm trying to POST a file, Action name, and an id:
Html.BeginForm("Edit", "Expenses", FormMethod.Post, new { enctype = "multipart/form-data", actionName = actionName, id = idInt })
If I keep it the way it is, the Action name is null, but if I remove the FormMethod.Post portion from the BeginForm method, the Action name is posted successfully and the file is null.

A: You are using the Html.BeginForm helper method incorrectly! You mixed route values and html attributes to a single object !
Your current call matches the below overload
public static MvcForm BeginForm(
    this HtmlHelper htmlHelper,
    string actionName,
    string controllerName,
    FormMethod method,
    IDictionary<string, object> htmlAttributes
)

The last parameter is the htmlAttributes. So with your code, it will generate the form tag markup like this
<form action="/Expenses/Edit" actionname="someActionName" enctype="multipart/form-data"
                                                                     id="22" method="post">

</form>

You can see that Id and action became 2 attributes of the form !
Try this overload where you can specify both route values and htmlAttributes
@using (Html.BeginForm("AddToCart", "Home",  new {  actionName = "Edit", id = 34 },
                                 FormMethod.Post,new { enctype = "multipart/form-data", }))
{
        <input type="submit"/>
}

which will generate the correct form action attribute value using the route values you provided.


text:
Q: adding new hosts in icinga web Using Ubuntu 12.10 server.
icinga with idoutils and icinga-web.
Have ability to see hosts if I add them in the localhost_icinga.cfg
however from my understanding you can create a host.cfg based on systems.
example: windows.cfg to monitor all windows machines via NSclient++ (similar to Nagios)
Everytime I create a new host.cfg icinga either gives me a duplicate error or it does not like the define host line.
 Example:
    (localhost_icinga.cfg working)
define host{
     use generic-host
     host_name  mikedoppdesk
     alias  mikedoppdesk
     address 192.168.0.56
}
 However if I create a windows.cfg
 Example:
   define host{
      use windows
      host_name mikedoppdesk
      alias mikedoppdesk
      address 192.168.0.56
}
and use: /usr/sbin/icinga -v /etc/icinga/icinga.cfg
output error line 1 windows.cfg
I have been chasing the icinga web docs trying to get a straight answer. I know I am missing something critical but cannot find rhyme or reason.
Please educate or prove me dumb.
Thanks in advance

A: In your main configuration file which is usually /usr/local/icinga/etc/icinga.cfg you should add a line with no spaces at the beginning:
cfg_file=/usr/local/icinga/etc/conf.d/hosts.cfg

(you can see it here as well: http://docs.icinga.org/latest/en/configobject.html).
It means that you define objects (here hosts) in the file specified above. In that file you should define the monitored host itself
Example:
 define host{
        host_name                       bogus-router
        alias                           Bogus Router #1
        address                         192.168.1.254
        parents                         server-backbone
        check_command                   check-host-alive
        check_interval                  5
        retry_interval                  1
        max_check_attempts              5
        check_period                    24x7
        process_perf_data               0
        retain_nonstatus_information    0
        contact_groups                  router-admins
        notification_interval           30
        notification_period             24x7
        notification_options            d,u,r
        }

All possible options and their definitions you can be found here (http://docs.icinga.org/latest/en/objectdefinitions.html#objectdefinitions-host).


text:
Q: Is it possible to have custom JSON serialzier specific to endpoint? I would like to output the very same class with different set of fields in different endpoints.
Is it possible?

A: Yes you can do that with Jackson's @JsonView support in RESTEasy Reactive.
See this for more details.
For even more advanced customization, you can use @CustomSerialization, as mentioned here.

A: No, but you can output string. You will have full control over serialization that way.


text:
Q: How to connect google sheet with power bi? I am trying to connect google sheet with power bi using R Studio, there is a video on youtube by stephnie locke, but that is just a short video and dont help completely. any one there which can help properly and completely.

A: An easier way:
Go to Get data, search Web.
Select Web
Select Web
on the URL.
-> Modify the URL.
From:
https://docs.google.com/spreadsheets/d/emphasized textgoogle-sheet-guid/edit?usp=sharing
To:
https://docs.google.com/spreadsheets/d/google-sheet-guid/export?format=xlsx&id=google-sheet-guid
Paste.
Paste link
And there is your sheet.
Select your sheet

A: To build upon @Joseph A's perfect answer, if you would like to make it refreshable after publishing your report to the Power BI service from Desktop:

*

*Navigate to the workspace where the report is published (i.e. My Workspace)

*Click Datasets

*Under Actions, click the ellipses and choose Settings

*Expand Data source credentials and click Edit Credentials

*Change Authentication method to Basic

*Enter User Name and Password of Google Docs account where the file resides and click Sign In

Your report can now be refreshed and updated (manually or scheduled) to reflect changes in your Google Sheets doc!

A: If you're not limited to R Studio, there is another way to access Google Sheet data from Power BI:
Sample data:

*

*Get shareable link of the Google Sheet (Permission at least Anyone with the link can view):

*Modify the shareable link and add the following parts:
From:
https://docs.google.com/spreadsheets/d/google-sheet-guid/edit?usp=sharing
To:
https://docs.google.com/spreadsheets/d/google-sheet-guid/export?format=xlsx&id=google-sheet-guid
e.g.
https://docs.google.com/spreadsheets/d/1ohAz8SD6viEGIrcor-JC-vCt2yRbgY1c-7Uflv-_hrA/edit?usp=sharing
->
https://docs.google.com/spreadsheets/d/1ohAz8SD6viEGIrcor-JC-vCt2yRbgY1c-7Uflv-_hrA/export?format=xlsx&id=1ohAz8SD6viEGIrcor-JC-vCt2yRbgY1c-7Uflv-_hrA

*Create a blank query in Power BI and get the source as below:
let
    Source = Excel.Workbook(Web.Contents("the-link-in-step-2"), null, true)
in
    Source

*If you drill into the Table cell you should be able to see the data and work from there.


text:
Q: How to get origin data of renderer console in electron The first, Happy new year 2021.
I'm working with ElectronJS. I want to control the console of the renderer.
In the main process, I have been listen event console-message.
But when I use console.log to print the object, I have received [object Object] message.
Example: I print:
var a = {
    b: 'c'
};
console.log(a);

I have received: [object Object]
How can I get the value is:
{ b: 'c' } // <-- Origin data

Origin data maybe any type: object, array, function and any more.
Thanks in advance for any help

A: Convert your object to String so you can print or alert it.

console.log(JSON.stringify(a,null,2))

//to print with functions, undefined, NaN, etc.

function printAnything(o) {
  var out = '';
  for (var p in o) {
    out += p + ': ' + o[p] + '\n';
  }
  console.log(out);
}

printAnything(a);


text:
Q: Detecting if HDMI input is currently the TV's selected source, using Raspberry PI I am using a RPi connected through HDMI to a Samsung TV. I am attempting to trigger RPi processes so that they are only active when the HDMI output is being used by the TV. Effectively, I would like to start the process when the correct HDMI input is selected from the TV and terminate it when another TV source is selected.
I have tried to use tvservice –s for that end, but the command's output does not change depending on whether the TV is configured to use the RPi's HDMI or any other source.
Therefore, I welcome suggestions on what other mechanisms could be used (e.g. low-level drivers, libCEC, xrandr) to determine if the TV is currently using the RPI's HDMI.
Thanks!

A: HDMI sink devices (like TVs) no longer break the HDMI "handshake" when switching sources.  When HDMI was young, switching sources would take 3-6 seconds... generally with a black screen during the interim.   TV consumers found this unacceptable, so manufacturers created inputs which were "always on."  This makes the connection appear to remain on even when switched.

A: You may try
"tvservice --name"
I have tried without connecting display it replied with
"[E] No device present"
Maybe it replies with Name of Tv when connected.

A: No matter how I try to use tvservice -s or tvservice -m and no matter if TV is on, stand by or off, it still reports same value state 0x120001 [TV is off]. My TV is some older Samsung, device is RPi 4B.
The only solution I found to detect the TV is on or goes to stand by is by using cec-ctl -m which monitors CEC commands. When TV goes to stand by it sends a message containing STANDBY text. So I monitor CEC and grep first STANDBY message, then I poweroff RPi.
cec-ctl -m --tv | grep -m 1 STANDBY.
Maybe this will help someone. I can post my full shell script if someone find it interesting.


text:
Q: InApp Purchase product list doesn't load in iPhone app I am trying to use a consumable InApp Purchase in my iPhone app. I am using this tutorial for reference. I have followed the tutorial correctly. But my products are not loading. Here is my code.
+ (RageIAPHelper *)sharedInstance {
static dispatch_once_t once;
static RageIAPHelper * sharedInstance;
dispatch_once(&once, ^{
NSSet * productIdentifiers = [NSSet setWithObjects:
                                  @"com.ilfmobile.hero.twohundredconnects",
                                  @"com.ilfmobile.hero.onethousandconnects",
                                  nil];

 sharedInstance = [[self alloc] initWithProductIdentifiers:productIdentifiers];
});
return sharedInstance;
}

And my get product list code.
- (void)reload {
     products = nil;
     [MBProgressHUD showHUDAddedTo:self.view animated:YES];
     [[RageIAPHelper sharedInstance] requestProductsWithCompletionHandler:^(BOOL success, NSArray *theProducts) {

     [MBProgressHUD hideAllHUDsForView:self.view animated:YES];
     if (success) {
        products = theProducts;
        [self.tblview reloadData];
    }
    }];
}

And I  implement the  InApp purchases in Xcode Capabilities. I have attached screenshots as below.
I have enabled InApp Purchases on iTunes Connect and added both of the products in the InApp list.

Please suggest where I am wrong. Thank you for giving your precious time to suggestion. I am using Xcode5.1 and my app development target iOS7.1

A: It may happen if you are not running your app in Device. ios simulator cause these type or issues.

A: Create your certificates again and test your app in iPhone or iPad device.


text:
Q: Vb.net Webbrowser dropdown value changes but event doesn't trigger I am working on a way to navigate a webpage through code.  If you manually navigate to the page if you pick an option from the dropdown the page changes based on the option chosen.
When trying in code I can get the value to change according to what I want, however the page doesn't automatically change afterwards.  I want to be able to invoke the onsubmit to get the page to change based on the option selected.
I have tried
Dim option As HtmlElement = WebBrowser1.Document.GetElementById("Account")
option.SetAttribute("value", "1")
option.SetAttribute("selected", "selected")

Along with various combinations of RaiseEvent and InvokeMember with "onChange", "click", "submit", "onSubmit", etc on the form, input, and select

<form action="javascript:void(0);" id="StatementssFilterForm" onsubmit="updateView('StatementsContainer','/Secure/Statements/StatementByAccountAndDate', this);">
<input type="submit" id="StatementsFilterSubmit" class="chaseutil-hide" />

        Account
        <Select id="Account" class="chasejs-submitsform chaseanalytics-track-option" name="Account">
            <Option Value="1" Selected="Selected">Option 1</Option>
            <Option Value="2">Option 2</Option>
            <Option Value="3">Option 3</Option>
            <Option Value="4">Option 4</Option>
            <Option Value="5">Option 5</Option>
        </Select>

How can I programatically get the event to trigger?
The following is the UpdateView function
var updateView = function(a) {
return function(b, c, d, e, f, g) {
    var h = a(".chasejs-isexpanded");
    if (h.length) {
        h.removeClass("chasejs-isexpanded")
    }
    var i, j, k = a(d),
        l = false;
    if (b.jquery) {
        i = b;
        j = i.attr("id")
    } else {
        if (b.tagName) {
            i = a(b);
            j = i.attr("id")
        } else {
            i = a("#" + b);
            j = b
        }
    }
    l = i.hasClass("chasejs-show-overlayspinner");
    if (d && (optionSelectedIsIgnored(d) || optionSelectedIsFlyout(d) || optionSelectedIsModal(d) || optionSelectedIsInstructionText(d) || optionSelectedIsFlyoutNav(d))) {
        return
    }
    if (e && i.is(".chasejs-hasbeenupdated")) {
        return false
    }
    if (d && k.is(".chasejs-flyoutlink")) {
        if (k.not(".chasejs-triggeredupdateview").length) {
            k.click(function() {
                if (k.not(".chasejs-triggeredupdateview").length) {
                    k.addClass("chasejs-triggeredupdateview");
                    updateView(b, c, d, e, f)
                }
            })
        }
    }
    var m = "GET";
    var n;
    var o = function(a) {
        updateViewCallback(i, a, d, j, g);
        i.trigger("updateViewCompleted")
    };
    var p = getViewportHeight();
    var q = displaySpinnerDiv(i, l);
    var r = displayDefaultError(i);
    if (c.indexOf("PropertiesList") > -1) r = '

We\'re unable to process your request. Our system is temporarily unavailable. We apologize for any inconvenience. Please try again later.

';
    var s = function() {
        i.fastempty().append(r)
    };
    if (f) {
        var t = new Object;
        a.each(f, function(b, c) {
            var d = a("#" + c);
            var e = d.attr("name");
            if (!e) {
                e = c
            }
            var f = d.attr("type");
            var g;
            if (f == "checkbox" || f == "radio") {
                g = d.prop("checked")
            } else {
                g = d.attr("value")
            }
            t[e] = g
        });
        c = appendQueryParameters(c, t)
    }
    if (k.is("form")) {
        formHandler(k);
        k.find(".chasejs-cleardefault").each(function() {
            removeDefaultValue(this)
        });
        n = k.serialize();
        k.find(".chasejs-cleardefault").each(function() {
            restoreDefaultValue(this)
        });
        m = "POST";
        try {
            a(window).attr("postedform", d)
        } catch (u) {}
    }
    if (i.is("#chasejs-contexthelpfloater")) {
        i.find(".chaseui-contexthelpcontentbody").fastempty().append(q)
    } else if (isDesignFamily.BP()) {
        q = '

';
        i.fastempty().append(q);
        a(".chaseui-modalheader").css("border", "none")
    } else if (i.is(".chaseutil-suppress-spinner")) {
        i.fastempty()
    } else if (k.is(".chaseui-eip-buttonsubmit") && i.is(".chaseui-summaryblock")) {
        var v = a(".chaseui-eip-innercontainer").parent(".chaseui-eip-outercontainer").find("form");
        v.find(".chasejs-cleardefault").each(function() {
            removeDefaultValue(this)
        });
        DisableEditInPlaceCloseButton(true);
        n = v.serialize();
        m = v.attr("method");
        a(".chaseui-eip-innercontainer").fastempty().append(q)
    } else if (l) {
        i.append(q)
    } else {
        i.contents().hide().end().append(q)
    }
    if (isDesignFamily.Mol()) {
        a("div.chaseui-ajaxloader > img").addClass("chaseui-ajaxloader_new")
    } else {
        if (a("div.chaseui-ajaxloader").height() > p) {
            a("div.chaseui-ajaxloader > img").addClass("chaseui-ajaxloader_new")
        }
    }
    if (k.is("not:(.chasejs-flyoutlink)")) {
        a("#chasejs-contexthelpfloater").remove()
        }
        i.addClass("chasejs-hasbeenupdated");
        chasejax({
            url: c,
            type: m,
            dataType: null,
            data: n,
            $errorContainer: i,
            success: o,
            error: s
        })
    }
}(nisijQuery);


text:
Q: Responsive versions not working although viewport tag i'm working on a website where the responsive versions are not working (both on browser and on device). The mobile version is actually getting the queries but some issues are still occurring.
And yes i have already used the viewport tag as it follows:
<meta name="viewport" content="width=device-width, initial-scale=1">

Here's the link of the website: http://www.zetasportitalia.com/


text:
Q: Is it possible to programmatically define a new function in a given namespace? I'm currently bringing a system under test that has never been under test previously (nor was really written with testing in mind). I have to edit the source code as little as humanly possible. This is a directive from on high, not my own idea. Ideally, I accomplish my aim without editing any source code at all.
A function I'm testing uses the built-in function file(). Previously, I've faked built-in functions by, in my test case, creating a new function, with the same name, in the same namespace as the function I'm testing, since PHP will search in the same namespace first.
namespace My\Function\Namespace

class MyClass
{
    public function theMethodImTesting()
    {
        file(...);
        ...
    }
}

namespace My\Function\Namespace

function file()
{
    \\ fake stuff for testing
}

namespace My\Testsuite\Namespace

class MyTestsuite
{
    ...
}

This has worked when I wanted to fake out the method for the entire test suite, but now I've encountered a case where I want to fake the function for just a single test.
Is there any way to programmatically define a function, inside a namespace?

A: Here's something that you could do using built-in PHP functionality.
Warning
This is a bit awkward (and might not work in every situation), therefore I wouldn't recommend this unless you can't use any of the stuff rightfully recommended in the comments (although I'm not familiar with them, so I can't be sure).
It should however do the job, despite how ugly it looks (yes, it does make use of the universally hated eval, but since it's for testing purposes, it should never deal with non-controlled input anyway).
Stuff that you only need to define once (and should be in its own file)
Now that this is out of the way, here it is. You add the following code somewhere, which defines the fake function and then all the (actual) fake functions you want (such as file), under a specific namespace:
namespace Fake\BuiltIn\Functions;

/**
 * Executes the given statements using fake built-in functions.
 *
 * @param callable $statements Statements to execute.
 * @return mixed Whatever $statements returns.
 * @throws \ReflectionException
 */
function fake(callable $statements)
{
  $function = new \ReflectionFunction($statements);

  $start_line = $function->getStartLine();
  $end_line = $function->getEndLine();
  $function_source = implode('',
    array_slice(file($function->getFileName()), $start_line - 1, $end_line - $start_line + 1));

  if (preg_match('/(?<={).*(?=})/s', $function_source, $matches)) {
    $function_body = $matches[0];
    $namespace = __NAMESPACE__;

    return eval("
      namespace $namespace;
      $function_body
    ");
  }

  throw new \RuntimeException('Failed to execute statements.');
}

// Below are all the fake functions

function strlen($string) {
  return 'fake result';
}

Usage
Then, whenever you need to call a chunk of code using the fake functions, you replace:
function myTestFunction() {
  // some code
  $length = strlen($mystring);
  // some code
}

with:
use function Fake\BuiltIn\Functions\fake;

function myTestFunction() {
  fake(function () {
    // some code
    $length = strlen($mystring);
    // some code
  });
}

In short, you just add fake function () { before the chunk and close it with } below. This requires minimal editing as requested.
Explanation
Basically, eval appears to be the only built-in way of evaluating, at runtime, a specific chunk of code in the context of a given namespace (unless you can call that chunk within its own namespace to begin with, obviously).
The fake function:

*

*receives a callable (the statements to execute),

*uses reflection to retrieve the statements' code,

*uses evals to evaluate these statements under the fake namespace.

Demo
https://3v4l.org/LriLW


text:
Q: How to get the current value from the foreach loop using jquery and codeigniter Here is my code:

        <a data-toggle="modal" data-target="#modal_edit" onclick="modal_edit('<?php echo base_url() ?>leave/save')"   class="btn btn-default pull-right" href=""> Add Leave

Employee Leave History

                    #
                    Employee Name
                    Leave Type
                    Subject
                    From date - To date
                    Reason
                    Status

                <?php $count = 1 ?>
                <?php foreach ($leave as $leave): ?>

                        <?php echo $count++ ?>
                        <?php echo $leave->first_name . ' ' . $leave->last_name ?>
                            <input type="button" id="employee_id" value="<?php echo $leave->employee_id ?>"/>

                        <?php echo $leave->name ?>
                        <?php echo $leave->subject ?>
                        <?php echo $leave->from_date . ' - ' . $leave->to_date ?>
                        <?php echo $leave->reason ?>

                            <select  id="status" data-plugin-selectTwo class="form-control populate placeholder" >
                                <option value="Pending">Pending</option>
                                <option value="Granted">Granted</option>
                                <option value="Rejected">Rejected</option>
                            </select>

                <?php endforeach; ?>

I have foreach loop and there is a drop-down list with values. If i have 4 loops then I want to update leaves for only 1-st loop, means id = 1, using ajax it works perfectly.
Now I want to update the leave for id = 2 but the problem is, jquery is not getting the id = 2 value, it selects the first id value means id =1 .
now I would like to update the id = 2 to update their leave as well.

A: You can't use same id multiple times.
First change in your html
<?php foreach ($leave as $leave): ?>

    <?php echo $count++ ?>
    <?php echo $leave->first_name . ' ' . $leave->last_name ?>
        <input type="button" class="employee_id" value="<?php echo $leave->employee_id ?>"/>

    <?php echo $leave->name ?>
    <?php echo $leave->subject ?>
    <?php echo $leave->from_date . ' - ' . $leave->to_date ?>
    <?php echo $leave->reason ?>

        <select  id="<?php echo $leave->employee_id ?>" class="status" data-plugin-selectTwo class="form-control populate placeholder" >
            <option value="Pending">Pending</option>
            <option value="Granted">Granted</option>
            <option value="Rejected">Rejected</option>
        </select>

<?php endforeach; ?>

In Javascript:

I hope this will solve your problem.


text:
Q: how to retrieve data form post API flutter im beginner in flutter, i want to get data form API but the API is 'post' tipe. how to retrieve the data? please help me. thank you (:
example, i have API data "post" and the data is 'phonenumber', 'password', 'address', 'name', 'class'. how to get all of the data and show/display it all?

A: I have a code snippet of it which you can refer
This is about calling the POST API of the student and pass the credentials as a body.
Future<Map<String, dynamic>> loginUser(String phone, String pass) async {
    http.Response response = await http.post(
      EndPoint.Login,
      body: jsonEncode(
        {
          "phonenumber": phone,
          "password": pass,
        },
      ),
      headers: {"Content-Type": "application/json"},
    );
    var parsed = jsonDecode(response.body);
    Map<String, dynamic> authfailed = {};
    if (parsed['message'] == "Auth failed") {
      authfailed['message'] = "Auth failed";
      return authfailed;
    }
    // print(parsed);
    return parsed;
  }


text:
Q: Get Revit Workshared cloud model as C# Autodesk.Revit.DB Document class I have a Revit plug-in, I want it to do some operations on a workshared cloud model.
I can't figure out how to get the Revit model as a Document class (Autodesk.Revit.DB)
which is stored live on BIM360 cloud, not a local copy, nor downloaded copy.
Seems like I have to use different API's and there are multiple steps to this although
I was expecting something relatively simpler, I quickly realised this actually may have
multiple steps which I honestly can't figure out.
Is there a working relevant code example on git hub for this ?
Edit: I was able to find the below code but it doesn't compile
because ForgeClient and OSSObjectsApi doesn't exist in the latest
forge sdk package, how can I fix that ?
using System;
using System.IO;
using System.Threading.Tasks;
using Autodesk.Forge;
using Autodesk.Forge.Model;
using Autodesk.Forge.Client;
using Newtonsoft.Json.Linq;

namespace BIM360Downloader
{
    class Program
    {
        static void Main(string[] args)
        {
            // These are the client ID and client secret that you obtained
            // when you registered your application on the Forge developer portal.
            string clientId = "YOUR_CLIENT_ID";
            string clientSecret = "YOUR_CLIENT_SECRET";

            // Replace these with the project ID and file ID of the model you want to download.
            string projectId = "YOUR_PROJECT_ID";
            string fileId = "YOUR_FILE_ID";

            // Create a new Forge API client.
            ForgeClient client = new ForgeClient(clientId, clientSecret);

            // Get the access token for the client.
            TwoLeggedApi oauth = new TwoLeggedApi();
            dynamic token = oauth.Authenticate(clientId, clientSecret, "client_credentials", new Scope[] { Scope.DataRead });
            string accessToken = token.access_token;

            // Set the bearer token for the client.
            client.Configuration.AccessToken = accessToken;

            // Download the model from BIM 360.
            MemoryStream modelStream = DownloadModelAsync(client, projectId, fileId).Result;
            Console.WriteLine("Successfully downloaded model to memory stream.");
        }

        static async Task<MemoryStream> DownloadModelAsync(ForgeClient client, string projectId, string fileId)
        {
            // Set up the request to download the model.
            OSSObjectsApi objectsApi = new OSSObjectsApi();
            dynamic objectDetails = await objectsApi.GetObjectDetailsAsync(projectId, fileId);
            string bucketKey = objectDetails.bucketKey;

            // Download the model data.
            dynamic data = await objectsApi.GetObjectAsync(bucketKey, fileId);
            byte[] modelData = data.Body;

            // Create a new MemoryStream object to store the model data.
            MemoryStream modelStream = new MemoryStream(modelData);
            return modelStream;
        }
    }
}

A: To open a live Revit Could Model (RCM), you can use ModelPathUtils.ConvertCloudGUIDsToCloudPath() to convert the project and model guid into a ModelPath. You can then use this ModelPath to open the document using Application.OpenDocumentFile() method.
Also read the sections Getting the CloudPath for a Model and SaveAsCloudModel Information from the Web Browser in this link on how to find the account, project, and model guids of the model you are interested in.
var cloudModelPath = ModelPathUtils.ConvertCloudGUIDsToCloudPath(region, projectGuid, modelGuid);
Document doc = app.OpenDocumentFile(cloudModelPath, new OpenOptions());

This code will work in a desktop addin as long as a valid user is logged in and that user has access to the input model. While you have not explicitly mentioned that you need this to work on Design Automation for Revit, you have added the tag #autodesk-designautomation to your question. The good news is the same code above should work for Design Automation addin (app bundle), but there is an extra step on how to provide user context to the design automation job. Please refer to this blog post and github sample for Design Automation for RCM.


text:
Q: Feature Linked Annotation, annotation does not behave the way the labels do (extra line space) I created a feature-link annotation layer by converting labels created in MapPlex to annotation.  I'm using a balloon callout label and my label expression has tags that change the font size (label font size is 8) on a second line, example:
[name] & vbnewline &"<fnt size = '5'>" &[other_name] &"</fnt> "

After converting the labels to annotation, the appearance is really nice and compact. But if I change the attributes of the source feature or add a new feature, the annotation changes in appearance such that it looks like extra space is added between the two lines.  It is as if the second line has a height of 8 point when I want it to be 5. I've tried looking through the annotation attribute table as well as compare the label properties, tab by tab, to find differences between the two different appearances but am unable to find any.  I can create work-arounds, but because there are so many labels to be placed, I'd really prefer the compact version. Anyone else run across this?
Here is a visual:

A: It's one of those things, if you look at it long enough, the solution comes into focus:  I switched the font size of the default label and the tags, so my new expression, with the label as a 5 point font, is:
"<fnt size = '8'>" &[name] & "</fnt> "& vbnewline &[other_name]

Now I have nice compact labels!


text:
Q: Class properties not applying to all divs I am creating a footer section which has 4 div each having a common class. The first div for some reason is taking more width than it should be taking. The remaining 3 div are taking the width of the elements in it, why isn't it the case with the first div?. I know I can change the dimensions of that div manually, but I want to know the reason why this is happening.

Also, I set a align-items: flex start for all the div, but the property only seems to apply to the first div.
My HTML and CSS Code:

#footer{
  background-color: #1a1a1a;
  height:60vh;
  display: flex;
  align-items: center;
  justify-content: center;
}

#footer .container{
  display: flex;
  flex-direction: column;
  align-items: flex-start;
  justify-content: center;
  margin-right: 2rem;
}

.contact-handle img{
  width: 20%;
}

#footer h4{
  color: white;
  font-weight: 500;
  font-size: 18px;
}

#footer p{
  color: grey;
  font-size: 1rem;
  margin:0;
  margin-bottom: 1rem;
}

#footer i{
  color: grey;
  margin-right: 1rem;
}

Contact

Address: XXX ABCDE Road, Street 32, Mumbai

Phone: (+91) 01234 56789/(+01) 2222 365

Hours: 10:00 - 18:00, Mon - Sat

Follow Us

About

About Us

Delivery Information

Privacy Policy

Terms & Conditions

Conatct Us

My Account

Sign In

View Cart

My Wishlist

Track Order

Help

Install App

A: I'm a little unclear on what you are asking for from the question. However, it appears you have nothing actually setting the dimensions of the divs. That first div with class of container is simply larger because of the info that is in it.
If you change the justify-content: center; in your #footer selector
to justify-content: space-between;
it should give you what I suspect is the desired effect, where everything is spaced evenly.
Also, I wanted to note you are talking about a header but your HTML you posted has a section id of footer. Be sure to check everything in your question before you post to avoid any future confusion.

A: A slightly different approach would be to add the  element as the parent and set the background-color and height to that element. Remove height: 60vh; and use height: 100%; with padding to get that extra space. Then just set align-items: flex-start; on #footer.

footer {
  height: 100%;
  background-color: #1a1a1a;
  padding: 4em 1em;
  /* add padding instead of 60vh height */
}

#footer {
  display: flex;
  align-items: flex-start;
  justify-content: center;
}

#footer .container {
  display: flex;
  flex-direction: column;
  align-items: flex-start;
  justify-content: center;
  margin-right: 2rem;
}

.contact-handle img {
  width: 20%;
}

#footer h4 {
  color: white;
  font-weight: 500;
  font-size: 18px;
}

#footer p {
  color: grey;
  font-size: 1rem;
  margin: 0;
  margin-bottom: 1rem;
}

#footer i {
  color: grey;
  margin-right: 1rem;
}

Contact

Address: XXX ABCDE Road, Street 32, Mumbai

Phone: (+91) 01234 56789/(+01) 2222 365

Hours: 10:00 - 18:00, Mon - Sat

Follow Us

About

About Us

Delivery Information

Privacy Policy

Terms & Conditions

Conatct Us

My Account

Sign In

View Cart

My Wishlist

Track Order

Help

Install App

You can also try this Fiddle for Sahil. This version allows the footer to stretch full width and divides each column width for equal spacing.

A: Your particular case can be solved by using rem or em unit
What really happened?
when you use flex, the size of each containers are on auto adjusted based on the largest intrinsic dimension of the element inside.
In the first div, it's your image which has the largest intrinsic dimension.
When you tell the image to have 20% of the parent container's width (that's what % means - relative to parent container) the image adjust accordingly. And if you check the width of the parent container, it retained the exact intrinsic value of the image dimension.
I'm not sure why it behaves the way it does (someone more knowledge can comment), the best approach is to usually avoid using % in general and use rem/em.
Here's one using rem:

footer {
  height: 100%;
  background-color: #1a1a1a;
  padding: 4em 1em;
  /* add padding instead of 60vh height */
}

#footer {
  display: flex;
  align-items: flex-start;
  justify-content: center;
  /* use space-around */

}

#footer .container {
  display: flex;
  flex-direction: column;
  /* align-items: flex-start; */
  justify-content: center;
  margin-right: 2rem;
}

img {
  width: 5rem;
}

#footer h4 {
  color: white;
  font-weight: 500;
  font-size: 18px;
}

#footer p {
  color: grey;
  font-size: 1rem;
  margin: 0;
  margin-bottom: 1rem;
}

#footer i {
  color: grey;
  margin-right: 1rem;
}
<<!DOCTYPE html>

    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" type="text/css" href="style.css">
    <title></title>

Contact

Address: XXX ABCDE Road, Street 32, Mumbai

Phone: (+91) 01234 56789/(+01) 2222 365

Hours: 10:00 - 18:00, Mon - Sat

Follow Us

About

About Us

Delivery Information

Privacy Policy

Terms & Conditions

Conatct Us

My Account

Sign In

View Cart

My Wishlist

Track Order

Help

Install App


text:
Q: JPA Date and Timezone confusion I'm having a problem reading dates from a database using JPA. I'm using EclipseLink and PostgreSQL
I've populated my database from a CSV file, witch had dates as strings (in this format: 6/30/2009-23:59:56). I used the following snipet to convert it to a Date object:
public static Date parseDate(String s){
    DateFormat formatter = new SimpleDateFormat("d/M/yyyy-k:m:s");
    try {
        return new Date( ((java.util.Date)formatter.parse(s)).getTime() );
    } catch (ParseException ex) {
        Logger.getLogger(Type.class.getName()).log(Level.SEVERE, null, ex);
        return null;
    }
}

The date is correctly converted and stored in the database as expected. Here is how i map the Date object to the database:
@Column(name="data_ts", nullable=false)
@Temporal(TemporalType.TIMESTAMP)
private Date dataTs;

The problem seems to happen when i try to read the Date from the database to use it in a chart(Highcharts). The record with that same timestamp above get read as:
Mon Jun 06 23:59:56 BRT 2011 and it's timestamp as 1307415596000
Note that it is in Brazilian Time(+3h), so the timestamp (that is calculated from GMT) is 3 hours shifted. Once ploted, the timestamp turns to point to 07/06/2011 02:59:56
Here's an example:
List<TimedataEnt> timeData = currentWellsite.getTimeData();
String debug = timeData.get(timeData.size()-1).getDataTs().toString() + ">>>" + timeData.get(timeData.size()-1).getDataTs().getTime();

where currentWellsite is and JPA Entity, and getDataTs() returns a java.util.Date object.
The string turns out to be "Tue Jun 30 23:59:56 BRT 2009>>>1246417196000"
How do I tell JPA not to convert the timestamp read from the database?

A: As said, Date and Timestamps have no timezone consideration. It seems that the issue is caused because Java considers that the time it reads from the database is the current default timezone.
So, if the database contais 2011-04-04 14:00:00 and my current timezone is +3, assigning that to java Date will generate 2011-04-04 14:00:00 BRT time(+3), with a timestamp shifted 3 hours (since timestamps are caclulated from UTC).
Solved the issue by getting an calculated timestamp:
long ts = myDate().getTime() + TimeZone.getDefault().getRawOffset();

It's important to say that getRawOffset() does not take Daylight Saving periods in consideration. For that, use getOffset()

A: Your date is 6/30/2009-23:59:56. I read that as 30 june 2009, 23:59:56. So the format to parse it should be M/d/yyyy-HH:mm:ss or M/d/yyyy-kk:mm:ss (depending on if your hours go from 1 to 24 or from 0 to 23). But definitely not d/M/yyyy-k:m:s: the month comes before the day.
Also, a Timestamp doesn't have any time zone. It's a universal instant in time. It's only when you display its value that the timezone is important, because then you have to choose which time zone to use to display the time. Use a DateFormat with the appropriate timezone set to display your timestamp.

A: Your issue seems to be that you are storing your Timestamp (which does not have a timezone) into a java.util.Date (which has a timezone offset).
If you want control over how the timezone is set, then store your Timestamp as a java.sql.Timestamp, or use your own @Converter.
In general Calendar should be used in Java instead of java.util.Date, which is for the most part deprecated.  Calendar also has a Timezone, so you may have similar issues.


text:
Q: Relationship Between Theoretical Moments and Sample Moments When studying "Moments" in Probability and Statistics, we are told the following. Given a random variable $x$ with a probability distribution function $f(x)$:

*

*The theoretical $k$-th moment is given by : $\int_{x} x^k \cdot f(x) \mathrm{d}x$
Now, suppose we have some measurements $x_1, x_2... x_n$. For these observations (regardless of our assumption on their probability distribution):

*

*The sample $k$-th moment is given by: $\frac{1}{n} \sum_{i=1}^n x_i^k$
For me, the definition of the theoretical moment seems reasonable because it depends on the probability distribution. For example, the k-th moment of a Normal Distribution (i.e. Gaussian Distribution) would be completely different than the k-th moment of an Exponential Distribution.
However, I find the idea of the sample moment to be more confusing. This time around, regardless of the probability distribution being assumed, the k-th order Moment for all probability distributions is identical. This brings me to my question:

*

*Is this true only by definition? Otherwise, why should the k-th order sample Moment not depend on a probability distribution?

Thanks!


text:
Q: Could someone explain where BatchNorm is performed in ResNeXT https://github.com/facebookresearch/ResNeXt neural network? I was reading the original paper that described ResNeXT   (variation of Resnet) at https://arxiv.org/pdf/1611.05431.pdf.
On Page-5 top right column, it says:

ReLU is performed right after eachBN, expect for the output of the
  block where ReLU is per-formed after the adding to the shortcut,
  following [14].

This sentence doesn't make sense, esp the part after comma "expect for the output of....".

*

*Could someone explain what this sentence means?

*Where is BN performed?

A: ResNeXt uses the same conv-bn-relu policy as ResNet. Scheme is following:

You can check scheme for ResNet in official ResNet repo.
Probably you were confused by the typo in the paper: the word "expect" you should read as "except".


text:
Q: Refresh DataGridView cell values immediately I have a DataGridView with two checkbox columns. When any rows on both of them are checked, I want to clear the checkmarks. The grid is populated from a DataTable. It works like this:
if (bothColumnsAreChecked)
{
    DataRow first = SelectedFirstItems.First();
    DataRow second = SelectedSecondItems.First();

    // stuff...

    first["IsCheckedFirst"] = false;
    second["IsCheckedSecond"] = false;
}

As per this, I have modified the code to fire the CellValueChanged event immediately after clicking the checkbox, not when losing focus:
void brandsGridView_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
    brandsGridView.CommitEdit(DataGridViewDataErrorContexts.Commit);
}

The problem is that, after clearing the checkmarks, one of the rows is still selected (because I just clicked on a checkbox in that row), and the checkmark on this row is still visible -- it doesn't disappear until I unselect the row. How do I achieve that? I tried:
1) Refresh() on the grid. No avail; the grid is refreshed, but not redrawn before moving the cursor.
2) CommitEdit() and EndEdit(). This doesn't even clear the last selected checkbox.
What can I do?
EDIT: I'm bad at explaining. Here's a simple walkthrough:
There are two checkbox columns: c1 and c2.
1) I click c1 on row r1. c1 becomes checked and r1 becomes selected.
2) I click c2 on row r2 (or even r1). c2 becomes checked and r2 becomes selected.
3) c1 and c2 are now cleared (after logging checkbox info somewhere).
The problem is that, while the chackmark disappears from c1 in r1, it stays there, in the checkbox on r2, until r2 loses focus.
Hope that helps.

A: It's a bit clearer right now. You could always deselect rows in dgv, but I don't know if that's what you're after
brandsGridView.ClearSelection();

A: I think the easies way is to first set up binding for this DataGridView like:
DataGridView dg = new DataGridView();
DataTable dt = GetDataTable();
dg.DataSource = dt;

And then when you want to refresh it you set up binding again. Yes, I realize it is dirty hacky way but it is the easiest.
DataTable dt = GetDataTable();
dg.DataSource = dt;

Old answer:
I think you could use BindingGroup for that:
http://msdn.microsoft.com/en-us/library/system.windows.data.bindinggroup.aspx

A: I had a very similar problem. (Well it is a different context, but the problem was the same)
After a lot of trying and reading, this and other related threads, I found a solution. It is a bit rudimentary but it works for me.
The problem was related with the DataGridView having the focus. So I changed momentarily the focus to another control (a button for example) and then brought it back to the DataGridView
In your case could be like this:
button1.focus();
if (bothColumnsAreChecked)
{
    DataRow first = SelectedFirstItems.First();
    DataRow second = SelectedSecondItems.First();

    // stuff...

    first["IsCheckedFirst"] = false;
    second["IsCheckedSecond"] = false;
}
brandsGridView.focus();

I hope it could help. But if someone finds a better solution or a more detailed explanation about why this is happening. It would be highly appreciated.

A: Using the following command after setting the desired cell values worked for me, which I found on a Microsoft forum thread.
brandsGridView.RefreshEdit();


text:
Q: Azure AD Conditional Access Audit Log? Looking for any documentation or reference for Azure AD Conditional Access Audit\Sign-In Logs. For example, i'd like to generate a report of all users who have been blocked due to a defined Conditional Access Policy.
It seems that events (such as blocking users through policy) do not appear in the Azure Active Directory Sign-In or Audit logs. Are these events recorded anywhere within OMS \ Azure Reporting?

A: If you go to Sign-ins logs, you can see a dropdown for Conditional Access where you can check if users are blocked.


text:
Q: Getting wrong result after Subtracting a day from a date Using LocalDateTIme and ZonedDateTime I am testing with "2016-03-28T02:00:00+0200" (1459123200 in UTC Sec.)
After subtracting 1 day, DST is applied and output should be:

"2016-03-27T03:00:00+0200"

But I am getting this:

2016-03-26T01:00+01:00[Europe/Stockholm]

CODE:
public class DateFormatSampleCode {
    public static void main(String[] args)
    {
        LocalDateTime localDateTime = LocalDateTime.ofEpochSecond(1459123200, 0, ZoneOffset.UTC);

        System.out.println(localDateTime);
        localDateTime = localDateTime.minusDays(1);
        System.out.println(localDateTime);

        ZonedDateTime zonedDateTime = ZonedDateTime.of(localDateTime, ZoneId.of("Europe/Stockholm"));

        System.out.println(zonedDateTime);
    }
}

Please check and point out where I am going wrong.

A: Good you found a solution, I'd just like to add some insights and suggest a little improvement to your answer.
Setting the JVM default timezone using TimeZone.setDefault is not the best way to achieve this. Although it might work for most times, it's a little risky and error prone if you consider this code running in a more complex environment.
That's because TimeZone.setDefault changes the default timezone for the whole JVM. Any other application running in the same JVM will be affected by it. Other parts of the same application will also be affected, and even this same code running in multiple threads might give you wrong results (and race conditions are hard to debug).
I noticed that you're using TimeZone.setDefault(TimeZone.getTimeZone(timezone));. This means that you are  already working with a specific timezone, so there's no need to rely on the JVM's default. If you have a specific timezone name, just use it instead of the default. So I suggest you that the addDays method should be like this:
public ZonedDateTime addDays(long myUTCTimeInSeconds, int days, String timezone) {
    // get the instant from the UTC seconds
    Instant instant = Instant.ofEpochSecond(myUTCTimeInSeconds);
    // get the instant at the specified timezone
    ZonedDateTime z = instant.atZone(ZoneId.of(timezone));

    // add days
    return z.plusDays(days);
}

The improvements made:

*

*plusDays already subtracts 1 day if you pass -1 to it. There's no need to check the value and use abs method.

*don't use the JVM default timezone: instead of ZoneId.systemDefault(), use the timezone that you already have (the one you were using in the setDefault method)

*instant.atZone is equivalent to ZonedDateTime.ofInstant. IMO, atZone is more "readable", but in this case it's a matter of choice and code-style. It doesn't make difference in the final result.

With this, you could do:
// call directly, no need to change the default timezone
System.out.println(addDays(1459123200, -1, "Europe/Stockholm"));

This will print:

2016-03-27T03:00+02:00[Europe/Stockholm]

A: I think I can answer my above question.
Here is the code.
public ZonedDateTime addDays(long myUTCTimeInSeconds, int days) {
    Instant instant = Instant.ofEpochSecond(myUTCTimeInSeconds);
    ZonedDateTime dateTimeWithOffSet = ZonedDateTime.ofInstant(instant, ZoneId.systemDefault());
    if (localDays >= 0) {
        dateTimeWithOffSet = dateTimeWithOffSet.plusDays(localDays);
    } else {
        dateTimeWithOffSet = dateTimeWithOffSet.minusDays(abs(localDays));
    }
    return dateTimeWithOffSet;
}

If the timezone is different from that of system, we can set the Default TimeZone and after calling above method reset the timezone as:
TimeZone systemDefaultTimeZone = TimeZone.getDefault();
TimeZone.setDefault(TimeZone.getTimeZone(timezone));

addDays(1459123200, 1);
TimeZone.setDefault(systemDefaultTimeZone);


text:
Q: PhoneGap - setInterval() fails to execute I am trying to build a PhoneGap app that updates the Location every few seconds.  I have tired to impliment the setInterval() function.  But it fails to run!
My code segment looks like this...
// Set time interval and keep excuting every 3 secs
var i = 0;
setInterval(GetCurrentPosition(), 3000); // this will call GetCurrentPosition() each 3 sec

function GetCurrentPosition() {
    // retrieve your info here
    console.log('i = ' + z i);
    i = i + 1;
    navigator.geolocation.getCurrentPosition(onSuccess, onError);
}

As you can see I added a counter to see if it is firing... it only fires when I call it manually.
Anyone got any suggestions to what I am doing wrong or need to add to correct my error?
Thanks

A: The way you use setInterval is incorrect. You should pass the reference to the function like this:
setInterval(GetCurrentPosition, 3000);


text:
Q: Is there a way to apply a color from a text string in flutter? I have a ListView that is being populated by data returned from an HTTP GET Request. The request returns String values for an id, label, and color. I would like to use the color string that the GET Request returns to create a small colored container on the left of the ListTile. I have everything built but cannot figure out how to take the string returned by the GET Request and use it to specify the color.
The code for the ListView:
Widget buildList (AsyncSnapshot<ButtonsModel> snapshot) {
  return ListView.separated(
    padding: EdgeInsets.symmetric(vertical: 8),
    itemCount: snapshot.data.buttons.length,
    separatorBuilder: (BuildContext context, int index) => Divider(),
    itemBuilder: (BuildContext context, int index) {
      return ListTile(
        leading: Container(
          width: 10,
          decoration: BoxDecoration(
            color: Colors.green, //Should be the color returned from the HTTP GET Request
            borderRadius: BorderRadius.circular(10),
            ),
        ),
        title: Text(snapshot.data.buttons[index].label),
      );
    },
  );
}

A: You would want to implement something like this. You would have a map of all possible color names mapped to the Color you then when you get the color name you just reference the map.
const Map<String, MaterialColor> kColors = {
  'Red': Colors.red,
  'Teal': Colors.teal,
  'Blue': Colors.blue,
  'Aqua': Colors.cyan,
  'Amber': Colors.amber,
  'Green': Colors.green,
  'Indigo': Colors.indigo,
  'Light Blue': Colors.lightBlue,
  'Lime': Colors.lime,
  'Orange': Colors.orange,
  'Pink': Colors.pink,
  'Purple': Colors.purple,
  'Yellow': Colors.yellow,
  'Brown': Colors.brown,
};

Widget buildList (AsyncSnapshot<ButtonsModel> snapshot) {
  return ListView.separated(
    padding: EdgeInsets.symmetric(vertical: 8),
    itemCount: snapshot.data.buttons.length,
    separatorBuilder: (BuildContext context, int index) => Divider(),
    itemBuilder: (BuildContext context, int index) {
      return ListTile(
        leading: Container(
          width: 10,
          decoration: BoxDecoration(
            color: kColors[snapshot.data.buttons[index].color],
            borderRadius: BorderRadius.circular(10),
            ),
        ),
        title: Text(snapshot.data.buttons[index].label),
      );
    },
  );
}

If you want to keep your main file clean you can keep your map in a constants file.

A: first the color should be an int .
here is a method to set the color so you can save it on your backend
int setProfileColor(Color color) {
   String colorString = color.toString();
   String valueString = colorString.split('(0x')[1].split(')')[0];
   int colorInt = int.parse(valueString, radix: 16);
   return colorInt;
}

then to use it all you need is to put that int inside a color widget
 color: Color("The int value you get from the request")


text:
Q: How to define an inductive predicate inside locale? Here is an example of a simple locale:
locale test =
  fixes test_less_eq :: "'a ⇒ 'a ⇒ bool"
begin

inductive test_eq where
  "test_less_eq x y ⟹ test_less_eq y x ⟹ test_eq x y"

end

It defines inductive test_eq. It can be defined using definition, but I need it to be an inductive predicate.
Then I define a trivial interpretation of the locale and try to use it:
interpretation interp: test "op <" .

inductive some_pred where
  "interp.test_eq x y ⟹
   some_pred x y"

code_pred [show_modes] some_pred .

The problem is that I get the following error for code_pred:
Type mismatch of predicate test.test_eq (trying to match ?'a
                   ⇒ ?'a ⇒ bool and ('a ⇒ 'a ⇒ bool)
                                      ⇒ 'a ⇒ 'a ⇒ bool) in ?x1 < ?y1 ⟹
          ?y1 < ?x1 ⟹ interp.test_eq ?x1 ?y1

What is a cause of the error and how to fix it?

A: The predicate compiler has never been localized, i.e., it cannot directly deal with predicates that are defined inside a locale. There are two ways to make this work nevertheless.
Either, use global_interpretation with a defines clause to introduce a new constant for the predicate (plain interpretation only introduces an abbreviation). Then, you also have to re-declare the introduction rules to code_pred and prove the corresponding elimination rule.
global_interpretation interp: test "op <"
  defines interp_test_eq = interp.test_eq .

declare interp.test_eq.intros[code_pred_intro]

code_pred interp_test_eq by(rule interp.test_eq.cases)

Or, leave the interpretation as is and re-declare the introduction rules of the internal constant to which the definition in the locale is mapped. This is <locale_name>.<predicate_name>, i.e., test.test_eq in your case. This works only if your locale has no assumption.
declare test.test_eq.intros[code_pred_intro]

code_pred test.test_eq by(rule test.test_eq.cases)


text:
Q: How to print associated data in the index view $subjects = $this->Subjects
    ->find('all', [
        'contain'=> [
            'Users'
        ],
        'fields'=> [
            'Users.username',
            'Users.email'
        ]
    ])
    ->hydrate(false)
    ->toArray();

$this->set('subjects', $subjects);

how can i loop the data in the INDEX view of Subjects controller to display like this image

A: I tested it. E.g This is your subject array.
<?php
$array = array(
    0 => array(
        'Users'=>
        array('name' => 'John Doe',
        'email' => 'john@example.com'
        )
    ),
    1 => array(
        'Users'=>array(
        'name' => 'Abs Doe',
        'email' => 'jane@example.com'
        )
    ),
);
?>

This is loop in your index file.

        name
        email

        <?php foreach($array as $subject) :?>

                <?=$subject['Users']['name']?>
                <?=$subject['Users']['email']?>

        <?php endforeach;?>

It's worked as expected.

I can not give you answer. Because, I don't have access to your environment. But, at least you can get idea which code need amend.
Hope this help.

A: Sample Result from your vardump :
<?php
$array = array(
    0 => array(
        'math'=>40,
        'english'=>40,
        'history'=>40,
        'science'=>40,
        'user_id'=>64
        'user'=>
            array(
            'id' => 6
            'name' => 'User',
            'email' => 'user1@sample.com'
            )
    )
);
?>

This is the sample code writing based on the vardump you provided:

    /// Give your table headers

    <?php foreach($subjects as $subject) :?>

            <?=$subject['math']?>
            <?=$subject['english']?>
            <?=$subject['history']?>
            <?=$subject['science']?>
            <?=$subject['user_id']?>
            <?=$subject['user']['id']?>
            <?=$subject['user']['name']?>
            <?=$subject['user']['email']?>

    <?php endforeach;?>

A: Do play some css first. Hopefully, this code snippet can help you.
You need to do some changes in this.
'fields'=> [
        'Users.username',
        'Users.email',
        //add more fields that you want to display here
]

         math
         english
         history
         science
         id
         user_id
         username
         email

        <?php foreach($subjects as $subject) :?>

                <?=$subject['Users']['match']?>
                <?=$subject['Users']['english']?>
                <?=$subject['Users']['history']?>
                <?=$subject['Users']['science']?>
                <?=$subject['Users']['id']?>
                <?=$subject['Users']['user_id']?>
                <?=$subject['Users']['username']?>
                <?=$subject['Users']['email']?>

        <?php endforeach;?>


text:
Q: Godaddy ASP.NET membership database woes I purchased a Windows shared hosting account on godaddy that came with 2 MSSQL databases. I setup one to hold my site data and the other installed aspnet membership schema to store site members. The site works perfectly even displaying data from the 1st database. However when I try to login or register I get this nasty error

Exception Details:
  System.Configuration.Provider.ProviderException:
  The SSE Provider did not find the
  database file specified in the
  connection string. At the configured
  trust level (below High trust level),
  the SSE provider can not automatically
  create the database file.

Ive gone through my web.config and there's nothing wrong with my 2 connection strings. It seems godaddy has a problem with using 2 mssql databases simultaneously when 1 is for membership.
Does anyone know a solution or a workaround?

A: I hope my experience benefits every one. Basically if you want to avoid aspnet membership problems on godaddy always use "LocalSqlServer" as the connectionstring. i.e
<providers>
    <remove name="AspNetSqlMembershipProvider" />
    <add name="AspNetSqlMembershipProvider" connectionStringName="LocalSqlServer"
        ..other attributes here... />
</providers>

Then create the "LocalSqlServer" connectionString...remember to remove it first
<connectionStrings>
    <remove name="LocalSqlServer"/>
    <add name="LocalSqlServer"
        connectionString="Data Source=xxxx; Initial Catalog=xxx; User ID=xxx; Password=xxx;"
        providerName="System.Data.SqlClient" />
</connectionStrings>

A: I ran into same problem and am using MVC3. Above solution works but with some other changes in MVC3. It took me long time to figure it out so if anybody has similar issue in MVC3 it might help them:
Search for "connectionStringName" in web.config and replace the name with connectionStringName="LocalSqlServer"
Also under connectionstrings make sure
-To add  (As this is important for all who are using shared hosting it will replace machine.config LocalSqlServer connectionstring with yours.)
-Keep your current connectionstring (In my case it is FilmiDb, this is required for you to connect to the database in EF model. Without this you will get errors.)
<connectionStrings>
    <remove name ="LocalSqlServer"/>
    <add name="LocalSqlServer" connectionString="Data Source=.\SQLExpress;Initial Catalog=SofilmiDb;Integrated Security=SSPI" providerName="System.Data.SqlClient" />
    <add name="FilmiDb" connectionString="Data Source=.\SQLExpress;Initial Catalog=FilmiDb;Integrated Security=SSPI" providerName="System.Data.SqlClient" />
  </connectionStrings>