text:
Q: Android: Sugar ORM No Such Table Exception I am getting the No Such table exception when i am Using Sugar ORM with GPU image Android Library. I am using Gradle and Android Studio. Once i remove GPU image this issue is solved. So i don't know whats causing this exception. Details about this exception are also being discussed in this git issue
and it seems a lot of people are still facing it.
My crash log is posted below
> 10-09 11:30:21.511 4326-4831/com.example.app E/SQLiteLog: (10) Failed
> to do file read, got: 0, amt: 100, last Errno: 2 10-09 11:30:26.506
> 4326-4831/com.example.app E/SQLiteLog: (1) no such table: IMAGE 10-09
> 11:30:26.516 4326-4831/com.example.app E/AndroidRuntime: FATAL
> EXCEPTION: AsyncTask #1 10-09 11:30:26.516 4326-4831/com.example.app
> E/AndroidRuntime: java.lang.RuntimeException: An error occured while
> executing doInBackground() 10-09 11:30:26.516
> 4326-4831/com.example.app E/AndroidRuntime:     at
> android.os.AsyncTask$3.done(AsyncTask.java:299) 10-09 11:30:26.516
> 4326-4831/com.example.app E/AndroidRuntime:     at
> java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:352)
> 10-09 11:30:26.516 4326-4831/com.example.app E/AndroidRuntime:     at
> java.util.concurrent.FutureTask.setException(FutureTask.java:219)
> 10-09 11:30:26.516 4326-4831/com.example.app E/AndroidRuntime:     at
> java.util.concurrent.FutureTask.run(FutureTask.java:239) 10-09
> 11:30:26.516 4326-4831/com.example.app E/AndroidRuntime:     at
> android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230) 10-09
> 11:30:26.516 4326-4831/com.example.app E/AndroidRuntime:     at
> java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1080)
> 10-09 11:30:26.516 4326-4831/com.example.app E/AndroidRuntime:     at
> java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:573)
> 10-09 11:30:26.516 4326-4831/com.example.app E/AndroidRuntime:     at
> java.lang.Thread.run(Thread.java:838) 10-09 11:30:26.516
> 4326-4831/com.example.app E/AndroidRuntime:  Caused by:
> android.database.sqlite.SQLiteException: no such table: IMAGE (code
> 1): , while compiling: SELECT * FROM IMAGE 10-09 11:30:26.516
> 4326-4831/com.example.app E/AndroidRuntime:     at
> android.database.sqlite.SQLiteConnection.nativePrepareStatement(Native
> Method) 10-09 11:30:26.516 4326-4831/com.example.app E/AndroidRuntime:
> at
> android.database.sqlite.SQLiteConnection.acquirePreparedStatement(SQLiteConnection.java:886)
> 10-09 11:30:26.516 4326-4831/com.example.app E/AndroidRuntime:     at
> android.database.sqlite.SQLiteConnection.prepare(SQLiteConnection.java:497)
> 10-09 11:30:26.516 4326-4831/com.example.app E/AndroidRuntime:     at
> android.database.sqlite.SQLiteSession.prepare(SQLiteSession.java:588)
> 10-09 11:30:26.516 4326-4831/com.example.app E/AndroidRuntime:     at
> android.database.sqlite.SQLiteProgram.<init>(SQLiteProgram.java:58)
> 10-09 11:30:26.516 4326-4831/com.example.app E/AndroidRuntime:     at
> android.database.sqlite.SQLiteQuery.<init>(SQLiteQuery.java:37) 10-09
> 11:30:26.516 4326-4831/com.example.app E/AndroidRuntime:     at
> android.database.sqlite.SQLiteDirectCursorDriver.query(SQLiteDirectCursorDriver.java:44)
> 10-09 11:30:26.516 4326-4831/com.example.app E/AndroidRuntime:     at
> android.database.sqlite.SQLiteDatabase.rawQueryWithFactory(SQLiteDatabase.java:1314)
> 10-09 11:30:26.516 4326-4831/com.example.app E/AndroidRuntime:     at
> android.database.sqlite.SQLiteDatabase.queryWithFactory(SQLiteDatabase.java:1161)
> 10-09 11:30:26.516 4326-4831/com.example.app E/AndroidRuntime:     at
> android.database.sqlite.SQLiteDatabase.query(SQLiteDatabase.java:1032)
> 10-09 11:30:26.516 4326-4831/com.example.app E/AndroidRuntime:     at
> android.database.sqlite.SQLiteDatabase.query(SQLiteDatabase.java:1238)

A: I had the same problem, it's related to Instant Run. Disable instant run, reinstall the application, and it works.
See this link for details on how to enable or disable Instant Run.

A: Disable your instant Run go to
File > settings > Build, Execution, Deployment > Instant Run

A: Resolved
I don't know but the SugarDb.onCreate is not called. So put this code in MainActivity.onCreate and the Sugar ORM will work
    SugarDb db = new SugarDb(this);
    db.onCreate(db.getDB());

A: If you are using Android studio 2.0
Having same issue!
So instant run is not compatible with Sugar ORM

*

*open setting

*

*now run your project

Enjoy!

A: To create model tables, I use to execute this for all my models once my Application starts:
Book.findById(Book.class, (long) 1);
Car.findById(Car.class, (long) 1);

My Application extends SugarApp, so this forces Sugar to create all tables.
On the other hand, to update your database, you have to change your version to 2.
And finally, having an empty constructor is a must.
Hope this helps! ;)

A: In my case, I removed the following line from AndroidManifest.xml and it works!

A: I was also having this issue, my class only had 1 String property. I was using version 1.3. Just comment this code from AndroidManifest.xml file and you're good to go :)
<meta-data
 android:name="DOMAIN_PACKAGE_NAME"
 android:value="com.project.database.entities" />

Reference:

https://github.com/satyan/sugar/issues/75

A: I had this problem. I executed all suggestions posted here. But neither worked. Then I applied all together, and finally got rid of that problem. What I did-
1. Disabled instant run. (as Parth Vora said.)
2. Then I added the following class-

   import android.app.Application;
   import android.content.res.Configuration;
   import com.orm.SugarApp;
   import com.orm.SugarContext;

   public class SugarOrmTestApplication extends SugarApp {

      @Override
      public void onConfigurationChanged(Configuration newConfig) {
         super.onConfigurationChanged(newConfig);
      }

      @Override
     public void onCreate() {
        super.onCreate();
        SugarContext.init(getApplicationContext());
        Book.findById(Book.class, (long) 1);
     }

     @Override
     public void onLowMemory() {
       super.onLowMemory();
     }

     @Override
     public void onTerminate() {
       super.onTerminate();
     }
 }

 3. Modified manifest file-
    <application
      //Added the following lines-
       android:name="SugarOrmTestApplication">
       <meta-data android:name="DATABASE" android:value="sugar_example_new.db" />
       <meta-data android:name="VERSION" android:value="2" />
       <meta-data android:name="QUERY_LOG" android:value="true" />
    </application>

And this is my model class-
public class Book extends SugarRecord {
   String title;
   String edition;

   public Book(){
   }

   public Book(String title, String edition){
      this.title = title;
      this.edition = edition;
   }
}

Now my application works good.

A: I was facing the same issue. Disabling "Instant run" didn't solve the problem. I didn't enable proguard too. Later I removed all meta data of sugarORM from android manifest (except query log) and that solved the problem. So remove the following 3 lines from android manifest:
    <meta-data android:name="DATABASE" android:value="edikodik.db" />
    <meta-data android:name="VERSION" android:value="2" />
    <meta-data android:name="QUERY_LOG" android:value="true" />

EDIT:
As per comment of jrhamza, if above solution doesn't work, try disabling Instant Run.

A: Did you try to change version to 2??? This could be different version, try other values as well.
Also, make sure you do have empty constructor on your SugarRecord classes.
Change de database name if you are using then is another approuche.
If you are creating the table without unistalling the app, please make the version number +1.

A: I had the same problem and solved it not by disabling instant run but by changing my:
<meta-data android:name="VERSION" android:value="1" />

to
<meta-data android:name="VERSION" android:value="2" />

Since the lowest value should be 2

A: As mentioned by others, Android Studio instant run might be the problem (known SugarORM issue), try to turn it off.
However, I've had the same problem, and that wasn't sufficient for me, the problem persisted. I fixed this by changing allowBackup="true" in my manifest to false, running the app, and remove > re-install the app afterwards.
Why I guess that's the problem: I found out my preferences were kept saved even after re-installation. If this also happens to the corrupt SQL table (due to instant run), then even re-installation wouldn't fix it. My problem was immediately fixed after changing allowBackup to false and re-installing. I'm not yet able to reproduce the error, so cannot reproduce the fix either.
Hope this addition might help anyone from headaches like me!

A: I am using version 1.5 and have tried many ways here but not work.
And I found the solution!
This will force to create tables when starting the app:
public class SugarOrmTestApplication extends SugarApp {
    @Override
    public void onCreate() {
        super.onCreate();
        SugarContext.init(getApplicationContext());

        // create table if not exists
        SchemaGenerator schemaGenerator = new SchemaGenerator(this);
        schemaGenerator.createDatabase(new SugarDb(this).getDB());
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
    }

    @Override
    public void onLowMemory() {
        super.onLowMemory();
    }

    @Override
    public void onTerminate() {
        super.onTerminate();
        SugarContext.terminate();
    }
}

A: If you add new model(new table) in your code, you need change version of database in Manifest file. New value > Old value (update)
 <meta-data
            android:name="VERSION"
            android:value="1"/>

A: I also faced this Problem. After hunted 2 days, I solved it by following tricks In android studio
Step 1. Write compile 'com.github.satyan:sugar:1.5' in dependencies  in build.gradle file of app
Step 2. Write classpath 'com.android.tools.build:gradle:2.1.0' in dependencies of build.gradle file of project
Step 3. DB version should greater than 1 always as documented in sugarORM

A: When you're starting initial development and don't want to have to increase your Database version for changes made during quick iterations of your models (something I do a lot while I'm fleshing out unforeseen requirements), use this during your applications start-up:
SugarDb sugarDb = new SugarDb(getApplicationContext());
new File(sugarDb.getDB().getPath()).delete();
Model.findById(Model.class, (long) 1); // Perform this for each SugarRecord  model

// Insert test data:
Modelrecord = new Model("Model Title", "Model content", false);
record.save();

Be warned - this will remove all data from your database so persisted changes between debug sessions won't work, however it does allow you to release version 1 of your app version 1 of your database.
I do not recommend doing this after version 1 has been officially released, make sure you log ALL changes needed using the SugarORM Migration Method.

A: Make sure the meta data package name points to where you've put your model entities not app package name

A: For me the Issue was, In my app I had two different Database. so, I only changed the  from version 1 to version 2. My first DB had version 1

A: As stated in the README from the github repo, if you are using proguard, you should ensure that entities remain un-obfuscated so table and columns are named correctly.
To do so, add this line to proguard-rules.pro:
-keep class com.yourpackage.yourapp.domainclasspackage.** { *; }

A: In my case it's problem of library Sugar. It has bad method to getting domain Classes (com.orm.util.ReflectionUtil#getDomainClasses). The method always returns no classes. So Sugar may not initialize database tables. I has downgraded to gradle 1.3.0 (that method works correctly) and problem is gone.

A: Please check this property
    <`meta-data android:name="DOMAIN_PACKAGE_NAME" android:value="trending.hashtags.pojo" />`

This should be exactly where your POJO class is not the package name only.


text:
Q: Messaging not working in Python firebase-admin I am trying to send notifications to topics in firebase using python. However, I am having a problem.
This is the error message:     message = messaging.Message( NameError: name 'messaging' is not defined
This is the code:
import firebase_admin
from firebase_admin import credentials

cred = credentials.Certificate("path")
firebase_admin.initialize_app(cred)

topic = 'TestTopic'
def sendPush(title, msg):
    message = messaging.Message(
        data = {
            'title': 'TestTitle',
            'body': 'sometest',
        },
        topic=topic
    )

    response = messaging.send(message)

sendPush('hello', 'test')

Any help is greatly appreciated.
Thank  you

A: I think, you forgot to define this:
from firebase_admin import messaging

redpajama_set_name: RedPajamaStackExchange


text:
Q: python pandas groupby: percent of key2 values of key1 I have a dataframe and I grouped it by two keys df.groupby(['key1',key2']). For each key2 entry, how do I display the its percent of key1 values?

A: Here's an alternative method using one groupby statement.
Group by k1, select column k2 and apply a lambda function.  The lambda gets frequency counts for each level of k2 within k1 and then we divide by the count of k1:
In [1]: df.groupby('k1')['k2'].apply(lambda x: pd.value_counts(x)/x.count().astype(float))

Out[1]:
k1
a   x    0.500000
    y    0.500000
b   y    0.666667
    x    0.333333

Performance:
HYRY's method:
100 loops, best of 3: 3.07 ms per loop

My method:
1000 loops, best of 3: 1.98 ms per loop

A: call groupby twice for "k1" and ("k1", "k2"), and then do div:
import pandas as pd
k1 = ["a", "a", "a", "a", "b", "b", "b"]
k2 = ["x", "x", "y", "y", "x", "y", "y"]
df = pd.DataFrame({"k1":k1, "k2":k2})

df.groupby(["k1", "k2"]).k2.count().div(
    df.groupby("k1").k1.count().astype(float), level=0)

output:
k1  k2
a   x     0.500000
    y     0.500000
b   x     0.333333
    y     0.666667


text:
Q: TypeError: f[s] is not a function for jquery form submission I'm trying to get a form to submit in a roundabout way, since I need it to append new inputs before it submits. Since putting appends in the actual $(form).submit() function will not gather them for post, I've added an html button to call a submitCheck(), and then submit the actual function.
function init() {
  $("#submit").click(submitCheck);
  //and lots of other stuff
}

function submitCheck() {
    //go through fabric canvases, save xml to input.
    for (var i=1; i<probNum; i++) {
        var csvg = gcanvas[i].toSVG();
        $('#output').append("<input type='hidden' name='svg"+probNum+"' value='"+csvg+"'></input>");
    }
    //make sure a topic was selected. If not cancel submission and don't do anything.
    if ($("#topic").val() == '-1')
    {
        $('#error').html("You must select a valid topic");
    } else {
        //submit the form
        alert('should submit now');
        $("form:first").submit();
    }
}

But... it fails, throwing the type error:
TypeError: f[s] is not a function

I've found no documentation on this particular error. Any ideas?

A: You have some input with name="submit" in your form, which overrides the native form.submit (programmatically submits the form) method that is being called internally in jQuery. You need to change that to some other name.
See the Additional Notes paragraph in the documentation.
You can also use DOMLint to see other possible conflict issues.


text:
Q: Get an exception when loading Android Layout XML file For some reason I get the following exception when I load the XML layout in eclipse.
I am not too sure what might be causing this as I don't believe I have made any new changes to the file. Also when I render the layout with API 19 in eclipse, there is no exception. However, when I render with API 21, I get the below exception? What might trigger this sort of exception?
java.lang.NullPointerException
at android.view.ViewGroup_Delegate.drawShadow(ViewGroup_Delegate.java:74)
at android.view.ViewGroup_Delegate.drawChild(ViewGroup_Delegate.java:61)
at android.view.ViewGroup.drawChild(ViewGroup.java:3404)
at android.view.ViewGroup.dispatchDraw(ViewGroup.java:3198)
at android.view.View.draw(View.java:15017)
at android.view.ViewGroup.drawChild_Original(ViewGroup.java:3404)
at android.view.ViewGroup_Delegate.drawChild(ViewGroup_Delegate.java:53)
at android.view.ViewGroup.drawChild(ViewGroup.java:3404)
at android.view.ViewGroup.dispatchDraw(ViewGroup.java:3198)
at android.view.View.draw(View.java:15017)
at android.view.ViewGroup.drawChild_Original(ViewGroup.java:3404)
at android.view.ViewGroup_Delegate.drawChild(ViewGroup_Delegate.java:53)
at android.view.ViewGroup.drawChild(ViewGroup.java:3404)
at android.view.ViewGroup.dispatchDraw(ViewGroup.java:3198)
at android.view.View.draw(View.java:15017)
at android.view.ViewGroup.drawChild_Original(ViewGroup.java:3404)
at android.view.ViewGroup_Delegate.drawChild(ViewGroup_Delegate.java:53)
at android.view.ViewGroup.drawChild(ViewGroup.java:3404)
at android.view.ViewGroup.dispatchDraw(ViewGroup.java:3198)
at android.view.View.draw(View.java:15223)
at android.widget.FrameLayout.draw(FrameLayout.java:592)
at android.widget.ScrollView.draw(ScrollView.java:1689)
at android.view.View.draw(View.java:15022)
at android.view.ViewGroup.drawChild_Original(ViewGroup.java:3404)
at android.view.ViewGroup_Delegate.drawChild(ViewGroup_Delegate.java:53)
at android.view.ViewGroup.drawChild(ViewGroup.java:3404)
at android.view.ViewGroup.dispatchDraw(ViewGroup.java:3198)
at android.view.View.draw(View.java:15017)
at android.view.ViewGroup.drawChild_Original(ViewGroup.java:3404)
at android.view.ViewGroup_Delegate.drawChild(ViewGroup_Delegate.java:53)
at android.view.ViewGroup.drawChild(ViewGroup.java:3404)
at android.view.ViewGroup.dispatchDraw(ViewGroup.java:3198)
at android.view.View.draw(View.java:15017)
at android.view.ViewGroup.drawChild_Original(ViewGroup.java:3404)
at android.view.ViewGroup_Delegate.drawChild(ViewGroup_Delegate.java:53)
at android.view.ViewGroup.drawChild(ViewGroup.java:3404)
at android.view.ViewGroup.dispatchDraw(ViewGroup.java:3198)
at android.view.View.draw(View.java:15117)
at android.view.View.draw(View.java:15022)
at android.view.ViewGroup.drawChild_Original(ViewGroup.java:3404)
at android.view.ViewGroup_Delegate.drawChild(ViewGroup_Delegate.java:53)
at android.view.ViewGroup.drawChild(ViewGroup.java:3404)
at android.view.ViewGroup.dispatchDraw(ViewGroup.java:3198)
at android.view.View.draw(View.java:15117)
at com.android.layoutlib.bridge.impl.RenderSessionImpl.render(RenderSessionImpl.java:587)
at com.android.layoutlib.bridge.Bridge.createSession(Bridge.java:334)
at com.android.ide.common.rendering.LayoutLibrary.createSession(LayoutLibrary.java:332)
at com.android.ide.eclipse.adt.internal.editors.layout.gle2.RenderService.createRenderSession(RenderService.java:517)
at com.android.ide.eclipse.adt.internal.editors.layout.gle2.GraphicalEditorPart.renderWithBridge(GraphicalEditorPart.java:1584)
at com.android.ide.eclipse.adt.internal.editors.layout.gle2.GraphicalEditorPart.recomputeLayout(GraphicalEditorPart.java:1309)
at com.android.ide.eclipse.adt.internal.editors.layout.gle2.GraphicalEditorPart.activated(GraphicalEditorPart.java:1066)
at com.android.ide.eclipse.adt.internal.editors.layout.LayoutEditorDelegate.delegatePageChange(LayoutEditorDelegate.java:686)
at com.android.ide.eclipse.adt.internal.editors.common.CommonXmlEditor.pageChange(CommonXmlEditor.java:360)
at org.eclipse.ui.part.MultiPageEditorPart$2.widgetSelected(MultiPageEditorPart.java:294)
at org.eclipse.swt.widgets.TypedListener.handleEvent(TypedListener.java:248)
at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java:84)
at org.eclipse.swt.widgets.Display.sendEvent(Display.java:4353)
at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:1061)
at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:1085)
at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:1070)
at org.eclipse.swt.widgets.Widget.notifyListeners(Widget.java:782)
at org.eclipse.swt.custom.CTabFolder.setSelection(CTabFolder.java:3110)
at org.eclipse.swt.custom.CTabFolder.onMouse(CTabFolder.java:1794)
at org.eclipse.swt.custom.CTabFolder$1.handleEvent(CTabFolder.java:283)
at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java:84)
at org.eclipse.swt.widgets.Display.sendEvent(Display.java:4353)
at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:1061)
at org.eclipse.swt.widgets.Display.runDeferredEvents(Display.java:4172)
at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java:3761)
at org.eclipse.e4.ui.internal.workbench.swt.PartRenderingEngine$9.run(PartRenderingEngine.java:1151)
at org.eclipse.core.databinding.observable.Realm.runWithDefault(Realm.java:332)
at org.eclipse.e4.ui.internal.workbench.swt.PartRenderingEngine.run(PartRenderingEngine.java:1032)
at org.eclipse.e4.ui.internal.workbench.E4Workbench.createAndRunUI(E4Workbench.java:148)
at org.eclipse.ui.internal.Workbench$5.run(Workbench.java:636)
at org.eclipse.core.databinding.observable.Realm.runWithDefault(Realm.java:332)
at org.eclipse.ui.internal.Workbench.createAndRunWorkbench(Workbench.java:579)
at org.eclipse.ui.PlatformUI.createAndRunWorkbench(PlatformUI.java:150)
at org.eclipse.ui.internal.ide.application.IDEApplication.start(IDEApplication.java:135)
at org.eclipse.equinox.internal.app.EclipseAppHandle.run(EclipseAppHandle.java:196)
at org.eclipse.core.runtime.internal.adaptor.EclipseAppLauncher.runApplication(EclipseAppLauncher.java:134)
at org.eclipse.core.runtime.internal.adaptor.EclipseAppLauncher.start(EclipseAppLauncher.java:104)
at org.eclipse.core.runtime.adaptor.EclipseStarter.run(EclipseStarter.java:382)
at org.eclipse.core.runtime.adaptor.EclipseStarter.run(EclipseStarter.java:236)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at org.eclipse.equinox.launcher.Main.invokeFramework(Main.java:648)
at org.eclipse.equinox.launcher.Main.basicRun(Main.java:603)
at org.eclipse.equinox.launcher.Main.run(Main.java:1465)
at org.eclipse.equinox.launcher.Main.main(Main.java:1438)

A: I had the same issue in Android Studio. In my case, the root layout was a LinearLayout. In there, I had a nested RelativeLayout with the layout height and width as match_parent and a DrawerLayout included whose layout height and width was also match_parent. I also had a Button and TextView in the RelativeLayout. I think AndroidStudio couldn't draw the Button and/or TextView because of all the nested 'match_parent's.
I would try looking at the nested layouts. If your issue isn't the nested layouts, I would try altering your layout little by little to see what the IDE isn't able to render.


text:
Q: @ObservedObject changes not reflecting after an async operation I am a beginner at Swift and I've roughly tried to create an MVVM kinda architecture based on some tutorials
However I find that the @ObservedObject variable wallpaperViewModel having some @Published value properties doesn't reflect the changes after a network operation
The Network Operation works fine and I confirmed it by printing the received values to the console
Here is the required code
WallpaperViewModel
class WallpaperViewModel: ObservableObject {
    @Published var wallpapers : [Wallpaper] = [Wallpaper]()
    @Published var allBanners : [Banner] = [Banner]()
    @Published var error: String = ""

    //Handles error in requests, enum NetworkError has three cases unknown custom requestFailed
    func errorHandler(error: NetworkError){
         switch error {
             case .custom(let customErr):
                 self.error = customErr
                 print(customErr)
             case .requestFailed:
                 self.error = "Request Failed,Please check your internet connection"
                 print("Request Failed")
             case .unknown:
                 self.error = "An unknown error occured"
                 print ("An unknown error occured")
             case .networkNotConnected:
                 self.error = "Network not connected"
                 print ("Network not connected")
         }
     }

    func getAllWallpapersfromApi (order: String, page: String){
            NetworkingUtil().getAllWallpapers(orderBy: order, page: page){result in
                switch result{
                case .success(let wallpapers):
                         self.wallpapers = wallpapers
                case .failure(let err):
                        self.errorHandler(error: err)
            }
        }

    }

    func getAllBanners(){
        NetworkingUtil().getAllBanners(){result in
            switch result{
            case .success(let banners):
                self.allBanners = banners
                print("allBanners: (in VM)", banners)
            case .failure(let error):
                self.errorHandler(error: error)
            }
        }
    }
}

And here is my main view
struct ContentView: View {

    @ObservedObject var wallpaperViewModel = WallpaperViewModel()
    @State private var selectedTab = 0
    var body: some View {

        VStack{
            if(wallpaperViewModel.error.isEmpty){
                TabView(selection: $selectedTab){
                    if(wallpaperViewModel.allBanners.count == 0){
                       Text("Loading..")
                   }
                   else{
                    ForEach(0..<wallpaperViewModel.allBanners.count){ bannerIndex in
                           //let banner = banners[bannerIndex]
                           Image("cover-cheetah")
                               .resizable()
                               .scaledToFill()
                               .frame(height:selectedTab == bannerIndex ? 230 : 180)
                               .cornerRadius(12)
                       }
                   }

               }
               .frame(height: 230)
               .tabViewStyle(PageTabViewStyle())
               .animation(.easeOut)
               .padding(.horizontal)
            }
            else{
                Text("\(wallpaperViewModel.error)")
            }
        }
        .onAppear{
            self.wallpaperViewModel.getAllBanners()
            print("allBanners in ContentView",wallpaperViewModel.allBanners)
            self.wallpaperViewModel.getAllWallpapersfromApi(order: "created", page: String(0))
            print("allWallpapers in ContentView",wallpaperViewModel.wallpapers)
        }

Here is the values logged to the console

And here is the output on the Simulator


text:
Q: PHPUnit - Test fopen, fwrite return I used PHPUnit to test a function with contents:
$fp = fopen($file_path,'wb');

if( $fp === false ) {
     ...
}

$ret = fwrite($fp, $content) ;
if( $ret === false ) {
     ...
}

I have a problem, fopen always return a resource and fwrite always return a integer value but i want them return FALSE.
How should i do?
Thank everyone :).

A: You could write a FileHandler class encapsulating all the file handling parts so you can inject a stub for it in your tests and setup the stub to return what you want in the different tests. You don't have to test that library functions work, only that you are calling them as expected


text:
Q: How create a new schema and make a migration for every new user registration approved? I'm working on a project that will be a marketplace for a shop here in my country, I already have experience for projects multitenant when is a small number of clients like 100 and we have 2 days for approval and we make a new database for that client.
But in this project, the client can't wait for 2 days and we make some tests here and Laravel takes so much time to make a migration for a newly created schema. But this job of migration we make this manually and we want to make this programmatically.
I search on the web for tutorials or examples like this but don't find it. What is the fastest way to create a schema and populate it with the databases from migration?
Can you guys show me some tutorial or an idea of how to make this automatic when the user makes a registration on our website, and automatically creates the schema and populate with new tables!

A: First, add your existing database in project then:-
Use package migrations-generator. Install it using:-
composer require --dev "xethron/migrations-generator"

Then run:-
php artisan migrate:generate

For selected tables use:-
php artisan migrate:generate table1,table2,table3,table4,table5

For ignoring selected tables:-
php artisan migrate:generate --ignore="table3,table4,table5"

It will directly create in migration folder of your project directory i.e. database > migrations


text:
Q: Query previous row value and merge to current row Is there a way how can I query the previous row value and merge to current row, here is my sample table scenario:
+-------------------------------------+
| ColA | ColB | ColValue |    Date    |
|------|------|----------|------------|
| AAA  | 111  |     5    | 2017-04-23 |
| AAA  | 111  |     4    | 2017-04-22 |
| AAA  | 111  |     3    | 2017-04-21 |
| BBB  | 222  |     5    | 2017-04-30 |
| BBB  | 222  |     4    | 2017-04-29 |
+-------------------------------------+

And my expected result should be this, just want to get the previous and current value and group it by selected columns and date.
+--------------------------------------------------+
| ColA | ColB | PreValue |  CurValue  |    Date    |
|------|------|----------|-------------------------|
| AAA  | 111  |     4    |     5      | 2017-04-23 |
| AAA  | 111  |     3    |     4      | 2017-04-22 |
| AAA  | 111  |    N/A   |     3      | 2017-04-21 |
| BBB  | 222  |     4    |     5      | 2017-04-30 |
| BBB  | 222  |    N/A   |     4      | 2017-04-29 |
+--------------------------------------------------+

any suggestions or solution, thanks in advance
Here is my actual query from my actual data as reference:
SELECT ai.APName, tbap.Value , tbap.DateTime, tbap.Comment, tbap.ModifiedBy, tbap.ToolName, d.Name as Strategy FROM (SELECT dt.*,ins.Value as ToolName FROM (SELECT av.*,ai.DocumentID,ai.IndexID FROM ControlAutomation.appartitionindexes ai
JOIN (SELECT * FROM ControlAutomation.appartitionvalues
where DateTime > '2017-04-22 23:17:13' and DateTime < '2017-04-26 23:18:28') av
ON ai.APPartitionID = av.APPartitionID) dt INNER JOIN factory.indexes ins ON ins.ID = dt.IndexID
where dt.comment  like '%updateAdjustableParameter%'
group by dt.ID) tbap
INNER JOIN ControlAutomation.documents d ON d.ID =  tbap.DocumentID
INNER JOIN appartitionindexes ai ON ai.APPartitionID = tbap.APPartitionID
GROUP BY tbap.ID
ORDER BY tbap.ToolName DESC, d.Name, tbap.DateTime DESC
LIMIT 100

A: Hope I correctly got your question: http://sqlfiddle.com/#!9/d815c/6
select
  prev_query.cola as ColA,
  prev_query.colb as ColB,
  rhs.colvalue as PreValue,
  prev_query.colvalue as CurValue,
  prev_query.coldate as ColDate
from
  prev_query left join prev_query as rhs
    on prev_query.cola = rhs.cola
    and prev_query.colb = rhs.colb
    and prev_query.colvalue = rhs.colvalue + 1
order by
  prev_query.cola, prev_query.colb, prev_query.coldate desc;


text:
Q: Safari AJAX bug - Failed to load resource since today I have a pretty strange bug in an web app I'm working on. I haven't done anything to the code and from one day to another this bug appeared:
I execute AJAX requests (not with jquery but with normal js) to our local server running MAMP PRO. All works fine in chrome and firefox (testing on a mac). But in safari the request always throws an error: Failed to load resource: the network connection was lost
When I try to load the url of the request manually (not via AJAX) everything works fine. I also tested the request with a setTimeout and found something interesting:
When I do the request directly after page load (up to 60 millisecs) all works fine. After that the connection is lost sporadicly till 6000 milliseconds where everything works fine again! Pretty strange behaviour... I'm not working with any other setTimeouts so the problem can only be caused by safari.
Am I doing something wrong or is this just a very new safari bug?

A: In developing a large new feature for our web app, we ran into this problem as well.  We use an XHR request from the JS client to get user favorites from the Tomcat server hosted on Amazon Linux.  The initial connection works fine as expected.  However, the second identical request fails with "Failed to load resource: the network connection was lost" in the client JS console.  I suspect Safari recognizes the second request as a mistaken duplicate of the first.
The current workaround we are using for Tomcat is to effectively disable KeepAlive support.  Unfortunately, this affects all connections, not just for Safari on desktop and/or mobile.  This solution for Tomcat is to set a parameter on the Connector for HTTPS in ${CATALINA_HOME}/conf/server.xml...
maxKeepAliveRequests="1"

There might be other solutions to limit the damage to only Safari connections.  If I discover them, I'll come back and update this post.  The better band aid would be to cache results in our app and avoid the problem altogether.

A: I have seen some mention elsewhere that Safari on Mac has problems with keep alive.  Some people are posting the solution is to disable keep alive for safari on mac at the server.
BrowserMatch "Safari" nokeepalive


text:
Q: Multi query and transaction I do some treatment on many data, so i do a loop.
@Transactional
@Override
public void processPayment(List<Long> paymentsId, PaymentModeEnum paymentMode) throws ProcessPaymentException{
   ...
   processCreditCardPayment(payments);
}

private void processCreditCardPayment(List<Payment> payments) throws ProcessPaymentException {
    for (Payment payment : payments) {

         try {
              //save to db
         }catch (ProcessPaymentException ppe) {
         }

    }
}

ProcessPaymentException extends Exception
If I loop on 10 item, on the last one, error happen.
Everything is rollbacked (all my item) or only the one in error?

A: In this case nothing would be rolled back. It is because you caught the exception and it didn't pass Spring transaction boundary.
Read here in Spring Docs:

The recommended way to indicate to the Spring Framework's transaction
  infrastructure that a transaction's work is to be rolled back is to
  throw an Exception from code that is currently executing in the
  context of a transaction. The Spring Framework's transaction
  infrastructure code will catch any unhandled Exception as it bubbles
  up the call stack, and make a determination whether to mark the
  transaction for rollback.


text:
Q: Ruby scope of DATA after __END__ I'm using this Ruby trick with __END__ and DATA to put some data inside my program file:
class Foo
  def initialize()
    puts DATA.read.inspect
  end
end
puts DATA.read.inspect
Foo.new
__END__
test

This generates the following output:
"test"
""

I had assumed DATA would be the same globally, but inside the class it has no content. How  would I get access to the data after __END__ inside a class (apart from the obvious and ugly solution using global variables)?
ADDED: I see how reading DATA twice gives me nothing the second time. I could use rewind to get back to the start, but read then gives me the entire source code of my program. Is there an easier way to get to just the part after __END__ on subsequent uses of DATA, or would I be better of reading it once and storing it somewhere else for future use?

A: DATA is the same. You would get the same output if instead of doing Foo.new you would do DATA.read a second time.
This is because after the first read DATA (which is an IO) has reached the end of the stream, so any further reads will return an empty string, unless you append additional data to DATA or rewind DATA to the beginning of the stream.
Edit: To seek back to the point right after the __END__ you have to read DATA.pos before performing any reading on DATA and then restore pos to that value after reading. The easiest solution is probably just doing FOO = DATA.read at the beginning of the script and then using FOO.

A: rewind DATA first, because it's a stream.
class Foo
  def initialize()
    DATA.rewind
    puts DATA.read.inspect
  end
end
puts DATA.read.inspect
Foo.new
__END__
test


text:
Q: Reindex Not Happening Automatically Magento 2.3 Every time I update a product stock in magento it updates perfectly in the backend but only when I manually run a reindex via SSH does it update on the front end.
Very annoying when I am sometimes updating stock several times a day with deliveries.
So for example a product has 0 in stock, if i change to qty 5  the back end shows in stock qty 5 but front end still shows out of stock.
After reindex it updates on the front end.
Any idea what is wrong?

A: You can change indexing settings to, update on save,
here is the difference:
Update on Save :The index is set to update whenever a change is saved.
Update on Schedule :The index is set to update on schedule according to a cron job.

A: Check your Cron, and Cron logs.
You can also run
php bin/magento cron:install

Cron jobs are responsible for reindex

A: First Remove old Cron :-
php bin/magento cron:remove
After that install New Cron :-
php bin/magento cron:install


text:
Q: How do I resolve this error; 'document.getElementById('myChart').getContext' is undefined)? I have tried looking at related answered problems regarding the error:
TypeError: document.getElementById('myChart').getContext is not a function. (In 'document.getElementById('myChart').getContext('2d')', 'document.getElementById('myChart').getContext' is undefined)

but no suggestions have come through for me thus far. I'm trying to work with chart.js library and keep getting the error in the title. Below are my HTML and javascript codes, the js code is in a separate file called app.js Any help would be appreciated. Thanks.
<!DOCTYPE html>

    <title></title>

    <link rel="stylesheet" type="text/css" href="contxt.css" />

And here is the JS:
if (document.readyState == 'loading') {
    document.addEventListener('DOMContentLoaded', fire)
}else{
    fire()
}

function fire() {

var ctx = document.getElementById('myChart').getContext('2d');
var myChart = new Chart(ctx, {
    type: 'bar',
    data: {
        labels: ['Red', 'Blue', 'Yellow', 'Green', 'Purple', 'Orange'],
        datasets: [{
            label: '# of Votes',
            data: [12, 19, 3, 5, 2, 3],
            backgroundColor: [
                'rgba(255, 99, 132, 0.2)',
                'rgba(54, 162, 235, 0.2)',
                'rgba(255, 206, 86, 0.2)',
                'rgba(75, 192, 192, 0.2)',
                'rgba(153, 102, 255, 0.2)',
                'rgba(255, 159, 64, 0.2)'
            ],
            borderColor: [
                'rgba(255, 99, 132, 1)',
                'rgba(54, 162, 235, 1)',
                'rgba(255, 206, 86, 1)',
                'rgba(75, 192, 192, 1)',
                'rgba(153, 102, 255, 1)',
                'rgba(255, 159, 64, 1)'
            ],
            borderWidth: 1
        }]
    },
    options: {
        scales: {
            yAxes: [{
                ticks: {
                    beginAtZero: true
                }
            }]
        }
    }
});

}

A: Only a canvas can have a context. Please change

for

    <canvas id='myChart'></canvas>


text:
Q: Cannot reassign a global variable within an onEdit function So I'm trying to update a global variable from within an onEdit function yet it will not reassign. It seems to retain its original value.
The global variable is declared at the very top of the script so it shouldn't be hoisting issues as far as I know.
var strategy = "empty";

Within the onEdit there is:
test1.setValue(strategy);
strategy = "TEST";
test2.setValue(strategy);

The test 1&2 references are just two different cells (in a google sheet) used to test the before and after results of the onEdit code.
The result of this shows: test1 = "empty"  &  test2 = "TEST"
However, when onEdit is called again, the test results are exactly the same. Despite the very last action of the onEdit being to reassign the value to "TEST", it resets to the default value of "empty" at some point before onEdit is ran again.
Has anybody else seen something like this before.... What am I missing here ?

A: The state of the script does not persist
Every time you run any function in Apps Script (including an onEdit), think of it like this: It will concatenate all the separate script files and run everything.
So if you have
var globalVar = 1;

function test() {
    globalVar = globalVar + 1
    console.log(globalVar)
}

Every time you run the function test, the result will be 2. Because everything runs again.
If you want to persist data across the different executions, then you need to store that in a Spreadsheet, for example.
Properties Service
You can also take advantage of the properties service. This is a small store of information that you can persist across executions. Data that you may only want to use as a developer, and for it not to be available to a user in a Spreadsheet for instance.
It works with getters and setters though, so its not as straightforward as simple declaring a variable.
To set a value to persist across different executions, you would need to run this example function once.
function initializeProperties() {
    var scriptProperties = PropertiesService.getScriptProperties();
    scriptProperties.setProperty('globalVar', 1); // setting a property
}

Then from another function, such as an onEdit, you could:
var scriptProperties = PropertiesService.getScriptProperties();
var oldValue = scriptProperties.getValue('globalVar') // getting a property
scriptProperties.setProperty('globalVar',  oldValue + 1)
console.log(scriptProperties.getValue('globalVar'))

Reference

*

*properties service.

*getters and setters


text:
Q: angularJs call function from different controllers We are trying to develop an app using phonegap onsen and angularJS.
I am trying to call a function from a different controllers. I have seen alot of documentation on how to do this like this
But for certain reason it doesn't work for me. Here is my code so far.
module.run(function ($rootScope) {
    $rootScope.$on('some-event-here', function (event, data) {
        console.log('1');
        $rootScope.$emit('show-dialog-of-some-event', data);

        //I also tried
        //$rootScope.$broadcast('show-dialog-of-some-event', data);
    });
});

module.controller('controller1', ['$scope', '$http',  function($scope, $http) {
    $scope.proceed = function() {
        console.log('0');
        $scope.$emit('some-event-here', {});
    }
}]);

module.controller('controller2', ['$scope', '$http',  function($scope, $http) {
    $scope.$on('show-dialog-of-some-event', function (event, data) {
        console.log('2');
        ons.createDialog('some-dialog.html').then(function(dialog) {
            //some code here
        });
    });
}]);

It show on the console '0' and '1' but it doesn't show '2'.
This could be an easy problem but I can't seem to find the problem with my code.
Thanks in advance.

A: I think what may be occurring is that you declare an event handler for the event 'show-dialog-of-some-event' in the local scope of controller2, i.e. $scope. You emit an event in the $rootScope. Emitted events bubble up not down, so the event 'show-dialog-of-some-event' does not "bubble down" from the $rootScope to $scope. You may want to define the event handler for 'show-dialog-of-some-event' on the root scope instead, e.g.
    $rootScope.$on('show-dialog-of-some-event', function(e,d) {});

A: If you are communicating between sibling controllers and from parent controller to child controller you have to use $scope.$broadcast but If you want to communication from child to parent you have to use $scope.$emit

A: 2 things are wrong with your code:
1: $broadcast bubbles events down the scope hierarchy, $emit is for bubbling them up the scope hierarchy, instead use this:
$rootScope.$broadcast('show-dialog-of-some-event', data);

For more info see this answer: $rootScope.$broadcast vs. $scope.$emit
2: the run function of your module will be executed before your controller will attach an event handler for this event, therefore the event will have already passed by the time you configure an event handler in your controller:
Again, see this answer AngularJS app.run() documentation?
So the solution to your answer is:

*

*change the $emit to $broadcast

*move the $broadcast call later into the lifecycle so the controller will have attached its listener

Here's a plunkr where I'm calling $broadcast later in the lifecycle (in this case when the window loads):
http://plnkr.co/edit/W7efiKqIlu4va4AcBTbG

A: If you don't need to process anything on rootscope you can just inject $rootScope into controller
module.controller('controller1', ['$scope', '$http', '$rootScope', function($scope, $http, $rootScope) {
    $scope.proceed = function() {
        console.log('0');
        $rootScope.$boardcast('some-event-here', {});
    }
}]);

module.controller('controller2', ['$scope', '$http',  function($scope, $http) {
    $scope.$on('some-event-here', function (event, data) {
        console.log('2');
    });
}]);

It's less clean than using a service but you can use this pattern if it's not too often.


text:
Q: I'm trying to "draw" a circle using a span, sometimes work, sometimes doesn't This puzzles me a lot. I'm writing a Laravel application, and I want to draw a circle besides a description. The circle must be either gray or yellow depending on a condition, so my code is:
...

  @foreach ($section->lessons as $lesson)

      complete ? 'bg-yellow-400' : 'bg-gray-500' }} rounded-full">
      {{ $lesson->name }}

  @endforeach

...

This code works, no problem with it, but with the display. Check the span Tailwind classes: "inline-block w-4 h-4 mt-1 mr-2 bg-yellow-400 }} rounded-full", this should draw a perfect circle (w-4 h-4) right?
Now see what it displays:

As you can see, for the one line descriptions, the circle is perfect, but for the ones that have two lines, it becomes sort of an oval, and it moves the margin slightly to the left
Why this happens and how can I fix it?

A: You have a flex container so you don't need inline-block on the spans but flex is also the reason your long line span element is getting squashed.
A simple fix is to add flex-shrink-0 to those spans.
Here it is working on Tailwind Play https://play.tailwindcss.com/H0kZFOVNaX

      Some regular sized content

      Some extra large XXXL sized content that has way too long of a title and can smash an inline element.


text: Q: Btrfs: Is there an easy way to find a file by block numbers it occupies? Say, you have filesystem Btrfs formatted, then you, all of the sudden as it happens, wonder — what files occupy blocks #356 and #789, how you gonna answer this question?


text:
Q: USING MOD_WSGI with Python Inside our web application, we using PHP to with EXEC command to call some python scripts and it is working fine except we found there are always has 3-5 seconds delay when calling it. If run the same python script right inside the IDE and it runs less than a second.
I did some research, it seems is because the python interpreter keeps loading everytime we execute the script from PHP. We would like to eliminate that few seconds delay.
Then I found the Mod_WSGI that comes with Apache may be able to help on it and think that can let us call the python script directly.
Just followed the instruction on https://modwsgi.readthedocs.io/en/develop/
and get the mod_wsgi up an running.
add some line in my httpd.conf as follow and I'm able to run the "hello world" WSGI application from the browser
WSGISocketPrefix /var/www/html/public_html/wsgi/
WSGIDaemonProcess myserver_wsgi processes=2 threads=15 display-name=%{GROUP}
WSGIProcessGroup myserver_wsgi

    WSGIScriptAlias /wsgi /var/www/html/public_html/wsgi/myapp.wsgi

    <Directory /var/www/html/public_html/wsgi/>
     Order allow,deny
     Allow from all
    </Directory>

Now, I have no idea how to use the WSGI to call all my python PY scripts. The httpd.conf is pointing to a specific myapp.wsgi, how can I run more than one of those scripts?
Here are my questions.

*

*Is that a right solution to eliminate the overhead/delay when running python script through PHP

*We are using AngularJS framework as front end and PHP as the backend, is that possible to call the python script directly from the JS file? like using the $http service?
If yes, how to do that?
I'm stuck now and only get the WSGI "hello world" working and don't know what to do next,  any ideas and solution are welcome and thank you in advance.


text:
Q: Kindle: Get furthest read location I'm clutching at straws a little here but was wondering if anyone had any insight into whether this was possible. It doesn't seem as though Amazon provide any kind of [public] API for getting data about a users kindle books and specifically how far through them they have read, but I'm hoping I've missed something.
So basically, given a users amazon login or kindle email address or some other unique identifier I would like to be able to connect to a web service to get back the list of kindle books the user has purchased/downloaded and then determine how far through them they have read. Amazon must have this data in order to be able to sync books across devices, but it doesn't appear that they have made available an API to get this data.

A: You are correct, Amazon does have this data but as you suspected there is not a public API for non-Kindles to query it.


text:
Q: How to correctly work with dates on Android I'm working on a Android project with Kotlin where we need to perform validations on dates both from the device and from our backend. So far we've been working with the Date class to represent dates, the SimpleDateFormat class to parse strings and format dates and the Calendar class to perform operations on dates such as getting the date from x days ago and stuff like that. I've come accross some resources that state that the correct way to work with dates is to use the java.time package (classes such as LocalDateTime, LocalTime, etc.). I'm interested in knowing exactly what should be the correct way to work with dates (from parsing to formatting) and if I need to take into account timezones. I've seen similar questions but none of them really summarizes what I'd like to know.

A: The correct way of working
To work correctly with dates and times requires that you understand something about what dates and times are and how they behave in the real life of your users. Working correctly is not about using this or the other library class. Depending on the work you do you will need to know about leap years, and/or the Julian, the Gregorian and the proleptic Gregorian calendar and/or many different solar and lunar calendar systems.
To work correctly with times there is hardly a way to avoid taking time zone into account. For an introduction to time zones I recommend the video that I link to at the bottom. It's entertaining and explains the basics well.
The recommended library classes to use
It's definitely recommended to use java.time, the modern Java date and time API, for your date and time work. Compared to the outdated date and time classes from Java 1.0 and 1.1 some differences are:

*

*The old classes pretend that some things are simple that really are not simple, some programmers do not realize the complexity of correct date and time handling and leave errors in their code that go undetected. The modern classes in many cases force the programmer to decide what we want, leaving much less room for unintentional errors. We must decide whether we want a date or a time or both, which time zone we want, etc., etc.

*Along the same line the old classes pretend that dates and times are the same and can be considered with or without time zones, which is not true. Believing it will cause all kinds of errors in corner cases. Using java.time you need to choose between LocalDate, Instant, ZonedDateTime and many other date-time classes, which may feel a hassle at first, but which will make your code clearer and improve the chances that it is also correct.

*In many cases the old classes accept garbage input/arguments, again allowing obvious errors to go undetected. The modern classes do a much greater job of validation.

*The old classes generally aren't thread-safe. The modern ones are.

Links

*

*YouTube video: The Problem with Time & Timezones - Computerphile

*Oracle Tutorial: Date Time

*Oracle technical article Java SE 8 Date and Time

*Still using java.util.Date? Don't! on Programming Hints

*What's wrong with Java Date & Time API? [closed]

*Jon Skeet's answer to Why is January month 0 in Java Calendar?; the interesting part is the EDIT in the last half of the answer


text:
Q: Can I use a greedy method as an heuristic for an A* algorithm? I am trying to find a heuristic to solve a travel salesman problem but with more restrictions.
Using the greedy is giving me a total cost of 3.839.
Using A* with some estimation as a heuristic is giving me results of 4.0 to 5.35.
Using A* while using greedy as a heuristic gives me the best result of 3.5.
Is this wrong? Using a greedy method as a heuristic for a A* algorithm?
Does this fall under the category of non-optimistic? Meaning that It can't be used as a heuristic?
ps: this is a graph with many restrictions, with about 5 metrics, so I can't just calculate a distance to the final point.


text:
Q: Confusion over Mathematica 9.0, when calculating the limit. Why in Wolfram Mathematica 9.0 I get $\displaystyle \lim_{x \to -1 }\dfrac{1+ \sqrt[5]{x}}{1+ \sqrt[3]{x}}=\frac{1+\sqrt[5]{-1}}{1+\sqrt[3]
   {-1}}$.
 But, my solution is: 1.
Thanks.

A: I don't think the correct answer is $\;1\;$. Using $\;x^n+1=(x+1)(x^{n-1}-x^{n-2}+\ldots-x+1)\;$ for odd $\;n\;$
$$\frac{1+\sqrt[5]x}{1+\sqrt[3]x}=\frac{x^{2/3}-x^{1/3}+1}{x^{4/5}-x^{3/5}+x^{2/5}-x^{1/5}+1}\xrightarrow[x\to-1]{}\frac35$$

A: You can also use L'Hopital's rule explicitly, here, because both the numerator and denominator approach zero, and their derivatives exist. Hence:
$\displaystyle \lim_{x \to -1 }\dfrac{1+ \sqrt[5]{x}}{1+ \sqrt[3]{x}}=\displaystyle \lim_{x \to -1} \frac{\frac{1}{5}x^{-\frac{4}{5}}}{\frac{1}{3}x^{-\frac{2}{3}}}=\displaystyle \lim_{x \to -1} \frac{3}{5} x^{-\frac{2}{15}}=\frac{3}{5}$

A: With L'Hôpital's rule $$\lim _{ x\to -1 }{ \frac { 1+\sqrt [ 5 ]{ x }  }{ 1+\sqrt [ 3 ]{ x }  }  } =\lim _{ x\to -1 }{ \frac { \frac { 1 }{ 5\sqrt [ 5 ]{ { x }^{ 4 } }  }  }{ \frac { 1 }{ 3\sqrt [ 3 ]{ { x }^{ 2 } }  }  } =\frac { 3 }{ 5 }  }  $$


text:
Q: What is the difference between "as much as" and "much as"? What is the difference between the following sentences?

As much as I admire him for his sterling qualities, I cannot excuse him for being unfair to his friends.

Much as I admire him for his sterling qualities, I cannot excuse him for being unfair to his friends.

A: These two constructions are not equivalent, but the line between them has been blurred over the past two or three generations.
As much as, strictly, should be used only in comparisons:

Jane admires John as much as I admire Joan. ⇨
  As much as I admire Joan, (so much) Jane admires John.

Much as has two distinct uses.

*

*In one, it alternates with much like, depending on what follows,
and much acts as a modifier to the following conjunctive:

Much like me, Jane admires John. = Jane is (much) like me in admiring John.
  Much as I admire Joan, Jane admires John. = Jane admires John in (much) the same way as I admire Joan.

*The other use is the one which you employ. Here as has the same sense as though (and alternates with it) and much, which modifies the verb, is moved to the front of the clause for emphasis.

Though I admire him much, I cannot excuse him. ⇨
  Much though I admire him, I cannot excuse him. ⇨
  Much   as   I admire him, I cannot excuse him.

Other terms than much can be treated the same way:

Little as I admire him, I cannot condemn him.
  Deeply as I admire him, I cannot excuse him.
  Honourable though I hold him to be, I cannot excuse him.

These three uses are rarely confused when the clause falls in its "natural" place after the main clause. Moving the clause to the beginning of the sentence, to secure emphasis, is a rhetorical and primarily literary device; and the much as use has never, I think, fallen entirely comfortably on the ear. Consequently, there is a strong tendency to translate much as to the more familiar as much as. And it may be the case that this use, though literally meaningless, is now so widespread that it has become the ordinary idiom—witness David Schwartz' answer.
My advice would be to avoid the use. It's literary, and sounds (and reads) affected, in either form; and each form is bound to annoy somebody, either those who adhere to my opinion or those who adhere to David Schwartz'. Instead, use an ordinary untransposed construction with "although" or "even though":

Even though I admire him greatly, I cannot excuse ...

A: They describe almost the opposite relationship between the two things.

As much as I admire him for his sterling qualities, I cannot excuse him for being unfair to his friends.

Here, "as much as" means "even though". Essentially, it means that my admiring someone would make you think I could excuse them, but I cannot. That is, it shows a conflict between two truths. Since these things do conflict, we might excuse unfairness from those we admire, this makes sense.

Much as I admire him for his sterling qualities, I cannot excuse him for being unfair to his friends.

Here, "much as" means "in about the same way". Essentially, this means that I admire him and in the same way, cannot excuse his unfairness. Since these two things don't really seem equivalent, it's hard to see how this would make sense.

A: "Much as I admire him" means "Although I much admire him" (or more typically, "although I admire him a lot").  "As much as" is usually used in a construction where you are comparing two ideas and expressing them to be equivalent.  For example:

I admire him for his good looks as much as his integrity.

Means that you hold his good looks and his integrity in equal esteem.  Other examples:

I eat steak as often as chicken.

Joe runs as fast as Jim.

On the other hand, "as well as" can have the same meaning.

He plays piano as well as I do.

But it can also mean "and" or "in addition to."

The omelette had chicken as well as onions.


text:
Q: Why this angularjs code is not working? This is my html code, and it's not giving the proper output. Ιt's not working by using {{expression}}, that's why I use ng-bind. Βut still not working, although I use both the way to print the enter value. What is the mistake in this code?
Τhis is the output it's showing:

firstname:
lastname:
fullname:{{firstname}}

<!doctype html>

            first name:<input type="text" ng-model="firstname"/>

             last name:<input type="text" ng-model="lastname"/>

full name    {{firstname}}

A: Just convert this

to this


text:
Q: Failure to launch Android Studio; Failed to create JVM: error code -1 When trying to launch Android Studio on Windows I get the following error:
Failed to create JVM: error code -1
JVM Path: C:\Program Files\Java\jdk1.8.0_91\jre
I have tried setting the JAVA_PATH variable and I have also tried uninstalling Android Studio and Java and then reinstalling. I came to this error while trying to mess with the path variables to use an external Java library.
Any suggestions on fixing this problem?
EDIT: The solution I gave below seems to work for error code -1 and -4 in my case. The only issue is that you lose your user settings if you use the solution given.

A: With: Failed to create JVM: error code -1
I tried deleting the studio64.exe.vmoptions file
(from: C:\Users\vungnho.AndroidStudio3.1\config)
(vungnho - my user name;  .AndroidStudio3.1 - config folder for current Studio)
and it worked!

Exactly, I tried reinstall Android Studio but the problem still occur,
so I tried rename .AndroidStudio3.1 folder, but it have many my configs :(

A: Problem solved!
This thread was extremely helpful:
failed to create jvm error code 4 android studio
What ended up working for me was deleting the Android Studio setting folder in my user folder.
C:\Users\my_username.AndroidStudio
Then re-open Android Studio then everything work fine for me.

A: For those that are using the Android studio version 4, can find the .vmoptions in the following path:  C:\Users\YourUserName\AppData\Roaming\Google\AndroidStudio4.1
as mentioned here in the official documentation of Android: https://developer.android.com/studio/intro/studio-config


text:
Q: Firebase ProjectSettings API KEY is safe to be public? I'm using firebase and i have a question. I'm generateing email reset link with firebase using generatePasswordResetLink function from firebase auth. This function send a generate an email and send it. Everyting is okay. But when i open the email and click the button for "reset password" the url contains oobCode, continueUrl and apiKey.
This apiKey is actully my firebase project apiKey and is it safe to be public like this? The generated url is like below
"https://<url>/reset-password?mode=resetPassword&oobCode=<oobcode>&apiKey=<ApiKey>&continueUrl=<continour Url>"
I just check but i couldn't find the answer


text:
Q: What is meant by a "diagonalization argument"? From Wikipedia:

A variety of diagonal arguments are used in mathematics.

*

*Cantor's diagonal argument

*Cantor's theorem

*Halting problem

*Diagonal lemma

Besides the above four examples, there is another one I found in a blog. When proving that "if a sequence of measurable mappings converges in measure, then there is a subsequence converging a.e.", the construction of the subsequence is also called diagonalization:

The method for establishing this result is fairly typical of such
  arguments: we rely on diagonalization along with the control that
  Borel-Cantelli gives us. Let $f_n$ be a sequence that converges in
  measure to $f$. This means that for any n we have a $f_{m_n}$ with
  $\mu(|f_{m_n} - f| > 1/n) < 2^{-n} $. Applying Borel-Cantelli to the
  sequence  of sets $A_n = \{x | |f_{m_n}(x) - f(x)| > 1/n\}$ yields
  $\mu(\limsup_m \cup_{n=m}^\infty A_n) = 0$. But this is simply saying
  that the set of points on which $f_{m_n}$ doesn't converge to $f$ has
  measure $0$.

As someone who has not been very much exposed to "diagonalization arguments", I wonder if the examples above have something in common, so that we may answer what "diagonalization argument" is and what kinds of problems it may help to solve?

A: Someone with more experience might be better equipped to address this question, but here's my perspective. "Diagonal arguments" are often invoked when dealings with functions or maps. In order to show the existence or non-existence of a certain sort of map, we create a large array of all the possible inputs and outputs. Moving along the diagonal, we use a self-referential construction to introduce an object that cannot possibly be on the list, and the desired object is obtained.
Cantor's Diagonal Argument: The maps are elements in $\mathbb{N}^{\mathbb{N}} = \mathbb{R}$. The diagonalization is done by changing an element in every diagonal entry.
Halting Problem: The maps are partial recursive functions. The killer $K$ program encodes the diagonalization.
Diagonal Lemma / Fixed Point Lemma: The maps are formulas, with input being the codes of sentences. The diagonalization is accomplished by a somewhat confusing self-referential construction.
Cantor's Theorem ($|A| < |P(A)|$) : The maps are the correspondences between elements of $A$ and elements in $P(A)$. Diagonalization is accomplished by considering a self-referential subset in $P(A)$ that nothing can map to.

A: Yes, I would consider the "diagonal argument" a general proof-construction technique, similar to, say, the pigeonhole principle or other combinatorial principles.
Perhaps the most general form of the diagonal argument is the following:

Theorem: Let $X$ be a set with more than one member, let $I$ be an arbitrary set, and let $X^I$ denote the set of functions from $I$ to $X$.  Then there exists no surjection from $I$ to $X^I$.

Proof: Let $f$ be a function from $I$ to $X^I$, and let $a$ and $b$ be distinct members of $X$.  For notational convenience, let $f_i$ denote the function $f(i)$.  We construct a function $g \in X^I$ as follows:
$$g(i) = \begin{cases} a & \text{if }f_i(i) \ne a \\ b & \text{if }f_i(i) = a \end{cases}$$
By construction, for every $i \in I$, $g(i) \ne f_i(i)$, and thus $g \ne f_i$.  Therefore $g$ is not in the image of $f$, and thus $f$ is not a surjection. $\square$
(Correction: Contrary to what I originally wrote, the proof above does work also for $I = \emptyset$.  In that case, the only function $f: I \to X^I$ is the empty function, which is indeed not surjective, and the construction above vacuously but correctly yields a counterexample $g \in X^I$, where $g$ is itself the empty function from $I$ to $X$.)
By setting up a bijection between the powerset $\mathcal P(I)$ and the set $\{0,1\}^I$ (sometimes written as $2^I$), we also obtain the following corollary:

Corollary: There exists no surjection from $I$ to $\mathcal P(I)$.

A nice feature of this particular form of the diagonal argument is that it makes very few logical or set-theoretical assumptions: for instance, it doesn't use proof by contradiction or make any reference to cardinalities.  Thus, it works even in many oddball versions of logic and set theory than some people occasionally consider.  However, in standard set theory, the theorem above can be given a more succint form:

Corollary: If $X$ has more than one member, then $X^I$ has strictly greater cardinality than $I$.  Also, $\mathcal P(I)$ has strictly greater cardinality than $I$.

A: The Arzelà Ascoli theorem is an instance of this. See http://en.wikipedia.org/wiki/Arzel%C3%A0%E2%80%93Ascoli_theorem. What is interesting about this example is that this theorem has applications in differential equations. One example of an application is the theorem that in a hyperbolic surface, every free homotopy class of loops has a unique geodesic in that class.


text:
Q: Converting double?[ ] to object[ ] in c# I am using DotNet.Highcharts in my C# program. The data element for series  items requires an object[]. The data I'm using is coming from a LINQ method as shown below. The code below also converts the double?[] to a List<object> then to the desired object[].
double?[] data = (from c in context.CTSeries
                 select c.CTDI).Take(1000).ToArray();

List<object> dataList = new List<object>();

foreach (double? ctdi in data)
{
    dataList.Add( Convert.ChangeType(ctdi, typeof(Object)));
}

object[] dataArray = dataList.ToArray();
return dataArray;

Is there a better/more efficient way of getting the object[] from a double?[]?

A: Use LINQ and cast double? to object
List<object> dataList = data.Select(d => (object)d).ToList();

or  to return an array
return data.Select(d=> (object)d).ToArray();

A: You can just Cast<object>() instead of creating extra intermediate array:
 double?[] data = (from c in context.CTSeries
                     select c.CTDI).Take(1000)
     .Where(v => v.HasValue) // if needed
     .Cast<object>()
     .ToArray();

A: List<object> dataList = data.Select(d =>  d == null ? null : (object)d).ToList();


text:
Q: Wigner-D in MMA Can some nice MMA fellow explain to me why buit-in Wigner-D function is defined as
$D_{mm'}^{J} = e^{i(\phi m+ \gamma m')} d_{mm'}^{j}(\theta)$
against the convention, used by most people on Earth, ex.,
$D_{mm'}^{J} = e^{-i(\phi m+ \gamma m')} d_{mm'}^{j}(\theta)$
Just curious...
P.S.: I hope I just mess up the definition somewhere.


text:
Q: Search through the data with a loop or nested loops in SAS I am rather a beginner in SAS. I have the following problem. Given is a big data set (my_time) which I imported into SAS looking as follows

I want to implement the following algorithm
for every account look for a status and if it is equal to na then look for the same contract after one year (one year after it gets the status na) and put the information "my_date", "status" and "money" in three new columns "new_my_date", "new_status" and "new_money" like in

I need something like countifs in excel. I found loops in SAS like DO  but not for the purpose to look through all rows.
I do not even know for which key word I have to look.
I would be grateful for any hint.

A: A simple method would be by sorting, then exploiting the special variable prefix first. and retain statement to get the desired result.
Step 1: Sort by account, date, and status
proc sort data=have;
    by account my_date status;
run;

This will guarantee that your data is in the order that you need. Since we are looking only for year+1 after the status = 'na', anything that happens in-between that doesn't matter.
Step 2: Use a data step to remember the first year when na happens for that account
data want;
    set have;
    by account my_date status;

    retain first_na_year first_na_account;

    if(first.account) then call missing(first_na_year,first_na_account);

    if(status IN('na', 'tna') ) then do;
         first_na_year    = year;
         first_na_month   = month;
         first_na_account = account;
    end;

    if(    year           = first_na_year+1
       AND first_na_month = month
       AND account        = first_na_account)
       AND status NOT IN('na', 'tna') )
    then do;
        new_status  = status ;
        new_my_date = my_date;
        new_money   = money;
    end;

    if(cmiss(new_status, new_my_date, new_money) ) = 0;

    drop first:;
run;

For each row, we compare three things:

*

*Is the status not 'na'?

*Is the year 1 year bigger than the last time it was 'na'?

*Is this the same account we're comparing?

If all are true, then we want to create the three new variables.
What's happening:
SAS is inherently a looping language, so we do not need to use a do loop here. When SAS goes to a new row, it will clear all variables in the Program Data Vector (PDV) in preparation for filling them in with the new values in the row.
Since SAS the SAS data step only goes forwards and doesn't like to go backwards, we want it to remember the first time that na occurs for that account. retain tells SAS not to discard the value of a variable when it reads a new row.
When we are done doing our comparison and we've moved onto the next account, we reset these variables to missing. by group processing allows SAS to know exactly where the first and last occurrence of the account is in the dataset.
At the end, we output only if all 3 of the new variables are not missing. cmiss counts how many variables are not missing. Note that output is always implied before the run statement, so we simply need to use an "if without then" in this case.
The final statement, drop first:;, is a simple shortcut to remove any variables that start with the phrase first. This prevents them from being shown in the final dataset.


text:
Q: how to call object dynamically in jButton action? i want to do something like this
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
        int i = 0;

        NewClass[] obj = new NewClass[i];

        obj[i] = new  NewClass(args..);

         i++;
}

every time the button clicks, it creates a new object.

A: Firstly, place
int i = 0;
NewClass[] obj;

outside the method.
Secondly, why use an Array and not a Collection? It would then be simply:
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
  //somewhere outside: List<NewClass> obj = new ArrayList<>();
  obj.add(new NewClass(args..);
}


text:
Q: Place a button over an image without using a wrapper div I'm writing a chrome extension that blocks certain images on web pages and adds a button to reveal the blocked images. I need this button to appear somewhere within the bounds of the blocked image, as it appears on the screen.
Were I in control of the whole webpage, the natural way to do this would be to wrap the image in a div and position the button relative to that. However in practice this has not worked well, for two reasons:

*

*Very frequently, img tags are placed in containers that resize the image or hide overflow. Getting the wrapper to match the size the of the actual "image" on the screen is hard to do.

*Injecting a div into the page tends to cause chaos. It picks up unwanted CSS styling and messes with React or Angular websites.
Currently, I'm just inserting the button as a sibling of the image, position it relative to the image's container, and hoping for the best.
JS:
function blockImage(image){
    image.classList.add('blockedImage');
    let button = makeRevealButtonForImage(image);
    image.parentNode.insertBefore(button, image.nextSibling);
}

function makeRevealButtonForImage(img){
    let template = document.createElement('template');
    template.innerHTML =
    '<button type="button" class="reveal-button" ' +
    '">Reveal</button>';
    var button = template.content.firstChild;
    ...
    return button;
}

HTML winds up looking like this:

  <button type="button" class="reveal-button">Reveal</button>

Essential CSS:
.blockedImage {
    background-image: url('chrome-extension://__MSG_@@extension_id__/images/blocked.png');
    background-repeat: no-repeat;
    background-position: center center;
    object-position: -99999px 99999px;
}

.reveal-button {
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    -ms-transform: translate(-50%, -50%);
}


text:
Q: How to add class to html elements in layout [ASP.NET MVC] I have the following problem.
In layout I have menu

            @Html.ActionLink("Blog","Posts","Blog",null,null)

            @Html.ActionLink("Książki", "Books", "Books", null,null)

            @Html.ActionLink("O mnie", "AboutMe", "Blog", null,null)

I want to set class='active' for element that was clicked, so I wrote script below (Ignore that it can be written better) which is also in layout page.

@RenderSection("scripts", required: false)

But after I click on a link it doesn't change. I mean it changes when I step over the script, but after that it seems that the whole page is requested again and changes are overriden. How do I solve this?
Thanks for any replies.
Paweł

A: The problem you are running into here is that you are using a javascript function to set styling on a hyperlink...as you click on the link and begin to navigate away from the page. Javascript is a stateless language, and has no sense of the state it, or the page it is on, was in when you change pages...which is what clicking a hyperlink would be doing.
A better alternative in this case would be to use the onload event, look at your URL, and set the classes based on that. So, something to this effect:
html

            @Html.ActionLink("Blog","Posts","Blog",null,null)

            @Html.ActionLink("Książki", "Books", "Books", null,null)

            @Html.ActionLink("O mnie", "AboutMe", "Blog", null,null)

js
$(document).load(function(){
    var currentUrl = window.location.href;
    if (currentUrl.toLowerCase().indexOf("blog") >= 0){
        $('#BlogLink').addClass('active');
    }
    if (currentUrl.toLowerCase().indexOf("books") >= 0){
         //And so on...
    }
});

I think there is a slightly better way to tackle this, but if you are going to use a stateless language to control your styling, you have to do it on the same page load where you want it to be visible.

A: Could you try something like this?
jQuery(document).ready(function () {
    $('.navbar-nav li').click(function (event) {
        $('.navbar-nav li').removeClass('active');
        $(this).addClass('active');
        event.preventDefault();
        return false;
    });
});

A: It seems you are confused about how JavaScript works with respect to separate HTTP requests and the loading of the page. JavaScript code is part of the current page and executes in the client's browser. Once you navigate to a different page, the whole process starts over again. The page loads, and then any JavaScript code is executed.
Your JavaScript code may be doing what you intend it to do, but after it runs, that page is left and another page is loaded from the server, so any client-side state is lost.
This code should be put on the server, instead of in JavaScript on the client. When you render the HTML in your views, you should set the active class on the appropriate element at that point. When the user clicks a link, it will request a different page from the server, and when you render the HTML for that page, you set the active class accordingly. No JavaScript code is required.


text:
Q: Android 4.4 sdCard files can't be deleted? This question is asking many times but still I didn't get any answer. In my case application is not able to delete files from sdCard in OS 4.4 but many application like Es file explorer Clean master can delete it.
Please help.

A: Maybe you can list your code so we can figure out why you can't delete a file. In my projects, I didn't have this trouble. Permissions missing or wrong path may cause this problem. And if you are reading the file (InputStream is not close), you'll not delete the file either.

A: you might not have enough permission in your app like writing to external storage. You need to add this permission if your app targets below API 19. Read more here: http://developer.android.com/reference/android/Manifest.permission.html#WRITE_EXTERNAL_STORAGE


text:
Q: PortalSiteMapProvider.GlobalNavSiteMapProvider get parent nodes when "display the same navigation items as the parent site" is set We are trying to build a Custom Navigation Web Control to handle our Global Navigation.
The below code works fine until the subsites have "Display the same navigation items as the parent site" set. Then the result is blank.
PortalSiteMapProvider oMap = PortalSiteMapProvider.GlobalNavSiteMapProvider;

foreach (SiteMapNode node in oMap.CurrentNode.ChildNodes)
{
    // add the children of the root site
    htmlOutput += renderTopLevelLink(node, isfirst, currUrl);
    isfirst = false;
}

When "Display the same..." is set, how can I retrieve the parent navigation node?
I've tried using the FindSiteMapNode(oWeb.Url) but the result is my Root Navigation.
P.S. I get the oWeb.Url this way:
protected SPWeb GetNavigationWeb(SPWeb oWeb)
{
    if (oWeb.Navigation.UseShared == true)
    {
        oWeb = GetNavigationWeb(oWeb.ParentWeb);
    }
    return oWeb;
}


text:
Q: Monotonicity and strict order relations Suppose we have a function $g$ that is differentiable (and hence continuous) and monotonically increasing on the interval $[P,Q]$.
I know that this alone is not enough to imply that if $a,b\in [P,Q]$ and $a>b$, then $g(a)>g(b)$, because this is a strict order relation and we only know that $g$ is monotonically increasing.
However, it is definitely true that $\forall m,n\in\mathbb{R}$, if $m>n$ then $m^3>n^3$. This strict order relation is definitely true, even though the cubic function $x^3$ is only monotonocally increasing on $(-\infty,\infty)$. My thought is that this is true because the cubic function $x^3$ is strictly increasing except at $x=0$.
This gave me the following thought:

Question
Suppose there is a function $f(x)$ that is differentiable for all $x\in [P,Q]$. Also, $f(x)$ is strictly increasing  for $x\in[P,Q]$, except for finitely many values of $x$. And, over the interval $[P,Q], f$ is monotonically increasing.
Is the following statement true?: $\forall m,n\in [P,Q]$, if $m>n$ then $f(m)>f(n)$

To clarify, the function is monotonocally increasing on $[P,Q]$, and it is only stationary at finitely many points. I made this restriction so that the graph of $f(x)$ has no "horizontal lines" in $[P,Q]$, and this should mean that the strict order relation holds.
To me, this is intuitively true, although I haven't been able to come up with a formal proof. Like the function $x^3$, the strict order relations will hold for my function $f$, because the function is only stationary at a finite number of points.
Thanks in advance.

A: Just prove it by contardiction. If $m>n$ and $f(n)=f(m)$ then $f(m)\geq f(x) \geq f(n)$ for all $x$ between $n$ and $m$ (by monotonicity)  which makes $f$ constant througout the interval $(n,m)$. But this contradicts your hypothesis.


text:
Q: Getting the error recognizer.train(x_train, np.array(y_labels)) TypeError: src is not a numpy array, neither a scalar Below is my code. When I run it I am getting this error:

recognizer.train(x_train, np.array(y_labels))
  TypeError: src is not a numpy array, neither a scalar

I have tried using recognizer.train(x_train, y_labels) instead of recognizer.train(x_train, np.array(y_labels)) but still get some error?
import cv2
import os
from PIL import Image, ImageEnhance
import numpy as np
import pickle
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
image_dir = os.path.join(BASE_DIR, "images")

face_cascade = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')

path = 'images'
recognizer = cv2.face.LBPHFaceRecognizer_create()

current_id = 0
label_ids = {}
y_labels = []
x_train = []

for root, dirs, files in os.walk(image_dir):
    for file in files:
        if file.endswith("png") or file.endswith("jpg"):

           path = os.path.join(root, file)
           label = os.path.basename(os.path.dirname(path)).replace(" ", "_").lower()
           #print(label, path)
           if not label in label_ids:
               label_ids[label] = current_id
               current_id += 1
               id_ = label_ids[label]
               #print(label_ids)

           y_labels.append(label)
           x_train.append(path)

           pil_image = Image.open(path).convert("L")
           #contrast_enhancer = ImageEnhance.Contrast(pil_image)
           #pil_enhanced_image = contrast_enhancer.enhance(2)
           #enhanced_image = np.asarray(pil_enhanced_image)

           size = (550, 550)
           final_image = pil_image.resize(size, Image.ANTIALIAS)

           image_array = np.array(final_image)
           #print(image_array)
           faces = face_cascade.detectMultiScale(image_array , scaleFactor=1.3, minNeighbors=5)
           for (x,y,w,h) in faces:
               roi = image_array[y:y+h, x:x+w]
               x_train.append(roi)
               y_labels.append(id_)

#print(y_labels)
#print(x_train)
#x_train = np.asarray(x_train)

with open("labels.pickle", "wb") as f:
    pickle.dump(label_ids, f)

recognizer.train(x_train, np.array(y_labels))
recognizer.save("trainner.yml")

A: you may try this, it worked for me:
recognizer.train(x_train, y_labels)

or
recognizer.update(x_train, y_labels)


text:
Q: Failing code check for CS50P, "Little Professor" problem. Can' see why I am trying to solve the "Little Professor" problem from CS50P Problem Set 4. My Python code is not passing the "check50" automatic code check. It's failing on "At Level 1, Little Professor generates addition problems using 0–9." Also failing at Level 2 and Level 3. The error message from check50:

Could not find the following in the output:
6 + 6 =

Actual Output:
6 + 0 =

import random
import sys

def main():
    level = get_level()
    generate_integer(level)

    score = 0

    for i in range(10):
        a = generate_integer(level)
        b = generate_integer(level)

        for j in range(3):
            ans = input(f"{a} + {b} =")
            if int(ans) == int(a + b):
                score += 1
                break
            else:
                print("EEE")
                if j == 2:
                    print(a+b)
            j += 1

        i += 1

    print(f"Score: {score}")
    sys.exit(0)

# Prompts the user for a level, n
# If the user does not input 1, 2, or 3, the program should prompt again.

# get_level prompts (and, if need be, re-prompts) the user for a level and returns 1, 2, or 3,
def get_level():
    while True:
        try:
            level = int(input())
            if level < 1 or level > 3:
                level = input()
            else:
                break
        except ValueError:
            level = input()
    return level

# generate_integer returns a randomly generated non-negative integer with level digits or raises a ValueError if level is not 1, 2, or 3
def generate_integer(level):
    if level == 1:
        y = random.randint(0, 9)
    elif level == 2:
        y = random.randint(10, 99)
    elif level == 3:
        y = random.randint(100, 999)
    else:
        raise ValueError

    return y

if __name__ == "__main__":
    main()

I feel like I'm missing something obvious. Code seems to work as intended when I run it. It seems that check50 is looking for a specific addition problem (6 + 6), but the code is supposed to generate a random addition problem.
Any ideas?

A: I'm almost certain that the testcase is doing something like this:
import random
random.seed(0)
user_module.main()
# check output

Because if you randomly generate 3 numbers with seed 0, you get
import random
random.seed(0)
print(random.randint(0, 9)) # 6
print(random.randint(0, 9)) # 6
print(random.randint(0, 9)) # 0

Given the same random.seed(), randint will always give the same outputs in order.
The issue is this line:
def main():
    level = get_level()
    generate_integer(level) # !!! issue !!!

    score = 0

That value is immediately discarded, so you don't need it. It doesn't do any harm, it's just ignored. But it means that random.randint() gets called one extra time, so the numbers that get used in the code are the 2nd and 3rd outputs of the random seed, rather than the 1st and 2nd. The testcase is based around assuming that you'll give it the 1st and 2nd outputs.

A: In fact generate_integer(level) was useless code and was confusing the code checker.
Thanks for the feedback.


text:
Q: C# Storing Folder Permissions I'm having a little trouble with storing Folder Permissions. I was able to find a some documentation on writing them and reading them. What I'm trying to do is read the permissions on a folder for a specific user > Store it > change the permissions > after installer program finishes, change the permissions back.
I have all of it down (only due to code from many others) EXCEPT how to store the original folder permissions and set it back. I'll gladly read any material that you suggest, we receive several fatal errors with the software and this is one step to resolving many of them. All help is welcome and appreciated.
Below is an example of how I'm setting the permissions. Yes I know that I have everyone, but it is just for testing right now
 public void setPermDir()
    {
        try
        {
            string DirectoryName = "C:\\Temp1\\";

            Console.WriteLine("Adding access control entry for " + DirectoryName);

            // Add the access control entry to the directory.
            AddDirectorySecurity(DirectoryName, @"Everyone", FileSystemRights.FullControl, AccessControlType.Allow);

            Console.WriteLine("Done.");
        }
        catch (Exception e)
        {
            Console.WriteLine(e);
        }

        Console.ReadLine();
    }

    // Adds an ACL entry on the specified directory for the specified account.
    public static void AddDirectorySecurity(string FileName, string Account, FileSystemRights Rights, AccessControlType ControlType)
    {
        // Create a new DirectoryInfo object.
        DirectoryInfo dInfo = new DirectoryInfo(FileName);

        // Get a DirectorySecurity object that represents the
        // current security settings.
        DirectorySecurity dSecurity = dInfo.GetAccessControl();

        // Add the FileSystemAccessRule to the security settings.
        dSecurity.AddAccessRule(new FileSystemAccessRule(Account,
                                                        Rights,
                                                        ControlType));

        // Set the new access settings.
        dInfo.SetAccessControl(dSecurity);

    }

A: If you return the DirectorySecurity dSecurity from AddDirectorySecurity then you could just call Directory.SetAccessControl(directoryName, dSecurity); once you were done with the modified access rules.
Update
If just SetAccessControl doesn't work the next step might be to explicitly remove the permissions you have granted using FileSystemSecurity.RemoveAccessRule.
Just keep a reference to the FileSystemAccessRule you create:
FileSystemAccessRule toRemoveWhenDone = new FileSystemAccessRule(Account, Rights, ControlType);


text:
Q: Microsoft Graph API I can't access my calendar (ResourceNotFound) I work with a client who wants to retrieve events from an outlook calendar.
So I registered from the azure portal an application to access the API.
I manage to generate the token and also to load my user infos with urls :
https://login.microsoftonline.com/{tenantid}/oauth2/v2.0/token (worked)
https://graph.microsoft.com/v1.0/users (worked)

For scope for generate my token, I use "https://graph.microsoft.com/.default".
When I want to access my calendar (the email of my azure account and the same as my outlook account) I have an error :
https://graph.microsoft.com/v1.0/users/{user_id}/calendar

My response :

Screen of my calendar :

From this url :
https://outlook.live.com/calendar/0/view/month

Permissions of my app are done.

To summarize, I can access my user info but my calendar seems to be non-existent. How can I make my calendar known to my application? Thanks !

A: The error Resource not found usually occurs if the users don't have active licenses assigned to the accounts.
I tried to reproduce the same error in my environment
I have registered an application in Azure AD and granted below API permissions:

I got the access token with same scope https://graph.microsoft.com/.default as below:

I'm able to access the users successfully as below:

I tried to access calendar for specific user who does not have any active O365 license like below:

I got "Resource not found" error if the user has no license like below:

I tried to access calendar of specific user who have active O365 licenses like below:

I got the response successfully like below:

So, make sure to have these licenses active while you are trying to get calendar of Outlook.
If still the error persists, please check this Microsoft Q&A


text:
Q: Multiple JFrames in single java code I have two JFrames in my java code, when I close one frame second frame is closed automatically, please tell how I can make them independent of each other?
My code is like this:
JFrame frame1 = new JFrame();
JFrame frame2 = new JFrame();

frame1.setExtendedState(JFrame.MAXIMIZED_BOTH);
frame1.setUndecorated(true);
frame1.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame1.setVisible(true);

frame2.setSize(200,100);
frame2.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame2.setVisible(true);

A: Yours is a common Swing newbie error, and while yes, you could set the JFrame default close operation to DO_NOTHING_ON_CLOSE, you're then still stuck with a bad program design.
Instead, you should almost never display two JFrames at once as a JFrame is meant to display a main application window, and most applications, including and especially professional applications don't have multiple application windows. Instead, make the "mother" window a JFrame, and the child or dependent Window a JDialog, and your problem is solved in that when the child window closes, the application must remain open. The JDialog has the additional advantage of allowing it to be either modal or non-modal as the need dictates.
Other decent solutions including avoiding multiple windows altogether including use of JTabbedPane or the CardLayout to swap views.
Please read: The use of multiple JFrames, good bad practice

Edit
For example
import java.awt.Dialog.ModalityType;
import java.awt.Dimension;
import javax.swing.*;

public class DialogEx {

   private static void createAndShowGui() {
      JFrame frame1 = new JFrame("DialogEx");
      frame1.setExtendedState(JFrame.MAXIMIZED_BOTH);
      frame1.setUndecorated(true);
      frame1.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      frame1.setVisible(true);

      JDialog nonModalDialog = new JDialog(frame1, "Non-Modal Dialog", ModalityType.MODELESS);
      nonModalDialog.add(Box.createRigidArea(new Dimension(200, 200)));
      nonModalDialog.pack();
      nonModalDialog.setLocationByPlatform(true);
      nonModalDialog.setVisible(true);

      JDialog modalDialog = new JDialog(frame1, "Modal Dialog", ModalityType.APPLICATION_MODAL);
      modalDialog.add(Box.createRigidArea(new Dimension(200, 200)));
      modalDialog.pack();
      modalDialog.setLocationByPlatform(true);
      modalDialog.setVisible(true);
   }

   public static void main(String[] args) {
      SwingUtilities.invokeLater(new Runnable() {
         public void run() {
            createAndShowGui();
         }
      });
   }
}

A: This is because you set the default close operation of both the frames to EXIT_ON_CLOSE hence the program with exit irrespective of which frame's close button you clicked on. For your main frame you may set it to EXIT_ON_CLOSE and for other you may set it to DO_NOTHING_ON_CLOSE.
Also, as others have suggested use JDialogs instead of multiple frames.


text:
Q: Throws "No embeddedresource found for NameSpace.App" on iOS but not on Android I'm building a cross-platform application but in iOS, no matter what I try it always throws an XamlParseException in the App.Xaml.g.cs thus preventing me to moving forward on my iOS development
I've tried searching for possible solution about my problem but none of them works. I already checked if the x:Class on the App.xaml and .csproj contents are correct.

A: Bump... deleted the bin and obj folder in all solutions then Build all fixed my problem


text:
Q: Local sync with Azure Table Storage I want to sync data in the Azure Table Storage with a local windows desktop client. The desktop client should work without being online all the time so he has to download the newest data from the ATS and upload any changes which are made to the local data.
Is there something premade to take care of that or do I have to code this from scratch?
Maybe there are some articles on the net I didn't see yet. I suppose the Sync Framework is the way to go here but I did not find anything specific on usage with the Azure Table Storage.

A: I think that actual syncing the data itself is the least of your problems.  Actually emulating  the azure storage while disconnected so that majority of your code is abstracted away from actual implementation is likely to be a lot more challenging.  Azure Table Storage is hard to emulate.  You can attempt to use SQL Express on the local client desktops and in it tables with PartitionKey, RowKey, TimeStamp, and xml-based BLOB to store the objects in a similar way that ATS does it, but it'll be pretty tough to get the to emulation properly.
I haven't seen any technologies or frameworks that do this.  Is your need for capacity and/or scalability that great that you have to use Azure table storage?  Can you do with SQL Azure instead?  Running SQL Express on local desktop clients, syncing SQL Azure with SQL Express, and switching between the two data stores will be MUCH simpler.

A: The Microsoft Sync Framework might help?
https://msdn.microsoft.com/en-us/library/bb902854(v=sql.110).aspx

A: A different approach would be to expose your data via a RESTful service (have a look at asp.net web api). The idea would be that you would simply call out to the a url to get your data
 GET //yourapi/someresource

In the header or the query string you can attach some data to help the service make the decision on what to give you back. In my case I pass up the device id (On Device Generated Guid) and a last sync timestamp.
Using these you can right a small sync manager behind the web service that gives you back all entities changed from other locations after a certain time. To keep all this in sync I have a sync journal in azure storage with has the userId, entityId, deviceId, Timestamp.
By querying and updating this table I can have the server quickly tell me what has changed and it is fast because the partition is per customer.
Since I have abstracted away the table storage I don't actually need to replicate it on the client, I can store the data however I want.