text:
Q: How to use provider? After days of trying to change my methods methods, i finally get a result. But here's my problem: I have a wrapper that is calling from main Every time I restart the app. Im want to use this in my wrapper class:
if(FirebaseAuth.instance.currentUser.emailVerified){}

And this is my wrapper class at the moment:
import 'package:flutter/material.dart';
import 'package:projectandroidstudiodenya/seitenleiste/homepage.dart';
import 'package:provider/provider.dart';
import 'authenticate/authenticate.dart';
import 'models/user.dart';

class Wrapper extends StatelessWidget {
  static const route='/Wrapper';

  @override
  Widget build(BuildContext context) {
    //Auth.auth().currentUser.isEmailVerified;
    //final user = Provider.of<UserCredential>(context);

    final user = Provider.of<User>(context);

    if(user == null){
      return Authenticate();
    }else {
      return Homepage();
    }
    //return Home or Authenticate widget
  }
}

It should look like this:
import 'package:firebase_auth/firebase_auth.dart';
import 'package:flutter/material.dart';
import 'package:projectandroidstudiodenya/seitenleiste/homepage.dart';
import 'package:provider/provider.dart';
import 'authenticate/authenticate.dart';
import 'models/user.dart';

class Wrapper extends StatelessWidget {
  static const route='/Wrapper';

  @override
  Widget build(BuildContext context) {
    //Auth.auth().currentUser.isEmailVerified;
    //final user = Provider.of<UserCredential>(context);

    final user = Provider.of<User>(context);

    if(user == null){
      return Authenticate();
    }else if(FirebaseAuth.instance.currentUser.emailVerified){
      return Homepage();
    }
    //return Home or Authenticate widget
  }
}

So as you can see I calling user.emailVerified. But this is wrong what I really need is what you see at the top . But when im trying to change in my code im getting this error
The name 'User' is defined in the libraries 'package:firebase_auth/firebase_auth.dart' and 'package:projectandroidstudiodenya/models/user.dart'.

I really don't know that to do and how to change.
This is  my Authclass:

import 'dart:async';

import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:firebase_core/firebase_core.dart';
import 'package:flutter/cupertino.dart';
import 'package:projectandroidstudiodenya/authenticate/register.dart';
import 'package:projectandroidstudiodenya/authenticate/signin.dart';
import 'package:projectandroidstudiodenya/authenticate/verifyemail.dart';

import 'package:projectandroidstudiodenya/models/user.dart' as Model;
import 'package:projectandroidstudiodenya/services/database.dart';

import 'database.dart';
import 'database.dart';
import 'database.dart';

class AuthService {
 // final FirebaseAuth _auth = FirebaseAuth.instance.currentUser as FirebaseAuth;
  final FirebaseAuth _auth = FirebaseAuth.instance  ;

  String error;
  String result="";

  //create user obj based on FirebasedUser
  Model.Userr _userFromFirebaseUser(User user) {
    return user != null ? Model.Userr(uid: user.uid) : null;
  }

  Stream <Model.Userr> get user{
    return FirebaseAuth.instance.authStateChanges().map(_userFromFirebaseUser);
}

//SIGNOUT
  Future<void> signOut() async {
    await FirebaseAuth.instance.signOut();
  }
  //sign in anon
  Future signInAnon() async {
    try {
      UserCredential result = await _auth.signInAnonymously();
      User user = result.user;
      return _userFromFirebaseUser(user);
    } catch (e) {
      print(e.toString());
      return null;
    }
  }
  //sign in with passwort and email
  Future signIN(String email, String password) async {
    try {
      //if (FirebaseAuth.instance.currentUser.emailVerified) {print('fuckyooooooo');

      (await _auth.signInWithEmailAndPassword(
          email: email.trim(), password: password)).user?.emailVerified;
    }

      on FirebaseAuthException catch (e) {
      switch (e.code) {
        case 'invalid-email':
          {
            return 'Email is not valid';
          }
        case 'user-disabled':
          {
            return 'Account is not active';
          }
        case 'user-not-found':
          {
            return 'No user found';
          }
        case 'wrong-password':
          {
            return 'wrong password';
          }
        default:
          {
            return 'Please verify you account and restart the App';
          }
      }

    }

      return null;

  }

//register with passwort an email
  Future signUp(String email, String password,) async {
    try {

      UserCredential result =await _auth.createUserWithEmailAndPassword(
          email: email, password: password);
          result.user?.sendEmailVerification();
          User user =result?.user;
      await DatbaseService(uid:user.uid).updateUserData('0','new crew member','100','dfdssf');
          return ;

      //user.sendEmailVerification();
     // ( await DatbaseService(uid:user).updateUserData('0','new crew member','100','dfdssf')).user.uid;;
    } on FirebaseAuthException catch (e) {
      switch (e.code) {
        case 'invalid-email':
          {
            return 'Email is not valid';
          }
        case 'user-disabled':
          {
            return 'Account is not active';
          }
        case 'user-not-found':
          {
            return 'No user found';
          }
        case 'wrong-password':
          {
            return 'wrong password';
          }
        default:
          {
            return 'Unexpected error!';
          }
      }
    }
    return null;
  }

  Model.Userr getCurrentUser(User user) {

    return user != null ? Model.Userr() : null;
  }

  //resetpassword
  Future sendPasswordResetEmail(String email) async {
    try {
      return await _auth.sendPasswordResetEmail(email: email);
    } on FirebaseAuthException catch (e) {
      switch (e.code) {
        case 'invalid-email':
          {
            return 'Email is not valid';
          }
        case 'user-disabled':
          {
            return 'Account is not active';
          }
        case 'user-not-found':
          {
            return 'No user found';
          }
        case 'wrong-password':
          {
            return 'wrong password';
          }
        default:
          {
            return 'Unexpected error!';
          }
          return null;
      }
    }
  }
}

here's my main

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  await Firebase.initializeApp();
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context){
   return
      StreamProvider<Userr>.value(

        child: MaterialApp(
                  debugShowCheckedModeBanner: false,
                  title:'Appbar Scaffold',
                  theme: ThemeData(
                    scaffoldBackgroundColor: Colors.white,
                    primaryColor: Colors.white,
                  ),
                  //home: Homepage(),
                  //initialRoute: '/',
               // initialRoute: FirebaseAuth.instance.currentUser==null?LoginScreen():Homepage.route(),
                  routes:{'/':(_)=>Wrapper(),
                   Homepage.route:(_)=> Homepage(),

                    Beitraegedieichmag.route:(_)=> Beitraegedieichmag(),
                    MeinAccount.route:(_)=> MeinAccount(),
                    MeineBeitraege.route:(_)=>MeineBeitraege(),
                    MeineFreunde.route:(_)=> MeineFreunde(),
                    Nachrchten.route:(_)=> Nachrchten(),
                    LoginScreen.route:(_)=> LoginScreen(),
                  } ,

This is the error:
======== Exception caught by widgets library =======================================================
The following ProviderNotFoundException was thrown building Wrapper(dirty):
Error: Could not find the correct Provider<User> above this Wrapper Widget

This happens because you used a `BuildContext` that does not include the provider
of your choice. There are a few common scenarios:

- You added a new provider in your `main.dart` and performed a hot-reload.
  To fix, perform a hot-restart.

- The provider you are trying to read is in a different route.

  Providers are "scoped". So if you insert of provider inside a route, then
  other routes will not be able to access that provider.

- You used a `BuildContext` that is an ancestor of the provider you are trying to read.

  Make sure that Wrapper is under your MultiProvider/Provider<User>.
  This usually happens when you are creating a provider and trying to read it immediately.

  For example, instead of:

  Widget build(BuildContext context) {
    return Provider<Example>(
      create: (_) => Example(),
      // Will throw a ProviderNotFoundError, because `context` is associated
      // to the widget that is the parent of `Provider<Example>`
      child: Text(context.watch<Example>()),
    ),
  }

  consider using `builder` like so:

  Widget build(BuildContext context) {
    return Provider<Example>(
      create: (_) => Example(),
      // we use `builder` to obtain a new `BuildContext` that has access to the provider
      builder: (context) {
        // No longer throws
        return Text(context.watch<Example>()),
      }
    ),
  }

If none of these solutions work, consider asking for help on StackOverflow:
https://stackoverflow.com/questions/tagged/flutter

The relevant error-causing widget was:
  Wrapper file:///Users/yavuzatmaca/StudioProjects/projectandroidstudiodenya/lib/main.dart:44:36
When the exception was thrown, this was the stack:
#0      Provider._inheritedElementOf (package:provider/src/provider.dart:332:7)
#1      Provider.of (package:provider/src/provider.dart:284:30)
#2      Wrapper.build (package:projectandroidstudiodenya/wrapper.dart:20:27)
#3      StatelessElement.build (package:flutter/src/widgets/framework.dart:4661:28)
#4      ComponentElement.performRebuild (package:flutter/src/widgets/framework.dart:4587:15)

====================================================================================================
Reloaded 16 of 687 libraries in 640ms.

This is my user class

import 'package:flutter/cupertino.dart';

class Userr{

 final String uid;

 Userr({this.uid});

}

This is the error now:

======== Exception caught by widgets library =======================================================
The following NoSuchMethodError was thrown building Wrapper(dirty, dependencies: [_InheritedProviderScope<Userr>]):
The getter 'emailVerified' was called on null.
Receiver: null
Tried calling: emailVerified

The relevant error-causing widget was:
  Wrapper file:///Users/yavuzatmaca/StudioProjects/projectandroidstudiodenya/lib/main.dart:47:36
When the exception was thrown, this was the stack:
#0      Object.noSuchMethod (dart:core-patch/object_patch.dart:54:5)
#1      Wrapper.build (package:projectandroidstudiodenya/wrapper.dart:22:42)
#2      StatelessElement.build (package:flutter/src/widgets/framework.dart:4661:28)
#3      ComponentElement.performRebuild (package:flutter/src/widgets/framework.dart:4587:15)
#4      Element.rebuild (package:flutter/src/widgets/framework.dart:4281:5)
...
====================================================================================================

======== Exception caught by widgets library =======================================================
The following NoSuchMethodError was thrown building Wrapper(dirty, dependencies: [_InheritedProviderScope<Userr>]):
The getter 'emailVerified' was called on null.
Receiver: null
Tried calling: emailVerified

The relevant error-causing widget was:
  Wrapper file:///Users/name/StudioProjects/projectname/lib/main.dart:47:36
When the exception was thrown, this was the stack:
#0      Object.noSuchMethod (dart:core-patch/object_patch.dart:54:5)
#1      Wrapper.build (package:projectname/wrapper.dart:22:42)
#2      StatelessElement.build (package:flutter/src/widgets/framework.dart:4661:28)
#3      ComponentElement.performRebuild (package:flutter/src/widgets/framework.dart:4587:15)
#4      Element.rebuild (package:flutter/src/widgets/framework.dart:4281:5)
...
====================================================================================================

A: Try this:
class Wrapper extends StatelessWidget {
  static const route='/Wrapper';

  @override
  Widget build(BuildContext context) {

    final user = Provider.of<Userr>(context);

    if(user == null){
      return Authenticate();
    }else if(FirebaseAuth.instance.currentUser.emailVerified){
      return Homepage();
    }
    //return Home or Authenticate widget
  }}

Main.dart:
void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  await Firebase.initializeApp();
  runApp(StreamProvider<Userr>.value(
    value: AuthService().user,
    child: MaterialApp(
      home: MyApp(),
    ),
  ));
}
class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      ...
    );
  }
}


text:
Q: Location of java.security and deployment.properties files Where are java.security and deployment.properties files located on Mac OS Yosemite??

A: OSX Yosemite 10.10.5

/Library/Java/JavaVirtualMachines/jdk1.7.0_67.jdk/Contents/Home/jre/lib/security/java.security

redpajama_set_name: RedPajamaStackExchange


text:
Q: Laravel Nova gate doesn't stop from entering login in production I implemented Laravel Nova as admin panel for my application. I'm not using the default guard for authentication, instead I use an admin guard and admin users table. Everything works fine.
Now I wanted to implement it to the production server. However, the gate is not working, since every user can still enter the Nova login at myapplication.com/nova. This should only be possible in a local environment.
I even tried to change the return of the gate to false, however it seems that nova is not entering the gate function either.
My NovaServiceProvider.php looks like this:
protected function gate()
    {
        Gate::define('viewNova', function ($user) {
            return false;
        });
    }

Why doesn't Nova enter the gate, even on production server? Is there any chance to fix this?

A: /**
 * Configure the Telescope authorization services.
 *
 * @return void
 */
protected function authorization()
{
    $this->gate();

    Telescope::auth(function ($request) {
        return app()->environment('local') ||
               Gate::any(['viewTelescope', 'Access Telescope'], [$request->user()]);
    });
}

Try overriding the authorization method


text:
Q: Interactively building a "multiple-step" function using lambda functions in python I am trying to build a function that is a fuction of "r" and takes two array of parameters r0 and V, as well as n which is the number of elements of r0.
The function is defined such as : if r is below r[0], return V[0]; if r is between r[0] and r[1], return V[1] etc… and finally, if r is above r[n], return V[n+1]. This illustrates the function when defined manually for n = 3:

Here is a sample code I tried to do so using lambda functions:
n = 3
r0 = [10,30,60]
V = [1., -5. , 10., 3. ]

def makefn(r0, V):
    return lambda r : (V[0]-V[1])/2 if r < r0[0] else (V[1]-V[0])/2

for i in range(n):
    temp_function[i] = makefn(r0[i:i+1],V[i:i+2])

step_function = lambda r : (V[0]+V[-1])/2 + [temp_function[i](r) for i in range(n)]

The problems are : – I do not know how to pre-allocate a list of functions, so it returns " "temp_function" undefined." " – I do not know how to "add" functions so they combine there result.
Any idea on how to fix this code ?


text:
Q: Insert space before middle initial name In column A I have a list of names. For example in cell A1 I have:
Johnson,BenE.

The "E." is the middle initial part of the name. I needed to insert a space so that it looks like
Johnson,Ben E.

I can't seem to figure out the proper formula for it.

A: And, to make use of a rarely used function:
=REPLACE(A1,LEN(A1)-1,0," ")

A: =LEFT(A1,SEARCH(".",A1)-2) &" " & RIGHT(A1,2)
Got it!

A: Assuming the middle initial is always one letter followed by a period
=LEFT(A1,LEN(A1)-2)&' '&RIGHT(A1,2)


text:
Q: SQL Server: NonClustered index not used I have read a lot about indexing and differences between them. Now i am working on query optimization in my project. I have created nonclustered index, that should be used on query execution, but that is not the case. Details below:
Table:

Index:
CREATE NONCLUSTERED INDEX [_IXProcedure_Deleted_Date] ON [por].[DailyAsset]
(
    [Deleted] ASC,
    [Date] DESC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
GO

Query generated by Entity Framework:
exec sp_executesql N'SELECT
[Project1].[C1] AS [C1],
[Project1].[AssetId] AS [AssetId],
[Project1].[Active] AS [Active],
[Project1].[Date] AS [Date]
FROM ( SELECT
    [Extent1].[AssetId] AS [AssetId],
    [Extent1].[Active] AS [Active],
    [Extent1].[Date] AS [Date],
    1 AS [C1]
    FROM [por].[DailyAsset] AS [Extent1]
    WHERE (0 = [Extent1].[Deleted]) AND ([Extent1].[Date] < @p__linq__0)
)  AS [Project1]
ORDER BY [Project1].[Date] DESC',N'@p__linq__0 datetime2(7)',@p__linq__0='2014-05-01 00:00:00'

Execution plan:

Missing index details:
The Query Processor estimates that implementing the following index could improve the query cost by 23.8027%.

CREATE NONCLUSTERED INDEX [<Name of Missing Index, sysname,>]
ON [por].[DailyAsset] ([Deleted],[Date])
INCLUDE ([AssetId],[Active])

I am aware that with inclusion of AssetId and Active columns to index, index will be used.
Now, why it is not working without column inclusion?
This is simplified example of another queries, where all columns are fetched as a result. The only solution to (force) index seek usage, is to include all columns in index, which has the same Estimated Subtree cost (obvious).
Another annoying issue here is Sort ignorance. Date columns is in index and set to DESCENDING. It is completly ignored, and ofcourse, Sort operations takes expensive place in execution plan.
UPDATE 1:
As @Jayachandran pointed out, IndexSeek + KeyLookUp should be used in query above, but covering index is well documented, and it assumes that AssetId and Active columns should be included. I agree with that.
I am creating UPDATE 1 to demonstrate covering index usefulness in query below. Same table, larger result set. As far as i can figure it out, not a single columns should not be used in index, and index stays created for Date and Deleted columns.
exec sp_executesql N'SELECT
[Project1].[DailyAssetId] AS [DailyAssetId],
[Project1].[AssetId] AS [AssetId],
[Project1].[CreatedByUserId] AS [CreatedByUserId],
[Project1].[UpdatedByUserId] AS [UpdatedByUserId],
[Project1].[TimeCreated] AS [TimeCreated],
[Project1].[TimeUpdated] AS [TimeUpdated],
[Project1].[Deleted] AS [Deleted],
[Project1].[TimeDeleted] AS [TimeDeleted],
[Project1].[DeletedByUserId] AS [DeletedByUserId],
[Project1].[Active] AS [Active],
[Project1].[Date] AS [Date],
[Project1].[Quantity] AS [Quantity],
[Project1].[TotalBookValue] AS [TotalBookValue],
[Project1].[CostPrice] AS [CostPrice],
[Project1].[CostValue] AS [CostValue],
[Project1].[FairPrice] AS [FairPrice],
[Project1].[FairValue] AS [FairValue],
[Project1].[UnsettledQuantity] AS [UnsettledQuantity],
[Project1].[UnsettledValue] AS [UnsettledValue],
[Project1].[SettlementDate] AS [SettlementDate],
[Project1].[EffectiveDate] AS [EffectiveDate],
[Project1].[PortfolioId] AS [PortfolioId]
FROM ( SELECT
    [Extent1].[DailyAssetId] AS [DailyAssetId],
    [Extent1].[AssetId] AS [AssetId],
    [Extent1].[CreatedByUserId] AS [CreatedByUserId],
    [Extent1].[UpdatedByUserId] AS [UpdatedByUserId],
    [Extent1].[TimeCreated] AS [TimeCreated],
    [Extent1].[TimeUpdated] AS [TimeUpdated],
    [Extent1].[Deleted] AS [Deleted],
    [Extent1].[TimeDeleted] AS [TimeDeleted],
    [Extent1].[DeletedByUserId] AS [DeletedByUserId],
    [Extent1].[Active] AS [Active],
    [Extent1].[Date] AS [Date],
    [Extent1].[Quantity] AS [Quantity],
    [Extent1].[TotalBookValue] AS [TotalBookValue],
    [Extent1].[CostPrice] AS [CostPrice],
    [Extent1].[CostValue] AS [CostValue],
    [Extent1].[FairPrice] AS [FairPrice],
    [Extent1].[FairValue] AS [FairValue],
    [Extent1].[UnsettledQuantity] AS [UnsettledQuantity],
    [Extent1].[UnsettledValue] AS [UnsettledValue],
    [Extent1].[SettlementDate] AS [SettlementDate],
    [Extent1].[EffectiveDate] AS [EffectiveDate],
    [Extent1].[PortfolioId] AS [PortfolioId]
    FROM [por].[DailyAsset] AS [Extent1]
    WHERE (0 = [Extent1].[Deleted]) AND ([Extent1].[Date] < @p__linq__0)
)  AS [Project1]
ORDER BY [Project1].[Date] DESC',N'@p__linq__0 datetime2(7)',@p__linq__0='2014-05-01 00:00:00'

A: The difference with a scan and a seek (with key lookup) in this case is because of the number of the rows being returned.  The volume is too great and so the optimizer has chosen a cheaper plan - just scan the whole table.  This will be faster than using the NC index.
Imagine if you had forced it to use the NC index and it had to do a key lookup for 40% of the rows in the table.  This would be like a foreach loop executing many times.  So SQL has chosen to just scan the table because it would be faster than the loop.
Regarding your question about how to account for other columns that might be included in other queries, there are really a couple of choices.  You could create a covering index that includes the most commonly used columns or you could change the primary key to orient it towards your most common access path.  i.e. by date, deleted and an identity column for uniqueness.
On another note, using a guid for a primary key causes all sorts of problems with your clustered index and all other indexes (because the key for the PK will be included in all other indexes).  The random ordering of guids causes rows to be inserted in random order in pages.  Because the index is ordered, pages must constantly be split in order to account for new rows.  It would be far better to create an index that naturally increments and this would likely help the problem above as well, depending on the types of queries that are written.

A: The ideal index for a specific query is one where (1) all the fields in the WHERE clause are in the index, and (2) all the fields in the SELECT clause are included in the index. If (1) is not met, SQL Server will weight the cost of accessing multiple indexes and pick the one it think is fastest; if (2) is not met, that means an expensive Key Lookup operation. SQL Server may think it's worth it if the index has very high selectivity (few duplicate values).
In your case, condition (2) is clearly not met. SQL Server thinks that the Key Lookup operation is too expensive compared to a clustered index scan so it chose the later. You can force SQL Server to use a particular index, but I don't know how to do that with Entity Framework.
If this query must be speedy for you, create the index as SQL Server says.


text:
Q: Qt Drag and Drop - Change image display while dragging I started a drag with image.
QDrag* drag = new(QDrag)(this);
drag->setPixmap(*pixmap);
drag->exec(Qt::CopyAction | Qt::MoveAction);

I want to change the image display when my drag reach certain point in the widget.
Currently I have an idea. After I start the first drag, when my drag reaches a certain point, I cancel the first drag then I restart a new drag with a new image.
I do this in dragMoveEvent. I'm able to start a new drag with a new image. But I seem to be unable to cancel the first drag. I find that the the previous drag/drop action is still being performed.
Anyone could suggest:
if (event->mimeData()->hasText())
{
  if (need_to_change_pixmap())
  {
    event->setDropAction(Qt::IgnoreAction);
    change_pixmap_restart_drag();
  }
  else
  {
    event->setDropAction(Qt::MoveAction);
    event->accept();
  }
}
else
{
  event->ignore();
}

The change_pixmap_restart_drag function just do start drag.

A: According to Qt's documentation, you can't change the pixmap once the dragging has started.
Qt uses:

*

*a frameless windows which follow the mouse on X11. The pixmap is painted on the widget, and setGrabMouse is used to receive mouse events, since the widget is not directly under the mouse.

*the function SetCursor on Windows, with a copy of the pixmap where the cursors for each action has been painted in the corner.

*the function SetDragImageWithCGImage on Mac, but needs a DragRef object which is declared as an inaccessible local variable in qdnd_mac.mm.

You could try to use the X11 method on all platforms, or use SetCursor if you only plan to deploy your application on Windows.

A: From QDrag docs:
void QDrag::setPixmap ( const QPixmap & pixmap ) :

Sets pixmap as the pixmap used to represent the data in a drag and drop operation. You can only set a pixmap before the drag is started.
So, I'm sorry, but you can't!
Even setDragCursor() is a method with no effects...


text:
Q: Make jQuery no conflict I am creating a web widget to be posted on other websites. In the widget it will call jQuery and I dont want the jQuery to conflict with other JavaScript libraries that the website may have installed. When I load the jQuery I would like to call jQuery like this:
JQuery_MYSite('id').find('selector');

I found out if I do this then $ will not be able to be used even if the other website uses $.

When the widget loads it find out if jQuery is loaded. If so, then it will use the $ to call jQuery. But I know $ is not unique to just jQuery - other javascript libraries use it. So how can I use my own jQuery prefix with without interfering with the website owners prefix.

A:
In the widget it will call jQuery and I dont want the jQuery to
  conflict with other JavaScript libraries that the website may have
  installed.

I don't think you can achieve this, because jQuery.noConflict() must be called after the other scripts have been loaded. So, if there is no way for you to know about the other scripts, then you won't have a way to avoid the conflicting.

When the widget loads it find out if jQuery is loaded. If so, then it
  will use the $ to call jQuery. But I know $ is not unique to just
  jQuery - other javascript libraries use it. So how can I use my own
  jQuery prefix with without interfering with the website owners prefix.

Wrap your widget code with an auto-executing anonymous function:
(function($){

// your widget code here
// $ will always be jQuery

})(jQuery);

A: var myJquery = jQuery.noConflict();

then if you want to get fancy:
(function($){
    $(".whatever").doSomeStuff();
})(myJquery);

A: use noConflict
<script type="text/javascript">
  $.noConflict();
  jQuery(document).ready(function($) {
    // Code that uses jQuery's $ can follow here.
  });
  // Code that uses other library's $ can follow here.
</script>

A: look at noConflict
$.noConflict();
(function($){
   // $ is jQuery here
})(jQuery);

A: Check out jQuery.noConflict().


text:
Q: PHP application state In ASP.NET I can store both session and application state.  Is the same true of PHP?  I can't seem to find information on application state.
If not, what are best practices for shared state information?  I need to build a somewhat complex data structure that all clients can utilize.  It takes a while to build but is never edited after it's built.
thanks,
Michael

A: PHP doesn't have any equivalent to Application State. Your best option would be to maintain your data structure within APC or memcache (or WinCache on a Windows server).

A: PHP doesn't have any application state, however you can use different PHP runtime - Phalanger (http://phalanger.codeplex.com/). It is PHP to .NET compiler and allows you to take advantage of most of .NET features. Among others, you can define real static variable.
class X {
    [AppStatic]
    static $x;
}
echo X::$x;

Of course you have to take care of critical sections etc.

A: While PHP doesn't have an inbuilt application state system, you can emulate one pretty easy if you don't write after it's built (you can emulate it if you need to write, but concurrency issues will make it a lot harder to do properly).
Basically, PHP provides a serialize method to store objects in strings.  You could then build a simple caching layer in a factory class to store the object on the filesystem:
class Factory {
    public static function getFooObject() {
        $signature = 'foo';
        $obj = self::getStoredObject($signature);
        if (!$obj) {
            $obj = new Foo();
            self::storeObject($signature, $object);
        }
        return $obj;
    }
    public static function getFooBarObject($arg1) {
        $signature = 'foobar_'.md5(serialize($arg1));
        $obj = self::getStoredObject($signature);
        if (!$obj) {
            $obj = new FooBar($arg1);
            self::storeObject($signature, $object);
        }
        return $obj;
    }
    protected function getStoredObject($signature) {
        $path = PATH_TO_CACHE . $signature;
        if (file_exists($path)) {
            $data = file_get_contents($path);
            $obj = @unserialize($data);
            return $obj;  //Would return false on error, so we're ok
        }
        return false;
    }
    protected function storeObject($signature, $obj) {
        $path = PATH_TO_CACHE . $signature;
        file_put_contents($path, serialize($obj));
    }
}

That's all there really is to it.  If you wanted to get fancy you could implement a meta-data system and version your classes so that if you made a change to the underlying class it would implicitly flush the cached object and re-initialize it.


text:
Q: Gatsby app deploy to Netlify issue Netlify is supposed to be amazing for depoying a gatsby site but having issues such as "Gatsby command not found" when this is the default.
Tried changing to just "BUILD" since this is my package.json script but still nothing... any thoughts?

A: The docs at Gatsby instruct you to install the cli globally: npm install --global gatsby-cli. This probably results in a missing dependency in production, hence the gatsby command not found error.
In short, make sure gatsby is part of your dependencies inside package.json

A: Romeo is right, but you have to install gatsby-cli locally (npm i gatsby-cli), so that it appears in the package.json file, and saved to Git.
(npm i -global gatsby-cli will probably fail, because that will not record the dependency in the package.json file.)
That way, when the netlify build process uses the package.json file to build the package, gatsby-cli is in there, and the "gatsby build" command will be available.


text:
Q: How to catch update exception and what kind of notification to do here? I have a trigger with helper class and test. But I don't know how to test update there and what kind of notification I need. Thanks for any help.
Trigger:
trigger ArchivedTrigger on Item__c (after update) {
JTriggerHelper triggerHelper = new TriggerHelper();

if(Trigger.isUpdate){
    for(Item__c item : Trigger.new){
        if(item.Status__c == 'Old'){
            triggerHelper.remove(item);
        }
    }
}
}

Helper:
public void remove(Item__c item){
    List<Tool__c> toolsList  = [SELECT Id, CustomIDs__c FROM Tool__c];

    for(Tool__c tool : toolsList){
        if(tool.CustomIDs__c != null && tool.CustomIDs__c.contains(item.CustomIDs__c)){
            List<String> positionIdsList = String.valueOf(tool.CustomIDs__c).split(' ');

            for(Integer i=0; i<positionIdsList.size(); i++){
                if(positionIdsList[i] == item.CustomIDs__c){
                    positionIdsList.remove(i);
                }
            }
            tool.CustomIDs__c = String.join(positionIdsList,' ');

            try{
                update tool;
            //How to test an exception here?
            } catch(Exception e){
                //What is better to do here? Email? Logs for developer?
            }
        }
    }
}

Test:
@isTest
static void testUpdateTrigger() {
    TriggerHelper triggerHelper = new TriggerHelper();

    Tool__c tool = new Tool__c(Email__c = 'test@test.com', CustomIDs__c = 'text 999999');
    insert tool;
    Item__c testTool = new Item__c(CustomIDs__c = '999999');
    insert testTool;

    testTool.Status__c = 'Old';
    update testTool;

    Test.startTest();
        triggerHelper.removePositionId(testTool);
    Test.stopTest();

    Tool__c toolTest = [SELECT CustomIDs__c FROM Tool__c WHERE Email__c = 'test@test.com'];
    System.assertEquals('text', toolTest.CustomIDs__c);
}

A: First thing you don't need to do this in after update, as you are just populating tool.CustomIDs__c field. You can do the same in before update trigger and no need to update records explicitly.
Second, you are trying to update single record at a time in a for loop which is not recommended, every DML must be bulkified, I would suggest you to learn in detail about apex triggers here
after modification your code be like
Trigger
trigger ArchivedTrigger on Item__c (before update) {
    JTriggerHelper triggerHelper = new TriggerHelper();

    if(Trigger.isUpdate){
        for(Item__c item : Trigger.new){
            if(item.Status__c == 'Old'){
                triggerHelper.remove(item);
            }
        }
    }
}

Helper:
public void remove(Item__c item){
    List<Tool__c> toolsList  = [SELECT Id, CustomIDs__c FROM Tool__c];

    for(Tool__c tool : toolsList){
        if(tool.CustomIDs__c != null && tool.CustomIDs__c.contains(item.CustomIDs__c)){
            List<String> positionIdsList = String.valueOf(tool.CustomIDs__c).split(' ');

            for(Integer i=0; i<positionIdsList.size(); i++){
                if(positionIdsList[i] == item.CustomIDs__c){
                    positionIdsList.remove(i);
                }
            }
            tool.CustomIDs__c = String.join(positionIdsList,' ');

            /* no need to update as in before trigger any changes made in trigger context records will be saved in database
            */
        }
    }
}


text:
Q: shebang and path Why does a shebang need a path?
Wrong
#!ruby

Correct
#!/usr/local/bin/ruby

#!/usr/bin/env ruby

The operating system should have the information regarding the path for a registered command, and why does it still expect it to be given?

A: You can get PATH-searching semantics using env, so:
#!/usr/bin/env ruby

has the semantics you would like from
#!ruby

The reason that depending on PATH is not considered good practice is that the script can make no assumptions about the content of the PATH environment variable, breaking the "sequential dependency model" of binaries where

*

*/bin contains the executables needed at boot time;

*/usr/bin contains the other executables used by the OS installation;

*/usr/local/bin contains executables installed by the system administrator that are not part of the base OS.

*~/bin contains the user's own executables.

Each level should not assume the existence of binaries later in the sequence, which are more "application" but may rely on binaries earlier, which are more "fundament".  And the PATH variable tends to run from applicationy to fundamental, which is the opposite direction to the natural dependency above.
To illustrate the problem, ask yourself what happens if a script in ~/bin invokes an script in /usr/local/bin that invokes Ruby?  Should that script depend on the OS installed version at /usr/bin/ruby, or on the personal copy the user happens to have at ~/bin/ruby?  PATH searching gives the unpredictable semantics associated with the latter (maybe ~/bin/ruby is a broken symbolic link), while baking in the path to #! gives the former.
There isn't really any other platform-independent "operating system ... information regarding the path for a registered command", so the simplest thing is to insist on the path being provided in the #!.

A: Probably to keep the kernel simpler.  I don't think the kernel ever searches your path to find an executable.  That's handled by the C library.  #! processing is done in the kernel, which doesn't use the standard C library.
Also, I don't think the kernel has a notion of what your path is.  $PATH is an environment variable, and only processes have an environment.  The kernel doesn't.  I suppose it could access the environment of the process that did the exec, but I don't think anything currently in the kernel ever accesses environment variables like that.

A: I believe that's so you can specify an alternate interpreter if you need or want to. For example:
#!/home/user/myrubyinterpreter

More often seen with shell scripts:
#!/bin/bash
#!/bin/sh
#!/bin/dash
#!/bin/csh

A: From Classic Shell Scripting book:

Shell scripts typically start with #! /bin/sh. Use the path to a
  POSIX-compliant shell if your /bin/sh isn't POSIX compliant. There are
  also some low-level "gotchas" to watch out for:

*

*You have to know the full pathname to the interpreter to be run. This can prevent cross-vendor portability, since different vendors put
  things in different places (e.g., /bin/awk versus /usr/bin/awk).

A: There are other reasons, but from a security perspective I would never want a script to make assumptions about the correct path. What if it is wrong and it runs the wrong shell or interpreter? One that has been inserted by a malicious user? Or what if it relies on a particular shell and will crash out if the wrong shell is used?
Users may mess around with their path and break stuff - don't trust the user:-) I have conducted numerous attacks which rely on the user doing the wrong thing with their path - usually getting things in the wrong order - so I can subvert a normal script call.
Yes, I know if you've written the script yourself you can quite rightly claim that you have sorted out your own path, but an interpreter can't make those decisions.


text:
Q: html 5 canvas: using draw image in game makes loop very slow i am making a game based on draw images and clear it every some part of second.
i started with:
var peng = new Image();

and then:
  peng.onload = function() {
context.drawImage(peng, pengXPosition, pengYPosition, pengWidth, pengHight);
};

and in the loop:
var i=0;
function pengMoveRight(){ i++;if(i==1){peng.src = 'images/1.png';}else if(i==2)
       {peng.src = 'images/2.png';} else if(i==3){peng.src = 'images/3.png';}else if(i==4){
        peng.src = 'images/4.png';}else if(i==5){peng.src = 'images/5.png';}else if(i==6){
        peng.src = 'images/6.png';i-=6;}}

when i run it it works well on IE but on chrome and mozilla it`s too slow and the character is about to disappear .. i used setinterval(); once and window.requestAnimationFrame(); once and both of them cause the same problem.
what should i do to make it smooth move?
here is the full script http://mark-tec.com/custom%20game/

A: Instead of changing the source, try to create several Image objects instead. That way, the drawImage call can always use a pre-loaded image.

A: You need to preload all the images or use the sprite method (all images packed into a single sprite) in order to avoid the initial delay caused by the image loading only when it's needed.
However, after that initial problem, your example should run fine once all the images are cached.


text:
Q: VS2010 gives errors when programming in qt I've got a question regarding the use of Qt with Microsoft Visual Studio 2010.
I've installed Visual Studio, Qt and the Qt VS2010 plugin. Everything works fine, and I can compile simple programs. Only one thing that doesn't work like it should.
When I am writing code in the VS2010 editor, I get errors like "Error: identifier QApplication is undefined." or "Error: cannot open source file QApplication". The code that I am using is
#include <QApplication>
#include <QtGui>

int main(int argc, char *argv[]) {
    QApplication a(argc, argv);
    test w;
    w.show();
    return a.exec();
}

I think it has something to do with linking the code checker to the source files of Qt but I can't find this option somewhere in VS2010.
Regards,


text:
Q: How does upcasting works in Java? I was going with the concept of upcasting and downcasting in java, which are also referred as widening and narrowing.

*

*UpCasting (Widening) happens automatically from derived class to base class. i.e if it has a is-a relationship.

*Downcasting has to be done explicitly for run time check.

Okay, I got the concept and everything. But, how its working in this case?
public class ObjPair {
    Object first;
    Object second;

    public ObjPair(Object first, Object second) {
        this.first = first;
        this.second = second;
    }

    public Object getFirst() {
        return first;
    }
    public Object getSecond() {
        return second;
    }

    public static void main(String[] args) {
        ObjPair objPair = new ObjPair("A",2.2); // Goes widning conversion
        System.out.println(objPair.getFirst());
        System.out.println(objPair.getSecond());
    }
}

ObjPair objPair = new ObjPair("A",2.2);

*

*This is going through upcast, String to object and Double to object and the state gets store in the objPair. Great..!!!

Now,when i do objPair.getFirst() and objPair.getSecond(). It returns me A and 2.2.

*

*How does it remember the string and double, widening/upcast is supposed to remember the super-class states and methods.

*How is it able to access sub-class types and values?

A: Casting of object references does not change the object. It simply allows assigning it into a reference of a different type. The object itself remains the same.
In your case, it needs two Object references, it checks compatibility (no problem there), and then the references are set in variables of type Object. The instances themselves do not change. If they have methods that override those of Object, then the overriding methods will be called.
Thus, when it comes to the part where it prints the object, it simply uses String.valueOf, which calls the object's toString() method. The instance accessed from the Object variables is actually a String object, and String overrides toString() to return itself. Double also overrides toString. These overrides are called, as the instance is still an instance of String and an instance of Double. Only the reference is Object.
Note that you also have a cast from double to Double there. This implicit boxing does change the object - it takes a primitive and creates a new Double from it.

A: If you simply test this code:
public class Main {

    public Object first;
    public Object second;

    public static void main (String[] args){
        Main a = new Main();
        a.first = new String("foo");
        a.second = 5;

        System.out.println(a.first.getClass().toString());
    }
}

It outputs class java.lang.String. You can see that it isn't stored as an Object. This is achieved through the use of metadata.

A: Keep in mind: the object in memory is what it is. If you create a Double object, then it is a Double object resembling the numerical value.
The fact that the variable that holds the reference uses a super type doesn't affect the object referenced to at all!
In your example, the auto-boxing create a Double object under the cover, andgetSecond() returns a reference to that Double object.
That is all there is to this.

A: Okay so here it is, lets take an example. You have a big square box,named Object and another small box. If you keep this small box inside your big box,all the properties of small box and big box are in the big box.
Then inside the small box,there are two sticks,you are labeling the first stick as  'A' and second as '2.2'.
Now the big box can see what is inside of small box. Now for that instant,  the small box is having two sticks and labelled as the way they are.
(Rememeber the Object class is always the super class/parent of every classes in java).


text:
Q: How can I blit the frame rate on my screen with pygame? I know that I can print the fps in the shell using print(clock.get_fps()), but I want to blit the fps on the screen while I'm playing.
I tried to use
fps_text = game_font.render(clock.get_fps(), True, (255, 255, 0))
win.blit(fps_text, (1000, 100))

(font is already initialized, I use it somewhere else in my program)
I get the error TypeError: text must be a unicode or bytesfor the first line of the code.
Is there a way to do what I'm trying to do ?
Thanks for the answers

A: clock.get_fps() returns a float. The first argument of 'render' needs to be a str.
Do this instead:
game_font.render(str(clock.get_fps()), True, (255, 255, 0))


text:
Q: MongoDB and Big Data I have a big database with one collection counting nearly 500 million documents, which looks as follow:
{'WP43234' : '12312312'}

First one is an accession, second is ID - basically it's a collection of links between two datasets. The problem is that many accessions point to the same ID, which makes it huge. I have an index on the first field, which speeds up lookup procedure, but it's still too slow (about 2 min per record):
[
    {
        "v" : 2,
        "key" : {
            "_id" : 1
        },
        "name" : "_id_",
        "ns" : "TaxIDMapper.links"
    },
    {
        "v" : 2,
        "unique" : true,
        "key" : {
            "ProteinID" : 1
        },
        "name" : "ProteinID_1",
        "ns" : "TaxIDMapper.links"
    }
]

Main aim is to speed up following procedure in my app (written in python):

*

*User uploads file with accessions (protein ID) (say up to 100k)

*Look up accession and associated ID (most time consuming part)

*Get data from second collection (small, works fast, no need to do anything with it)

Personally I think these should work:

*

*Database on SSD instead of HDD

*More powerful CPU

*Multiprocessing - requesting data in parallel (maybe threads are better?)

However I am not sure the speed up will be significant enough to process huge user requests. Is there anything else one could do? I was thinking about switching to SQL but it seems that MongoDB performs better.

A: You should use a different structure for your collection : group the accession by taxonId like this:
{
  _id: taxonID,
  acc: [ "WP43234",
         "WP43234.1",
         "WP43234.2"
       ]
}

then create an index on acc field.
Before thinking of upgrading hardware, make sur that your queries are optimized. Look at the explain() and make sure that index are correctly used (IXSCAN and not COLLSCAN).
Use mongodb 3.4, wiredTiger engine with snappy compression


text:
Q: Why does the read-out efficiency increase when coupling an atomic ensemble to an optical cavity? I went through a paper where it mentioned that the read-out efficiency of a quantum memory would be increased by coupling the atomic ensemble with an optical cavity.
I think rydberg atoms were used to make the atomic ensemble, and the rydberg blockade effect was used.
Can anybody explain to me, how the read-out efficiency increases?
The DOI of the paper is: 10.1109/PHOSST.2017.8012667


text:
Q: XML cannot be serialized - parameterless constructor error, even with constructor I'm trying to serialize an object to xml using XmlSerializer but keep getting this error:
System.InvalidOperationException: [MySql.Data.MySqlClient.MySqlParameter] cannot be serialized because it does not have a parameterless constructor.

I followed the solution to why xml serializable class need a parameterless constructor which seems to have solved the problem for everyone else, but I still get an error. When I add public MyClass() it gives me 'MyClass.MyClass()' must declare a body because it is not marked abstract, extern, or partial, so I add a body and the first error comes back.
Note that originally there aren't any constructors, parameterless or otherwise, so I don't understand why it isn't just automatically creating its own.
What am I doing wrong?
Code added:
MyFile.cs
public async Task Save(MyClass xmlObj)
{
    XmlSerializer xmlSer = new XmlSerializer(this.GetType()); //I think the problem is likely to be here
    StringWriter strWriter = new StringWriter();

    xmlSer.Serialize(strWriter, xmlObj);
    objToUpdate.ColName = (strWriter.ToString());
    await dbContext.SaveChangesAsync();
}

File.cs
public async Task<IActionResult> SaveData(params...)
{
    await new MyFile<MySqlParameter>(accessParam, dbContext).Save(xmlObj);
}

A: I figured it out...
I had been creating a new XmlSerializer and passing in a parameter as posted in a SO answer:
XmlSerializer xmlSer = new XmlSerializer(this.GetType());
When really it works perfectly fine to use the same XmlSerializer as the deserialization:
XmlSerializer objSer = new XmlSerializer(typeof(MyClass));

A: You should have added
public MyClass(){}

to the class. There is a difference between no body and an empty body which is what you want on this constructor.


text: Q: How to specify custom streaming parser in eclipse microprofile restclient? I need to consume a large payload ( hundreds of MB's) and am using eclipse microprofile restclient to make REST call, but I am not aware how I can specify my own JSON parser to be used for this particular call. Appreciate any examples/references.


text:
Q: What is the equivalent of Spring Application Context in Koin I'm new to Koin and Kotlin. I'm developing a client/server application (both sides). There are several beans. Some should be configured differently for sever and client, and some can be configured similarly in both. In fact, I have two questions:

*

*In Spring terms, I want to define two different application contexts each with the necessary set of beans. I think even similar beans in server and client should be different instances when running both client and server in single JVM (for testing purposes)

*I want to know what is the equivalent of a spring application context in Koin?


text:
Q: MissingMethodException: no parameterless constructor defined for this object I am trying to call a class of a dll from my console application. All the classes which I am trying to call from the dll have parameterized constructors. I wish to pass user and pass as the two parameters to any class I am trying to invoke. I know there is something wrong with how I am invoking the methods, but am unable to figure out what.
Can someone please correct my code?
The error occurs in the line - "object instance = Activator.CreateInstance(type)"
Console app -
class Program
{
    static void Main(string[] args)
    {
        string test_method = args[2];
        string user = args[0];
        string pass = args[1];

        Assembly myassembly = Assembly.LoadFrom("Tests.dll");

        Type type = myassembly.GetType("Tests." + test_method);

        object instance = Activator.CreateInstance(type);
        MethodInfo[] methods = type.GetMethods();
        methods[0].Invoke(instance, new object[] {user, pass });

        Console.WriteLine("\n"+test_method + " has passed.");

    }
}

An example class which is being called -
public class Test_3456 : ePO
{
    public Test_3456(string a, string b) : base (a, b)
    {
        MultipleWebclipsSameNameDifferentUrl_3456();
    }

    [TestMethod]
    public void MultipleWebclipsSameNameDifferentUrl_3456()
    {
        PolicyCatalog.GoTo();
        PolicyCatalog.PolCatSelect("iOS (User-Based Policy)");

        WebClip.iOSWebClipsTab();
        WebClip.Add2WebClipsSameNameDifferentUrl();
        WebClip.Ok();
        WebClip.Save();
    }
}

The constructor here is a dummy constructor. The base class takes in the user and pass parameters.
Base class -
 public class ePO
{
    public ePO(string a, string b)
    {
        Init(a, b);
    }

    [TestInitialize]
    public void Init(string username, string password)
    {
        Driver.initialize();
        Login.GoTo();
        Login.LoginAs(username).WithPassword(password).Login();
    }
}

A: As Activator.CreateInstance() creates the object, that's where you need to give the constructor parameters:
object instance = Activator.CreateInstance(type, new object[] {user, pass });


text:
Q: Domain Controller dropped from domain While in the process of making some changes in my environment I set up a new Domain Controller (2019) and promoted it, did some testing and verified it was working properly.
I demoted my old DC (2016) (I know I should not have done this without first setting up a third DC but I guess I won't make that mistake again)
I began installing the AD connector from JumpCloud (Again I did not look and see that it is not supported on 2019. Another mistake I won't make again)
On reboot, my DC did not come back up and instead had the infinite circle error.
I ended up trying to get it up and running and eventually went through and selected start using last known good configuration.
When I got back in I noticed that the computer name was now changed back to the system default.
I attempted to change the computer name back to what I had set it to that did not work, I removed the DC from the domain and put it into a workgroup. (VERY BAD DECISION)
Now my only DC is not on my domain and won't rejoin the domain.
I have about 6 users and 9 devices that are all relying on this domain to function properly so just starting over or anything like that wont work.


text:
Q: Grails - %252F in the url I am using spring security plugin for login in application. The spring security has default auth.gsp page for login. I have created my own auth.gsp page to add additional thing
auth.gsp
<g:form action='${postUrl.encodeAsURL()}' method='POST' id='loginForm'  autocomplete='off' class="login-form">
            <g:textField class="field" name="username" value="${params.userName}"/>
            <g:passwordField class="field" name="password"/>
            <button>login</button>

Forgot Password?

Have Invitation Code?

        </g:form>

The problem is that ${postUrl} contains %252F in the url. Here is the complete url: http://localhost:8080/login/%252Flogin%252Fauthenticate/loginForm. I have tried every possible answer given on stackoverflow but nothing worked.

A: Try using
<g:form url='${postUrl}' method='POST' id='loginForm'  autocomplete='off' class="login-form">
        <g:textField class="field" name="username" value="${params.userName}"/>
        <g:passwordField class="field" name="password"/>
        <button>login</button>

Forgot Password?

Have Invitation Code?

    </g:form>

When setting complete urls, you use 'url' attribute. If you use "action", then you must set a action name.
Also don't use encodeAsURL(). encodeAsURL means, you want to escape special characters like '/','?' which are replaced with '%..' entities.


text:
Q: How to traverse an XML document? I am trying to browse a XML file with JDOM's the code to browse:
import java.io.*;
import org.jdom.*;
import org.jdom.input.*;
import org.jdom.filter.*;
import java.util.List;
import java.util.Iterator;

public class PremierJdom {

   static org.jdom.Document document;
   static Element racine;

   public static void main(String[] args)
   {
      //On crée une instance de SAXBuilder
      SAXBuilder sxb = new SAXBuilder();
      try
      {
         //On crée un nouveau document JDOM avec en argument le fichier XML
         //Le parsing est terminé ;)
         document = sxb.build(new File("Example.wsdl"));
      }
      catch(Exception e){}

      //On initialise un nouvel élément racine avec l'élément racine du document.
      racine = document.getRootElement();
      //System.out.println(racine.getName());

      //Méthode définie dans la partie 3.2. de cet article
      afficheALL();
   }

//Ajouter cette méthodes à la classe JDOM2
static void afficheALL()
{
   //On crée une List contenant tous les noeuds "etudiant" de l'Element racine
   List listEtudiants = racine.getChildren("binding");

   //On crée un Iterator sur notre liste
   Iterator i = listEtudiants.iterator();
   while(i.hasNext())
   {
      //On recrée l'Element courant à chaque tour de boucle afin de

      Element courant = (Element)i.next();
      //On affiche le nom de l'élément courant
      System.out.println(courant.getAttributeValue("name"));

   }
}
}

But the problem that arises here is that when I execute this class I will have no output.
and here is the file Example.wsdl
<?xml version="1.0"  encoding= "UTF-8" ?>
<definitions name= "Web Service Mediation"
 targetNamespace="http://these-info.univ-tun.com/Web Service Mediation "
xmlns=" http://these-info.univ-tun.comstem online"
   xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/"  >

  <binding name="ConnTWSAlt" type="wsdlns:SimplePortType">
<soap:binding style="rpc"
 transport="http://schemas.xmlsoap.org/soap/http"/>
<operation name="foo">
<soap:operation soapAction="http://tempuri.org/action/binding.ConnTWSAlt"/>
<input>
<soap:body use="encoded"
 encodingStyle="http://schemas.xmlsoap.org/soap/encoding/"/>
</input>
<output>
<soap:body use="encoded"
encodingStyle="http://schemas.xmlsoap.org/soap/encoding/" />
</output>
</operation>
</binding>
</definitions>

Someone can help to correct this error.

A: You really, really, really should be using JDOM 2.x and not JDOM 1.x There are many reasons for this, including that JDOM 1.x is old, and no longer maintained. JDOM 2.x was released more than 3 years ago, and includes support for generics and so on. See this list of new features
Using JDOM 2.x would also make your issue easier to see.
Right, your problem is that you are calling getChildren(...) without using a namespace:

   //On crée une List contenant tous les noeuds "etudiant" de l'Element racine
   List listEtudiants = racine.getChildren("binding");

That code says: get all child elements of  racine that are in the namespace with the URL "". What you want is to get child elements in the namespace http://schemas.xmlsoap.org/wsdl/soap/ with the local name binding.
To do that, you need to get a Namespace instance in the correct URL, and use that for the getChildren call too:
Namespace soap = Namespace.getNamespace("soap", "http://schemas.xmlsoap.org/wsdl/soap/");
.....
List listEtudiants = racine.getChildren("binding", soap);

Note that, in JDOM 2.x, that would be:
List<Element> listEtudiants = racine.getChildren("binding", soap);

and as a consequence, your current code:

static void afficheALL()
{

   //On crée une List contenant tous les noeuds "etudiant" de l'Element racine
   List listEtudiants = racine.getChildren("binding");

   //On crée un Iterator sur notre liste
   Iterator i = listEtudiants.iterator();
   while(i.hasNext())
   {
      //On recrée l'Element courant à chaque tour de boucle afin de

      Element courant = (Element)i.next();
      //On affiche le nom de l'élément courant
      System.out.println(courant.getAttributeValue("name"));

   }
}

should all be reduced down to:
private static final Namespace SOAP = Namespace.getNamespace("soap", "http://schemas.xmlsoap.org/wsdl/soap/");

static void afficheALL()
{
   //On crée une List contenant tous les noeuds "etudiant" de l'Element racine
   for (Element courant : racine.getChildren("binding", SOAP))
   {
      //On affiche le nom de l'élément courant
      System.out.println(courant.getAttributeValue("name"));
   }
}


text:
Q: Generate GUID in XSLT I need to generate a GUID with XSLT and if needed C#, does anyone know how to best do this?
It is to generate unique IDs for HTML items.

A: The XSLT generate-id function returns a string that uniquely identifies a node in the document. Note these warnings from the spec:

An implementation is under no
  obligation to generate the same
  identifiers each time a document is
  transformed. There is no guarantee
  that a generated unique identifier
  will be distinct from any unique IDs
  specified in the source document.

However, if all you need is to uniquely identify each element in your output, then generate-id is sufficient.

A: C# provides a handy Guid.NewGuid() static method.  I'd expect any XSLT implementation would heavily leverage some system-specific component since Guids are often generated in part based on hardware/MAC address/etc. on the underlying machine.

A: I ended up just using an extension method and wrapping Guid.NewGuid() in a static method, then calling this from my XSLT, it was easy enough once I figured out how extension methods work.

A: With C#, it can be achieved easily with Script Blocks Using msxsl:script.
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
  xmlns:msxsl="urn:schemas-microsoft-com:xslt"
  xmlns:user="urn:my-scripts">
  <msxsl:script language="C#" implements-prefix="user">
  <![CDATA[
  public string getguid(){
     return Guid.NewGuid().ToString();
  }
  ]]>
  </msxsl:script>
  <xsl:template match="data">
    <Guid><xsl:value-of select="user:getguid()"/></Guid>
  </xsl:template>
</xsl:stylesheet>


text:
Q: Weird characters when printing out strings in an array? I'm currently working on a program that reads strings from a file and stores them into a 2-D array. However, when I try to print out the contents of the array, I get a random character every time. Here is my code:
#include <stddef.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main(){
    FILE* file_pointer;
    char user_input[80];
    char line[81];
    char all_lines_array[100][81];
    int total_lines = 0;
    while (1){
        printf("Please enter a command: ");
        scanf("%s", &user_input);
        if (strstr(user_input, "read") != NULL){
            file_pointer = fopen("C:\\Users\\Tyler\\Desktop\\Hello.txt","r");
            while (fgets(line, 100, file_pointer)) {
                line[strlen(line)+1] = "\0";
                *all_lines_array[total_lines] = line; //My guess is this is wrong
                total_lines++;
        }
        fclose(file_pointer);
    }
}
return 0;
}

I suspect that this is because I'm incorrectly inserting string into my 2-D array, but I have no idea what it is I'm doing wrong. I've set the numbers so that there can only be a maximum of 100 lines in a file, and each line can only be 80 characters long (with the "\0" at the end).
Here is my input file:
John Doe    1221 Washington St.    1234567
Jane Doe    1233 Washington St.    1234568
Cain Doe    1234 Washington St.    1234569

A: There where some statements flagged when compiling with -Wall [which I always recommend doing], which may have helped with some of the errors.
Here's the corrected version, annotated with comments [please pardon the gratuitous style cleanup]:
#include <stddef.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int
main()
{
    FILE *file_pointer;
    char user_input[80];
    char line[81];
    char all_lines_array[100][81];
    int total_lines = 0;

    while (1) {
        printf("Please enter a command: ");

        // compiler flagged this with a warning
#if 0
        scanf("%s", &user_input);
#else
        scanf("%s", user_input);
#endif

        if (strstr(user_input, "read") != NULL) {
#ifndef CRAIG
            file_pointer = fopen("C:\\Users\\Tyler\\Desktop\\Hello.txt", "r");
#else
            file_pointer = fopen("input.txt", "r");
#endif
            if (file_pointer == NULL) {
                printf("file not found\n");
                continue;
            }

            // NOTE: using sizeof here is better as 100 was specified but
            // "line" was only 81
            while (fgets(line, sizeof(line), file_pointer)) {
                // NOTE: I presume this is to strip the newline
                // in the original form, it would add garbage chars to the end
                // [because of "\0" instead of '\0']
#if 0
                line[strlen(line) + 1] = "\0";
#else
                line[strlen(line) - 1] = 0;
#endif

                // NOTE: the compiler flagged this as well
#if 0
                *all_lines_array[total_lines] = line;   // My guess is this is wrong
#else
                strcpy(all_lines_array[total_lines],line);
#endif
                total_lines++;
            }

            fclose(file_pointer);
        }
    }

    return 0;
}

A: fgets is reading 100 chars but your static allocated variable char line[81] is only allocates memory for 81 chars.
instead of the = operator use strcpy


text:
Q: How do I use Berkelium library in C++ code? I want to use this library (https://github.com/sirikata/berkelium/downloads) with g++ compiler. It has 3 folders: bin, lib and include. What I do with files in each of the folder? And in my C++ code, do I need to use only headers in include folder? Thanks. I need to do this on g++ in Ubuntu 12.04 and I am not using any IDE just vi.
Edit: lib folder has a so file.

A: To compile programs with this library, you need to tell the compiler where are the include files, for object generation, and the library files for the linker job.
In one command line:

g++ -I/path/to/berkelium/include -L/path/to/berkelium/library -o executable yourprogramname -llibberkerium

A: I would go for https://developers.google.com/native-client/peppercpp/ , that library looks like it's just a wrapper and it's not officially supported.


text:
Q: QGraphicsScene::items returns no items for a given rect I'd like to select all items within a certain area and change their opacity. I'm using QGraphicsScene::items() to do this, but I can't seem to get it to return any items. An example:
#include "MainWindow.h"
#include "ui_MainWindow.h"

#include <QDebug>
#include <QKeyEvent>
#include <QGraphicsPixmapItem>

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
  , scene(new QGraphicsScene())
{
    ui->setupUi(this);

    ui->graphicsView->setScene(scene);
    ui->graphicsView->installEventFilter(this);
    ui->graphicsView->show();

    for (int y = 0; y < 20; ++y) {
        for (int x = 0; x < 20; ++x) {
            QPixmap pixmap("desert.png");
            QGraphicsPixmapItem* newItem(scene->addPixmap(pixmap));
            newItem->setPos(x * 25, y * 25);
            newItem->setOpacity(0.0);
            qDebug() << newItem;
        }
    }
}

MainWindow::~MainWindow()
{
    delete ui;
    delete scene;
}

bool MainWindow::eventFilter(QObject *obj, QEvent *event)
{
    if(event->type() == QEvent::KeyPress) {
        QKeyEvent *keyEvent = static_cast<QKeyEvent*>(event);
        if (keyEvent->key() == Qt::Key_Space) {
            QRectF rect(0, 0, 25 * 3, 25 * 3);
            QList<QGraphicsItem*> items(scene->items(rect, Qt::ContainsItemBoundingRect, Qt::AscendingOrder));
            qDebug() << items;
            foreach (QGraphicsItem *item, items) {
                item->setOpacity(1.0);
            }
        }
        return true;
    }
    return QObject::eventFilter(obj, event);
}

I'm pretty sure that I don't need to supply the deviceTransform argument, and I know that the rect I'm passing in should cover 9 tiles. What am I doing wrong?

A: When creating the items, you already set their opacity to 0 so that they are not visible -  items() returns visible items only, see http://qt-project.org/doc/qt-4.8/qgraphicsscene.html#items-10:

Returns all visible items ...

Set the opacity to a value > 0 in your constructor, e.g.
newItem->setOpacity(0.001);

When now pressing the space bar, the four items in the given rectangle will appear.


text:
Q: cannot get Object(or JObject) in asp.net web api with get method and appliction/json I cannot get Object in asp.net web api method via get method.

*

*if I use post ,it's working

*if I use get ,it's 'null'

*my settings:set 'application/json' when I request.

this is my code screenshots images


text:
Q: Printing a matrix of structs and enums this is my first post here so if i make any mistake please tell me.
So i'm making this mini game for my class and i need to create a matrix of n size (from input) that is filled with a struct of enums, the function that does that is crea_scacchiera.
when i want to print the matrix i pass to another function (stampa_scacchiera), i tried everything but i cant find a solution to print the matrix without a segmentation fault.
the minigame is divided in 3 files : main.c that only prints a menu, gamelib.h that defines the enums and structts, and gamelib.c where there is the function that creates and print the matrix.
i think the matrix is filled right, i just cant find a way to print it in the other function.
//gamelib.h
extern void crea_mappa();
extern void gioca();
extern void termina_gioco();

enum Tipo_pericolo {nessun_pericolo, trappola, alieno} pericolo;
enum Stato_giocatore {vulnerabile, scudo_vita, solo_vita, solo_scudo};
enum Tipo_oggetto {nessun_oggetto, medikit, pozione, materiale, colpi_lanciarazzi} oggetto;

struct Giocatore
{
  enum Stato_giocatore stato;
  int Posizione_x;
  int Posizione_y;
  int zaino[4];
  int alieni_uccisi;

};

struct Cella
{
  enum Tipo_pericolo pericolo;
  enum Tipo_oggetto oggetto;

};

//gamelib.c
#include "gamelib.h"
#include <stdio.h>
#include <stdlib.h>

//penso ci vadano anche dichiarazioni di variabili
int n;
void crea_scacchiera();
void stampa_scacchiera(struct Cella *scacchiera);
struct Cella *scacchiera= NULL;
static struct Giocatore Ninja;
static struct Giocatore Ciccio;

void crea_mappa()
{
   int choice;

  do {
  printf("                  \n");
  printf("Sceglia cosa fare\n");
  printf("1} crea scacchiera\n");
  printf("2} stampa scacchiera\n");
  printf("3} termina creazione\n");
  printf("                    \n");
  scanf("%d",&choice );

  switch (choice) {
    case 1 :
            crea_scacchiera();
            break;

    case 2 :
            printf("stampa della scacchiera in corso\n");
            stampa_scacchiera(scacchiera);
            break;

    case 3 :
            printf("ritorno al menu della mappa\n");
            system("clear");
            break;
  }
}
while (choice!=3);

}

void gioca()
{
  printf("prova funzione, gioca\n");
}

void termina_gioco()
{
  printf("prova funzione, termina gioco\n" );
}

void crea_scacchiera()
{
//  enum Tipo_oggetto oggetto;
  //enum Tipo_pericolo pericolo;
  int i,j,rows,cols;
  extern  int n;
  //static int perc1,perc2,perc3,perc4,perc5,perc6,perc7,perc8;
   printf("                                       \n ");
   printf("inserisci la grandezza della scacchiera\n ");
   scanf("%d",&n);\
     rows=n;
     cols=n;
     scacchiera = (struct Cella *)malloc(rows* cols* sizeof(struct Cella));
     //int offset = i * cols + j;
      for (i=0; i<n; i++){
        for (j=0; j<n; j++){

           scacchiera[i*cols+j].pericolo= trappola;

            scacchiera[i*cols+j].oggetto= pozione;

        }
      }

    Ninja.stato = solo_vita;
    Ninja.Posizione_x= rand()%n+1;
    Ninja.Posizione_y= rand()%n+1;
    Ciccio.stato = solo_vita;
    Ciccio.Posizione_x= rand()%n+1;
    Ciccio.Posizione_y= rand()%n+1;
    printf("%d\n",n );

}

 void stampa_scacchiera(struct Cella *scacchiera) //FuncB
{

int i,j,cols;
cols = n;
extern int n;
cols=n;

for (i=0; i<n; i++){
  for (j=0; j<n; j++){

  printf("oggetto scacchiera [%d] [%d] : %d\n",i,j,(scacchiera[i*cols+j]).oggetto );
  printf("pericolo scacchiera [%d] [%d] : %d\n",i,j,(scacchiera[i*cols+j]).pericolo );
 }
}

}

I have modified the program now and this are the errors that is giving me

  gamelib.c:154:39: error: declaration of 'scacchiera' shadows a global declaration [-Werror=shadow]
  void stampa_scacchiera(struct Cella *scacchiera) //FuncB
                                       ^~~~~~~~~~
gamelib.c:11:15: note: shadowed declaration is here
 struct Cella *scacchiera= NULL;
               ^~~~~~~~~~

A: Your program has majorly serious issues:

*

*never use your original language in code. Always write in english (variable names, function names and so on). Otherwise almost noone will bother.

*don't use shortcut names like crea_. How much time did it save you not to type those two missing letters? While everyone else will look at this and wonder what crea is. Yea, sure, "everyone" knows, its shortcut from create. But not everyone is you, not everyone is master of english and even then it will take them additional time of their live to decipher your "style" (read: mess).

*formatting matters. Otherwise once again almost noone will bother.

*Try this:
 scacchiera = (struct Cella *)malloc(rows* cols* sizeof(struct Cella));

instead of
    int *scacchiera = (int *)malloc(rows* cols* sizeof(struct Cella));

You forgot to initialize your global variable.

*After trying to assign to global variable your compiler barks on you, because types don't match. Try this:
scacchiera = (struct Cella*)malloc(rows* cols* sizeof(struct Cella));

*You also pass invalid value to printf (probably). Try this instead (removal of & operator). Otherwise you'll print address of a variable instead of it's value.
printf("oggetto scacchiera [%d] [%d] : %d\n",i,j,(scacchiera[i*cols+j]).oggetto );
printf("pericolo scacchiera [%d] [%d] : %d\n",i,j,(scacchiera[i*cols+j]).pericolo );


text:
Q: Many-to-many relationship with compound primary key constraint I got a requirement for many-to-many relationship design in DBMS with other constraints.
There are two tables, t1 and t2 where t1.id and t2.id are primary keys respectively. t1 and t2 has many-to-many relationship, so a natural design is to add a third table t3 with foreign keys. e.g.,
t3:
id
t1_id     (foreign key refereed to t1.id)
t2_id     (foreign key refereed to t2.id)

Another requirement is pair(t1.id, t2.id) should have one-to-one relationship with t4.id. Is it good to add t5 with primary_key(t1.id, t2.id)? or we can directly using t3's t1_id, t2_id as compound primary key? We need to fast scan whether pair(t1.id, t2.id) has an entity in t4, i.e., pair(t1.id, t2.id) has one-to-one relationship with t4.id.
Appreciate if you could give me some hints.

A: If you have to enforce a one-to-one relationship between (t1.id,t2.id) and t4.id, that seems to indicate that (t1.id,t2.id) would be unique.
If that's the case, if (t1.id,t2.id) should be UNIQUE in t3, then you could make that the PRIMARY KEY for t3.
You could add a foreign key reference to t4, and make that UNIQUE so no more than one row in t3 can be related to t4. Or, you can make the foreign key reference go the other way, and store the primary key values of t3 in t4.
For example, to make the foreign key in t3 to t4
 CREATE TABLE t3
 ( t1_id  INT NOT NULL       COMMENT 'pk, fk ref t1'
 , t2_id  INT NOT NULL       COMMENT 'pk, fk ref t2'
 , t4_id  INT                COMMENT 'fk ref t4'
 , PRIMARY KEY (t1_id,t2_id)
 , CONSTRAINT t3_ux2 UNIQUE KEY (t4_id)
 , CONSTRAINT fk_t3_t1 FOREIGN KEY (t1_id) REFERENCES t1(id)
     ON DELETE CASCADE ON UPDATE CASCADE
 , CONSTRAINT fk_t3_t2 FOREIGN KEY (t2_id) REFERENCES t2(id)
     ON DELETE CASCADE ON UPDATE CASCADE
 , CONSTRAINT fk_t3_t4 FOREIGN KEY (t4_id) REFERENCES t4(id)
     ON DELETE RESTRICT ON UPDATE CASCADE
 ) ...

Or, you could introduce a surrogate primary key on t3. (We typically only do this if there are other tables that have a foreign key reference to t3; because now t3 is acting more like an actual entity, than a pure relationship. And that avoids us having to use a composite key as a foreign key in another table to reference t3.
For example:
 CREATE TABLE t3
 ( id     INT NOT NULL       COMMENT 'pk'
 , t1_id  INT NOT NULL       COMMENT 'fk ref t1'
 , t2_id  INT NOT NULL       COMMENT 'fk ref t2'
 , PRIMARY KEY (t3_id)
 , CONSTRAINT t3_ux1 UNIQUE KEY (t1_id,t2_id)
 , CONSTRAINT fk_t3_t1 FOREIGN KEY (t1_id) REFERENCES t1(id)
     ON DELETE CASCADE ON UPDATE CASCADE
 , CONSTRAINT fk_t3_t2 FOREIGN KEY (t2_id) REFERENCES t2(id)
     ON DELETE CASCADE ON UPDATE CASCADE
 ) ...

You could add a foreign key in this table t3 to reference to t4, as in the previous example.
Or you could implement the relationship from t4 to reference t3.
Either way works.
My decision would be primarily based on
1) avoiding composite keys as foreign keys (if no entity tables have composite keys)
2) do we want or need ON DELETE CASCADE functionality, and which way does that need to work... a delete from t3 should cascade deletes to  t4, or the other way around.
I showed ON DELETE RESTRICT in the example I gave adding t4_id fk column to t3. I figured that a delete from t4 should probably not "break" the relationship between t1 and t2 by removing rows from t3.


text:
Q: type hint for an instance of a non specific dataclass I have a function that accepts an instance of any dataclass.
what would be an appropriate type hint for it ?
haven't found something official in the python documentation

this is what I have been doing, but i don't think it's correct
from typing import Any, NewType

DataClass = NewType('DataClass', Any)
def foo(obj: DataClass):
    ...

another idea is to use a Protocol with these class attributes __dataclass_fields__, __dataclass_params__.

A: There is a helper function called is_dataclass that can be used, its exported from dataclasses.
Basically what it does is this:
def is_dataclass(obj):
    """Returns True if obj is a dataclass or an instance of a
    dataclass."""
    cls = obj if isinstance(obj, type) else type(obj)
    return hasattr(cls, _FIELDS)

It gets the type of the instance using type, or if the object extends type, the object itself.
It then checks if the variable _FIELDS, which equals __dataclass_fields__, exists on this object. This is basically equivalent to the other answers here.
To "type" dataclass i would do something like this:

class DataclassProtocol(Protocol):
    __dataclass_fields__: Dict
    __dataclass_params__: Dict
    __post_init__: Optional[Callable]

A: Despite its name, dataclasses.dataclass doesn't expose a class interface. It just allows you to declare a custom class in a convenient way that makes it obvious that it is going to be used as a data container. So, in theory, there is little opportunity to write something that only works on dataclasses, because dataclasses really are just ordinary classes.
In practice, there a couple of reasons why you would want to declare dataclass-only functions anyway, and something like this is how you should go about it:
from dataclasses import dataclass
from typing import ClassVar, Dict, Protocol

class IsDataclass(Protocol):
    # as already noted in comments, checking for this attribute is currently
    # the most reliable way to ascertain that something is a dataclass
    __dataclass_fields__: ClassVar[Dict]

def dataclass_only(x: IsDataclass):
    ...  # do something that only makes sense with a dataclass

@dataclass
class Foo:
    pass

class Bar:
    pass

dataclass_only(Foo())  # a static type check should show that this line is fine ..
dataclass_only(Bar())  # .. and this one is not

This approach is also what you alluded to in your question. If you want to go for it, keep in mind that you'll need a third party library such as mypy to do the static type checking for you, and if you are on python 3.7 or earlier, you need to manually install typing_extensions since Protocol only became part of the standard library in 3.8.
Also noted that older version of mypy (>=0.982) mistakenly expect __dataclass_fields__ to be an instance attribute, so the protocol should be just __dataclass_fields__: Dict[1].

When I first wrote it, this post also featured The Old Way of Doing Things, back when we had to make do without type checkers. I'm leaving it up, but it's not recommended to handle this kind of feature with runtime-only failures any more:
from dataclasses import is_dataclass

def dataclass_only(x):
    """Do something that only makes sense with a dataclass.

    Raises:
        ValueError if something that is not a dataclass is passed.

    ... more documentation ...
    """
    if not is_dataclass(x):
        raise ValueError(f"'{x.__class__.__name__}' is not a dataclass!")
    ...

[1]Kudos to @Kound for updating and testing the ClassVar behavior.

A: You can indeed use a Protocol, but by I suggest @ decorating that Protocol as a runtime_checkable dataclass:
@runtime_checkable
@dataclasses.dataclass
class DataclassProtocol(Protocol):
    pass

The above results in:

*

*type-hinting with DataclassProtocol is possible and makes sense to type checkers (mypy 0.982, PyCharm 2022.2.3 CE)

*isinstance(obj, DataclassProtocol) is equivalent to dataclasses.is_dataclass(obj)

*because dataclasses.is_dataclass(DataclassProtocol), type checkers' special handling of dataclasses work

*DataclassProtocol does not require use of internal dataclass fields

The first is also accomplished by the previously given Protocols. The second results from @ decorating with runtime_checkable.
The latter two points rely on @ decorating by dataclass.
While this answers the question, personally I'd want to subclass DataclassProtocol into a DataclassInstanceProtocol, which specializes for not isinstance(obj, type). But until now, I couldn't find that.


text:
Q: Weird infinite sum Evaluate
$\sum_{n=0}^{\infty}{\frac{(-1)^n}{3n+1}=1-\frac{1}{4}+\frac{1}{7}-\frac{1}{10}+...}
$
This looks a lot like the series expansion for $\ln(1+x)$ when $x=1$, but I cannot find the relationship.

A: The log series hints at finding the function
$$ f(x) = \sum_{n=0}^{\infty} \frac{(-1)^nx^{3n+1}}{3n+1} $$
when $x=1$. Taking the derivative, we find
$$ f'(x) = \sum_{n=0}^{\infty} (-1)^n x^{3n} = \sum_{n=0}^{\infty} (-x^3)^n = \frac{1}{1+x^3} $$
Therefore
$$ f(1) = \int_0^1 \frac{1}{1+t^3} dt $$
You can solve the integral using partial fractions. WolframAlpha gives the solution as well as the anti-derivative here
$$ f(x) = \frac13 \ln (x+1) - \frac16 \ln(x^2-x+1) + \frac{1}{\sqrt{3}}\arctan \left(\frac{2x-1}{\sqrt{3}}\right) $$
$$ f(1) = \frac13 \ln 2 + \frac{\pi}{3\sqrt{3}} $$

A: We will use imprecise argument to guess the value of the sum. We know that
$$\sum_{n=0}^\infty x^{3n} = \frac{1}{1-x^3}.$$
By integrating it both sides we have $$\sum_{n=0}^\infty \frac{x^{3n+1}}{3n+1} = \int_0^x \frac{1}{(1-u)(1+u+u^2)}du = \frac{1}{6}\left(\log\left(\frac{x^2+x+1}{(1-x)^2}\right)+ 2\sqrt{3}\arctan\left(\frac{2x+1}{\sqrt{3}}\right)\right).$$
Hence we can guess
$$\sum_{n=0}^\infty \frac{(-1)^{3n+1}}{3n+1} = \frac{1}{6}\left(\log\left(\frac{1}{4}\right)- \frac{2\sqrt{3}\pi}{6}\right).$$
Our argument is not strict as we need to justify we can exchange the integral and the infinite sum. Moreover, we don't know our sum is coincide with the result of the integration.
(Note. The sum in left-hand-side is not equal to your sum, but it is in fact same as the negation of your sum.)
We can justisfy our result as follows: note that
$$\frac{1}{1-x^3} = \sum_{n=0}^N x^{3n} + \frac{x^{3N+3}}{1-x^3}$$
We can integrate from 0 to -1 it both sides then we have
$$\frac{1}{6}\left(\log\left(\frac{1}{4}\right)- \frac{2\sqrt{3}\pi}{6}\right) = \sum_{n=0}^N \frac{-1}{3n+1} + \int_0^{-1}\frac{x^{3N+3}}{1-x^3}dx$$
Here the last term can be regarded as an errer term. It satisfies
$$
\begin{align}
\left|\int_0^{-1}\frac{x^{3N+3}}{1-x^3}dx\right|&
\le \int_{-1}^0\left|\frac{x^{3N+3}}{1-x^3}\right|dx \\
&\le \int_{-1}^0 |x|^{3N+3}dx\\
&= \frac{1}{3N+4} \xrightarrow[N\to\infty]{} 0,
\end{align}$$
since $|1/(1-x^3)|\le 1$ if $-1\le x\le 0$. Now take $N\to\infty$.

A: Recall how we can obtain the Taylor series of $\ln (1+x)$ - Integrate $\frac{1}{1+x} = 1-x+x^{2}-x^{3}+\cdots$ term by term. (You should be careful for $x=1$, but it still works by Abel's limit theorem.) Now your series maybe obtained by
$$
\int_{0}^{1}\frac{1}{1+x^{3}}dx.
$$
(Also, there's some convergence issue for $x=1$. But certainly we can deal with it.)


text:
Q: Partial Derivatives Homework I just started learning partial derivatives on my own, and I get confused about concepts such as independence and dependence of variables.
For example I needed to find du/dx given the following equation:
$u = x^u + u^y$
What I did was to rearrange the equation to:
$\ln u / u = \ln x / (1-y)$
Then I expressed the partial derivative as:
$du/dx = u^2 / (x(1-y)(1-\ln u))$
I'm not sure how to find the derivative implicitly without separating u (the dependent variable) from x, y (the independent variables).
The reason I rearranged the equation was because I thought that one couldn't treat the 'u' terms on the right side of the equation as constants (during the partial differentiation) since they are dependent on x.
Clarifications would be greatly appreciated!

A: Look at it this way: You have three variables $u$, $x$, $y$ (modeling, e.g., physical quantities) that are related by the "constituent equation"
$$\bigl(F(x,y,u):=\bigr)\qquad x^u+u^y-u=0\ .\tag{1}$$
An admissible state is, e.g., the point ${\bf p}_0:=(1,0,2)$. The equation $(1)$ reduces the number of degrees of freedom from $3$ to $2$; therefore we may nourish the idea that given $x$ and $y$ the value of $u$ is determined. In other words: There is an underlying function
$$\phi:\quad(x,y)\mapsto u=\phi(x,y)\ ,$$
which produces for all suitable $(x,y)$ an $u$ such that the triple ${\bf p}:=\bigl(x,y,u\bigr)$ is  admissible. This means that
$$F\bigl(x,y,\phi(x,y)\bigr)=0\quad\forall x,\ \forall y\ .$$
Taking partial derivatives with respect to $x$ and $y$, and using the chain rule we can deduce that
$$F_x\bigl(x,y,\phi(x,y)\bigr)+F_u\bigl(x,y,\phi(x,y)\bigr)\phi_x(x,y)\equiv0,\quad
F_y\bigl(x,y,\phi(x,y)\bigr)+F_u\bigl(x,y,\phi(x,y)\bigr)\phi_y(x,y)\equiv0\ .$$
Solving for the partial derivatives of $\phi$ we get
$$\phi_x(x,y)=-{F_x\bigl(x,y,\phi(x,y)\bigr)\over F_u\bigl(x,y,\phi(x,y)\bigr)}, \quad
\phi_y(x,y)=-{F_y\bigl(x,y,\phi(x,y)\bigr)\over F_u\bigl(x,y,\phi(x,y)\bigr)}\ .$$
This can be interpreted as follows: Near any admissible point ${\bf p}_0=(x_0,y_0,u_0)$  the "local" function $(x,y)\mapsto u:=\phi(x,y)$ has partial derivatives
$${\partial u\over\partial x}=-{F_x({\bf p})\over F_u({\bf p})}, \quad
{\partial u\over\partial y}=-{F_y({\bf p})\over F_u({\bf p})}\ ,\tag{2}$$
under the essential condition that $F_u({\bf p}_0)\ne0$.
In our example $F_u(x,y,u)=\log x\cdot x^u- y u^{y-1}-1$; so at the point ${\bf p}_0:=(1,0,2)$ we have $F_u({\bf p}_0)=-1$. Therefore the formula $(2)$ is applicable at ${\bf p}_0$. I leave it to the OP to compute the values of the partial derivatives appearing therein.

A: For this problem you need to use implicit differentiation. So you treat $u$ as a function of the variable $x$ and you treat $y$ as a constant. So you could write $u = f(x)$ if that makes it easier. So you find
$$
\frac{d}{dx} f(x) = \frac{d}{dx} x^{f(x)} + f(x)^y \quad \Rightarrow \\
f'(x) = f'(x)\ln(x) + \frac{f(x)}{x} + \ln(y)f(x)^yf'(x).
$$
Now you solve this for $f'(x) = u'$.


text:
Q: Can't upvote on Meta even though I've been an SO member for more than a year? I've had my account on Stack Overflow for more than a year now. Today, I followed a question that was migrated to Meta.
I found a few interesting comments that I wanted to upvote. But the intelligent JavaScript warned me that I was not logged in because of it being a different site.
After I logged in, it suggested I merge/associate my Meta account with my SO account. (Simply brilliant that it was just a single click. Bravo to the dev team!)
When I tried to vote up these comments from before, I was then told that I didn't have enough reputation.
What's the point of having a minimum of 15 rep and having an account for over a year when I can't upvote on the other, related, sites?
Meta Stack Overflow is user support for the main trilogy of sites and the users of such should be able to vote on the ideas and feature requests that relate to those sites.
In the real world, if you had reputation, it would stick with you wherever you went.

A: Simple answer.

*

*You need 15 points to vote. That is one question with 2 votes, or one answer with 2 votes, or one question and one answer each with one vote, is it really that hard?

*If you associate your accounts and any of your accounts on the other sites have more then 200 reputation you automatically get a 100 rep boost. After a year you should have at least 200 points right?

*The requirement is there to prevent users creating sock puppet accounts and up-voting themselves to gain unnecessary reputation.

*Just because you are trusted on SO, doesn't mean you can be trusted on the other sites which cover completely different topics.

Reputation is earned through interaction on the site, not through how long you have been a member. The latter is irrelevant if you hardly ever visit the site.

A: Reputation limits, which are similar but not the same on meta, function to keep the anonymous google user from being able to dump all over the site.  You need to invest a (very) little to get voting privileges on meta, just like you do on all of the other sites to be trusted to vote on other people questions and answers.  Essentially, the sites says you have to care a little to get to participate more.  The more you care -- as shown by participation in asking and answering questions, especially with good questions/answers -- the more you get to do. I think this is a perfectly reasonable requirement, especially since the bar is so low for what you want to do.  Having been on SO for more than a year, I would have expected you to know how it works.

A: There is no cross-pollination of rep.  SO and MSO are different communities and you need to earn the respect of the community to enjoy the perks you reference.


text:
Q: laravel livewire image form I have form submit function which is working just fine in normal controller but since I've moved my function to livewire component it returns error
Error
ErrorException
Undefined index: attachment

Code

Error line commented

$chat = new BidChat;
// other fields
if ($this->attachment) {
    $attachment = $this->attachment;
    $filename = 'chat-attachment' . '-' . time() . '.' . $attachment->getClientOriginalExtension();
    $location = public_path('images/' . $filename);

    $valid_images = ['image/jpeg','image/gif','image/png'];
    if(in_array($_FILES['attachment']['type'], $valid_images)){ <-- error comes from this line
        Image::make($attachment)->resize(1300, 362)->save($location);
    }

    $chat->attachment = $filename;
}
$chat->save();

Debug
Result of dd($this->attachment);
Livewire\TemporaryUploadedFile {#1559 ▼
  +"disk": "local"
  #storage: Illuminate\Filesystem\FilesystemAdapter {#1538 ▶}
  #path: "livewire-tmp/najcwwb2OMw5wq0khtJp5hvkFfWk36-metaYmlkLWF0dGFjaG1lbnQtMTUzODEwMDQ0MS5wbmc=-.png"
  -test: false
  -originalName: "najcwwb2OMw5wq0khtJp5hvkFfWk36-metaYmlkLWF0dGFjaG1lbnQtMTUzODEwMDQ0MS5wbmc=-.png"
  -mimeType: "application/octet-stream"
  -error: 0
  #hashName: null
  path: "C:\Users\root\AppData\Local\Temp"
  filename: "najcwwb2OMw5wq0khtJp5hvkFfWk36-metaYmlkLWF0dGFjaG1lbnQtMTUzODEwMDQ0MS5wbmc=-.png"
  basename: "phpBAD0.tmp"
  pathname: "C:\Users\root\AppData\Local\Temp\phpBAD0.tmp"
  extension: "tmp"
  realPath: "C:\laragon\www\mysite\storage\app\livewire-tmp/najcwwb2OMw5wq0khtJp5hvkFfWk36-metaYmlkLWF0dGFjaG1lbnQtMTUzODEwMDQ0MS5wbmc=-.png"
  size: 15036
  writable: false
  readable: false
  executable: false
  file: false
  dir: false
  link: false
}

HTML
<form wire:submit.prevent="submit" enctype="multipart/form-data" method="post">
  @csrf
  <input type="file" wire:model="attachment" class="form-control" />

  <button class="button btn-block">Save</button>
</form>

Any idea?
Update
It seems to be known issue

A: in livewire you can't $_FILES['attachment']['type'] access this data for validation you can do like this
$chat = new BidChat;
// other fields
if ($this->attachment) {
    $attachment = $this->attachment;
    $filename = 'chat-attachment' . '-' . time() . '.' . $attachment->getClientOriginalExtension();
    $location = public_path('images/' . $filename);

    $this->validate([
        'attachment' => 'image|mimes:jpeg,png,jpg,gif',
    ]);

    Image::make($attachment)->resize(1300, 362)->save($location);
    $chat->attachment = $filename;
}
$chat->save();

ref link https://laravel-livewire.com/docs/2.x/file-uploads


text:
Q: puppet only exec when file does NOT exist I only want to exec following command when file (/usr/local/bin/papply) does not exist.  not sure what to put there.
    exec { 'git add url':
        command =>'git remote add origin https://github.com/testing/puppet.git',
        require => Exec['git init'],
        cwd => '/home/vagrant/django',
        user => 'vagrant',
        onlyif => "not sure what to put here"
    }

A: If you're on linux just do
unless => 'ls /somefile'

ls will return with a non-zero return code if the file does not exist and unless will only let the exec it is under execute if its test returns a non-zero return code.

A: Have you tried this?
onlyif => "test ! -f /usr/local/bin/papply"

Not sure if Puppet can use the '!' character
Perhaps a better alternaltive:
creates => '/usr/local/bin/papply'

even if i don't like the fact that the command doesn't really creates the file

A: On linux and puppet >3.8 try:
exec { 'test':
   command => '/bin/echo HI',
   unless  => 'test -f /a/file.txt',
}

exec will not run if /a/file.txt exists.

A: You might want to consider using creates, which exists for this purpose:
exec { 'git add url':
  command => 'git remote add origin https://github.com/testing/puppet.git',
  creates => '/usr/local/bin/papply'
}


text:
Q: matplotlib.pyplot polygon with equal aspect and tight layout I want to draw a set of polygons on an axis of equal aspect and apply tight layout on the figure.
However, it seems like the figure size doesn't get correctly adjusted when equal aspect and tight layout are used together.
Attempt 1
Equal aspect and tight layout
import matplotlib.pyplot as plt
from matplotlib.patches import Polygon
import numpy as np

fig, ax = plt.subplots(1,1)
l = 5
h = 1
poly = Polygon(
    np.array([
        [0,0],
        [l,0],
        [l,h],
        [0,h]
    ]),
    edgecolor="black",
    facecolor="gray",
)
ax.add_patch(poly)
ax.set_aspect("equal")
ax.set_xlim(0,l)
ax.set_ylim(0,h)
ax.set_xlabel(r"$x$")
ax.set_ylabel(r"$y$", rotation=0, labelpad=5)
fig.tight_layout(pad=0.25)
plt.show()

Output: notice the extra space on top and bottom. Also notice that the y axis label is out of bounds.

Attempt 2
Tight layout without equal aspect
import matplotlib.pyplot as plt
from matplotlib.patches import Polygon
import numpy as np

fig, ax = plt.subplots(1,1)
l = 5
h = 1
poly = Polygon(
    np.array([
        [0,0],
        [l,0],
        [l,h],
        [0,h]
    ]),
    edgecolor="black",
    facecolor="gray",
)
ax.add_patch(poly)
# ax.set_aspect("equal")
ax.set_xlim(0,l)
ax.set_ylim(0,h)
ax.set_xlabel(r"$x$")
ax.set_ylabel(r"$y$", rotation=0, labelpad=5)
fig.tight_layout(pad=0.25)
plt.show()

Output: works well, except that the aspect ratio is unequal

How to achieve tight layout and equal aspect ratio?

A: Additional margins appear if the aspect ratio of the Figure (default size from rcParams["figure.figsize"] defaults to [6.4, 4.8], i.e. an aspect ratio of 1.33) differs from the aspect ratio of the Axes. To avoid this, you need to adjust the aspect ratio of the Figure to match the aspect ratio of the Axes including ticks and labels. You can get it using get_tightbbox after you have drawn the Figure (for instance using draw_without_rendering).
For better visual result I recommend using constrained rather than tight layout.
import matplotlib.pyplot as plt
from matplotlib.patches import Polygon
import numpy as np

fig, ax = plt.subplots(1,1, layout='constrained')
l = 5
h = 1
fig.set_size_inches(10,2)
poly = Polygon(
    np.array([
        [0,0],
        [l,0],
        [l,h],
        [0,h]
    ]),
    edgecolor="black",
    facecolor="gray",
)
ax.add_patch(poly)
ax.set_aspect("equal")
ax.set_xlim(0,l)
ax.set_ylim(0,h)
ax.set_xlabel(r"$x$")
ax.set_ylabel(r"$y$", rotation=0, labelpad=5)

# adjust Figure aspect ratio to match Axes
fig.draw_without_rendering()
tb = fig.get_tightbbox(fig.canvas.get_renderer())
fig.set_size_inches(tb.width, tb.height)

plt.show()


text:
Q: Re-applying Event Listeners in Meteor Template for Newly Created Elements Some background: In my app, I have these input text-boxes and when you type into them, it uses the Session to hold a reactive variable so that the user can see a live preview of what they are typing.
I want to let a user click on a button to add a new input box. And whenever the user types into that new input box, it should also generate a live preview in the same way that the first one did. However, it seems that the event handler is not applied to those newly created elements. As a result, the live preview does not update until I type something into the original input box again.
Template.makeEntry.helpers({
    goals: function() {
        return Session.get('todayGoals');
    }
});

Template.makeEntry.events({
  'input .goal': function(e) {
    var tempGoals = [];
    $('.goal').each(function(i){

        tempGoals.push($(this).val());
    });
    Session.set('todayGoals',tempGoals);
  },
  'click .add-goal': function(e) {

    var lastGoal = $('.goal').last();

    $('<input class="goal" type="text" name="goal" placeholder="Type your goal here...">').insertAfter(lastGoal);
  }
});

Template.makeEntry.rendered = function(){
    Session.set('todayGoals',[]);
}

HTML:
<template name="makeEntry">

Sunday, February 1st

    <input class="goal" type="text" name="goal" placeholder="Type your goal here...">
    <button class="add-goal">Add</button>
    {{#if goals}}

Today's Goals

                    {{#each goals}}

{{{this}}}

                    {{/each}}

    {{/if}}
</template>

A: Try not to manipulate the DOM whenever possible outside of Blaze.
Template.makeEntry.created = function(){
  Session.set('todayGoals',[""]);
}

Template.makeEntry.events({
  'click .add-goal': function(){
    var goals = Session.get('todayGoals');
    goals.push("");
    Session.set('todayGoals', goals);
  }
});

Template.makeEntry.helpers({
  'goal': function(){
    return Session.get("todayGoals");
  }
});

and in the html
<template name="makeEntry">
  ...
  {{#each goal}}
    ... do something with goal
    <input class="goal" type="text" name="goal" placeholder="Type your goal here...">
  {{/each}}
</template>


text:
Q: TOra errors on usage of date function I am currently using TOra as a query browser.
When I run the following query, I get an ORA-00936 missing expression error. This occurs even though I have set values for the bind variables.
SELECT DISTINCT
    L.LOG_ID,
    L.EVENT_ARG4,
    L.EVENT_TYPE,
    L.EVENT_ARG1,
    L.EVENT_ARG3,
    L.PROD_ITEM_ID,
    TRUNC(L.LOG_DATE) AS LOG_DATE
FROM
    EVENTLOG L
WHERE
    L.LOG_DATE >= TO_DATE(:report_start_date, 'YYYY/MM/DD') AND
    L.LOG_DATE < TO_DATE(:report_end_date, 'YYYY/MM/DD')

What would be causing this problem?

A: Try removing the colons in your WHERE clause.
Your PL-SQL statement should look like this:
SELECT DISTINCT
    L.LOG_ID,
    L.EVENT_ARG4,
    L.EVENT_TYPE,
    L.EVENT_ARG1,
    L.EVENT_ARG3,
    L.PROD_ITEM_ID,
    TRUNC(L.LOG_DATE) AS LOG_DATE
FROM
    EVENTLOG L
WHERE
    L.LOG_DATE >= TO_DATE(report_start_date, 'YYYY/MM/DD') AND
    L.LOG_DATE < TO_DATE(report_end_date, 'YYYY/MM/DD');