text:
Q: Scrapy if Request error then return item I got stuck trying to work out a solution...
My Scrapy spider crawls a site and gets some data into item then returns a request based on the data scraped and goes to crawl some other site in order to complete the item.
What it happens is that sometimes the second URL can return errors so item does not get outputted and as well.
How can I carry the item to the errback function?
Thanks in advance.

A: From the docs:

errback (callable) – a function that will be called if any exception
  was raised while processing the request. This includes pages that
  failed with 404 HTTP errors and such. It receives a Twisted Failure
  instance as first parameter.

Try to use lambda:
    ...
    yield Request(..., errback=lambda failure, item=item: self.on_error(failure, item))

def on_error(self, failure, item):
    ...


text:
Q: mute не работает Делаю команду мута, всё работает отлично. Почти всё. Когда проходит заданное время, бот выдёт такую ошибку:

discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'int' object has no attribute 'sleep'

# мут
@client.command(pass_context=True)
@commands.has_permissions(manage_messages=True)
async def mute1(ctx, member: discord.Member, time: int, *, reason="причина не указана"):
    mute_role = discord.utils.get(ctx.message.guild.roles, name="mute")
    await ctx.message.delete()
    await member.add_roles(mute_role)
    embed = discord.Embed(title="╔=============================╗", colour=discord.Color.red(),
                          description=f"{member.mention} был замьючен на {time} минут по следующей причине: {reason}")
    embed.set_footer(text="Операция прошла успешно")
    embed.set_image(url="https://i.pinimg.com/originals/a9/0f/e2/a90fe21457dbc5d06b8579d55d7cbda1.gif")
    await ctx.send(embed=embed)
    time.sleep(time)
    await member.remove_roles(mute_role)

A: @client.command(pass_context=True)
@commands.has_permissions(manage_messages=True)
async def mute(ctx, member: discord.Member, time: int, *, reason="причина не указана"):
    mute_role = discord.utils.get(ctx.message.guild.roles, name="mute")
    await ctx.message.delete()
    await member.add_roles(mute_role)
    await member.send(f"Вас замьютили на сервере {ctx.guild.name}\nПричина: {reason}\nВремя мута: {time} минут")
    embed = discord.Embed(title="╔=============================╗", colour=discord.Color.red(),
                          description=f"{member.mention} был замьючен на {time} минут по следуйщей причине: {reason}")
    embed.set_footer(text="Операция прошла успешно")
    embed.set_image(url="https://i.pinimg.com/originals/a9/0f/e2/a90fe21457dbc5d06b8579d55d7cbda1.gif")
    await ctx.send(embed=embed)
    await asyncio.sleep(10) #ошибка была тут
    await member.remove_roles(mute_role)

redpajama_set_name: RedPajamaStackExchange


text:
Q: Bukkit - Get Variables From Other @EventHandlers? I was wondering how I would get a variable from a different @EventHandler. My variable in this instance is an array list.
My code is below:
@EventHandler
public void onBlockBreak(BlockBreakEvent event) {
    ArrayList<String> build = new ArrayList();
    Player player = event.getPlayer();
    if(!player.isOp()) {
        event.setCancelled(true);
    }else if(!build.contains(player)) {
        event.setCancelled(true);
    }else if(build.contains(player)) {
        event.setCancelled(false);
    }
}
@EventHandler
public void onPlayerJoin(PlayerJoinEvent event) {
    Player player = event.getPlayer();
    event.setJoinMessage("§4§l>>§a§l " + player + " §b§ljoined! §4§l<<");
    if(build.contains(player)) {
        build.remove(player);

Now, on the second @EventHandler it cannot resolve the variable "build" which is what I defined in the previous @EventHandler. So how can I make it so it works?

A: build is a local variable and is only available within the method onBlockBreak(BlockBreakEvent event).
What you want to do is declare a variable outside the method and initialize it in it's onEnable() method. You should also do what KingFaris10 metioned and store the player's UUID. You will also need someway to add the players to the ArrayList.
private ArrayList<UUID> build;
@Override
public void onEnable () {
    build = new ArrayList<UUID>();
}

@EventHandler
public void onBlockBreak(BlockBreakEvent event) {
    Player player = event.getPlayer();
    //Following derived from KingFaris10
    if (!player.isOp() || !build.contains(player.getUUID())) event.setCancelled(true);
    else event.setCancelled(false);
}
@EventHandler
public void onPlayerJoin(PlayerJoinEvent event) {
    Player player = event.getPlayer();
    event.setJoinMessage("§4§l>>§a§l " + player + " §b§ljoined! §4§l<<");
    UUID id = player.getUUID();
    if(build.contains(id)) {
        build.remove(id);


text:
Q: How to trigger an event on click of scroll bar in angular 5 In my project I have filter pop up to filter the data in the table. If I click any where outside the pop up in that table, pop up should close. The behavior is working properly when I click anywhere in the table. When scrollbar appear if I click on scrollbar it is not calling the function.
How to call the function on click of scroll bar in Angular 5.
Below is the stackblitz link please help me, thanks in advance.
https://stackblitz.com/edit/angular-uaig8q?file=src%2Fapp%2Fapp.component.html

A: You could make use of the scroll event. A solution not Angular specific is:
const myContainer = document.getElementById('my_element');
myContainer.addEventListener('scroll', () => {
  filterPopup.close()
});

A: Slight variation on Victor's answer, just add a scroll event listener on the entire window
 window.addEventListener('scroll', function(e) {
    popup.close();
 });


text:
Q: Cumulative Distribution Function with New Random Variable I'm really new to statistics and probability so sorry if this is a really basic question. I just wasn't sure how to do it. I tried looking it up but can't find much information.
If I'm given a cdf for a random variable X, how do I find it for a new random variable Y which was in terms of X? Do I just plug in Y? My example is following:
FX(x) = 1 −1/x
for 1 < x < ∞
Find the cdf for the new random variable Y = -X + 2

A: \begin{align}
F_Y(y) & = \Pr(Y\le y) = \Pr(-X+2\le y) = \Pr(X\ge 2-y) \\[8pt]
& = 1-\Pr(X\le 2-y) = F_X(2-y)
\end{align}
provided $2-y\ge 1$, which is the same as $y\le 1$.
If $y>1$ then
$$
F_Y(y) = \Pr(Y\le y) = \Pr(-X+2\le y) = \Pr(X\ge 2-y) = 1.
$$
Your way of phrasing the question makes me a bit suspicious: I wonder if you are expecting some prescribed way of solving a problem, rather than expecting to figure it out based on information you have.  The latter is the way to do math.


text:
Q: React Js AWS Amplify PubSub receiving multiple messages I have a react APP that uses the AWS Amplify PubSub library.
I have an IoT device that connect to AWS IoT and publishes message on topic/pub (topic).The message is only sent once (from the device) and when I see it in the AWS MQTT client console I can only see only 1 message (as expected) but in the react application I'm receiving multiple messages in the console.
App.js
...
import {Amplify} from 'aws-amplify';
import awsconfig from './aws-exports';
// import { withAuthenticator } from 'aws-amplify-react'; // or 'aws-amplify-react-native';
import { withAuthenticator, Button, Heading } from '@aws-amplify/ui-react';
import '@aws-amplify/ui-react/styles.css';

import { Auth } from 'aws-amplify';

Amplify.configure(awsconfig);
// Auth.currentCredentials().then(creds => console.log(creds));

function App() {
  return (
      ...

export default withAuthenticator(App,true);

Device Page.js

import {Amplify} from 'aws-amplify';
import awsconfig from './../aws-exports';
import { PubSub } from 'aws-amplify';
import { AWSIoTProvider } from '@aws-amplify/pubsub/lib/Providers';

Amplify.configure(awsconfig);

Amplify.addPluggable(new AWSIoTProvider({
    aws_pubsub_region: 'xx-xxxxxxx-x',
    aws_pubsub_endpoint: 'wss://<My endpoint from AWS IoT>/mqtt',
   }));

function GaugesComponent  ({id}) {

    PubSub.subscribe('test/pub').subscribe({
        next: data => {
            console.log(data.value);

        },
        error: error => console.error(error),
        complete: () => console.log('Done'),
    },);

    return (
    ...

export default GaugesComponent;

When my device publishes or I use the AWS MQTT client to publish a message the message is logged multiple times in the console.
Images:
AWS MQTT client console

console log messages of react app

A: Instead of adding the below code in the device.js where I'm subscribing to the MQTT topic I only added it once in my app.js after Amplify.configure(); like this
App.js
Amplify.configure(awsconfig);
Amplify.addPluggable(new AWSIoTProvider({
    aws_pubsub_region: 'xx-xxxxxxx-x',
    aws_pubsub_endpoint: 'wss://<My endpoint from AWS IoT>/mqtt',
   }));

Then I subscribe to the topic using useEffect() like this in my device.js
Device.js
sub_topic = PubSub.subscribe(id+'/live').subscribe({
    next: data => {/*do stuff with received data*/},
    error: error => console.error(error),
    complete: () => console.log('Done'),
},);
return ()=>{
       sub_topic.unsubscribe();
       console.log("Unsubscribed to topic");
    }
},[]);


text:
Q: Running ruby sript with Cron in Centos7 Docker image I've setup a cron job in my centos7 docker image but its not working
crontab -e
    >> * * * * * ruby myrubyfile.rb

This same cron job is working on my actual centos7 machine.

A: Cron was working all along, however when running inside the container i needed to have the full path to ruby. The following worked:
* * * * * /root/.rbenv/shims/ruby /myrubyfile.rb


text:
Q: Uncaught ReflectionException: Class App\Http\Kernel does not exist in /project/vendor/laravel/framework/src/Illuminate/Container/Container.php:721 When I try to run my Laravel project by using
php -S localhost:8000

or
php artisan serve

it throws this error log
PHP Fatal error:  Uncaught ReflectionException: Class App\Http\Kernel does not exist in /var/www/project/vendor/laravel/framework/src/Illuminate/Container/Container.php:721
Stack trace:
#0 /var/www/project/vendor/laravel/framework/src/Illuminate/Container/Container.php(721): ReflectionClass->__construct('App\\Http\\Kernel')
#1 /var/www/project/vendor/laravel/framework/src/Illuminate/Container/Container.php(600): Illuminate\Container\Container->build('App\\Http\\Kernel')
#2 /var/www/project/vendor/laravel/framework/src/Illuminate/Container/Container.php(567): Illuminate\Container\Container->resolve('App\\Http\\Kernel')
#3 /var/www/project/vendor/laravel/framework/src/Illuminate/Foundation/Application.php(708): Illuminate\Container\Container->make('App\\Http\\Kernel')
#4 /var/www/project/vendor/laravel/framework/src/Illuminate/Container/Container.php(246): Illuminate\Foundation\Application->make('App\\Http\\Kernel', Array)
#5 /var/www/project/vendor/laravel/framework/src/Illuminate/Container/Container.php(718): Ill in /var/www/project/vendor/laravel/framework/src/Illuminate/Container/Container.php on line 721

I have tried deleting vendor folder and reinstalling through composer by using this command
composer install

but it didn't work. I have tried to debug and tried all the possible solutions available on this platform but I was unable to resolve the error.
I have tried these commands as well
 php artisan config:clear
 php artisan cache:clear
 composer update
 composer dump-autoload

but unfortunetly none of them worked. Please help me to solve this issue.

A: First of all, does App\Http\Kernel.php exist?
Second, does it get bound to the service container in bootstrap\app.php?
It should look like this:
// ...Line 28
$app->singleton(
    Illuminate\Contracts\Http\Kernel::class,
    App\Http\Kernel::class
);

$app->singleton(
    Illuminate\Contracts\Console\Kernel::class,
    App\Console\Kernel::class
);

$app->singleton(
    Illuminate\Contracts\Debug\ExceptionHandler::class,
    App\Exceptions\Handler::class
);
// Line 43...

A: I also did run into class App\Http\Kernel.php not found.
Didn't know how but it happens that my  http folder had been moved to my project directory.
A simple copy of the \Http\ folder and pasting into the App folder resolved the issue


text:
Q: Forms with Prism: Application windows are expected to have a root VC I just implemented the Prism Library in my new application, and I'm using NavigationService. It works fine on Android, but when I attempt to debug my Xamarin Forms iOS App on a networked Mac, my Main method throws this exception:
  Unhandled Exception:

Foundation.MonoTouchException: Objective-C exception thrown.  Name: NSInternalInconsistencyException Reason: Application windows are expected to have a root view controller at the end of application launch
Native stack trace:
    0   CoreFoundation                      0x00000001021f2b0b __exceptionPreprocess + 171
    1   libobjc.A.dylib                     0x000000010cdcf141 objc_exception_throw + 48
    2   CoreFoundation                      0x00000001021f6cf2 +[NSException raise:format:arguments:] + 98
    3   Foundation                          0x0000000102da93b6 -[NSAssertionHandler handleFailureInMethod:object:file:lineNumber:description:] + 193
    4   UIKit                               0x0000000105ba0be6 -[UIApplication _runWithMainScene:transitionContext:completion:] + 3343
    5   UIKit                               0x0000000105b9d793 -[UIApplication workspaceDidEndTransaction:] + 182
    6   FrontBoardServices                  0x000000010fae35f6 __FBSSERIALQUEUE_IS_CALLING_OUT_TO_A_BLOCK__ + 24
    7   FrontBoardServices                  0x000000010fae346d -[FBSSerialQueue _performNext] + 186
    8   FrontBoardServices                  0x000000010fae37f6 -[FBSSerialQueue _performNextFromRunLoopSource] + 45
    9   CoreFoundation                      0x0000000102198c01 __CFRUNLOOP_IS_CALLING_OUT_TO_A_SOURCE0_PERFORM_FUNCTION__ + 17
    10  CoreFoundation                      0x000000010217e0cf __CFRunLoopDoSources0 + 527
    11  CoreFoundation                      0x000000010217d5ff __CFRunLoopRun + 911
    12  CoreFoundation                      0x000000010217d016 CFRunLoopRunSpecific + 406
    13  UIKit                               0x0000000105b9c02f -[UIApplication _run] + 468
    14  UIKit                               0x0000000105ba20d4 UIApplicationMain + 159
    15  ???                                 0x0000000124f647fc 0x0 +

My main method is so:
static void Main(string[] args)
        {
            // if you want to use a different Application Delegate class from "AppDelegate"
            // you can specify it here.
            UIApplication.Main(args, null, "AppDelegate");
        }

AppDelegate:
[Register("AppDelegate")]
    public partial class AppDelegate : global::Xamarin.Forms.Platform.iOS.FormsApplicationDelegate
    {

        // This method is invoked when the application has loaded and is ready to run. In this
        // method you should instantiate the window, load the UI into it and then make the window
        // visible.
        //
        // You have 17 seconds to return from this method, or iOS will terminate your application.
        public override bool FinishedLaunching(UIApplication app, NSDictionary options)
        {
            global::Xamarin.Forms.Forms.Init();
            this.LoadApplication(new Core.CitizenApp());

            return base.FinishedLaunching(app, options);
        }
    }

Forms App:
protected override void OnInitialized()
    {
        this.InitializeComponent();
        NavigationService.NavigateAsync("LaunchPage");
        return;
    }

Any help would be appreciated. I have the latest updates of Xamarin, Xamarin Forms, Prism, and Visual Studio, and I'm not sure what the issue could be.

A: You have an exception being thrown by your LaunchPage. Update OnInitialized to look more like this:
protected override async void OnInitialized()
{
    try
    {
        TaskScheduler.UnobservedTaskException += (sender, e) => {
            Logger.Log(e.Exception.ToString(), Category.Exception, Priority.High);
        };
        await NavigationService.NavigateAsync("LaunchPage");
    }
    catch(Exception e)
    {
        Logger.Log(e.Exception.ToString(), Category.Exception, Priority.High);
    }
}

This should help you to at least identify what the exception is. Without seeing your project it's hard to say, but I might guess that either you are using IPlatformInitializer and registered something on Android but not iOS, or you are relying on the Xamarin Forms Dependency Service and that dependency exists on Android but not iOS.


text:
Q: How to exchange/replace the shared (singleton) object in MEF container? This may be simple but as I am new to MEF arena that is why I am having some difficulty to figure out the solution to my problem.
I am working on an application using WPF + Prism with MEF as DI container. I want to tie my object (i.e. RuleFile) with each application instance by associating it with the file say RuleFile1.ruleapp. Therefore I have decorated it with attribute [PartCreationPolicy(CreationPolicy.Shared)] to treat it as singleton so that it remains same throughout the application with each application instance.
[Serializable()]
[Export]
[PartCreationPolicy(CreationPolicy.Shared)]
public class RuleFile : NotifyPropertyChanged, IRuleFile { }

Next, at the time of ViewModel [ImportingContructor] as shown below, the object is same as desired.
[ImportingConstructor]
public RuleViewModel(RuleFile ruleFile)

[ImportingConstructor]
public SchemaViewModel(RuleFile ruleFile)

Until now everything is smooth.
Using below piece of code, i am trying to get the same exported object that is passing to view model as mentioned above but container.GetExportedValue<IRuleFile>() is giving a new object reference that is not the same one:
var catalog = new AssemblyCatalog(System.Reflection.Assembly.GetExecutingAssembly());
var container = new CompositionContainer(catalog);
var exportObj = container.GetExportedValue<IRuleFile>();

Question 1: Why i am getting a different reference although object should be the same as it is a singleton object with CreationPolicy.Shared?
Question 2: Ultimately this all effort is to exchange/replace RuleFile exported object with the deserialized one in the MEF DI container?

A: You don't replace instances in a MEF container, that is not how it works, and it's dangerous and completely unmanageable. (Also keep in mind C# is not C where you can simply change pointed-to objects). Suppose a class X gets an instance from the container and has a factory method in which it passes this instance another class Y. Now suddenly you want to 'replace' that instance. First of all, what would have to happen to the old instance? Disposed? Kept alive? Mailed to your grandmother? Second, if X got the instance using GetExportedValue, how are you going to notify it the instance it has is now gone and is replaced by something else? You can't.. Third, suppose X used Import instead and by some magic it gets notified that it's instance has been replaced. How is it now in turn going to notify Y that the instance is replaced? You can't, unless you keep a list of Y. Etc, etc. I hope this made it clear replacing objects in a container isn't a good idea.
There are a couple of things you can do instead though:

*

*Just make sure your RuleFile is created and injected in the container before it is imported anywhere. This also makes most sense: I have the impression RuleFile is some kind of application-wide configuration, so it is desirable this configuration is setup completely before the application even starts. Override MefBootstrapper.ConfigureContainer, deserialize you RuleFile instance and use ComposeExportedValue to set it as the sole instance in the container. If deserializition fails, you aither show an error dialog and abort your app, or supply a default configuration and inject that instead.

*Provide a wrapper around RuleFile wich reads from the deserialized RuleFile if available, or else supplies default values. So the observed behaviour is the same as RuleFile being replaced in the container. However this has the major drawback that if there is code using the IRuleFile instance before the file is loaded, it gets different values than after the file is loaded. Which is why the first approach is better. Example:
private class DefaultRuleFile: IRulefile
{
  string SomeProperty
  {
    get{ return "DefaultValue"; }
  }
}

[Export( typeof( IRulefile ) )]
[Export( typeof( RuleFileImplementation ) )]
[PartCreationPolicy(CreationPolicy.Shared)]
public class RuleFileImplementation : IRulefile
{
  private IRuleFile impl;

  RuleFileImplementation()
  {
    impl = new DefaultRuleFile();
  }

  string SomeProperty
  {
    get{ return impl.SomeProperty; }
  }

  void LoadFromFile( string file )
  {
    impl = SerializationHelper.Deserialize<IRuleFile>( file );
  }
}

//at some point in the application:
container.GetExportedValue<RuleFileImplementation>().LoadFromFile( "file" )


text:
Q: Copy file before include it in the installer package NSIS For example I have a config file in D:\Project\InstallerPro\Platform\Windows8\Web.config
I need to move that file to D:\Project\InstallerPro\Web\Configuration\Web.config if the windows version is windows 8
After that, the installer will be generated from a nsi script in D:\Project\InstallerPro\PROinst.nsi
Is it possible to copy the files (not manually) before compiling it into an installer using NSIS?
I want to do something like this:
CopyFiles ".\Source\Platform\Windows8\Web.config" ".\Source\WEB\Configuration\Web.config"

A: CopyFiles is a runtime command, i.e a command that will run during the installer execution and not during the installer creation.
You could use the !system command that is executed during the compilation of the installer, e.g.:
!system `copy "c:\Source\Platform\Windows8\Web.config" "c:\Source\WEB\Configuration\Web.config"`

You will need to use absolute paths as the current working dir is from makensis.exe and not from the script being compiled.


text:
Q: $\mathcal B[0,\infty) \otimes \mathcal F$-measurability of $(t,\xi) \mapsto \xi(t)$ Let ${\bf D} = \{\xi : [0,\infty)\to\mathbb R^d \mid \xi \text{ is right-continuous with left-limits}\}$. For each $t\ge0$, define $x_t:{\bf D}\to \mathbb R^d$ by $x_t(\xi)=\xi(t)$. We write $x_t(\xi)=x(t,\xi)$ and consider the function $x:[0,\infty)\times {\bf D}\to \mathbb R^d$.
What I want to show is that $x$ is $\mathcal B[0,\infty) \otimes \mathcal F$-measurable in $(t,\xi)$, with $\mathcal F=\sigma(x_t:t\ge 0)$, the smallest $\sigma$-algebra where all $x_t$ are measurable in $\xi$.
I don't know how to prove this statement using the right-continuity (hint given). First time I tried to decompose each inverse image of compact set into product of measurable sets, but failed. What argument should I use?

A: Hint: $x(t,\xi)=\lim_{n\to\infty}\sum_{k=1}^{2^n}1_{[(k-1)/n,k/n)}(t)\xi(k/n)$. (Because of right continuity.) Argue that each term in the sum is $\mathcal B[0,\infty)\otimes\mathcal F$-measurable, hence to is the sum, hence so is the limit.


text:
Q: Multiple problems converting a Map to a List in DataTable builder I have some key/value data in a Map I wish to display in a flutter DataTable(), but I'm having a problem getting the syntax of the builder correct.
The row argument needs to be List<DataRow>
So far I've tried:
row: List<DataRow>.of(searchResultItem.detailsDataMap.forEach((k, v) =>
  DataRow(cells: [DataCell(Text(k)), DataCell(Text(v))])))

which gives: This expression has a type of 'void' so its value can't be used.
And, trying to cast it:
row: List<DataRow>.of(searchResultItem.detailsDataMap.(forEach((k, v) =>
  DataRow(cells: [DataCell(Text(k)), DataCell(Text(v))])) as DataRow))

which gives: The getter '(' isn't defined for the type 'Map<String, dynamic>'.
And finally mapping it:
row: List<DataRow>.of(searchResultItem.detailsDataMap.map<DataRow>((String key, dynamic value) =>
  DataRow(null)))

which gives: The argument type 'Map<dynamic, dynamic>' can't be assigned to the parameter type 'Iterable'.
What might be a way of going this that works?

A: Seems easier to map over the entries.  The following works:
          rows: searchResultItem.detailsDataMap.entries
            .map(
              (entry) => DataRow(
                cells: [
                  DataCell(Text(entry.key.toString())),
                  DataCell(Text(entry.value.toString()))
                ],
              ),
            )
            .toList(),


text:
Q: Error with Devise - Cannot run rails s or any devise commands I've recently added gem 'devise' but all of the sudden I can no longer run rails s or any devise commands without seeing this  Error message:
`c:3:in rescue in execute_if_updated': Rails::Application::RoutesReloader#execute_if_updated delegated to updater.execute_if_updated, but updater is nil: #<Rai
s::Application::RoutesReloader:0x276cf60 @paths=["c:/Sites/code/omrails/config/routes.rb"], @route_sets=[#<ActionDispatch::Routing::RouteSet:0x2ab40c0>]> (Runt
meError)
        from c:65535:in `execute_if_updated'
        from c:/RailsInstaller/Ruby1.9.3/lib/ruby/gems/1.9.1/gems/railties-4.0.0.rc2/lib/rails/application/finisher.rb:69:in `block in <module:Finisher>'
        from c:/RailsInstaller/Ruby1.9.3/lib/ruby/gems/1.9.1/gems/railties-4.0.0.rc2/lib/rails/initializable.rb:30:in `instance_exec'
        from c:/RailsInstaller/Ruby1.9.3/lib/ruby/gems/1.9.1/gems/railties-4.0.0.rc2/lib/rails/initializable.rb:30:in `run'
        from c:/RailsInstaller/Ruby1.9.3/lib/ruby/gems/1.9.1/gems/railties-4.0.0.rc2/lib/rails/initializable.rb:55:in `block in run_initializers'
        from c:/RailsInstaller/Ruby1.9.3/lib/ruby/1.9.1/tsort.rb:150:in `block in tsort_each'
        from c:/RailsInstaller/Ruby1.9.3/lib/ruby/1.9.1/tsort.rb:183:in `block (2 levels) in each_strongly_connected_component'
        from c:/RailsInstaller/Ruby1.9.3/lib/ruby/1.9.1/tsort.rb:219:in `each_strongly_connected_component_from'
        from c:/RailsInstaller/Ruby1.9.3/lib/ruby/1.9.1/tsort.rb:182:in `block in each_strongly_connected_component'
        from c:/RailsInstaller/Ruby1.9.3/lib/ruby/1.9.1/tsort.rb:180:in `each'
        from c:/RailsInstaller/Ruby1.9.3/lib/ruby/1.9.1/tsort.rb:180:in `each_strongly_connected_component'
        from c:/RailsInstaller/Ruby1.9.3/lib/ruby/1.9.1/tsort.rb:148:in `tsort_each'
        from c:/RailsInstaller/Ruby1.9.3/lib/ruby/gems/1.9.1/gems/railties-4.0.0.rc2/lib/rails/initializable.rb:54:in `run_initializers'
        from c:/RailsInstaller/Ruby1.9.3/lib/ruby/gems/1.9.1/gems/railties-4.0.0.rc2/lib/rails/application.rb:215:in `initialize!'
        from c:/RailsInstaller/Ruby1.9.3/lib/ruby/gems/1.9.1/gems/railties-4.0.0.rc2/lib/rails/railtie/configurable.rb:30:in `method_missing'
        from c:/Sites/code/omrails/config/environment.rb:5:in `<top (required)>'
        from c:/RailsInstaller/Ruby1.9.3/lib/ruby/gems/1.9.1/gems/railties-4.0.0.rc2/lib/rails/application.rb:189:in `require'
        from c:/RailsInstaller/Ruby1.9.3/lib/ruby/gems/1.9.1/gems/railties-4.0.0.rc2/lib/rails/application.rb:189:in `require_environment!'
        from c:/RailsInstaller/Ruby1.9.3/lib/ruby/gems/1.9.1/gems/railties-4.0.0.rc2/lib/rails/commands.rb:47:in `<top (required)>'
        from bin/rails:4:in `require'
        from bin/rails:4:in `<main>'

Gemfile:
source 'https://rubygems.org'

gem 'rails', '4.0.0.rc2'
gem 'jquery-rails'
gem 'devise', '3.0.0.rc'
gem 'turbolinks'
gem 'jbuilder', '~> 1.2'
gem 'bootstrap-sass', '~> 2.3.2.1'
gem 'pg'
gem 'simple_form', '3.0.0.rc'
gem 'protected_attributes'
gem 'rails_12factor', group: :production

ruby '1.9.3'

group :development, :test do
  gem 'sqlite3'
end

group :assets do
    gem 'sass-rails', '~> 4.0.0.rc2'
    gem 'uglifier', '>= 1.3.0'
    gem 'coffee-rails', '~> 4.0.0'
    gem 'bootstrap-sass', '~> 2.3.2.1'
end

group :doc do
  gem 'sdoc', require: false
end

Routes.rb
Omrails::Application.routes.draw do
  devise_for :installs
  # You can have the root of your site routed with "root"
  get 'about' => 'pages#about'
  root :to => 'pages#home'
end

A: Maybe you can shifting to rails edge.
gem 'rails', github: 'rails/rails'
gem "devise", "~> 3.0.1"

(https://github.com/rails/rails/issues/10559)


text:
Q: EclipseRCP - Multiple Visible-When CoreExpressions to HandledMenuItem? In my plugin.xml I have defined multiple restrictions like:
<extension
      point="org.eclipse.core.expressions.definitions">
   <definition id="my.stuff.readAccess1">
      <test>...</test>
   </definition>
   <definition id="my.stuff.readAccess2">
      <test>...</test>
   </definition>
</extension>

In my fragment.e4xmi file I would like to use multiple of these for a simple HandledMenuItem as a Visible-When Expression with a conjuction, is that possible somehow?
My issue is that I have many roles and other restrictions (this menu should be seen only in a specific perspective, etc.), and having to create a CoreExpression for all the menu items one-by-one seems a bit cumbersome.
Any hints if that could be avoided? Thanks in advance!

A: You can only specify the one core expression, but you can combine other expressions using and and or:
  <definition
        id="my.stuff.readAccess1and2">
       <and>
          <reference
                 definitionId="my.stuff.readAccess1">
          </reference>
          <reference
                 definitionId="my.stuff.readAccess2">
           </reference>
      </and>
  </definition>


text:
Q: What does class fields with the same data type as the class called? class DoublyCircularLL{

    DoublyCircularLL head;
    DoublyCircularLL next;
    DoublyCircularLL prev;
    DoublyCircularLL pointer; <----- This Things
}

My understanding is they are variables with the data type of the class. Is that right or they are something else?


text:
Q: Webcam light still on ever after disconnecting the drivers vb.net 2008 I want to capture image from webcam and I found an excellent code for that, the only problem is even after disconnecting webcam drivers webcam light still on. So it seems webcam still in use. How to adjust it?
 SendMessage(hHwnd, WM_CAP_DRIVER_DISCONNECT, DeviceID, 0)
        DestroyWindow(hHwnd)

Webcam Class
Public Class Form1
    Const WM_CAP As Short = &H400S
    Const WM_CAP_DRIVER_CONNECT As Integer = WM_CAP + 10
    Const WM_CAP_DRIVER_DISCONNECT As Integer = WM_CAP + 11
    Const WM_CAP_EDIT_COPY As Integer = WM_CAP + 30
    Public Const WM_CAP_GET_STATUS As Integer = WM_CAP + 54
    Public Const WM_CAP_DLG_VIDEOFORMAT As Integer = WM_CAP + 41
    Const WM_CAP_SET_PREVIEW As Integer = WM_CAP + 50
    Const WM_CAP_SET_PREVIEWRATE As Integer = WM_CAP + 52
    Const WM_CAP_SET_SCALE As Integer = WM_CAP + 53
    Const WS_CHILD As Integer = &H40000000
    Const WS_VISIBLE As Integer = &H10000000
    Const SWP_NOMOVE As Short = &H2S
    Const SWP_NOSIZE As Short = 1
    Const SWP_NOZORDER As Short = &H4S
    Const HWND_BOTTOM As Short = 1
    Private DeviceID As Integer = 0 ' Current device ID
    Private hHwnd As Integer ' Handle to preview window
    Declare Function SendMessage Lib "user32" Alias "SendMessageA" _
        (ByVal hwnd As Integer, ByVal wMsg As Integer, ByVal wParam As Integer, _
        ByRef lParam As CAPSTATUS) As Boolean
    Declare Function SendMessage Lib "user32" Alias "SendMessageA" _
       (ByVal hwnd As Integer, ByVal wMsg As Integer, ByVal wParam As Boolean, _
       ByRef lParam As Integer) As Boolean
    Declare Function SendMessage Lib "user32" Alias "SendMessageA" _
         (ByVal hwnd As Integer, ByVal wMsg As Integer, ByVal wParam As Integer, _
         ByRef lParam As Integer) As Boolean
    Declare Function SetWindowPos Lib "user32" Alias "SetWindowPos" (ByVal hwnd As Integer, _
        ByVal hWndInsertAfter As Integer, ByVal x As Integer, ByVal y As Integer, _
        ByVal cx As Integer, ByVal cy As Integer, ByVal wFlags As Integer) As Integer

    Declare Function DestroyWindow Lib "user32" (ByVal hndw As Integer) As Boolean
    Structure POINTAPI
        Dim x As Integer
        Dim y As Integer
    End Structure
        Private Sub LoadDeviceList()
        Dim strName As String = Space(100)
        Dim strVer As String = Space(100)
        Dim bReturn As Boolean
        Dim x As Short = 0
        '
        ' Load name of all avialable devices into the lstDevices
        '
        Do
            '
            '   Get Driver name and version
            '
            bReturn = capGetDriverDescriptionA(x, strName, 100, strVer, 100)
            '
            ' If there was a device add device name to the list
            '
            If bReturn Then lstDevices.Items.Add(strName.Trim)
            x += CType(1, Short)
        Loop Until bReturn = False
    End Sub

    Private Sub OpenPreviewWindow()
        ' Connect to device
        '
     SendMessage(hHwnd, WM_CAP_DRIVER_CONNECT, DeviceID, 0)
       End Sub

    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        LoadDeviceList()
             End Sub

    Private Sub ClosePreviewWindow()
        '
        ' Disconnect from device
        '
        SendMessage(hHwnd, WM_CAP_DRIVER_DISCONNECT, DeviceID, 0)
        DestroyWindow(hHwnd)
    End Sub

Start And Stop The Camera
    Private Sub btnStart_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnStart.Click
        DeviceID = lstDevices.SelectedIndex
        OpenPreviewWindow()
        Dim bReturn As Boolean
        Dim s As CAPSTATUS
        bReturn = SendMessage(hHwnd, WM_CAP_GET_STATUS, Marshal.SizeOf(s), s)
    End Sub

           Private Sub btnStop_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnStop.Click
        ClosePreviewWindow()
          SendMessage(hHwnd, WM_CAP_DRIVER_DISCONNECT, DeviceID, 0)
    End Sub

       End Class


text:
Q: Python variable variables without eval? Is there is a way to access variables using a variable string in python? For instance, I would like a neater way than using eval for the following:
def toggleListButtons (self):
    buttons = ["flip", "remove", "removeAll", "delete", "deleteAll", "loadDirectory"]
    for button in buttons:
        eval("self." + button + "Button.setEnabled(!self." + button + "Button.isEnabled())")

A: What you're looking for is the getattr() built-in function. There is also hasattr() and setattr().
button = getattr(self, 'flipButton')
button.setEnabled(True)


text:
Q: b2RevoluteJoint in cocos2d I have a CCNode subclass that is composed of a rectangular sprite that rotates around an anchor point. My object gets displayed in the world but I can't seem to get the b2RevoluteJoint working properly. The object simply remains static.
here's how my RotatingArm class looks.
-(id) init {
    if (self = [super init]) {
        rect = [CCSprite spriteWithFile:@"square.png"];
        [self addChild:rect z:1];
    }
    return self;
}

-(void) addBodyToWorld: (b2World*) world {
    b2BodyDef bodyDef;
    bodyDef.type = b2_dynamicBody;
    bodyDef.position.Set(self.position.x / PTM_RATIO,self.position.y / PTM_RATIO);
    bodyDef.userData = self;
    bodyDef.fixedRotation = true;
    self->body = world->CreateBody(&bodyDef);

   b2PolygonShape shape;
   shape.SetAsBox(rect.contentSize.width/PTM_RATIO/2,rect.contentSize.height/PTM_RATIO/2);
   [self createFixture:&shape forBody:body];

   [self addRotationJointInWorld:world];
}

- (void) addRotationJointInWorld:(b2World*)world  {

    CCSprite *sprite = [CCSprite spriteWithFile:@"anchor.png"];
    sprite.color = ccc3(50, 250, 50);
    [self addChild:sprite z:2];

    b2BodyDef rotationpointdef;
    rotationpointdef.type = b2_staticBody;
    rotationpointdef.position.Set(0,0);
    rotationpointdef.userData = sprite;
    rotationpointdef.fixedRotation = TRUE;
    rotationpoint = world->CreateBody(&rotationpointdef);

   b2PolygonShape rotationpointbox;
   rotationpointbox.SetAsBox(sprite.boundingBox.size.width / PTM_RATIO / 2.0,
                   sprite.boundingBox.size.height / PTM_RATIO / 2.0);

   [self createFixture:&rotationpointbox forBody:rotationpoint];

   b2RevoluteJointDef armJointDef;
   armJointDef.Initialize(rotationpoint, body, b2Vec2(rect.boundingBox.size.width/2/PTM_RATIO/2,rect.boundingBox.size.height/2/PTM_RATIO/2));
   armJointDef.enableMotor = TRUE;
   armJointDef.enableLimit = NO;
   armJointDef.motorSpeed  = 2;
   armJointDef.maxMotorTorque = 4800;

   armJoint = (b2RevoluteJoint*)world->CreateJoint(&armJointDef);

}

-(void) createFixture: (b2Shape*) shape forBody:(b2Body *) thebody {
    b2FixtureDef fixtureDef;
    fixtureDef.shape = shape;
    fixtureDef.density = 10.0f;
    thebody->CreateFixture(&fixtureDef);
}

Then in my main game layer I simply instantiate a rotating arm object like this:
RotatingArm *arm = [[[RotatingArm alloc] init] autorelease];
    arm.position = ccp(screen.width/2, screen.height/2);
    [self addChild:arm z:3];
    [arm addBodyToWorld:_world];

my main game layer also has an update method to update the sprite positions
 -(void) update: (ccTime) dt {
    world->Step(dt, 10, 10);
    for(b2Body *b = _world->GetBodyList(); b; b=b->GetNext()) {
      if (b->GetUserData() != NULL) {

        CCSprite *sprite = (CCSprite *)b->GetUserData();
        sprite.position = ccp(b->GetPosition().x * PTM_RATIO,
                              b->GetPosition().y * PTM_RATIO);

        sprite.rotation = -1 * CC_RADIANS_TO_DEGREES(b->GetAngle());
    }
}

A: I managed to make it work.
in my addbodytoworld method
bodyDef.fixedRotation = false;

instead of true. (I guess this was the main issue)
and I simplified the addrotationjoint method a bit
- (void) addRotationJoint {
    b2BodyDef bodyDef;
    bodyDef.position.Set(0,0);
    bodyDef.type = b2_staticBody;
    b2Body* staticBody = body->GetWorld()->CreateBody(&bodyDef);

    b2RevoluteJointDef armJointDef;
    armJointDef.Initialize(staticBody, body, b2Vec2(body->GetWorldCenter()));
    armJointDef.enableMotor = TRUE;
    armJointDef.enableLimit = NO;
    armJointDef.motorSpeed  = 2;
    armJointDef.maxMotorTorque = 4800;

    armJoint = (b2RevoluteJoint*)body->GetWorld()->CreateJoint(&armJointDef);
}


text:
Q: Insert into value of Radio button I am trying to insert the value of a radio button when its checked into mysql db table.  Below is the HTML and the PHP for doing so.  Please let me know what is going wrong?

Here is the HTML first:

    Business*:

    <input type="radio" name="bus" id="username" value="bus" maxlength="50" />

    Personal*:

    <input type="radio" name="pers" id="username" value="per" maxlength="50" />

Now the PHP:

function InsertIntoDB(&$formvars)
    {

        $confirmcode = $this->MakeConfirmationMd5($formvars['email']);

        $formvars['confirmcode'] = $confirmcode;

        $insert_query = 'insert into '.$this->tablename.'(
                name,
                email,
                username,
                password,
                confirmcode,
                dob,
                business,
                personal
                )
                values
                (
                "' . $this->SanitizeForSQL($formvars['name']) . '",
                "' . $this->SanitizeForSQL($formvars['email']) . '",
                "' . $this->SanitizeForSQL($formvars['username']) . '",
                "' . md5($formvars['password']) . '",
                "' . $confirmcode . '",
                "' . $this->SanitizeForSQL($formvars['dob']) . '",
                "' . $this->SanitizeForSQL($formvars['bus']) . '",
                "' . $this->SanitizeForSQL($formvars['pers']) . '"
                )';
        if(!mysql_query( $insert_query ,$this->connection))
        {
            $this->HandleDBError("Error inserting data to the table\nquery:$insert_query");
            return false;
        }
        return true;
    }

A: I think there is a logical error. You should only save one of the variable in radio button in database.

            "' . $this->SanitizeForSQL($formvars['bus']) . '",
           "' . $this->SanitizeForSQL($formvars['pers']) . '"


text:
Q: Fantasy book involving a post modern civilization and a young man on a quest with two large greyhound-type dogs People live in barricaded villages because wild dogs are a problem. The government 'taxes' men to dig in ruins, trying to find a particular giant computer.
After this young man starts his quest, two large greyhound-type dogs join him. He names them Followree & Followro, male & female. At some point they stand up on their hind legs and prophecy. He tells a myth 'explaining' the civil collapse: "That little man Atom was broken in two, his head separated from his body", and there were consequences from that. He came across a black  Mandelbrot Buddha-type figure that he understood was a powerful Female force or symbol.
I do not remember the ending, but I was interested in the author who did not write a lot but had another book with (?) Gurdjieff-type cosmic levels of consciousness  (I think). It was probably published in the 1980s or  earlier.

A: Sounds like you're thinking of Riddley Walker (1980) by Russell Hoban.
From Goodreads:

In the far distant future, the country laid waste by nuclear holocaust, twelve-year-old Riddley Walker tells his story in a language as fractured as the world in which he lives. As Riddley steps outside the confines of his small world, he finds himself caught up in intrigue and a frantic quest for power, desperately trying to make sense of things.

As detailed in the synopsis above, the story is set in a post-apocalyptic future and features a twelve-year-old male protagonist, named Riddley, on a quest to make sense of things.
Riddley speaks in broken English, and according to this quote provided within a Goodreads user review, he meets a pair of dogs, named Folleree & Folleroo, that stand up on their hind legs and talk like men.

"7. Thay dogs stud up on thear hyn legs & taukin lyk men. Folleree sed, Lukin for the 1 you wil aul ways fyn thay 2. Folleroo sed, They 2 is twice as bad as the 1."


text:
Q: in my application im having trouble updating my account, advice please? Im building the application that so far only focuses on reletive crud operations interacting with a jpa repository to save info to a database held in mysql.When trying to update an accoutn i get the following error
java.lang.UnsupportedOperationException: null
    at java.base/java.util.AbstractList.remove(AbstractList.java:167) ~[na:na]
    at java.base/java.util.AbstractList$Itr.remove(AbstractList.java:387) ~[na:na]
    at java.base/java.util.AbstractList.removeRange(AbstractList.java:598) ~[na:na]
    at java.base/java.util.AbstractList.clear(AbstractList.java:243) ~[na:na]
    at org.hibernate.type.CollectionType.replaceElements(CollectionType.java:580) ~[hibernate-core-5.6.9.Final.jar:5.6.9.Final]
    at org.hibernate.type.CollectionType.replace(CollectionType.java:757) ~[hibernate-core-5.6.9.Final.jar:5.6.9.Final]
    at org.hibernate.type.TypeHelper.replace(TypeHelper.java:167) ~[hibernate-core-5.6.9.Final.jar:5.6.9.Final]
    at org.hibernate.event.internal.DefaultMergeEventListener.copyValues(DefaultMergeEventListener.java:450) ~[hibernate-core-5.6.9.Final.jar:5.6.9.Final]
    at org.hibernate.event.internal.DefaultMergeEventListener.entityIsPersistent(DefaultMergeEventListener.java:205) ~[hibernate-core-5.6.9.Final.jar:5.6.9.Final]
    at org.hibernate.event.internal.DefaultMergeEventListener.onMerge(DefaultMergeEventListener.java:178) ~[hibernate-core-5.6.9.Final.jar:5.6.9.Final]
    at org.hibernate.event.internal.DefaultMergeEventListener.onMerge(DefaultMergeEventListener.java:70) ~[hibernate-core-5.6.9.Final.jar:5.6.9.Final]
    at org.hibernate.event.service.internal.EventListenerGroupImpl.fireEventOnEachListener(EventListenerGroupImpl.java:107) ~[hibernate-core-5.6.9.Final.jar:5.6.9.Final]
    at org.hibernate.internal.SessionImpl.fireMerge(SessionImpl.java:829) ~[hibernate-core-5.6.9.Final.jar:5.6.9.Final]
    at org.hibernate.internal.SessionImpl.merge(SessionImpl.java:816) ~[hibernate-core-5.6.9.Final.jar:5.6.9.Final]
    at java.base/jdk.internal.reflect.DirectMethodHandleAccessor.invoke(DirectMethodHandleAccessor.java:104) ~[na:na]
    at java.base/java.lang.reflect.Method.invoke(Method.java:577) ~[na:na]
    at org.springframework.orm.jpa.ExtendedEntityManagerCreator$ExtendedEntityManagerInvocationHandler.invoke(ExtendedEntityManagerCreator.java:362) ~[spring-orm-5.3.20.jar:5.3.20]
    at jdk.proxy4/jdk.proxy4.$Proxy111.merge(Unknown Source) ~[na:na]
    at java.base/jdk.internal.reflect.DirectMethodHandleAccessor.invoke(DirectMethodHandleAccessor.java:104) ~[na:na]
    at java.base/java.lang.reflect.Method.invoke(Method.java:577) ~[na:na]
    at org.springframework.orm.jpa.SharedEntityManagerCreator$SharedEntityManagerInvocationHandler.invoke(SharedEntityManagerCreator.java:311) ~[spring-orm-5.3.20.jar:5.3.20]
    at jdk.proxy4/jdk.proxy4.$Proxy111.merge(Unknown Source) ~[na:na]
    at org.springframework.data.jpa.repository.support.SimpleJpaRepository.save(SimpleJpaRepository.java:669) ~[spring-data-jpa-2.7.0.jar:2.7.0]
    at java.base/jdk.internal.reflect.DirectMethodHandleAccessor.invoke(DirectMethodHandleAccessor.java:104) ~[na:na]
    at java.base/java.lang.reflect.Method.invoke(Method.java:577) ~[na:na]
    at org.springframework.data.repository.core.support.RepositoryMethodInvoker$RepositoryFragmentMethodInvoker.lambda$new$0(RepositoryMethodInvoker.java:289) ~[spring-data-commons-2.7.0.jar:2.7.0]
    at org.springframework.data.repository.core.support.RepositoryMethodInvoker.doInvoke(RepositoryMethodInvoker.java:137) ~[spring-data-commons-2.7.0.jar:2.7.0]
    at org.springframework.data.repository.core.support.RepositoryMethodInvoker.invoke(RepositoryMethodInvoker.java:121) ~[spring-data-commons-2.7.0.jar:2.7.0]
    at org.springframework.data.repository.core.support.RepositoryComposition$RepositoryFragments.invoke(RepositoryComposition.java:529) ~[spring-data-commons-2.7.0.jar:2.7.0]
    at org.springframework.data.repository.core.support.RepositoryComposition.invoke(RepositoryComposition.java:285) ~[spring-data-commons-2.7.0.jar:2.7.0]
    at org.springframework.data.repository.core.support.RepositoryFactorySupport$ImplementationMethodExecutionInterceptor.invoke(RepositoryFactorySupport.java:639) ~[spring-data-commons-2.7.0.jar:2.7.0]
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186) ~[spring-aop-5.3.20.jar:5.3.20]
    at org.springframework.data.repository.core.support.QueryExecutorMethodInterceptor.doInvoke(QueryExecutorMethodInterceptor.java:163) ~[spring-data-commons-2.7.0.jar:2.7.0]
    at org.springframework.data.repository.core.support.QueryExecutorMethodInterceptor.invoke(QueryExecutorMethodInterceptor.java:138) ~[spring-data-commons-2.7.0.jar:2.7.0]
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186) ~[spring-aop-5.3.20.jar:5.3.20]
    at org.springframework.data.projection.DefaultMethodInvokingMethodInterceptor.invoke(DefaultMethodInvokingMethodInterceptor.java:80) ~[spring-data-commons-2.7.0.jar:2.7.0]
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186) ~[spring-aop-5.3.20.jar:5.3.20]
    at org.springframework.transaction.interceptor.TransactionInterceptor$1.proceedWithInvocation(TransactionInterceptor.java:123) ~[spring-tx-5.3.20.jar:5.3.20]
    at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:388) ~[spring-tx-5.3.20.jar:5.3.20]
    at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:119) ~[spring-tx-5.3.20.jar:5.3.20]
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186) ~[spring-aop-5.3.20.jar:5.3.20]
    at org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.invoke(PersistenceExceptionTranslationInterceptor.java:137) ~[spring-tx-5.3.20.jar:5.3.20]
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186) ~[spring-aop-5.3.20.jar:5.3.20]
    at org.springframework.data.jpa.repository.support.CrudMethodMetadataPostProcessor$CrudMethodMetadataPopulatingMethodInterceptor.invoke(CrudMethodMetadataPostProcessor.java:174) ~[spring-data-jpa-2.7.0.jar:2.7.0]
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186) ~[spring-aop-5.3.20.jar:5.3.20]
    at org.springframework.aop.interceptor.ExposeInvocationInterceptor.invoke(ExposeInvocationInterceptor.java:97) ~[spring-aop-5.3.20.jar:5.3.20]
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186) ~[spring-aop-5.3.20.jar:5.3.20]
    at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:215) ~[spring-aop-5.3.20.jar:5.3.20]
    at jdk.proxy4/jdk.proxy4.$Proxy115.save(Unknown Source) ~[na:na]
    at com.example.realtyKing.Service.UserServiceImpl.updateUser(UserServiceImpl.java:100) ~[classes/:na]
    at com.example.realtyKing.Controller.UserController.update(UserController.java:210) ~[classes/:na]
    at java.base/jdk.internal.reflect.DirectMethodHandleAccessor.invoke(DirectMethodHandleAccessor.java:104) ~[na:na]
    at java.base/java.lang.reflect.Method.invoke(Method.java:577) ~[na:na]

my user model
import lombok.*;
import org.hibernate.annotations.DynamicUpdate;

import javax.persistence.*;
import java.sql.Date;
import java.util.*;

@Getter
@Setter
@Builder
@AllArgsConstructor
@NoArgsConstructor
@Entity
@Table(name = "user", uniqueConstraints = @UniqueConstraint(columnNames = "email"))
public class User {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    @Column(name = "first_name", nullable = false)
    private String firstName;

    @Column(name = "last_name", nullable = false)
    private String lastName;
    @Column(nullable = false)
    private Date dob;
    @Column(name = "phone_number", nullable = false)
    private String phoneNumber;

    private String email;
    private String password;

    @Column(name = "email_config")
    private String emailConfig;
    @ManyToMany(fetch = FetchType.EAGER, cascade = CascadeType.ALL)
    @JoinTable(
            name = "users_roles",
            joinColumns = @JoinColumn(
                    name = "user_id", referencedColumnName = "id"),
            inverseJoinColumns = @JoinColumn(
                    name = "role_id", referencedColumnName = "id"))

    private Collection < Role > roles;
    public User(String firstName, String lastName,Date dob,String phoneNumber, String email, String password, Collection < Role > roles) {
        super();
        this.firstName = firstName;
        this.lastName = lastName;
        this.dob = dob;
        this.phoneNumber=phoneNumber;
        this.email = email;
        this.password = password;
        this.roles = roles;
    }
    public void urdToUser(UserRegistrationDto urd){
        setFirstName(urd.getFirstName());
        setLastName(urd.getLastName());
        setDob(urd.getDob());
        setPhoneNumber(urd.getPhoneNumber());
        setEmail(urd.getEmail());
        setPassword(urd.getPassword());
    }
}

my repository
import com.example.realtyKing.Model.User;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;

@Repository
public interface UserRepository extends JpaRepository<User, Long>{
    User findByEmail(String email);
    User findByPassword(String password);
    void deleteById(long id);
    User findById(long id);
}

my service and service impl
import com.example.realtyKing.Model.UserRegistrationDto;
import com.example.realtyKing.Model.User;
import org.springframework.security.core.userdetails.UserDetailsService;
import java.util.List;

public interface UserService extends UserDetailsService{
    List < User > getAllUsers();
    User getUserById(long id);
    void deleteById(long id);
    User save(UserRegistrationDto registrationDto);
    User getUserByEmail(String email);
    User getUserByPassword(String password);
    void updateUser(User user);
}

import java.util.List;

import java.util.Arrays;
import java.util.Collection;
import java.util.stream.Collectors;

import com.example.realtyKing.Model.UserRegistrationDto;
import com.example.realtyKing.Model.Role;
import com.example.realtyKing.Model.User;
import com.example.realtyKing.Repositories.UserRepository;
import com.example.realtyKing.Utility.MiscleaniousServices;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

@Service
public class UserServiceImpl implements UserService {

    private UserRepository userRepository;
    @Autowired
    MiscleaniousServices miscleaniousServices;
    @Autowired
    public void setUserRepository (UserRepository  userRepository) {
        this.userRepository= userRepository;
    }

    public UserServiceImpl(UserRepository userRepository) {
        super();
        this.userRepository = userRepository;
    }

    @Override
    public List <User> getAllUsers() {
        return userRepository.findAll();
    }

    @Override
    public User getUserById(long id) {
        User user= this.userRepository.findById(id);

        return user;
    }

    @Override
    public void deleteById(long id) {
        this.userRepository.deleteById(id);
    }
    @Override
    public User save(UserRegistrationDto registrationDto) {
        User user = new User(registrationDto.getFirstName(),registrationDto.getLastName(),
                registrationDto.getDob(),registrationDto.getPhoneNumber(),registrationDto.getEmail(),
                miscleaniousServices.bCryptPasswordEncoder().encode(registrationDto.getPassword()), Arrays.asList(new Role("ROLE_USER")));

        return userRepository.save(user);
    }

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

        User user = userRepository.findByEmail(username);
        if(user == null) {
            throw new UsernameNotFoundException("Invalid username or password.");
        }
        return new org.springframework.security.core.userdetails.User(user.getEmail(), user.getPassword(), mapRolesToAuthorities(user.getRoles()));
    }

    private Collection<? extends GrantedAuthority> mapRolesToAuthorities(Collection<Role> roles){
        return roles.stream().map(role -> new SimpleGrantedAuthority(role.getName())).collect(Collectors.toList());
    }

    @Override
    public User getUserByEmail(String email){
        User user = userRepository.findByEmail(email);
        if(user!=null)
        {
            return user;
        }
        return null;
    }

    @Override
    public User getUserByPassword(String password){
        User user = userRepository.findByPassword(password);
        if(user!=null)
        {
            return user;
        }
        return null;
    }
    @Override
    public void updateUser(User user){
                user.setPassword(miscleaniousServices.bCryptPasswordEncoder().encode(user.getPassword()));
                user.setRoles(Arrays.asList(new Role("ROLE_USER")));
                userRepository.save(user);
    }
}

my controller please note the request goes to post update
import com.example.realtyKing.Model.Mail;
import com.example.realtyKing.Model.UserAuthentification;
import com.example.realtyKing.Model.User;
import com.example.realtyKing.Model.UserRegistrationDto;
import com.example.realtyKing.Service.EmailService;
import com.example.realtyKing.Service.UserService;
import com.example.realtyKing.Utility.MiscleaniousServices;
import com.example.realtyKing.Utility.UserCreationValidator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import java.util.Locale;

//fix the id problem.

@Controller
public class UserController {
    @Autowired
    private EmailService emailService;

    @Autowired
    private UserService userService;

    @Autowired
    MiscleaniousServices miscleaniousServices;

    @Autowired
    private UserCreationValidator userCreationValidator;

    @ModelAttribute("user")
    public UserRegistrationDto userRegistrationDto() {
        return new UserRegistrationDto();
    }

    @GetMapping("/registration")
    public String userAuthentificationForm(Model model)
    {
        model.addAttribute("firstNameError", "");
        model.addAttribute("lastNameError", "");
        model.addAttribute("dobError", "");
        model.addAttribute("phoneNumberError", "");
        model.addAttribute("emailError", "");
        model.addAttribute("passwordError", "");
        model.addAttribute("user", miscleaniousServices.user());
        return "new_user";
    }
    //finsihed user sighnup
    @PostMapping("/registration")
    public String userAuthentificationForm(@ModelAttribute("user") UserRegistrationDto registrationDto,
                                           BindingResult bindingResult,Model model) {
        userCreationValidator.validate(registrationDto,bindingResult,false);

        if (bindingResult.hasErrors()) {

            String emailError="";
            String dobError="";
            String phoneNumberError="";
            String firstNameError ="";
            String lastNameError="";
            String passwordError="";

            userFilter(emailError, dobError, phoneNumberError,
                    firstNameError , lastNameError, passwordError,bindingResult);

            model.addAttribute("firstNameError", firstNameError);
            model.addAttribute("lastNameError", lastNameError);
            model.addAttribute("dobError", dobError);
            model.addAttribute("phoneNumberError", phoneNumberError);
            model.addAttribute("emailError", emailError);
            model.addAttribute("passwordError", passwordError);

            model.addAttribute("User", miscleaniousServices.user());

            return "new_user";
        }

        userService.save(registrationDto);
        return "redirect:/login";
    }
    //fixed get login.
    @GetMapping("/login")
    public String login() {
        return "login";
    }

    @GetMapping("/")
    public String home() {
        return "index";
    }
    @GetMapping("/deleteConfirmation")
    public String deleteConfirmation(Model model){
        UserAuthentification ua=new UserAuthentification();
        model.addAttribute("errors","");
        model.addAttribute("UserAuthentification",ua);
        return "delete_confirmation.html";
    }
    @PostMapping("/delete")
    public String delete(@ModelAttribute("UserAuthentification") UserAuthentification userAuthentification
            ,Model model) throws Exception {
           if(userAuthentification.getUsername().equals("")){
               model.addAttribute("email", "");
               model.addAttribute("errors","Invalid username or password.");
               return "delete_confirmation.html";
           }
           User user=null;

           try{
               user=userService.getUserByEmail(userAuthentification.getUsername());
                }
           catch(Exception e){

           }
           if(user==null){
               model.addAttribute("email", " ");
               model.addAttribute("errors","Invalid username or password.");
               return "delete_confirmation.html";
           }
           if(! miscleaniousServices.bCryptPasswordEncoder().matches(userAuthentification.getPassword(), user.getPassword())){
               model.addAttribute("email", user.getEmail());
               model.addAttribute("errors","Invalid username or password.");
               return "delete_confirmation.html";
           }
           userService.deleteById(user.getId());

           return "redirect:/logout";
       }
    @GetMapping("/forgotPassword")
    public String forgotPassword(Model model){
        User user=new User();
        model.addAttribute("user", user);
        model.addAttribute("confirmation", "");
        return "forgot_password";
    }
    @PostMapping("/forgotPassword")
    public String forgotPassword(@ModelAttribute("User") User user,Model model) {

        try{
            user=userService.getUserByEmail(user.getEmail());
            Mail mail = new Mail();
            mail.setFrom("realtyking69@gmail.com");//replace with your desired email
            mail.setMailTo(user.getEmail());//replace with your desired email

            emailService.remeberPassword(user,mail);
        }
        catch(Exception e)
        {
            model.addAttribute("User", user);
            model.addAttribute("confirmation", "their was a problem.");
            return "forgot_password";
        }

        model.addAttribute("User", user);
        model.addAttribute("confirmation", "email sent"+
                " password soon");
        return "forgot_password";
    }
    @GetMapping("update")
    public String update(Model model){
        User user=userService.getUserByEmail(miscleaniousServices.getUsername());
        UserRegistrationDto urd=new UserRegistrationDto();
        urd.userToUrd(user);
        model.addAttribute("firstNameError", "");
        model.addAttribute("lastNameError", "");
        model.addAttribute("dobError", "");
        model.addAttribute("phoneNumberError", "");
        model.addAttribute("emailError", "");
        model.addAttribute("passwordError", "");
        model.addAttribute("user", user);
        model.addAttribute("message", " ");
        return "update";
    }
        @PostMapping("update")
        public String update(@ModelAttribute("user") UserRegistrationDto registrationDto,
                BindingResult bindingResult,Model model) {
            userCreationValidator.validate(registrationDto,bindingResult,true);

            if (bindingResult.hasErrors()) {

                String emailError="";
                String dobError="";
                String phoneNumberError="";
                String firstNameError ="";
                String lastNameError="";
                String passwordError="";

                userFilter(emailError, dobError, phoneNumberError,
                        firstNameError , lastNameError, passwordError,bindingResult);

                model.addAttribute("firstNameError", firstNameError);
                model.addAttribute("lastNameError", lastNameError);
                model.addAttribute("dobError", dobError);
                model.addAttribute("phoneNumberError", phoneNumberError);
                model.addAttribute("emailError", emailError);
                model.addAttribute("passwordError", passwordError);
                model.addAttribute("message", "your account has not been succesfully updated.");
                model.addAttribute("User", registrationDto);

                return "update";
            }
            User user=userService.getUserByEmail(miscleaniousServices.getUsername());
            user.urdToUser(registrationDto);
            userService.updateUser(user);
            model.addAttribute("firstNameError", "");
            model.addAttribute("lastNameError", "");
            model.addAttribute("dobError", "");
            model.addAttribute("phoneNumberError", "");
            model.addAttribute("emailError", "");
            model.addAttribute("passwordError", "");
            model.addAttribute("user", registrationDto);
            model.addAttribute("message", "your account has been succesfully updated.");
            return "update";
    }

    public void userFilter(String emailError,
    String dobError,
    String phoneNumberError,
    String firstNameError ,
    String lastNameError,
    String passwordError,BindingResult bindingResult){

        try {
            firstNameError = miscleaniousServices.messageSource().getMessage(
                    miscleaniousServices.getErrorMessage("firstName", bindingResult), null, Locale.ENGLISH);
        }
        catch(Exception e){

        }

        try{
            lastNameError=miscleaniousServices.messageSource().getMessage(
                    miscleaniousServices.getErrorMessage("lastName",bindingResult),null, Locale.ENGLISH);
        }
        catch(Exception e){

        }
        try{
            dobError=miscleaniousServices.messageSource().getMessage(
                    miscleaniousServices.getErrorMessage("dob",bindingResult),null, Locale.ENGLISH);
        }
        catch(Exception e){

        }
        try{
            phoneNumberError=miscleaniousServices.messageSource().getMessage(
                    miscleaniousServices.getErrorMessage("phoneNumber",bindingResult),null, Locale.ENGLISH);
        }
        catch(Exception e){

        }
        try{
            emailError=miscleaniousServices.messageSource().getMessage(
                    miscleaniousServices.getErrorMessage("email",bindingResult),null, Locale.ENGLISH);
        }
        catch(Exception e){

        }
        try{
            passwordError=miscleaniousServices.messageSource().getMessage(
                    miscleaniousServices.getErrorMessage("password",bindingResult),null, Locale.ENGLISH);
        }
        catch(Exception e){

        }
    }
}

url:https://github.com/jonathanIckovich/realtyKing.git


text:
Q: Avoid Micron symbol μ to appear as M when using CSS text-transform: uppercase I have this HTML:

    aaaaaaaa 9″¾ 5μm

This CSS:
p.uppercase {
    text-transform: uppercase;
}

I get this result:
AAAAAAAA 9″¾ 5ΜM

How can I obtain this?
AAAAAAAA 9″¾ 5μM

p.uppercase {
  text-transform: uppercase;
}

  aaaaaaaa 9″¾ 5μm

A: try this code without style

aaaaaaaa 9″¾ 5μm

More information : http://www.theasciicode.com.ar/extended-ascii-code/lowercase-letter-mu-micro-sign-micron-ascii-code-230.html

A: I have found one alternative solution.

*

*Please remove text-transform: uppercase style

*You can use strtoupper PHP function

Like:
<?php echo strtoupper( "µ-Title" ); ?>


text:
Q: Calling I18n translation method from within a simple_form marked up using haml I am working with the I18n gem and am just wondering how the translation method can be called while using a haml based simple_form. Current my code is as follows:
\users\new.html.haml
    - content_for :title, "Admin | Create New User"
    .page-header
        %h1 Create New User
/config/localses/en.yml
    en:
      new_tenant:
        title: "Tenant Administration | Create New Tenant"
        header: "Create New Tenant"
/config/localses/de.yml
    de:
      new_tenant:
        title: "Mieter Administration | Create New Mieter"
        header: "Erstellen Neuer Mieter"
I have seen in Railcasts episode 138 that this could be called as follows:
<% title t('new_tenant.title') %>

<%= t 'new_tenant.header' %>

How can I apply this same method to the haml markup? Any tips would be greatly appreciated.

A: Here you go.
%title=t 'new_tenant.title'
%h2=t 'new_tenant.header'

Sometimes you can't use the i18n shorthand t, in those cases just use I18n.t instead of the shortcut. Good luck.


text:
Q: Parsing JSON error I am parsing JSON returned by Facebooks Graph request. I create an NSMutableArray called json to hold the results of the request, which returns information in JSON format.
I then try to add the information parsed to a table. To do this, I create an NSDictionary using:
NSDictionary *dict = [self.json objectAtIndex:0];

However, I get the error
-[__NSCFDictionary objectAtIndex:]: unrecognized selector sent to instance 0x6b2e1c0

I create self.json in the header file as a NSMutableArray synthesize it, and initialize it as follows:
NSURL *url = [NSURL URLWithString:@"https://graph.facebook.com/40796308305/albums"];
NSData *data = [NSData dataWithContentsOfURL:url];
NSError *err;
self.json = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&err];

I have also tried casting the data returned from NSJSONSerialization to an NSMutableArray, which didn't help.

A: Well from the error message it is quite obvious, that self.json does in fact not hold a NSMutableArray but a NSDictionary, which of course does not responde to -objectAtIndex:
It is containing a Dictionary probably because the service returns a JSON-Object. Take a look at the response (NSLog(@"%@", self.json) right after self.json = ...) and adjust your code appropriately.

A: Facebook is returning a dictionary and not an array.
Note that the data that's coming back starts with a '{' and not a '['.

A: Hope you already got the answer still for your reference The Dictionary Is just looks like the JSON Structure. Example JSON Object is { "key1" : "value1" , "key2" : "value2" ,"key3" : "value3" , "key4" : "value4" } (just for reference read hereto know more about JSON) and the Dictionary Object obviously holds the key:value pairs.

A: -(void) jsonRESTWebServiceMethod:(NSString*)method WithParameter:(NSMutableDictionary*)params{
    self.iResponseType = JSONTYPE;
    NSMutableDictionary *bodyDict = [NSMutableDictionary dictionaryWithObjectsAndKeys:method,@"name",params,@"body",nil,nil];
    NSData *data = [[CJSONSerializer serializer] serializeObject:bodyDict error:nil];
    NSString *strRequest = [[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding] autorelease];
    strRequest = [NSString stringWithFormat:@"json=%@",strRequest];
    NSData *body = [strRequest dataUsingEncoding:NSUTF8StringEncoding];
    NSString *strURL = [NSString stringWithString:WebServiceURL];
    NSString* escapedUrlString = [strURL stringByAddingPercentEscapesUsingEncoding:NSASCIIStringEncoding];

    NSMutableURLRequest *request= [NSMutableURLRequest requestWithURL:[NSURL URLWithString:escapedUrlString]];
    [request setHTTPMethod:@"POST"];
    [request setHTTPBody:body];
    NSString *msgLength = [NSString stringWithFormat:@"%d",strRequest.length];
    [request addValue:@"application/x-www-form-urlencoded" forHTTPHeaderField: @"Content-Type"];
    [request addValue:msgLength forHTTPHeaderField:@"Content-Length"];

    if (mydata) {
        [mydata release];
        mydata = nil;
    }
    conections = [[NSURLConnection alloc] initWithRequest:request delegate:self];
    mydata = [[NSMutableData alloc] init];
}

-(void)connectionFinish:(WebService*)webservice response:(NSData*)data{
       NSMutableDictionary *dctResponse = [[CJSONDeserializer deserializer] deserialize:data error:nil];
}


text:
Q: Spring Batch DelimitedLineTokenizer class quoteCharacter property behavior I have a item reader as below:
<beans:bean id="myItemReader" class="org.springframework.batch.item.file.FlatFileItemReader">
<beans:property name="resource" ref="myFileResource" />
    <beans:property name="lineMapper">
        <beans:bean class="org.springframework.batch.item.file.mapping.DefaultLineMapper">
            <beans:property name="lineTokenizer">
                <beans:bean class="org.springframework.batch.item.file.transform.DelimitedLineTokenizer">
                    <beans:property name="delimiter" value="|"/>
                    <beans:property name="quoteCharacter" value="~"/>
                    <beans:property name="names" value="${my_column_names}" />
                </beans:bean>
            </beans:property>
            <beans:property name="fieldSetMapper">
            <beans:bean class="${my_mapper_class_name}" />
        </beans:property>
    </beans:bean>
</beans:property>

As clear from above, I am changing the quote character from default " (double quotes) to ~ (tilt sign)
Now, Java Docs on DelimitedLineTokenizer on quote character says:
Public setter for the quoteCharacter. The quote character can be used to extend a field across line endings or to enclose a String which contains the delimiter. Inside a quoted token the quote character can be used to escape itself, thus "a""b""c" is tokenized to a"b"c.
Thus, if my data itself is containing delimiter (the pipe sign in my case), then I should surround it with the quote character - which I did. E.g. row below where third column contains the delimiter:
oneColumn|twoColumn|three~|~Column|fourColumn

However, the value which comes inside my java object for column three is "three~|~Column" and not "three|Column" as it should be.
Shouldn't the quote character used to escape a delimiter in the data be automatically handled and ignored while setting the value inside the property of the resultant java object item?
Is replacing the quote character with empty string again in the writer (PreparedStatementSetter or LineAggregator) the only solution to this ?
Thanks for reading!

A: A string is intended to be quoted if it starts/ends with quote char.
In your example:
oneColumn|twoColumn|~three|Column~|fourColumn

and you'll get three|Column
You have to quote string if it contains a separator, space, newline or the quoting char itself; quoting char must be doubled if part of value(see here)


text:
Q: Are x11 bitmapped fonts necessary? Are the x11 100 and 75 dpi fonts absolutely necessary?
If Ubuntu has TrueType support, (as well as OpenType) why do I need all those bit-mapped fonts hanging around?
Can I delete them?  (and/or generate ttf/ot versions for those I want to keep)
If I delete those fonts, will some ancient primitive packages still be looking for them and crash, or will I just get a substituted system default?
I've already read this topic: What fonts are absolutely required?
Answers were not really informative enough and kind of vague.  I'm hoping my questions are more specific so I get a more definitive idea of just what the font system requires and does not.

A: All modern GTK+ applications use Xft for font rendering. Xorg bitmap fonts are installed by default just for the sake of backward compatibility. In other words you can safely uninstall them if you don't use any legacy applications (eg. gitk).

A: The X server requires exactly two fonts, fixed and cursor, both of which are builtin to all recent versions of the libXfont library it uses.
Many older X applications however, may have specified those fonts - generally they'll fallback to using a default like fixed, but that may be missing some characters, and will probably be at a different size, thus leading to a different (sometimes broken) layout of menus, buttons, and other widgets spaced for the expected font/size.


text:
Q: Alignment of div elements at center and right I have four tabs developed with HTML5/CSS3/JS shown below.

I have used display:inline-block; for tab divs and text-align:center for their parent div to locate all four tabs at the center of the page.

YOU

DATABASE

TASKS

HELP

CSS3:
.parent{text-align:center;}
.tabItem{display:inline-block;}

Now I want to locate two of the tabs i.e. YOU and HELP at the right-side of the page, and the rest of the tabs i.e. DATABASE and TASKS at the center of the page. I wonder how I can do that.
It's preferred to have div elements follow the natural flow of the page.

A: Do something like this

.parent{text-align:center;}
.tabItem{display:inline-block;}
.right{float:right;}
.left{float:left;}

Content for Left

DATABASE

TASKS

YOU

HELP

A: here is your solution!

.parent{text-align:center;}
.tabItem{display:inline-block;}
.right {
float: right;
}

DATABASE

TASKS

YOU

HELP

A: Hope this helps!!

DATABASE

TASKS

YOU

HELP

Or just put those two divs in a parent container and give it an id="right" to avoid repeating id !!

A: I think you will need to set the tabs you need to relocate to absolute position, so they will be out of the normal content flow, then you can truly center the other two tabs.

.parent {
  background: pink;
  text-align: center;
  position: relative;
}
.tabItem {
  margin: 0 5px;
  display: inline-block;
  background: aqua;
}
.tabItem:nth-child(1) {
  position: absolute;
  right: 50px; /* width of "HELP" tab */
}
.tabItem:nth-child(4) {
  position: absolute;
  right: 0;
}

YOU

DATABASE

TASKS

HELP

A: CSS3 feature display:flex is an option too. Can play around with it to see if it would work.

.parent{
    display:flex;
    justify-content:center;
}

.item{
    padding: 10px;
    text-transform:uppercase;
}

.right{
    margin-left:auto;
}

.left{
    margin-right:auto;
}

you

database

tasks

help


text:
Q: Callback function executing in the call stack even when it's not empty When the click event is fired from the mouse, it behaves as expected:
First the listener 1 is pushed into the stack where it queues promise 1 in Microtask Queue(or Job Queue). When listener 1 is popped off, the stack becomes empty. And the promise 1 callback is executed before the listener 2(which is waiting in the Task Queue(or Callback Queue). After promise 1 callback is popped off, the listener 2 is pushed into the stack. So the output is :
Listener 1 Microtask 1 Listener 2 Microtask 2
However when the click is triggered via JavaScript code, it behaves differently:
The callback is pushed into the stack even before the click() function is completed (i.e. call stack is not empty). The output here is :
Listener 1 Listener 2 Microtask 1 Microtask 2

Here's the code:

window.onload = function(){
    document.getElementById("myBtn").addEventListener('click', () => {
        Promise.resolve().then(() => console.log('Microtask 1'));
        console.log('Listener 1');
    } );

    document.getElementById("myBtn").addEventListener('click', () => {
        Promise.resolve().then(() => console.log('Microtask 2'));
        console.log('Listener 2');
} );
}
function clickB(){

    document.getElementById("myBtn").click();
}
<!DOCTYPE html>
<html>
<button id="myBtn">Manual Click</button>
<button onclick="clickB()">JS Click</button>
</html>

My understanding is that items from Task Queue and Microtask Queue only get pushed into the Call Stack when it's empty. I might have made wrong assumptions. Please feel free to correct me. Thank you

A: Your observations are correct and the explanation is quite straightforward:
The microtask queue only gets visited when the JavaScript execution context stack (a.k.a. call-stack) is empty, (defined in cleanup after running a script, itself called by call a user's operation). Technically the event loop has quite a few calls to perform a microtask checkpoint, but the cases where the JS call-stack can be non-empty are so rare they can be disregarded.
Dispatching an Event through eventTarget.dispatchEvent() is synchronous, no new task is queued, the callbacks are just called from the current context, and moreover, the JS call stack is not empty.

const target = new EventTarget();
target.addEventListener("foo", () => console.log("new foo event"));
console.log("before");
target.dispatchEvent(new Event("foo"));
console.log("after");

So the microtask queue doesn't get visited either, it will only be after the JS call stack is done, which in your code is when the original click event's handler job is executed completely.
However Events dispatched "natively" by the engine will create a new JS job per callback, and thus between each of them the JS call stack will be empty, and the microtask queue will get visited.

A: As long as the <button onclick> is running, the .then() won't be executed.
This snippet shows the difference in the execution order a bit better:

window.onload = function() {
  [document.body, myBtn].forEach(node => {
    node.addEventListener("click", function(e) {
      const {
        currentTarget,
        target
      } = e;
      new Promise((r) => {
        console.log(
          "Promise()",
          currentTarget.tagName
        )
        r();
      }).then(() => {
        console.log(
          ".then()",
          currentTarget.tagName
        )
      });
    });
  });
}
<button id="myBtn" onclick="console.log('hello world');">Manual Click</button>
<button onclick="myBtn.click(); console.log('I will happen before the then');">JS click</button>


text:
Q: What do we know about the Protocol War? The Protocol War is referenced many times in the books.

 As far as I remember, there was no one clear revalation chapter about what the war was about, who were on what sides, and what are the big things that happened because of it.

So, the question is:

 What exactly do we know about The Protocol War so far, based on the references on the books?

I'm interested in answers from any of the books in the series. At the time of this question, these include The Quantum Thief and The Fractal Prince.

A: Hannu has indicated that we may get answers to some of this - I emphasise some - in the third book, The Causal Angel, which is scheduled for publication this April.


text:
Q: how can i got the recent Saved id of my SQL database in next form When i am trying to retrieve the last value from my data base it returns the first one.
By using the following Query.
SELECT [Id] from dbo.Tb_Patient;

I want to get the last value.
What query i should use?

A: Try this
SELECT Top(1) [Id] from dbo.Tb_Patient order by Id desc;

Alternatively if Id is Auto Incremented column then you can use MAX function as well to find Maximum value.
SELECT MAX([Id]) from dbo.Tb_Patient


text:
Q: How to implement custom icon in SAPUI5's Shellbar Control? I implemented a functionality so that the users of my SAPUI5 application can change between different SAPUI5 themes. Now I would like to place a button in the existing ShellBar of my app to trigger that functionality from there.
Currently I have a fragment with the following code, which I want to make use of within a simple button in the ShellBar. I tried different things like f.ex. calling it via the avaterPressed attribute from the shellbar, but it looks all messed up - I'd be very happy if someone could help me out here - Thanks!
<core:FragmentDefinition
    xmlns="sap.m"
    xmlns:core="sap.ui.core">
            <Menu itemSelected="onSelectTheme" >
                <MenuItem text="Choose Theme">
                    <items>
                        <MenuItem key="sap_fiori_3" text="Standard Light" />
                        <MenuItem key="sap_fiori_3_dark" text="Standard Dark" />
                        <MenuItem key="sap_hcw" text="High Contrast White" />
                        <MenuItem key="sap_hcb" text="High Contrast Black" />
                    </items>
                </MenuItem>
            </Menu>
</core:FragmentDefinition>

It should look like the "Administrator" button in the following example (Instead of "User Settings" there should be my text "Choose Theme" from the fragment shown above: https://sapui5.hana.ondemand.com/sdk/test-resources/sap/tnt/demokit/toolpageapp/webapp/index.html?sap-ui-theme=sap_horizon#/

A: If you want to keep using the ShellBar, you can implement the press event on the Avatar and use the ActionSheet for your needs.
https://sapui5.hana.ondemand.com/#/entity/sap.m.ActionSheet/sample/sap.m.sample.ActionSheet

A: The developers from the linked example don't use the SAPUI5 Control ShellBar, but instead they made use of ToolHeader, which you can also implement within the Control ToolPage.
With ToolHeader, you can simply add a Button wherever you'd like and also call the fragment from f.ex. the profile picture button (shown below).
<tnt:ToolHeader>
  <Avatar src="..." press="YOUR_FUNCTION_TO_OPEN_FRAGMENT"/>
</tnt:ToolHeader>


text:
Q: How to call a lightning web component from within CPQ quote line editor if anyone knows I want to add a new action on the quote line editor, as you may see in the screenshot I have already modified a button however I need it to call a lightning web component and I don't know which route to use for it or how to make it work, right know the button does nothing if clicked, also not sure if it's possible to be done.

A: Please support this Idea on Idea Exchange to make this feature listed.
[Idea Exchange link]
https://trailblazer.salesforce.com/ideaView?id=0874V000000UItAQAW

A: From your Custom Action you can call a Visualforce. In your case you need to dynamically create a Lightning cmp when initializing VF page. Code snippet below.
There is field on Custom Action - URL, add a link to your custom VF page so it looks like:
/apex/c__MyCustomVisualforcePage

it's important to provide __c prefix.
You can also reference to this useful link.
And here is an example of MyCustomVisualforcePage where we are dynamically creating  c:CustomLightningCmp:
<apex:page sidebar="false" showHeader="false" standardController="Opportunity"
       lightningStylesheets="true" standardStylesheets="false">

<apex:slds />
<apex:includeLightning />

    <apex:form >

    </apex:form>

</apex:page>


text: Q: W/System ( 9284): Ignoring header X-Firebase-Locale because its value was null I am getting this error when run the project in emulator and for this the firebase authentication does not work. But it's ok when I run it in google chrome or edge. My emulator's internet connection is ok. Also firebase authentication with email/password is enabled. I am trying to solve the problem from the last work. But all the solution from stackoverflow is not working. Please give me a solution.


text:
Q: mysql - need two limits? Given a table containing awards earned over several years by members of an organization that consists of multiple geographic districts, what mysql query would show the top award earner in each district?  I can easily get the top ten award earners across all districts with this query:
SELECT Membername,  count(Award)as Number FROM awards
GROUP BY Membername
ORDER BY Number desc
LIMIT 10

But I need a list with the top earner for each district (there are about 90 of them), and I haven't gotten it right yet.
I tried this:
SELECT Membername,  District, count(Award)as Number FROM awards
GROUP BY Membername, District
ORDER BY Number desc, District
LIMIT 90

It has accurate counts for the members, but isn't showing one per district, so some districts show up more than once.  How do I get it to list the top earner per district, with each district showing up just once?

A: You'll have to do it by applying a "rank" per district, then only grab per rank = 1... The @LastDistrict at the join location is defaulted to zero, in case the district is based on an ID.  If district is char based, you can just change it to = "" instead to match the data type.
To clarify what is happening.  The "AwardCounts" pre query does the entire query per district and member with however many award counts.  Then, ordered by district and member award count (descending), thus putting the highest award count at the first position per district.
That is joined to another bogus alias "SQLVars" which just creates inline variables to the query called @RankSeq and @LastDistrict.  So, the first time in, the "DistRankSeq" will become a 1 for the first district, then prime the "@LastDistrict" with the value of the district.  The next entry for the same district (since it will be in proper sequence order) will be assigned the rank of 2, then 3, etc... When there is a change from whatever the "LAST" District was to the new record being tested, the rank gets set back to 1 and starts over again.   So you could have one district with 100 members, another with 5, another with 17...
So, your final query has all of them with their respective ranks...  Now, apply the HAVING the final district rank = 1...  Doing this, you could also adjust the having to get the top 3 members per district (for example)...
select
      AwardCounts.District,
      AwardCounts.MemberName,
      AwardCounts.memberAwards,
      @RankSeq := if( @LastDistrict = AwardCounts.District, @RankSeq +1, 1 ) DistRankSeq,
      @LastDistrict := AwardCounts.District as ignoreIt
   from
      ( select
              a.district,
              a.membername,
              count(*) as memberAwards
           from
              Awards a
           group by
              a.district,
              a.membername
           order by
              a.district,
              memberAwards desc ) AwardCounts

      JOIN (select @RankSeq := 0, @LastDistrict = 0 ) SQLVars
   HAVING
      DistRankSeq = 1

EDIT PER FEEDBACK
If its the aggregation thats taking the time, then I would do the following.  Create a new table with nothing but the aggregations per district, name and initial rank for the district.  As any new record is added to this table, the trigger then adds one to the aggregate table count, then checks where that person is within their district and re-updates its new rank position.  You could take it a step further and have another table of just "TOP" member per district table that is one per district with the person's name.  When a new person hits the top position, their name is put in the table, overwriting whoever was there last.

A: There's a fairly common way to do this, using self-joins. The trick is to replace a search for 'largest' with a search for 'those items with nothing bigger'. As you have already found out
SELECT Membername,  District, count(Award) as Number FROM awards
GROUP BY Membername, District

returns you a nice result of award counts. Let's write ... to save a bit of space as shorthand for that.
Now consider
SELECT a.Membername, a.District, a.Number FROM (...) a LEFT JOIN (...) b
ON a.District=b.District
AND a.Number<b.Number
WHERE b.Membername IS NULL

where the ... is that stuff written above. It's basically saying, for every entry in the award counts (a), find me all the entries (b) in the same district with more awards, and only return (a) if there aren't any (b)'s... in other words, a is the champ.
You will need to finesse this a bit if there's more than one member in the same district with the same winning count... this query will return all the tied members. You'll have to decide how to handle that. And watch out for those districts that don't have any awards at all... they won't even appear in your table.

A: There's a page specifically dedicated to the problem - and if you look at the older manuals you'll see the max-concat trick - which is often still more efficient.


text:
Q: Obtaining a probability inequality from another? Let X and Y be two independent random variables. If I know for some function f that $E_Y[f(X,Y)]$ exists and $P_X[f(X,Y)>t|Y]<\delta$ holds (for any fixed instance of Y) then does it follow that $P_X[E_Y[f(X,Y)]>t]<\delta$?
Here is an attempt, but I'm not sure if it is correct or not:
Define the event $A="f(X,Y)<t"$. We know that $P_X(A)\ge 1-\delta$.
Let event B be $B="E_Y[f(X,Y)]<t"$. Now, $A=>B$. Therefore, $P_X(A) <= P_X(B)$, and since $P_X(A)\ge 1-\delta$ we get that $P_X(B)\ge 1-\delta$, which is the same as $P_X(\neg B)<\delta$.

A: I believe that this is not true. Let $X$ and $Y$ be uniform on $[0,1]$, let $\mu$ be the measure associated to $X$ and $\nu$ be the measure associated to $Y$. Fix $n \in \mathbb{N}$ and consider the function
$$
\begin{align}
f(x,y) = n(t+1) \sum_{k=0}^{n-1}  {\bf 1} \left[\frac{k}{n} \leq x,y \leq \frac{k+1}{n} \right].
\end{align}
$$
This function is $0$ everywhere except on the squares of size $1/n$ along the diagonal.
Then $\mathbb{P}(f(x,y) > t|Y) = 1/n $, $\nu$ a.s., but $\mathbb{E} \left[ f(X,Y) | X \right] = t+1$, $\mu$ a.s.
Here's why your answer doesn't work. You have $A = \left\{ (x,y) : f(x,y) < t \right\}$. Let $A_y = \left\{ x : f(x,y) < t \right\}$. Your hypothesis is that $\mu(A_y) \geq 1 - \delta$ a.s. with respect to $\nu$. Your event $B$ is
$\left \{ x : \int f(x,y) d\nu(y) < t \right \}$. It is not true that for a particular $y$ the random set $A_y$ contain $B$. It is true that $B$ is contained in $\cup_y A_y$ but this is an uncountable union. So you can't say anything about $\mu(A)$ from knowing $\mu(A_y)$ for $y$ a.s with respect to $\nu$.


text:
Q: Can two versions of $\omega_1^{CK}(\mathsf{Ord})$ ever coincide? The goal of this question is to fill in the gap in this old answer of mine.
For a transitive set $M$, thought of as an $\{\in\}$-structure, we define the following ordinals (this is not the notation used in the linked answer above, but on reflection I like it more, and to the best of my knowledge there is no standard notation):

*

*$\mathsf{Def}(M)$ is the supremum of the ordertypes of the well-orderings which are (first-order, with parameters) interpretable in $M$.

*$\mathsf{Ad}(M)$ is the height of the smallest admissible set with $M$ as an element.
Per the title, each of these can be thought of as a kind of "$\mathsf{Ord}$'s $\omega_1^{CK}$." Classically, $\omega_1^{CK}$ is defined as the smallest ordinal with no computable copy but is also the supremum of the definable well-orderings of $(\mathbb{N};+,\times)$ and the smallest admissible ordinal $>\omega$.
It's not hard to show that $\mathsf{Def}(A)\le\mathsf{Ad}(A)$ for all $A$, and equality does occur for some $A$ (e.g. $\mathsf{Ad}(L_\omega)=\mathsf{Def}(L_\omega)=\omega_1^{CK}$). However, $\mathsf{Def}(A)<\mathsf{Ad}(A)$ is also possible. The above-linked answer shows that we have $\mathsf{Def}(M)<\mathsf{Ad}(M)$ whenever $M\models\mathsf{ZFC}$ and $M^\omega\subseteq M$. My question is whether this closure condition is in fact needed:

Is there any transitive $M\models\mathsf{ZFC}$ with $\mathsf{Def}(M)=\mathsf{Ad}(M)$?

Note that since the definitions of $\mathsf{Def}$ and $\mathsf{Ad}$ are sufficiently simple, it's enough to ask whether there is a countable such $M$.

A: Every ordinal $α$ that is the least ordinal satisfying a given $Σ^1_1$ property (about $α$, equivalently, about $L_α$) is a Gandy ordinal, so $\mathsf{Def}(L_α)=\mathsf{Ad}(L_α)$.  This includes the least $L_α$ satisfying ZFC, and even includes the least $L_α$ with $α$ an inaccessible cardinal in $L_{α^{+\text{CK}}}$ (but using $L_{α^{+\text{CK}}+1}$ would fail).
The proof of being Gandy is analogous to the proof of existence of recursive pseudowellorderings.  Consider a theory $S$ including $\mathrm{ATR}_0$ and "ordinal $α$ satisfies a given $Σ^1_1$ property", with definable Skolem functions.  Let $T$ be the tree of (essentially) finite partial $α$-models (as in $ω$-models) of $S$:  A sequence of ordinals $<α$   $x_1,x_2,...,x_n$ is in $T$ iff there is no inconsistency proof shorter than $n$ for "$S$, symbols $x_1,x_2,...,x_n$, ordering of $x_1,x_2,...,x_n$, and $∃y<α \, φ(y) ⇒ φ(x_{⌈φ⌉})$ for the first $n$ one-variable formulas $φ$" ($⌈φ⌉$ is the Gödel number; $x_n$ is not used if $⌈φ⌉≤n$).  Then the Kleene–Brouwer order of $T$ has a well-ordered initial segment of length $α^{+\text{CK}}$.  The existence of the desired model ensures that the order is ill-founded, while its nonexistence in $L_{α^{+\text{CK}}}$ (since per assumption, $α$ is the least ordinal with the $Σ^1_1$ property, and we use $\mathrm{ATR}_0$) ensures that the well-founded length equals $α^{+\text{CK}}$.
In fact (not needed here), there is a recursive order-invariant linear order $f$ on $ℚ^{<ω}$ such that for all $α$ that are the least ordinal for some $Σ^1_1$ property, the initial well-founded portion of $f↾α^{<ω}$ has length $α^{+\mathrm{CK}}$ (by order invariance it does not matter how $α$ is order-preservingly embedded into $ℚ$).  The construction is to interleave separate partial models as above for all variations of the theory $S$, except that we can skip variations at the cost of choosing a higher branch.
A related result is that for every finite $n$, $\mathsf{Def}(L_α)=\mathsf{Ad}(L_α)$ for the minimum $α$ such that $L_α$ satisfies ZFC and is correct about well-foundedness of $\mathbf{Σ}_n^{L_α}$ relations.  The proof is as above except that we require that the partial models are correct about $Σ_{n+1}^{L_α}$ properties of the ordinals.  This way a resulting model is correct about well-foundedness of relevant relations, and hence cannot be shorter than $α$.
As an aside, the results may seem surprising since working in ZFC or NBG, we can develop a theory of proper class well-orderings, and using replacement, failure of well-foundedness would be witnessed as a set.  By diagonalization, increasing descriptive complexity gives strictly longer proper class well-orderings (at least for parameter-free complexity or if $V=HOD$), with 'longer' interpreted using embeddability into proper initial segments (which makes sense even though I think not all first-order definable class well-orderings are comparable using first-order definable classes).  And for extensions of ZFC (including the replacement schema) using infinitary logic or constructible hierarchy above $V$, the increase in well-ordering lengths continues transfinitely with even the supremum of $L_\mathrm{Ord}(V)$ well-orderings not reaching the height of $\mathsf{Ad}(V)$ (assuming correctness about well-foundedness).  But as soon as replacement (for countable sequences) fails (which presumably it would not for the 'true' $V$), in some cases, the supposed well-orderings may turn out to be an illusion.