text:
Q: DragTarget onWillAccept and onAccept not firing I'm starting with Flutter and I cannot make drag and drop functionality to work. I followed the documentation but have no idea what I'm doing wrong.
This sample app displays three squares and the blue is draggable. The other ones have DragTarget set, one inside the square and one outside the square. When I drag the blue square it prints info that the drag started but there is no print info when dragging or dropping over the DragTargets.
Here is the code:
import 'package:flutter/material.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.red,
      ),
      home: MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key key, this.title}) : super(key: key);

  final String title;

  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Center(
        child: Container(
          constraints: BoxConstraints.expand(),
          color: Colors.grey[900],
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.center,
            children: <Widget>[
              Container(
                width: 100,
                height: 100,
                color: Colors.red,
                child: DragTarget(
                  onWillAccept: (d) => true,
                  onAccept: (d) => print("ACCEPT 1!"),
                  onLeave: (d) => print("LEAVE 1!"),
                  builder: (a,data,c) {
                    print(data);
                    return Center();
                  },
                ),
              ),
              DragTarget(
                onWillAccept: (d){return true;},
                onAccept:(d) => print("ACCEPT 2!"),
                onLeave: (d) => print("LEAVE 2!"),
                builder: (context, candidateData, rejectedData){
                  return Container(
                    width: 150,
                    height: 150,
                    color: Colors.purple
                  );
                }
              ),
              Draggable(
                data: ["SOME DATA"],
                onDragStarted: () => print("DRAG START!"),
                onDragCompleted: () => print("DRAG COMPLETED!"),
                onDragEnd: (details) => print("DRAG ENDED!"),
                onDraggableCanceled: (data, data2) => print("DRAG CANCELLED!"),
                feedback: SizedBox(
                  width: 100,
                  height: 100,
                  child: Container(
                    margin: EdgeInsets.all(10),
                    color: Colors.green[800],
                  ),
                ),
                child: SizedBox(
                  width: 100,
                  height: 100,
                  child: Container(
                    margin: EdgeInsets.all(10),
                    color: Colors.blue[800],
                  ),
                ),
              ),
            ],
          )
        ),
      )
    );
  }
}

A: Apparently the Draggable and DragTarget need to have the generic type specified if you are passing data, otherwise the onAccept and onWillAccept will not be fired.
For example, if you want to pass data as int then use Draggable<int> and DragTarget<int> — this also applies to onAccept and onWillAccept, they need to accept int as a parameter.

A: You should setState when you call onAccept and add a boolean value to your stateful widget.
bool accepted = false;
onAccept: (data){
      if(data=='d'){
        setState(() {
          accepted = true;
        });
      },

A: I used ChangeNotifyProvider and a model to manage my Draggable and Dragable Target multiplication challenge and results.  I built a simple multiplication game using ChangeNotify that updates the Provider that is listening for changes.  The GameScore extends the ChangeNotifier which broadcast to the provider when changes occur in the model.  The Provider can either be listening or not listening.  If the user get the right answer than the Model updates its score and notifies the listeners.  The score is then displayed in a text box.  I think the provider model is a simplier way to interact with the widget for managing state.
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'dart:math';
class Multiplication
{
  int value1;
  int value2;
  int result;
  int answerKey;
  int fakeResult;
  Multiplication(this.value1,this.value2,this.result,this.answerKey,this.fakeResult);
}
class GameScore with ChangeNotifier
{
    int score=0;
    int number=0;
    List<Multiplication> lstMultiplication=[];
    late Multiplication currentMultiplication;
    GameScore()
    {
      var rng = Random();

      for(int i=0; i<=25; i++)
      {
        for(int j=0; j<=25; j++)
        {
          var answerKey=rng.nextInt(2);
          var fakeAnswer=rng.nextInt(25)*rng.nextInt(25);
          lstMultiplication.add(Multiplication(i,j,i*j,answerKey,fakeAnswer));
        }
      }

    }
    int getChallengeValue(int key)
    {
      int retVal=0;
      if (currentMultiplication.answerKey==key)
      {
        retVal=currentMultiplication.result;
      }
      else
      {
        retVal=currentMultiplication.fakeResult;
      }
      return retVal;
    }
    String displayMultiplication()
    {
      String retVal="";
      if (currentMultiplication!=null)
      {
          retVal=currentMultiplication.value1.toString()+ " X "+currentMultiplication.value2.toString();
      }
      return retVal;
    }
    nextMultiplication()
    {
      var rng = Random();
      var index=rng.nextInt(lstMultiplication.length);
      currentMultiplication= lstMultiplication[index];
    }
    changeAcceptedData(int data) {
      var rng = Random();
      score += 1;
      number=rng.nextInt(100);
      notifyListeners();
  }
    changeWrongData(int data) {
      var rng = Random();
      score -= 1;
      number=rng.nextInt(100);
      notifyListeners();
  }
}

void main() {
  runApp(const MyApp());
  //runApp(Provider<GameScore>(create: (context) => GameScore(), child: MyApp()));
}

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home:  //TestDraggableWidget(),
      ChangeNotifierProvider(create:(context)=>GameScore(),child: TestDraggableWidget())
  );
  }
}

class TestDraggableWidget extends StatefulWidget {
  TestDraggableWidget({Key? key}) : super(key: key);

  @override
  State<TestDraggableWidget> createState() => _TestDraggableWidgetState();
}

class _TestDraggableWidgetState extends State<TestDraggableWidget> {
  @override
  Widget build(BuildContext context) {
    Provider.of<GameScore>(context,listen:false).nextMultiplication();
    return Scaffold(appBar: AppBar(title:Text("Draggable")),body:
    Column(
      mainAxisAlignment: MainAxisAlignment.center,
      children: [
      Row(
        mainAxisAlignment: MainAxisAlignment.spaceAround,
        children: [
          EvenContainerWidget(),
          NumberContainerWidget(),
          OddContainerWidget(),
          SizedBox(width:100,child:Text("Score: ${Provider.of<GameScore>(context, listen: true).score}",style:TextStyle(color:Colors.green,fontSize:14)))
      ],)
    ],));
  }
}

class EvenContainerWidget extends StatefulWidget {
  EvenContainerWidget({Key? key}) : super(key: key);

  @override
  State<EvenContainerWidget> createState() => _EvenContainerWidgetState();
}

class _EvenContainerWidgetState extends State<EvenContainerWidget> {
  int? valueAccepted;

  _onAccept(BuildContext context, int data)
  {
    if (data==valueAccepted){
        Provider.of<GameScore>(context, listen: false).changeAcceptedData(data);
        setState(() {
          valueAccepted=data;
        });
    }
    else
    {
      Provider.of<GameScore>(context, listen: false).changeWrongData(data);
    }
  }
  bool _willAccept(int? data)
  {
    return true;
  }
  @override
  Widget build(BuildContext context) {
    valueAccepted=Provider.of<GameScore>(context, listen: false).getChallengeValue(1);
    return Container(
        width:60,
        height:60,
        decoration:BoxDecoration(borderRadius: BorderRadius.circular(10),color:Colors.blueAccent),
        child:
        DragTarget<int>(
          onAccept: (data)=> _onAccept(context,data),
          onWillAccept: _willAccept,
          builder:(context, candidateData, rejectedData) {
            return Center(child:Text("Choice 1: ${valueAccepted==null?'':valueAccepted.toString()}"));
          },

        )
    );
  }
}

class OddContainerWidget extends StatefulWidget {
  OddContainerWidget({Key? key}) : super(key: key);

  @override
  State<OddContainerWidget> createState() => _OddContainerWidgetState();
}

class _OddContainerWidgetState extends State<OddContainerWidget> {
  int? valueAccepted;

  _onAccept(BuildContext context, int data)
  {
    if(data==valueAccepted)
    {
      Provider.of<GameScore>(context, listen: false).changeAcceptedData(data);
      setState(() {
          valueAccepted=data;
        });
    }
    else
    {
      Provider.of<GameScore>(context, listen: false).changeWrongData(data);
    }

  }
  bool _willAccept(int? data)
  {
    /*if (data!.isOdd)
    {
      setState(() {
        valueAccepted=data;
      });
    }*/
    return true;
  }

  @override
  Widget build(BuildContext context) {
    valueAccepted=Provider.of<GameScore>(context, listen: false).getChallengeValue(0);
    return Container(
        width:60,
        height:60,
        decoration:BoxDecoration(borderRadius: BorderRadius.circular(10),color:Colors.blueAccent),
        child:
        DragTarget<int>(
          onAccept: (data)=> _onAccept(context,data),
          onWillAccept: _willAccept,
          builder:(context, candidateData, rejectedData) {
            return Center(child:Text("Choice 2: ${valueAccepted==null?'':valueAccepted.toString()}"));
          },
        )
    );
  }
}

class NumberContainerWidget extends StatelessWidget {
  const NumberContainerWidget({Key? key}) : super(key: key);

  _dragCompleted(BuildContext context){

  }
  @override
  Widget build(BuildContext context) {
    return Draggable(
      //information dropped by draggable at dragtarget
      data: Provider.of<GameScore>(context, listen: true).currentMultiplication.result,

      onDragCompleted:   _dragCompleted(context)  ,
      //Widget to be displayed when drag is underway
      feedback: Container(
        width:60,
        height:60,
        decoration:BoxDecoration(borderRadius: BorderRadius.circular(10),color:Colors.black26),
        child: Center(child:Text("${Provider.of<GameScore>(context, listen: false).displayMultiplication()}",style:TextStyle(color:Colors.green,fontSize:14))),

      ),
      child:
    Container(
      width:60,
      height:60,
      decoration:BoxDecoration(borderRadius: BorderRadius.circular(10),color:Colors.black26),
      child: Center(child:Text("${Provider.of<GameScore>(context, listen: false).displayMultiplication()}",style:TextStyle(color:Colors.blue,fontSize:14))),
    ));
  }
}


text:
Q: Associate .pl with Perl.exe I'm having a few problems running perl scripts and the association with Perl. I am unable to run the scripts as follows:
C:\perlscript.pl
I have to run them like this:
C:\perl perlscript.pl
I would like to be able to run them without typing "perl". I believe this is an issue with file assosiation however i have run the following commands and its still doing it:
assoc .pl=PerlScript
ftype PerlScript=C:\bin\perl.exe "%1" %*
I have also checked the ".pl" entry in the default file association list and it points at the Perl.exe
Any ideas guys?

redpajama_set_name: RedPajamaStackExchange


text:
Q: Pronunciation of luxury Is there a reason that Americans now pronounce luxury "lugsury" instead of "lucshury" while still pronouncing "extract" and "extra" with the more common "x" sound?

A: As David Garner mentioned in a comment, "extract" and extra" wouldn't be pronounced with a /g/ sound because the x is before /t/ in these words.
The letter "x" is sometimes pronounced with /g/ + a voiced fricative sound when it comes before a vowel; mainly when the following vowel is stressed (as in exact). In luxury, the following vowel is not stressed, but in the related word luxurious, it is. So it seems likely that the pronunciation of luxury with /g/ is derived from the pronunciation of luxurious with /g/. I don't know why there would be a difference between British and American speakers. As was mentioned in the comments, not all American English speakers use /g/ in luxury: some use /k/.

A: There is a common practice to smooth words out in American English. Some smoothing are not problematic and don't diminish from the general acceptability of the sentence such as "lugsury" or "jewlerry". They are written off. But then there are occurrences like "liberry" and "nucular" that make people sound uneducated.


text:
Q: Device Tree GPIO Pin Multipexing Value Calculation I am using a custom i.MX6 Board and I am configuring pin multiplexing in device tree.
Can anyone tell me how this value is calculated
MX6QDL_PAD_GPIO_0__CCM_CLKO1    0x130b0

Same GPIO is configured in different ways in different dtsi
MX6QDL_PAD_SD1_DAT2__GPIO1_IO19          0x80000000
MX6QDL_PAD_SD1_DAT2__GPIO1_IO19         0x030b0

What I know is that we configuring the PAD SDA1_DAT2 to GPIO1_IO19 mode.. But why is the value different..
Thanks for your time

A: To understand what the value actually means, you have to refer to the IMX6Q reference manual chapter 36.4.457 Pad Control Register  (IOMUXC_SW_PAD_CTL_PAD_SD1_DATA2).
You can also have a look at the kernel source documentation https://www.kernel.org/doc/Documentation/devicetree/bindings/pinctrl/fsl%2Cimx-pinctrl.txt for more general information about the device tree source.
This value is used to control the PAD (hysteresis, pull up , ..).
For example, if you want to enable hysteresis, you have to set the 16th bit of the register, and if you want open drain, then set the 11th bit.
In your case, you want to hog the SD1_DAT2 Pad to Signal GPIO1_IO19 and set the Pad control register value to 0x8000000 ( or 0x30b0 but you must set what is more convenient for you).


text:
Q: Rescue player from going wrong direction in dungeon game I'm trying to use rescue to save my dungeon game from an error if the player types in a direction that isn't available in the game and will instead repeat their location back to them again and ask where to go.  Here's the relevant code:
def go(direction)
    puts "You go " + direction.to_s
    @player.location = find_room_in_direction(direction)
    show_current_description
end

def show_current_description
    puts find_room_in_dungeon(@player.location).full_description
    puts "Where will you go?"
    answer = gets.chomp.downcase
        if answer == "exit"
            puts "You somehow teleported out of the cave. Good work."
            exit
        else
            answer = answer.to_sym
            begin
                go(answer)
            rescue
                puts "You can't go that way!"
                show_current_description
            end
        end
end

this is the result I get from typing in an unacceptable answer:

You find yourself in a large cavernous cave. To the west is a small aperture
Where will you go?
east
You go east
You can't go that way!
  You can't go that way!
  You can't go that way!
dungeon.rb:40:in show_current_description': undefined methodfull_description' for nil:NilClass (NoMethodError)
      from dungeon.rb:52:in rescue in show_current_description'
      from dungeon.rb:48:inshow_current_description'
      from dungeon.rb:20:in start'
      from dungeon.rb:89:in'

Here's all the code: My full Dungeon Code

A: Your rescue is catching the wrong thing. You perform the go operation, it assigns the next room; but it is nil. The thing that then fails is looking up the description on a nil. Instead of catching the error of failed room description lookup, you need to prevent the assignment if the room does not exist.
EDIT: Something like this might be okay.
def show_current_description
  loop do
    puts find_room_in_dungeon(@player.location).full_description

    puts "Where will you go?"
    answer = gets.chomp.downcase

    if answer == "exit"
      puts "You somehow teleported out of the cave. Good work."
      exit
    end

    next_location = find_room_in_direction(direction)
    if next_location
      puts "You go " + direction
      @player.location = next_location
      break
    else
      puts "You can't go that way!"
    end
  end
end


text:
Q: How to Theme a ListPicker from Style I have the following default style of the ListPicker control from the WPToolkit
<Style TargetType="toolkit:ListPicker" x:Key="ListPickerStyle1">
        <!--<Setter Property="Background" Value="{StaticResource PhoneTextBoxBrush}"/>-->
        <Setter Property="Foreground" Value="{StaticResource PhoneTextBoxForegroundBrush}"/>
        <Setter Property="FontSize" Value="{StaticResource PhoneFontSizeMediumLarge}"/>
        <Setter Property="HorizontalContentAlignment" Value="Left"/>
        <Setter Property="Margin" Value="{StaticResource PhoneTouchTargetOverhang}"/>
        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate TargetType="toolkit:ListPicker">
                    <StackPanel>
                        <VisualStateManager.VisualStateGroups>
                            <VisualStateGroup x:Name="PickerStates">
                                <VisualState x:Name="Normal"/>
                                <VisualState x:Name="Expanded">
                                    <Storyboard>
                                        <ObjectAnimationUsingKeyFrames
                                        Storyboard.TargetName="Border"
                                        Storyboard.TargetProperty="Background"
                                        Duration="0">
                                            <DiscreteObjectKeyFrame
                                            Value="{StaticResource PhoneTextBoxEditBackgroundColor}"
                                            KeyTime="0"/>
                                        </ObjectAnimationUsingKeyFrames>
                                        <ObjectAnimationUsingKeyFrames
                                        Storyboard.TargetName="Border"
                                        Storyboard.TargetProperty="BorderBrush"
                                        Duration="0">
                                            <DiscreteObjectKeyFrame
                                            Value="{StaticResource PhoneTextBoxEditBorderBrush}"
                                            KeyTime="0"/>
                                        </ObjectAnimationUsingKeyFrames>
                                    </Storyboard>
                                </VisualState>
                            </VisualStateGroup>
                        </VisualStateManager.VisualStateGroups>
                        <ContentControl
                        Content="{TemplateBinding Header}"
                        ContentTemplate="{TemplateBinding HeaderTemplate}"
                        Foreground="{StaticResource PhoneSubtleBrush}"
                        FontSize="{StaticResource PhoneFontSizeNormal}"
                        HorizontalContentAlignment="{TemplateBinding HorizontalContentAlignment}"
                        Margin="0 0 0 8"/>
                        <Grid>
                            <Border
                            x:Name="Border"
                            Background="{TemplateBinding Background}"
                            BorderBrush="{TemplateBinding Background}"
                            BorderThickness="2">
                                <Canvas x:Name="ItemsPresenterHost" MinHeight="46">
                                    <ItemsPresenter x:Name="ItemsPresenter">
                                        <ItemsPresenter.RenderTransform>
                                            <TranslateTransform x:Name="ItemsPresenterTranslateTransform"/>
                                        </ItemsPresenter.RenderTransform>
                                    </ItemsPresenter>
                                </Canvas>
                            </Border>
                            <!--<Popup x:Name="FullModePopup">
                                <Border Background="{StaticResource PhoneChromeBrush}">
                                    --><!-- Popup.Child should always be a Border --><!--
                                    <Grid>
                                        <Grid.RowDefinitions>
                                            <RowDefinition Height="Auto"/>
                                            <RowDefinition/>
                                        </Grid.RowDefinitions>
                                        <ContentControl
                                        Grid.Row="0"
                                        Content="{TemplateBinding FullModeHeader}"
                                        Foreground="{StaticResource PhoneForegroundBrush}"
                                        FontFamily="{StaticResource PhoneFontFamilySemiBold}"
                                        FontSize="{StaticResource PhoneFontSizeMedium}"
                                        HorizontalAlignment="Left"
                                        Margin="24 12 0 0"/>
                                        <ListBox
                                        x:Name="FullModeSelector"
                                        Grid.Row="1"
                                        ItemTemplate="{TemplateBinding ActualFullModeItemTemplate}"
                                        FontSize="{TemplateBinding FontSize}"
                                        Margin="{StaticResource PhoneMargin}">
                                            <ListBox.ItemsPanel>
                                                <ItemsPanelTemplate>
                                                    <StackPanel/>
                                                    --><!-- Ensures all containers will be available during the Loaded event --><!--
                                                </ItemsPanelTemplate>
                                            </ListBox.ItemsPanel>
                                        </ListBox>
                                    </Grid>
                                </Border>
                            </Popup>-->
                        </Grid>
                    </StackPanel>
                </ControlTemplate>
            </Setter.Value>
        </Setter>
    </Style>

But I would like to be able to add a border with a certain color based upon whether it is in the Expanded state or not. Also, the background needs to match the PhoneBackgroundBrush in the expanded state. Currently using this Style the Background does not change when the ListPicker is Expanded, and no border shows up whether the ListPicker is expanded or not. What can I do to change this?

A: Apply a template to your ListPicker
<toolkit:ListPicker Template="{StaticResource ListPickerControlTemplate1}">

Where ListPickerControlTemplate1 is a control template with Highlighted VisualState in which you can change the border brush, background color etc. In this case, I'm using a yellow background
<ControlTemplate x:Key="ListPickerControlTemplate1" TargetType="toolkit:ListPicker">
    <StackPanel>
        <VisualStateManager.VisualStateGroups>
            <VisualStateGroup x:Name="PickerStates">
                <VisualState x:Name="Normal"/>
                <VisualState x:Name="Highlighted">
                    <Storyboard>
                        <ObjectAnimationUsingKeyFrames
                          Storyboard.TargetName="UserControl"
                          Storyboard.TargetProperty="Foreground"
                          Duration="0">
                            <DiscreteObjectKeyFrame
                              Value="{StaticResource PhoneForegroundBrush}"
                              KeyTime="0"/>
                        </ObjectAnimationUsingKeyFrames>
                        <ObjectAnimationUsingKeyFrames
                          Storyboard.TargetName="Border"
                          Storyboard.TargetProperty="Background"
                          Duration="0">
                            <DiscreteObjectKeyFrame
                              Value="{StaticResource PhoneBackgroundBrush}"
                              KeyTime="0"/>
                        </ObjectAnimationUsingKeyFrames>
                        <ObjectAnimationUsingKeyFrames
                          Storyboard.TargetName="Border"
                          Storyboard.TargetProperty="BorderBrush"
                          Duration="0">
                            <DiscreteObjectKeyFrame
                              Value="Yellow"
                              KeyTime="0"/>
                        </ObjectAnimationUsingKeyFrames>
                    </Storyboard>
                </VisualState>
                ....
 ...........
</ControlTemplate>

I removed the ContentControl and some other parts from the control template because it's not so relevant.


text:
Q: Best way to ignore SSL certificate with request+python I have a application deployed in private server.
ip  = "100.10.1.1"
I want to read the source code/Web content of that page.
On browser when I am visiting to the page. It shows me "Your connection is not private".
So then after proceed to unsafe connection it takes me to that page.
Below is the code I am trying to read the HTML content. But it is not giving me the correct HTML content thought it is showing as 200 OK response.
I tried with ignoring ssl certificate with below code but not happening
import requests
url = "http://100.10.1.1"
requests.packages.urllib3.disable_warnings()
response = requests.get(url, verify=False)
print response.text

Can Someone share some idea on how to proceed or am i doing anything wrong on top of it?


text:
Q: Reading and printing user inputs in HTML in PHP I have got a form (php in html or the other way around). Once user selects an option in a drop down list, it would get the input value and create a few text boxes. It seems like I have to use onchange(). How do I read the input and perform logics within the script inself? Instead of opening another .php script?
Currently this is what I have.
<?php
$tables = $_POST["tables"];
?>

<form method="post" action="<?php echo $PHP_SELF;?>">
Table Name:

<select name="tables">
<option value="Applications">Application</option>
<option value="Device">Device</option>
</select>

</form>

<?
echo "".$tables."";
?>

A: You can't interact with PHP once the HTML is sent to the browser without either

*

*Refreshing the page, or

*Using AJAX (JavaScript).

If you know the options in the <select> beforehand (which it seems like you do), you should write some JavaScript to accomplish what you need. Here is a simple example using jQuery.
$('#tables_select').change(
    function( eventObject ){
        alert('You chose ' + $(this).val());
        switch( $( this ).val())
        {
            case 'Applications':
                $('#tables').append('<input type="text" name="application_name" value="Enter an application name" />"');
            break;
            case 'Device':
                $('#tables').append('<input type="text" name="device_name" value="Enter a device name" />"');
            break;
        }

    }
);

You will need to add additional logic to remove the inserted elements if the user changes their choice, and to insert the correct <input> elements when the page first loads, but it is a good starting point.

A: if you want to add any input type ... here is the demo demo with code
you use following method.
<form method="post" action="<?php echo $PHP_SELF;?>" onChange="return createTxtbox()">
Table Name:

<select name="tables">
<option value="Applications">Application</option>
<option value="Device">Device</option>
</select>

</form>

then write javascript,


text:
Q: Is there a way to auto-populate a C# HashSet with the enumerations included in an enum? Let's say I have an enum MyColors defined like this:
enum MyColors { Red, Green, Blue }

And I want to populate a HashSet with the enumerations of that enum.
The only way I know to do that is:
var allColors = new HashSet<MyColors> { MyColors.Red, MyColors.Green, MyColors.Blue }

The problem is that every time I add a color to the enum I have to update my hashset as well.
Is there a way to define that HashSet without manually copying the values from the enum?
Bonus points: The HashSet is a readonly field so it needs to be initialized when it is defined.
Note that Enum.GetValues and Enum.GetNames will not help because the HashSet is of type MyColors and those functions return different types.

A: Disregarding any other problem (conceptual or otherwise)
You could use GetValues then Cast
var set = new HashSet<MyColors>(Enum.GetValues(typeof(MyColors)).Cast<MyColors>());

// or

var set = Enum.GetValues(typeof(MyColors))
   .Cast<MyColors>()
   .ToHashSet();

Additional Resources
Enum.GetValues Method

Retrieves an array of the values of the constants in a specified
enumeration.

Enumerable.Cast(IEnumerable) Method

Casts the elements of an IEnumerable to the specified type.

Enumerable.ToHashSet Method

Creates a HashSet from an IEnumerable using the comparer to
compare keys.


text:
Q: await doesn't wait for function to end I know this has been asked a lot but I can't seem to use the existing answers to get my code to work. I am trying to use mongojs to make a single query, then put the results in a global (relative to the scope) variable to avoid nesting multiple callbacks. However, I can't seem to get the code to wait for the query to end before continuing.
async function taskmaster() {

    const db = mongojs(mongoUri.tasker);
    let currentDoc;

    const getTask = async function() {
        db.tasks.findOne({'task_id': {'$in': [taskId, null]}}, function(err, doc) {
            console.log(doc);
            currentDoc = doc;
        });
    }

    await getTask();
    console.log(currentDoc);

    // Code to process currentDoc below
}

No matter what I do, console.log(doc) shows a valid MongoDB document, yet console.log(currentDoc) shows "undefined". Thanks in advance!

A: Inside your async function, you use findOne method() in callback style, so it's totally normal that console.log(currentDoc) shows undefined, because it executes before
currentDoc = doc;
You can promisify the findOne method, to use it with async/await keyword.
I found a tutorial to promisfy a callback style function here, hope it help : https://flaviocopes.com/node-promisify/
--- EDIT ---
I rewrite your code when promising the findOne method, as suggested by O.Jones
async function taskmaster() {

    const getTask = async (taskId) => {
        return new Promise((resolve, reject) => {
           db.tasks.findOne({'task_id': {'$in': [taskId, null]}}, function(err, doc) {
              if(err) {
                  console.log("problem when retrieve data");
                  reject(err);
              } else {
                  resolve(doc);
              }
        });
    })

    const db = mongojs(mongoUri.tasker);

    const currentDoc = await getTask(taskId);
    console.log(currentDoc);
}


text:
Q: Evaluating $\lim_{y \to 0^+} (\cosh (3/y))^y$
Evaluating $$\lim_{y \to 0^+} (\cosh (3/y))^y$$

This is what I have tried:
$L = (cosh(3/y))^y$
$\ln L = \frac{\cosh(3/y)}{1/y}$, applying L'Hopital's rule, I get:
$\ln L = \frac{-3y^2(\sinh (3/y))}{(y^2)}$
$\ln L = 3\sinh (3/y)$
Now I seem to be stuck in a loop between $\sinh$ and cosh. I know the answer is supposed to be $e^3$, but how do I proceed from here?
Any help would be greatly appreciated!

A: Hint:
$$
\begin{align}
\cosh(3/y)^y
&=\left(\frac{e^{3/y}+e^{-3/y}}{2}\right)^y\\
&=e^3\left(\frac{1+e^{-6/y}}{2}\right)^y
\end{align}
$$


text:
Q: subset parameter in layers is no longer working with ggplot2 >= 2.0.0 I updated to the newest version of ggplot2 and run into problems by printing subsets in a layer.
library(ggplot2)
library(plyr)
df <- data.frame(x=runif(100), y=runif(100))
ggplot(df, aes(x,y)) + geom_point(subset=.(x >= .5))

These lines of code worked in version 1.0.1 but not in 2.0.0. It throws an error Error: Unknown parameters: subset.
I couldn't find an official change log or a way how to subset specific layers. Specially because this plyr solution was not very nice documented, I think I found it somewhere in stack overflow.

A: According to the comments in the ggplot2 2.0.0 code:
#' @param subset DEPRECATED. An older way of subsetting the dataset used in a
#'   layer.

Which can be found here: https://github.com/hadley/ggplot2/blob/34d0bd5d26a8929382d09606b4eda7a36ee20e5e/R/layer.r
One way to do that now would be this:
library(ggplot2)
library(plyr)
df <- data.frame(x=runif(100), y=runif(100))
ggplot(df, aes(x,y)) + geom_point(data=df[df$x>=.5,])

or this, (but beware of "Non Standard Evaluation" (NSE) :)
library(ggplot2)
library(plyr)
df <- data.frame(x=runif(100), y=runif(100))
ggplot(df, aes(x,y)) + geom_point(data=subset(df,x>=.5))

I think this is the one considered most safe as it has no NSE or dollar-sign field selectors:
library(ggplot2)
library(plyr)
df <- data.frame(x=runif(100), y=runif(100))
ggplot(df, aes(x,y)) + geom_point(data=df[df[["x"]]>=.5,])

But there are lots of others using pipes, etc...


text:
Q: Wordpress Site was hacked - No access admin,cpanel someone hacked my wordpress site and I cannot access ftp, cpanel and admin.
I contacted the hosting company and they send me the new password in order to access via ftp but I cannot access via admin and via cpanel.
How can I solve this problem? And How can I prevent this in the future?
I saw that there are some plugins like "Better WP Security". Is it enough to prevent future attacks?
Thanks for your help

A: Using Better WP Security is an option, yes, but most of all try to use strong passwords, always keep up to date your plugins and Wordpress itself.
Do not store your password on the computer as (text) files (try to remember them, I know, it sounds hard to do, but this is the only way).
Also check all computers, from which you login into Administration area for viruses and/or Trojan horses/key-loggers.
This was for prevention.
Now, how to deal with current situation - it depends, the best way is to disable (and remove) all plugins, and start with clean Wordpress installation. The posts and pages are inside the database, so you should not lose any information, but you can make a backup of all of your files (and custom page templates, if any).

A: That is lots of depend how your hosting manage there security for Wordpress or Other CMS in PHP the common way to hack admin and cpanel is SYMLINK attack. 1st check all the permission on the host like for change and modify and second thing use strong .htaccess in the your main index dir. And check all the your dir on your account if there is any PHP shell exists there than delete it immediately.

A: There are certain key points that you can use to make your website more secure.
First Check your site on sucuri.net to get more info on malware, spam etc...
1. Use security plugin
I recommend to use Wordfence. Which has lots of features and is able to do

*

*Scans over 44k+ malwares definitions

*Detects phishing attempts

*Removes Sh3lls

*Backdoors

*Trojans

*Monitors

*DNS security and many more...

Better WP Security (aka iThemes Security) is also good plugin to secure your WP. Which has also great features.
(both plugins works together - No doubt )
Comparison of Better WP Security and WordFence
2. Secure your .htaccess
secure wp-config.php
<Files wp-config.php>
    order allow,deny
    deny from all
    </Files>

Disable directory browsing
# directory browsing
Options All -Indexes

Protect .htaccess itself
<files .htaccess="">
order allow,deny
deny from all
</files>

Disable hot linking
RewriteEngine on
RewriteCond %{HTTP_REFERER} !^$
RewriteCond %{HTTP_REFERER} !^http(s)?://(www\.)?YourDomain [NC]
RewriteRule \.(jpg|jpeg|png|gif)$ - [NC,F,L]

3. Protect your self

*

*Use strong passwords, never share with anyone

*Save your self from Social Engineering

*Tips from Codex (Hardening Wordpress)
4. Get yourself updated.

*

*Use updated version of WordPress, Plugins, Themes.


text:
Q: Is there a placeholder for the drive letter of the TeXnicCenter installation? Because I want to run TeXnicCenter and MikTeX on an USB-Drive, I have to variable the drive letter within the output profiles. Is there any possibility? The TeXnicCenter-placeholders only have a placeholder for the drive letter of the project main file or the current file. And even this one ("%rm\") did't work.

A: As far as I know there is no such an variable for the drive letter.
To get it a changing of the code of TeXnicCenter is needed.
All windows programs at last have to use the registry for parameters for the usage of the program.  The worst case would be that you have to change one or more of the parameters inside the registry.
At last I suggest you to visit the homepage of TeXnicCenter and go to the  support page.  Make a feature request and ask there for adding such an parameter you need.


text:
Q: How to change CMake options from the Intellij platform plugin code? I want to change some options passed to the CMake command through the plugin code. Unfortunately I can't figure out how to do it.
Is there any API to communicate with CLion specific functionality?

A: You said "CMake command", which is unclear. I guess you want to change the CMake location.
This code can give you a CPPToolchains.Toolchain instance:
val Project.toolchains: CPPToolchains
    get() = ServiceManager
            .getService(this, CPPToolchains::class.java)
            .toolchains
            .firstOrNull()

Or if you don't understand Kotlin, use Java:
CPPToolchains.Toolchain tools = ServiceManager
        .getService(project, CPPToolchains.class)
        .getToolchains().get(0);

And you can get the settings by codes like
tools.getCMake().getExecutable()

Or change them by invoking methods like
com.jetbrains.cidr.cpp.toolchains.CPPToolchains.Toolchain#setCustomMakePath

Just explore through those classes and methods, you'll get what you want.
If you still can't find any, try replace CPPToolchains in the first two codes with CMakeSettings and see if there's something in the class that fits your expectation.

A: Settings->Build, Execution, Deployment -> CMake -> CMake Options


text:
Q: .NET Google Action WebHook Fulfillment RegisterUpdate Intent I am building a WebHook for Google actions - Dialogflow Intent Fulfillment.
At the beginning I was developing the WebHook on node.js but since Google block external API calls for the free plan I decided to switch to .NET WebHook (since this is a test project for some students we are not going to get a purchased plan). Easily the WebHook is calling some API of us.
The problem I am dealing with right now is a feature we implemented in the node.js original version, I am talking about the RegisterUpdate Intent that registers Daily updates.
I am wondering if it is possible to deal with this feature also if my WebHook is in c#. If so, How?
This are some of the official docs talking about this feature.
Currently we are developing the WebHook following this easy logic.
Thanks in advance!

A: From a technical perspective it is possible and not so hard, since everything in node.js just creates a JSON object what we have to do is create the same object as response and here it says how.


text:
Q: Suddenly the apk size increase from 24 mb to 88 mb I had used flutter build apk more than 20 times and it size was 24 mega byte
but now suddenly it is 88 mega byte in release mode
can anyone tell me why that happen
note : the assets file is 4.9 mega byte
note : i don't have any videos or gif in my app

A: I assume you built a universal APK. This type of APK contains all the files that are required for all types of CPU. This also makes the APK very large.
Try running flutter build apk --split-per-abi. This will create a seperate APK for the different CPU types.

A: Have you added any new dependencies since your last release build?


text:
Q: Azure AD User login fails even after admin consent in multi tenant web app I am running into the following issue while allowing administrators to sign up a company.
1)I created a multi-tenant web application with Azure authentication
    and deployed to Azure.
2)Under the Windows Azure AD permission settings for this app, I checked
    the following permissions
 Application Permissions :  Read Directory Data
 Delegated Permissions : Sign in and read user profile

3)When I try to launch the application and sign in as a user  I am
    presented with a screen that says

This application requires application permissions to another
  application. Consent for application permissions can only be performed
  by an administrator. Sign out and sign in as an administrator or
  contact one of your organization's administrators.

4)I logged in as the admin and I am now presented with the admin consent screen. After accepting, I was able to browse through the website.
admin consent screen
5)When I logged back as the user, i am still presented with the same application permission error screen. As the admin has already consented, I would expect that the user can now sign in to the web app.
Please let me know if i need to set anything else.

A: You need to add a link and/or button into your app that allows to consent for their tenant by including prompt=admin_consent in your OAuth2/Open ID Connect authorization request.
The "Admin consent" portion of this document goes into more detail:
https://learn.microsoft.com/en-us/azure/active-directory/active-directory-devhowto-multi-tenant-overview#admin-consent


text:
Q: How to add multiple slashes to a single cell I have a column with about 5k rows that I need to add slashes to. I need to add slashes to the first, second, and last space (" ") in the cell. Each cell has different lengths so there are different amounts of spaces between the second and last in each row.
Here's an example of some rows
NYLA D DURA FEMUR BCN LG
NULO D FZD GF BF 5oz
OMNI D BRTSH SLP LD GRN 4ft
OMNI D LIGHT S-HOOK
OMNI D SS BOWL 3qt

I need these converted to
NYLA/D/DURA FEMUR BCN/LG
NULO/D/FZD GF BF/5oz
OMNI/D/BRTSH SLP LD GRN/4ft
OMNI/D/LIGHT S-HOOK
OMNI/D/SS BOWL/3qt

I have tried using the substitute formula but that will only add one slash when I need to add 1-3. I'm not sure if nesting the substitute formula is possible in this scenario. If so, that should do it but I can't get it to work.

A: Nested SUBSTITUTE is the way to go:
=SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(A1," ","/",LEN(A1)-LEN(SUBSTITUTE(A1," ","")))," ","/",2)," ","/",1)

A: You can achieve this with the following formula:
=SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(A1," ","/",LEN(SUBSTITUTE(A1," ","  "))-LEN(A1))," ","/",1)," ","/",1)

It replaces the last instance of " " followed by the first two instances.
This might however return an error if there are less than three " " in the string.


text:
Q: Estimating Poincare constant for unit interval I want to show that the Poincare constant for the $W^{1,2}_0(0,1)$ is smaller than $1$. More specifically, I want to show that there is a constant $C<1$ such that for any $f\in C^\infty_c(0,1)$ (compactly supported smooth) we have the inequality
$$
\lVert f\rVert\leq C\lVert f'\lVert
$$
where $\lVert\cdot\rVert$ is the $L^2$ norm.
The proof of Poincare inequality that I know (using Cauchy-Schwarz) gives an estimate of $C=2$, while the Wikipedia article seems to say that optimally $C\leq \pi^{-1}$. I'm looking for a simple proof for this special case. I don't need a very sharp estimate, just smaller than $1$, and would appreciate a hint or a reference.

A: The constant you are looking for is the following:
$$\tag{1}\frac{1}{C^2}=\inf\left\{ \int_0^1 \left(f'\right)^2\, dx\ :\ \int_0^1 (f)^2\, dx=1\right\}. $$
Since
$$\int_0^1 \left(f'\right)^2\, dx = \langle -f'', f\rangle, $$
you are in fact looking for the first eigenvalue of the following Sturm-Liouville problem:
$$\tag{2}\begin{cases}
-\frac{d^2 f}{dx^2}=\lambda f, \\ \\f(0)=f(1)=0. \end{cases}$$
Indeed, we can now rewrite the minimization in (1) as
$$
\inf_{f\ne 0} \frac{\langle -f'', f\rangle}{\langle f, f\rangle}, $$
and this equals exactly the smallest eigenvalue of the problem (2), just like in ordinary linear algebra; see Wikipedia on the Rayleigh quotient.
The problem (2) can be integrated explicitly and you find that the first eigenvalue is $\pi^2$ with eigenfunction $\sin(\pi x)$ (and scalar multiples of it). Therefore
$$C=\frac{1}{\pi}<1.$$


text:
Q: RAMJobStore (quartz_jobs.xml) to AdoJobStore Data Move My team and I are trying to figure out a way to "load up" our Sql Server database with the Quartz.NET schema installed.
<add key="quartz.dataSource.default.provider" value="SqlServer-20"/>

For demo's, we've been storing our job-setups in .xml (quartz_jobs.xml).
My question is :
Is there a way to "load up" the scheduling data from .xml (quartz_jobs.xml) (Quartz.Simpl.RAMJobStore), and then "save it off" to a AdoJobStore (Quartz.Impl.AdoJobStore.JobStoreTX) ?
The reason is that our "start up" data could be easily written placed in the .xml.
Right now, the only way I see putting jobs into a AdoJobStore is "coding them up" in c# code through the Quartz.Net object model.
Or "playing back" some profiled TSQL (using Sql Profiler)  :(
Direct question is above "(getting xml into sql-server)".....the higher level question is "How does one populate a AdoJobStore with start up data...that isn't "coding them up" in c# code.
EDIT:
I'm putting in my code that works......using Marko's (accepted as the answer) response.
My configuration file:
<quartz>

    <add key="quartz.plugin.xml.type" value="Quartz.Plugin.Xml.XMLSchedulingDataProcessorPlugin, Quartz" />
    <add key="quartz.plugin.xml.fileNames" value="~/Quartz_Jobs_001.xml" />
    <add key="quartz.plugin.xml.ScanInterval" value="10" />

    <add key="quartz.jobStore.type" value="Quartz.Impl.AdoJobStore.JobStoreTX, Quartz" />
    <add key="quartz.jobStore.driverDelegateType" value="Quartz.Impl.AdoJobStore.SqlServerDelegate, Quartz"/>
    <add key="quartz.jobStore.dataSource" value="default"/>
    <add key="quartz.dataSource.default.connectionString" value="Server=MyServer\MyInstance;Database=QuartzDB;Trusted_Connection=True;Application Name='quartz_config';"/>
    <add key="quartz.dataSource.default.provider" value="SqlServer-20"/>

</quartz>

My code:
    NameValueCollection config = (NameValueCollection)ConfigurationManager.GetSection("quartz");
    ISchedulerFactory factory = new StdSchedulerFactory(config);
    IScheduler sched = factory.GetScheduler();
    sched.Clear();
    sched.Start();

NOTE:
I had to call IScheduler.Start() for the values to persist to the database.
The consequence of adding this line:
 <add key="quartz.plugin.xml.ScanInterval" value="10" />

was that I could add entries into the quartz_job.xml, and it would would (append-only) the data in the database (while the engine was running).
Aka, I can "add lookup data" (to the database) "on the fly"....without stopping the service.  A nice little tidbit.
Removing a job requires a restart.

A: You should be able to do this quite easily. You can combine the XML configuration and ADO job store. This will make the XML processor update the jobs in the persistent store.
Here's minimal configuration:
NameValueCollection properties = new NameValueCollection();

properties["quartz.jobStore.type"] = "Quartz.Impl.AdoJobStore.JobStoreTX, Quartz";
properties["quartz.jobStore.dataSource"] = "default";
properties["quartz.jobStore.driverDelegateType"] = "Quartz.Impl.AdoJobStore.SqlServerDelegate, Quartz";

properties["quartz.dataSource.default.connectionString"] = "Server=(local);Database=quartz;Trusted_Connection=True;";
properties["quartz.dataSource.default.provider"] = "SqlServer-20";

// job initialization plugin handles our xml reading, without it defaults are used
properties["quartz.plugin.xml.type"] = "Quartz.Plugin.Xml.XMLSchedulingDataProcessorPlugin, Quartz";
properties["quartz.plugin.xml.fileNames"] = "~/quartz_jobs.xml";

// First we must get a reference to a scheduler
ISchedulerFactory sf = new StdSchedulerFactory(properties);
IScheduler sched = sf.GetScheduler();

And our XML configuration contains overwrite instructions so that job store is refreshed:
<?xml version="1.0" encoding="UTF-8"?>

<job-scheduling-data xmlns="http://quartznet.sourceforge.net/JobSchedulingData"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
                version="2.0">

  <processing-directives>
    <overwrite-existing-data>true</overwrite-existing-data>
  </processing-directives>

  <schedule>

    <job>
      <name>jobName1</name>
      <group>jobGroup1</group>
      <description>jobDesciption1</description>
      <job-type>Quartz.Examples.Example15.SimpleJob, Quartz.Examples</job-type>
      <durable>true</durable>
      <recover>false</recover>
    </job>

    <trigger>
      <simple>
        <name>simpleName</name>
        <group>simpleGroup</group>
        <description>SimpleTriggerDescription</description>
        <job-name>jobName1</job-name>
        <job-group>jobGroup1</job-group>
        <start-time>1982-06-28T18:15:00.0Z</start-time>
        <repeat-count>-1</repeat-count>
        <repeat-interval>3000</repeat-interval>
      </simple>
    </trigger>

  </schedule>

</job-scheduling-data>

You can also make the XML to auto refresh the store on change (checked every 10 seconds) if you define:
properties["quartz.plugin.xml.ScanInterval"] = "10";


text:
Q: saving pictures in portrait orientation I am working on app that use camera preview to take pictures and displaying them in grid view in other activity. But when I take a portrait picture it is saved in my galaxy S4 SD Card in landscape and also display it in grid view in landscape!
Image 1
Image 2
Gridview Activity:
public class GridViewActivity extends Activity {

private ImageAdapter imageAdapter;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.grid_view);

    GridView gridview = (GridView) findViewById(R.id.gridview);
    imageAdapter = new ImageAdapter(this);
    gridview.setAdapter(imageAdapter);

    String ExternalStorageDirectoryPath = Environment
            .getExternalStorageDirectory()
            .getAbsolutePath();

    String targetPath = ExternalStorageDirectoryPath + "/JCG Camera";

    File targetDirector = new File(targetPath);

    File[] files = targetDirector.listFiles();
    for (File file : files){

        imageAdapter.add(file.getAbsolutePath());
    }
}

in ImageAdapter:
void add(String path){
    this.path = path;
    imageList.add(path);
}

@Override
public View getView(int position, View convertView, ViewGroup parent) {
    ImageView imageView;
    if (convertView == null) {
        imageView = new ImageView(context);
        imageView.setLayoutParams(new GridView.LayoutParams(320, 320));
        imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
        imageView.setPadding(5, 5, 5, 5);
    } else {
        imageView = (ImageView) convertView;
    }

    Bitmap bm = decodeSampledBitmapFromUri(imageList.get(position), 320, 320);
    imageView.setImageBitmap(bm);
    return imageView;
}

public Bitmap decodeSampledBitmapFromUri(String path, int reqWidth, int reqHeight) {

    Bitmap bm = null;
    final BitmapFactory.Options options = new BitmapFactory.Options();
    options.inJustDecodeBounds = true;
    BitmapFactory.decodeFile(path, options);
    options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);

    options.inJustDecodeBounds = false;
    bm = BitmapFactory.decodeFile(path, options);

    return bm;
}

public int calculateInSampleSize(

    BitmapFactory.Options options, int reqWidth, int reqHeight) {
    final int height = options.outHeight;
    final int width = options.outWidth;
    int inSampleSize = 1;

    if (height > reqHeight || width > reqWidth) {
        if (width > height) {
            inSampleSize = Math.round((float)height / (float)reqHeight);
        } else {
            inSampleSize = Math.round((float)width / (float)reqWidth);
        }
    }

    return inSampleSize;
}

in camera activity:
private PictureCallback getPictureCallback() {
    PictureCallback picture = new PictureCallback() {

        @Override
        public void onPictureTaken(byte[] data, Camera camera) {

            //make a new picture file

            File pictureFile = getOutputMediaFile();

            if (pictureFile == null) {
                return;
            }
            try {

                //write the file

                FileOutputStream fos = new FileOutputStream(pictureFile);
                fos.write(data);
                fos.close();
                Toast toast = Toast.makeText(myContext, "Picture saved: " + pictureFile.getName(), Toast.LENGTH_LONG);
                toast.show();

            } catch (FileNotFoundException e) {
            } catch (IOException e) {
            }

            //refresh camera to continue preview

            mPreview.refreshCamera(mCamera);
        }
    };
    return picture;
}

private static File getOutputMediaFile() {

    //make a new file directory inside the "sdcard" folder

    File mediaStorageDir = new File("/sdcard/", "JCG Camera");

    //if this "JCGCamera folder does not exist

    if (!mediaStorageDir.exists()) {

        //if you cannot make this folder return

        if (!mediaStorageDir.mkdirs()) {
            return null;
        }
    }

    //take the current timeStamp

    String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
    File mediaFile;

    //and make a media file:

    mediaFile = new File(mediaStorageDir.getPath() + File.separator + "IMG_" + timeStamp + ".jpg");
    return mediaFile;
}

I read about EXIF and exifinerface, but I do not know how to use it in my code!

A: ExiftInterface is a good approach I think. They only thing is that you must have a mechanism that tells you which way your image needs to be rotated (eg. clockwise, counterclockwise). This is what I am using to rotate image.
try {
    //You must replace _filePaths.get(position) with the desired object
    //You are trying to extract the rotation info. In your case is your data
    //But I think you have to save your image first, before you can rotate it.
    ExifInterface exif = new ExifInterface(_filePaths.get(position));

    //Here you extract the image's rotation info.
    int rotation = exif.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL );

    //Here you can convert it to degrees. Using helper method.
    int roationInDegrees = exifToDegress(rotation);
    Matrix matrix = new Matrix();

    //This is where you check if the rotation of the image is not what you want. 0f indicates a portait Image.
    if(rotation != 0f){

    //Here you specify which way you want to rotate your bitmap according
    //To the result of helper method.
    matrix.preRotate(roationInDegrees);
    image = Bitmap.createBitmap(image,0, 0, imageWidth, imageWidth, matrix, true);
}
} catch (IOException e1) {
     e1.printStackTrace();
    Log.d("activity#fail", e1.getMessage());
}

private int exifToDegress(int exifOrientation) {
    if (exifOrientation == ExifInterface.ORIENTATION_ROTATE_90) { return 90; }
    else if (exifOrientation == ExifInterface.ORIENTATION_ROTATE_180) {  return 180; }
    else if (exifOrientation == ExifInterface.ORIENTATION_ROTATE_270) {  return 270; }
    return 0;
}

Make sure you put code inside Try and catch in case the image your are attempting to rotate does not contain any "Orientation" information. Try adding this code right before you write the "data" with your fileoutputstream object.
Good Luck.


text:
Q: Select first non-null value by date for each column across multiple rows I have a table like the following:
+-------------------------+------+------+------+------+
|          Date           |  A   |  B   |  C   |  D   |
+-------------------------+------+------+------+------+
| 2010-11-16 10:02:00.000 | 10   | NULL | NULL | NULL |
| 2010-09-21 00:00:00.000 | 86   | 14   | NULL | 17   |
| 2010-07-27 00:00:00.000 | 125  | 12   | NULL | 11   |
| 2010-05-29 15:24:00.000 | NULL | NULL | 1250 | NULL |
+-------------------------+------+------+------+------+

I need a query to extract the first non-null value of each column. Some sort of "vertical coalesce".
The desired result would be:
+-------------------------+------+------+------+------+
|          Date           |  A   |  B   |  C   |  D   |
+-------------------------+------+------+------+------+
| 2010-11-16 10:02:00.000 | 10   | 14   | 1250 | 17   |
+-------------------------+------+------+------+------+

the table is ordered by date (desc)
the actual table has way more columns (40) and rows (up to 5000)
Edit:
My actual table has a lot more columns and rows (about 40 columns and up to 5000 rows let's say). I fear that multiple order-by queries could deteriorate the performance of the query. However, if no cleaner solution will show up, I'll go for it.

A: This is one possible appoach, if your order is descending by [Date] column:
Input:
CREATE TABLE #Table (
    [Date] datetime,
    A int,
    B int,
    C int,
    D int
)
INSERT INTO #Table
    ([Date], A, B, C, D)
VALUES
    ('2010-11-16T10:02:00.000', 10  , NULL, NULL, NULL),
    ('2010-09-21T00:00:00.000', 86  , 14  , NULL, 17  ),
    ('2010-07-27T00:00:00.000', 125 , 12  , NULL, 11  ),
    ('2010-05-29T15:24:00.000', NULL, NULL, 1250, NULL)

Statement:
SELECT
    [Date] = (SELECT TOP 1 [Date] FROM #Table WHERE [Date] IS NOT NULL ORDER BY [Date] DESC),
    [A] = (SELECT TOP 1 [A] FROM #Table WHERE [A] IS NOT NULL ORDER BY [Date] DESC),
    [B] = (SELECT TOP 1 [B] FROM #Table WHERE [B] IS NOT NULL ORDER BY [Date] DESC),
    [C] = (SELECT TOP 1 [C] FROM #Table WHERE [C] IS NOT NULL ORDER BY [Date] DESC),
    [D] = (SELECT TOP 1 [D] FROM #Table WHERE [D] IS NOT NULL ORDER BY [Date] DESC)

Output:
Date                    A   B   C       D
2010-11-16 10:02:00.000 10  14  1250    17

Update - another possible approach, using aggregate functions:
;WITH DatesCTE AS (
    SELECT
        [Date] = MAX([Date]),
        [DateA] = MAX(CASE WHEN A IS NOT NULL THEN [Date] END),
        [DateB] = MAX(CASE WHEN B IS NOT NULL THEN [Date] END),
        [DateC] = MAX(CASE WHEN C IS NOT NULL THEN [Date] END),
        [DateD] = MAX(CASE WHEN D IS NOT NULL THEN [Date] END)
    FROM #Table
)
SELECT
    d.[Date],
    A = MAX(CASE WHEN t.[Date] = d.[DateA] THEN A END),
    B = MAX(CASE WHEN t.[Date] = d.[DateB] THEN B END),
    C = MAX(CASE WHEN t.[Date] = d.[DateC] THEN C END),
    D = MAX(CASE WHEN t.[Date] = d.[DateD] THEN D END)
FROM DatesCTE d
CROSS APPLY #Table t
GROUP BY d.[Date]

A: You can try something like this to avoid order by. I know that it's pretty tedious in the start to define 50 variables, but you don't have to worry later.
declare @A int = (select top 1 A from #Table where A is not null)
declare @B int = (select top 1 B from #Table where B is not null)
declare @C int = (select top 1 C from #Table where C is not null)
declare @D int = (select top 1 D from #Table where D is not null)

select top 1 Date,@A,@B,@C,@D
from #Table

A: I have not tested this but it sure looks wicked enough:
with cte as (
    select date
         , a, max(case when a is not null then date end) over () as date_a
         , b, max(case when b is not null then date end) over () as date_b
         , c, max(case when c is not null then date end) over () as date_c
         , d, max(case when d is not null then date end) over () as date_d
    from t
)
select max(date) as date
     , min(case when date = date_a then a end) as a
     , min(case when date = date_b then b end) as b
     , min(case when date = date_c then c end) as c
     , min(case when date = date_d then d end) as d
from cte

Without window functions:
with cte as (
    select max(case when a is not null then date end) as date_a
         , max(case when b is not null then date end) as date_b
         , max(case when c is not null then date end) as date_c
         , max(case when d is not null then date end) as date_d
    from t
)
select max(date) as date
     , min(case when date = date_a then a end) as a
     , min(case when date = date_b then b end) as b
     , min(case when date = date_c then c end) as c
     , min(case when date = date_d then d end) as d
from t
cross join cte

Demo on db<>fiddle


text:
Q: How do we start implementing HipHop for our web servers? I want to use HipHop but I've got no idea how do I go about doing that. Does anyone know of any tutorials that teach us how to implement HipHop for our websites?
Is there alot of configuration to do or is it more like sort of a change a config file and everything just works sort of thing?

A: It appears that there are several examples in the documentation:
https://github.com/facebook/hiphop-php/wiki/Running-HipHop


text:
Q: runtime error 9 - Subscript Out of Range Error or runtime 1004 - method 'range of object' worksheet failed when trying to color cell I have a vba code that is intended to highlight cells based on value of the cell i.e. if it is empty. The code identifies the cell values correctly but it will not colour the cell.
I keep getting an runtime error 9 - Subscript Out of Range Error or runtime 1004 - method 'range of object' worksheet failed.
I have completed other searches and cannot seem to find the solution. As I can clearly see that the cell I am pointing to exists. I have even done a test with a msgbox for that cell and it shows that it exists.
The following is the code. whenever the if statement is met I get the runtime error:
For Each ws In ThisWorkbook.Worksheets
 If ws.Name = "raw data" Or ws.Name = "HP dealer permits" Or ws.Name = "HP harvester permits" Then
   'do nothing
   Else
   lastrow2 = ws.Range("B" & Rows.Count).End(xlUp).Row
     For i = 2 To lastrow2

     If ws.Range("D" & i).Value = "no match" Then ws.Range(ws.Cells(i, 2), _
       ws.Cells(i, 4)).Interior.ColorIndex = 3
     If ws.Range("E" & i).Value = "#NA" Then ws.Range(ws.Cells(i, 5)).Interior.ColorIndex = 3
     If ws.Range("J" & i).Value = "No" Then ws.Range(ws.Cells(i, 8), _
        ws.Cells(i, 11)).Interior.ColorIndex = 3
     If IsEmpty(ws.Range("L" & i)) = True Then ws.Range(ws.Cells(i, 12)).Interior.ColorIndex = 3
     If IsEmpty(ws.Range("N" & i)) = True Then ws.Range(ws.Cells(i, 14)).Interior.ColorIndex = 3
  Next i
Next ws
End sub

Regards,
Glenn

A: The issue was using the range when referring to one cell and the use of vbRed which does not appear to function for colouring the cell.
I had previously tried it by removing the 'ws.range' but still had the runtime error 9 - Subscript Out of Range Error occurring. Though I believe now this was because of the vbRed statement causing the runtime error 9. I trialled the vbRed when I thought the '3' was not working. I got the vbRed from https://p2p.wrox.com/excel-vba/72653-background-color-range-cells.html and Coloring a range of cells (VBA) which used the vbRed and vbWhite statement in their code.
I have removed the ws.Range when only referring to one cell, and only using the numbers for the colour index. This seems to be working now.


text:
Q: HTML code to be shown in messagebox WP8 In my windows phone 8 application, I receive a html code in the response. The designer has asked to show this data on WP8 MessageBox.
Is it possible or recommended to have a webbrowser in a windows phone 8 custom messagebox?
Also Is there any other approach for achieving the same?

A: I would just use the Windows Phone Toolkit's Custom Message Box and set its Content to a WebBrowser control with your custom HTML.
NuGet Windows Phone Toolkit or get it here : Windows Phone Toolkit.
Then the code is fairly simple
private void PhoneApplicationPage_Loaded(object sender, RoutedEventArgs e)
{
    // the web browser
    WebBrowser wb = new WebBrowser();
    wb.Height = 300;

    // the HTML to show inside to browser
    string my_html = "Hello from WP8";

    // nagivate to the HTML
    wb.NavigateToString(my_html);

    // create our Message box
    CustomMessageBox messageBox = new CustomMessageBox()
    {
        //Caption = "Allow this application to access and use your location?",
        //Message = "Sharing this information helps us provide and improve the location-based services offered for this phone. We won't use the information to identify or contact you.",
        Content = wb,
        LeftButtonContent = "allow",
        RightButtonContent = "cancel"
    };

    // show it
    messageBox.Show();

}

Code In Action

A: You cannot use HTML or any formatting at all in the standard MessageBox. You need to create a UserControl that behaves like a message box where you can use the HTMLTextBox (or HTMLViewer) from https://msptoolkit.codeplex.com/. It is more suited for short HTML text than WebBroser


text:
Q: Xcode5 does not automatically add file to compile sources and crashes after manually adding This seems to be happening deterministically.
I will add a file graphically through right clicking a group folder and selecting 'new file' or 'add file'. I will add this new file, then will get a linker error while building. After going to the project settings and adding the file to the 'compile sources' manually, Xcode will completely crash, but will still have added the file on reboot.
Has anyone else seen this bug, or know what would be happening here?

A: I had the same issue, but without the crash. I am adding the file, and checking the target in the inspector for that file, but it won't be listed in the 'Compile Sources' phase. I have to manually add it there. If I go back to the inspector for the file, uncheck the target, then it properly disappears from the 'Compile Sources', but again, will not come back to the 'Compile Sources' by just checking the box.
Restarting Xcode did set things back to normal.


text:
Q: Draw the period as a function of the energy for the simple pendulum I have to draw the graph of the period of the simple pendulum as a function of the energy $e$.
The equation of motion is $\ddot x= \sin(x)$. So I wrote the integral relating the energy with the period, which is
$T(e)=\int_{x_-}^{x^+} \frac{dx}{\sqrt{2(e-V(x))}}$
where the extrema are the inversion points of the periodic orbits and $V(x)=\cos(x)$ is the potential of the system.
I can see that $T(e)$ tends to zero as $e$ goes to infinity, but I don't know how to manage the singularities at the critical points of the potential energy

A: From
$$
\ddot x = \sin x\Rightarrow \ddot x \dot x = \sin x\dot x\Rightarrow \frac 12 \dot x^2 = -\cos x + E
$$
$$
dt = \frac{dx}{\sqrt{2(E-\cos x)}}\Rightarrow t(E) = \int_{\arccos E}^{2\pi-\arccos E}\frac{dx}{\sqrt{2(E-\cos x)}}-\pi
$$
So the graphics for $E \times t$ is something like


text:
Q: How do I see the help for the `dplyr::collect` method? I am trying to find out what additional arguments can be passed to dplyr::collect in the ellipsis .... I want to do this because I believe that the behaviour of collect has changed between dplyr version 0.4.3 and 0.5. It seems that in the new version collect() only downloads the first 100k rows, unless a new n = Inf argument is passed.
I have retrieved the methods associated with collect using:
> methods('collect')
[1] collect.data.frame* collect.tbl_sql*
see '?methods' for accessing help and source code

I have looked at the help file for S3 methods but cannot work out how to get help on collect.tbl_sql, as ?"dplyr::collect.tbl_sql" does not work.

A: As noted by Chrisss and Zheyuan Li:

*

*The asterisk/star/* next to the method name after running methods indicates that each of these methods are not exported from the dplyr namespace.

*To access the helpfile, one then needs to use three colons, i.e., ?dplyr:::collect.tbl_sql

*However, there is no helpfile for these methods, so we need to examine the source code to look at the behaviour of each of these functions in the respective versions.

In 0.4.3 by examining tbl-sqr.r file in the source code:
collect.tbl_sql <- function(x, ...) {
  grouped_df(x$query$fetch(), groups(x))
}

and in 0.5:
> dplyr:::collect.tbl_sql

function (x, ..., n = 1e+05, warn_incomplete = TRUE)
{
    assert_that(length(n) == 1, n > 0L)
    if (n == Inf) {
        n <- -1
    }
    sql <- sql_render(x)
    res <- dbSendQuery(x$src$con, sql)
    on.exit(dbClearResult(res))
    out <- dbFetch(res, n)
    if (warn_incomplete) {
        res_warn_incomplete(res, "n = Inf")
    }
    grouped_df(out, groups(x))
}

Thus, we can conclude that the behaviour of collect has indeed changed in the manner originally described in my question.


text:
Q: google chrome full reset? huge bars and default zoom issues i guess the dog sat on the wireless keyboard when we were watching a movie and now the bars... address bar and tabs are like 1/5 of my screen. i tried to uninstall and reintall and tried the restore defaults button to no avail. help me before i reinstall my OS!! running 12.04 lts is that helps...

A: The Google Chrome configuration is stored in ~/.config/google-chrome. You can try deleting or moving that folder.


text:
Q: Callback to Cordova plugin from Objective C delegate Situation: I'm building a cordova plugin to connect an existing iOS library with Ionic. The base mapping of methods is done and working, means I can call the iOS methods via Angular methods and getting success/error callbacks.
Problem: There's a login method which is called, and appropriate delegate methods (e.g. userDidLoginWithSuccess) are called afterwards. Callback from the login method to the cordova plugin is easy, but I need to somehow callback from the delegate method, in order to let the Ionic app know if the user was logged in successfully or not.
Any thoughts on this? Thanks.
PS: I checked this post, which didn't help, although it's a similar question. Phonegap - Send message to Javascript from Objective-c in a plugin delegate

A: On your .h create a property callbackId that you will use to store the callback identifier of the plugin
@property (nonatomic, strong) NSString* callbackId;

Then, on your plugin method, store the callbackId on the property you created.
self.callbackId = command.callbackId;

and finally, on the delegate send the plugin result using the callbackId
CDVPluginResult* result = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsString:@"string result"];
[self.commandDelegate sendPluginResult:result callbackId:self.callbackId];


text:
Q: Issue with Fractional Knapsack Here is my implemented code in Java. The getmax() function returns the index of the maximum element.The issue is, I am not getting one of my test cases correct. I don't know which one, but online judge is giving me following warning:

Failed case #7/13: Wrong answer
  got: 66152.57 expected: 66152.572
   (Time used: 0.19/1.50, memory used: 24469504/671088640.)

public class FractionalKnapsack {
private static double getOptimalValue(int capacity, int[] values, int[] weights) {
    float value = 0;
    //write your code here
    float[] ratio=new float[values.length];
    for(int i=0;i<values.length;i++)
    {
        ratio[i]=(float)values[i]/(float)weights[i];
    }
    int max=0;

    while(capacity>-1)
    {
        max=getMax(ratio);
        if(capacity==0)
        {
            return value;
        }
        if(capacity>0)
        {
            if(weights[max]>=capacity)
            {
                value=value+((float)ratio[max]*(float)(capacity));
                capacity=0;
            }
            else if(capacity>weights[max])
            {
                value=value+(weights[max]*ratio[max]);
                capacity=capacity-weights[max];
            }
            ratio[max]=0;
        }
    }
    return value;
}
private static int getMax(float[] arr)
{
    float max=0;
    int save=0;
    for(int i=0;i<arr.length;i++)
    {
        if(arr[i]>max)
        {
            max=arr[i];
            save=i;
        }
    }
    return save;
}
public static void main(String args[]) {
    Scanner scanner = new Scanner(System.in);
    int n = scanner.nextInt();
    int capacity = scanner.nextInt();
    int[] values = new int[n];
    int[] weights = new int[n];
    for (int i = 0; i < n; i++) {
        values[i] = scanner.nextInt();
        weights[i] = scanner.nextInt();
    }
    DecimalFormat df = new DecimalFormat();
    df.applyPattern(".0000");
    System.out.println(df.format(getOptimalValue(capacity, values, weights)));
}

}

A: The float type you use can not distinguish between 66152.57 (your output) and 66152.572 (desired output). You may check it here online, for example. See, the mantissa has only 23 bits of storage which means that relative error can well be on the order of 2-24. For magnitude 66152.572, it means the absolute error of 0.003943. If you become further interested in the why, look up some floating point guide (like this one).
The solution is to use double for floating-point calculations.
Note that, unless you actually know float precision is enough for your application, double is almost always the right type to use to avoid such unfortunate effects.


text:
Q: Backbone collection remove, ReferenceError: el is not defined I have a view for a collection, and when I invoke its remove method I call its collection remove method as well, and I'm getting a 'ReferenceError: el is not defined' which doesn't make any sense to me, why would a collection need an el.
Invoking code:
try {

 myAppModel=backboneApp.views.privateViews.myAppsTabView.myAppsView.views.myAppsPrivateView.collection.get(appId);
                                            backboneApp.views.privateViews.myAppsTabView.myAppsView.views.myAppsPrivateView.remove(myAppModel);

} catch(e) {
console.log("delFromMyAppsCollection: Failed to delete app from collection e= " + e);
}

Remove method within View:
remove : function(modelToRemove) {
        alert('Killing!');
        console.log("MyAppsPrivateView.remove called with model: ", modelToRemove );
        this.collection.remove(modelToRemove);
        console.log("MyAppsPrivateView.remove collection: ", this.collection );
        this._rendered = false;
    }

I guess it may be a better way to delete an element from a collection/view, but still it seems odd that the collection is complaining about not having an el, any ideas?
Thanks in advance.
Just in case,
view definition:
var MyAppsPrivateView = Backbone.View.extend( {
    // Reference to this collection's model.
    model:      PapsCatalog , // don't should be PapModel instead of a collection?
    templateId: Epc2G.myAppsTemplateId,
    template:   jQuery('#' + this.templateId).html(),

view instantiation:
var options = {
            className : "MyAppsContainer",
            uid : "myAppsPrivateView",
            collection : papsCollection,
            el : "#myAppsView"
        };

        var oMyAppsPrivateView = new MyAppsPrivateView(_.clone(options));

A: Might it relate to Backbone.View already having a remove method, and you're overriding it?
This sounds like a composite view situation, have you considered having a view for every model in the collection?


text:
Q: Word for "exaggerated to the point of no longer resembling the truth"? Like when a historical event has been retold and changed so many times that nobody knows the truth anymore. Like the Trojan Horse or the legend of Arthur or whatever.  "The event was ___. "

A: I would use the verb to mythologize.

1.1 Create or promote an exaggerated or idealized image of.

The event was mythologized.

Given the etymology of myth, I think its relation to truth is self-evident.

8.the talk of men, rumour, Soph., Eur.

A: Retelling a historical event of greater significance can easily deflect to exaggeration. Historical events are retold in books, online media, or more commonly in documentaries or feature-length movies. Some authors tend to be delinquent by stripping off the facts and adding events of personal interest to make the story attractive and intriguing. Such content additions, to make an original event more fascinating and sensational is called "embellishment."
Therefore, we can say: "The event was embellished."
Embellishment (Noun)
Definition 1: A decorative detail or feature added to something to make it more attractive.
Example: 'architectural embellishments.'
Definition 2: A detail, especially one that is untrue, added to a statement or story to make it more interesting.
Example: 'stripped of her embellishments, the core of hard fact was disappointingly small.'
More example sentences:
'Every time the story was told, a little more was added, a few embellishments created, until finally the story was unrecognizable as what really happened, but I liked it better that way, and so did everyone else.'
'An extraordinary story is told, then retold with embellishments and remodeled with favorable points emphasized while unfavorable ones are dropped.'
'If you have a chance to see the movie, you'll hear the main character's father tell the story, with the sort of embellishments that have nourished all the Alexander legends through the centuries.'
Source: OED


text:
Q: Getting HTTP 500 Internal Server Error, Webservice PHP/NuSOAP on resultset with more than 1000 rows I handle a small webservice with two methods, everything is running great until the resulset returns more than 1000 rows.
I know I have to put some code here, but the project is very confidential, so I put only basic Nosuap object parameters.
$namespace = 'urn:server';
$server = new nusoap_server;
$server->configureWSDL('SOME_NAME', $namespace);
$server->wsdl->schemaTargetNamespace = $namespace;
$server->register('ws_consultar_reclamos',
array('fechas' => 'tns:fechas_array'),
array('return' => 'tns:reclamacion_array'),
$namespace,
'urn:server#ws_consultar_reclamos',
'rpc',
'encoded');

I repeat, everything runs great until the resultset has more than 1000 rows.
I'm using PHP with NuSOAP.
Is there any configuration that I have to change to accept a bigger resultset?
Please help me, I'm running out of time with this situation.
Thanks a lot!

A: In case you haven't done it yet, activate logging:
error_reporting  =  E_ALL
log_errors = On

Have you tried to increase the memory limit in php.ini?

A: script may be timing out.  perhaps try settig the script timeout higher with
set_time_limit();

set_time_limit()

or modify it in your php.ini file.  its default to thirty so if you change it to 60 and all of a sudden 1000 rows works this is probably your issue.  5 minutes should be a safe bet, but good luck getting a user to wait that long.


text:
Q: SharePoint Tabs - Parent/Child Integraty? I need to develop a SharePoint 2010 application which will be having more than 120 Fields.
I would like to break the Fields into smaller modules (i.e., Summary, Impact, Dependencies, Plan, Decision, Closure, Documents) and thought of creating Lists to store the details separately.
Now, how do I ensure the referential integrity is maintained? means that, how do I maintain/pass the primary key value across the different tabs? what kind of webpart I can use?
or it is better to develop a classic aspx application.

A: You need to establish what the base point of entry will be so that all of your separate lists will have something to look up to.
This can live as a single form, but you'd need to submit the information to your master list first, get the list item id it generates and then split off the other segments in separate calls so you can set a lookup column to the created master item.
On display and edit forms, you'll need to use a data source that links all the lists together so you can render the sections as appropriate.
Mark Rackley has a few blog posts on creating parent/child relationships that might be of some use.
http://www.sharepointhillbilly.com/Lists/Posts/Post.aspx?ID=4


text:
Q: ios uiwebview stop request when shouldstartloadwithrequest I am receiving shouldstartloadwithrequest event and I need to stop request for some conditions. How to stop uiwebview request when shouldstartloadwithrequest? Thank you

A: You can invoke the stopLoading method for the UIWebView. Below code will check if the webview is loading and stop it.
   if([webView isLoading]) {
      [webView stopLoading];
   }

EDIT: After re-reading your question, I understood you want to return NO in the request to stop it from beginning to load, so you would do something like:
-(BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType {

    //Check your condition:
    if(myCondition == TRUE)
         return NO;

    return YES;
}

A: Check for the condition, then return NO in shouldStartLoadWithRequest. Make sure to set delegate appropriately and include the UIWebViewDelegate protocol in the interface of the delegate class.


text:
Q: Splash Theme is not changing anymore I followed this link
to create a SplashActivity which displayed a small icon while loading the MainActivity. Everythink worked fine and I could implement the icon successfully. Now I'm trying to change the icon for the SplashActivity but the Problem is that the icon in the application on my device is not updated. Everything else I change in the code will be updated successful expect the theme.
window_background.xml:
<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android"
android:opacity="opaque">

<item android:drawable="@color/white"/>
<item>
    <bitmap
        android:src="@drawable/logo"
        android:gravity="center"/>
</item>
</layer-list>

styles.xml:
<resources>

<!-- Base application theme. -->
<style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
    <item name="colorPrimary">@color/colorPrimary</item>
    <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
    <item name="colorAccent">@color/colorAccent</item>
</style>

<style name="AppTheme.LauncherTheme">
    <item name="android:windowBackground">@drawable/window_background</item>
</style>

AndroidManifest.xml:
<application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:theme="@style/AppTheme">
    <activity android:name=".SplashActivity"
        android:theme="@style/AppTheme.LauncherTheme"
        android:screenOrientation="sensorPortrait">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
...
</application>

I nearly tried everything to update the code (Clean Project, Rebuild Project, Invalidate Caches, restart Android Studio, Delete App on Device etc.) but just the theme is not working correctly on the device, everything else works.
Does anyone have a solution how to display the correct theme?
EDIT:
Even if I remove the theme from the mainfest file the theme is still there..
EDIT 2:
I figured out that the currently displayed icon is the standard ic_launcher icon which is centered in the middle. So the window_background.xml is completly ignored from the theme and I still don't know why. I also tried to set different themes as the parent for the AppTheme.LauncherTheme but it does not change anything. If I remove the AppTheme.LauncherTheme then the SplashActivity is emtpy and the ic_launcher icon is removed.

A: AppTheme.LauncherTheme should extend one of the Theme.AppCompat themes. I suggest such solution:
<style name="AppTheme.LauncherTheme" parent="AppTheme">


text:
Q: As lines are added to a file, how do I detect and read them in using a single file descriptor or stream? Background -
I'm trying to use node.js and the fs module to accomplish an end goal of monitoring a file, and detecting the lines that have been appended to it.
Current Implementation -
I'm currently using fs.watch to monitor the changes to the file persistently, and fs.readFile to read the file once the watch has been triggered.
Drawbacks -
The downside of this implementation is that it is computationally expensive and slow to derive the appended lines in this manner, especially since it requires reading in the entire file contents despite my interest in only the appended lines.
Ideal Solution -
I would like to instead use fs.createReadStream to somehow read the file up until the end, leave the file descriptor at the end, and start reading again once the file has been appended to.
I've found two ways to read the contents of a stream buffer, but in both implementations, which are readable.read() and readable.on('data',...), it seems the stream is ended once there is no more data to read, although the stream is not closed. I'm not exactly sure how to continue using a ended stream, as readable.resume() does not seem to do anything.
My Question -
How do I read appended lines from a file in a way that is triggered once the file is modified? Is my ideal solution down the right track?
Thank you for your time and help!

A: This is a problem I once had, and it was quite a headache. This is the implementation that I came up with.
var fs = require('fs');

var file = __dirname + '/file.log';
fs.stat(file, function(err, stats) {
  var start = stats.size;
  // read the entire file here if you need it
  watchFile(start);
});

function watchFile(start) {
  fs.watch(file, function(event, filename) {
    fs.stat(file, function(err, stats) {
      var stream = fs.createReadStream(file, {
        start: start,
        end: stats.size
      });

      var lines = new String();
      stream.on('data', function(data) {
        lines += data;
      });

      stream.on('end', function() {
        // you have the new lines
      });

      start = stats.size + 1;
    });
  });
};

First I find the size of the file, and pass it to a watch function. Every time the file changes, I find out the new size of the file and read from the old position to the new position. On some systems the watch function might fire twice per change, so you might want to add checks to get rid of useless reads such as when the start and end are the same byte.


text:
Q: Oracle delete user I have such table:

users:
id PK
.
.
.

workers:
id PK
user_id (FK to users)
.
.
.

evaluations:
id PK
worker_id (FK to workers)
.
.
.

And now I want to delete user. When I delete user then worker also should be deleted. How can I do this?

A: You have 2 options:

*

*Create 3 delete-statements,

*Create a cascading delete constraint.


text:
Q: How to write a recursive method that takes a string as an argument and returns that string turned inside out? You may assume that the argument string is non-null, not empty, and doesn't contain any spaces or punctuation.
This is the code that I have so far I think you first might have to reverse it so I tried to reverse at least one half but obviously you can tell that I dont know what I'm doing and how would you write this recursively.
public static String reverseString(String s) {
    return new (StringBuffer(s).reverse().toString()/2);
}

SO example: if the string was "abcde" it should return "cbdae"
if the string was "pq" then return"pq"
if the string was "321123" then return "112233"
How can I implement this?

A: While writing a recursive method, you need to keep in the following 2 aspects

*

*Terminating logic

*Repeating logic

For your present problem, the terminating case will be that either the string is null or has only 1 character. In both these cases, the value returned will be the string itself.
The repeating logic in your case is that the first letter of your string needs to be appended AFTER the reverse of the rest of the string.


text:
Q: Range of values for which the integrals converge I have two integrals
(i) $\int_\gamma e^{z^2}dz$ where $\{\gamma: z=se^{i\alpha}: -\infty<s<\infty\}$
(ii) $\int_0^{\infty}\frac{x^\beta dx}{1+x}$
I know that the first integral converges for $\pi/4\le\alpha\le 3\pi/4$ or $5\pi/4\le\alpha\le 7\pi/4$ and the second one converges for $-1<Re\beta<0$ where $Re$ refers to the real part of $\beta$
How can I derive these intervals? I do not see this from simply looking at the integral.


text:
Q: FRAMESET to IFRAMES I'm trying to convert some old code that uses FRAMESET to use IFRAMEs . The old code results in two horizontal frames.
<frameset rows="400,250" cols="*" framespacing="0" frameborder="yes" border="1">
<frame name="up" src="up.php" scrolling="yes" id="topFrame"  >
<frame name="below" scrolling="yes" target="main" id="belowFrame" src="below.php" >

how to do that suing iframes please ?

A: You will be able to achieve this by applying position:fixed to two separate iframes.
Working Example:

iframe {
display: block;
position: fixed;
left: 0;
border: none;
border-bottom: 2px solid rgb(191, 191, 191);
width: 100%;
}

#topFrame {
top: 0;
height: 400px;
}

#bottomFrame {
top: 401px;
height: 250px;
}
<iframe id="topFrame" src="">
<iframe id="bottomFrame"src="" >


text:
Q: how to delete value from database if it is not present in the array db.query('DELETE FROM position WHERE position <> ALL ($1)',[req.body.positionDetails.position],function(err,data){
  if (err) return callback(new Error(err));
  console.log('deleted')
})

Here I want to delete position value from the database which is not present in the array.
The array is like:
{
   "positionDetails":[
      {
         "position":"developer",
         "fullTime":"true",
         "unit":"er",
         "office_country":"india",
         "office_city":"gyu",
         "technology":"ghj",
         "framework":"fgb",
         "position_start":"1-2-2012",
         "position_end":"3-12-2020",
         "company_id":"1",
         "monthly_target":"200",
         "wage":"sdfg"
      },
      {
         "position":"manager",
         "fullTime":"true",
         "unit":"er",
         "office_country":"india",
         "office_city":"gyu",
         "technology":"ghj",
         "framework":"fgb",
         "position_start":"1-2-2012",
         "position_end":"3-12-2020",
         "company_id":"1",
         "monthly_target":"200",
         "wage":"sdfg"
      }
   ]
}

But it is deleting all the values from the database how to solve this??

A: var anyvalue=""
data.positionDetails.position.map((item,i)=>{
    if(item == DELETE_ITEM) {
        anyvalue += item+","
    }
})

NOTE : You have to remove last , from anyvalue by using trim or anyother functionality.
db.query('DELETE FROM position WHERE position IN (anyvalue),[data.positionDetails.position],function(err,data){
  if (err) return callback(new Error(err));
  console.log('deleted')
})

As postionDetail have position field which will delete specific position object.


text:
Q: scala - timer sample I have this piece of code, trying to build a timer that will decrease a given value in a TextField (which is supposed to contain minutes needed to finish a job, but those minutes will be given manually and then be decreased by this clock):
import scala.swing._

class ScalaTimer(val delay: Int) {
  val tmr: javax.swing.Timer = new javax.swing.Timer(delay, null)
  def start() = tmr.start()
  def stop() = tmr.stop()
}

object Test33 { //extends SimpleSwingApplication {
  val timer = new ScalaTimer(50)
  timer.tmr.start
  //def top = new MainFrame {
 def main(args: Array[String]) {
    timer.tmr.addActionListener(Swing.ActionListener(e => {
    println(timer.delay - 1)
    }))
 }
 //}
}

I don't get why it doesn't print anything when I use a main() method, but it prints the current given delay when I use a Frame :|

A: It won't print anything with your code as it stands because your application exits as soon as it's added the ActionListener, and before anything has had a chance to fire it!
Try adding
Thread.sleep(10000);

just before the end of your main method, and you'll find it'll print 49 repeatedly.
It works as it stands with a Frame because that prevents the application from terminating until the Frame is closed.


text:
Q: Hide username completely while the machine is auto logging in I have a unique requirement, I have setup a PC which would auto login to a particular user id say 'autologinuser', when ever we switch on the PC it would automatically logs into 'autologinuser' as configured.
During the login, it would show which using is getting logged in with welcome text under it.
I would like to hide the user name and don't want to visible during auto login process, only windows text should be visible.
Can this be possible?
Thanks & Regards,
-Anil Katta

A: Looks like windows operating system don't provide this feature at this point of time, and there is no specific registry to do so.
May be this feature good to expect in future releases.


text:
Q: What to use instead of sun.net.www.protocol.http.HttpURLConnection.userAgent? I receive this warning

[javac] SSLTunnelSocketFactory.java:120: warning:
  sun.net.www.protocol.http.HttpURLConnection is Sun proprietary API and
  may be removed in a future release
  [javac] + sun.net.www.protocol.http.HttpURLConnection.userAgent

for
  if(NetworkUtils.isIPV6Compatible()&& NetworkUtils.isValidIPV6Address(host)){
     msg = "CONNECT [" + host + "]:" + port + " HTTP/1.0\n"
       + "User-Agent: "
       + sun.net.www.protocol.http.HttpURLConnection.userAgent
       + "\r\n\r\n";
  }

Do you have an idea what can I use instead (preferably not a an external jar but from the installed JVM)?

A: By default that variable is defined as follows:
String javaVersion = "Java/" + System.getProperty("java.version");
String userAgent = System.getProperty("http.agent") == null ? javaVersion : System.getProperty("http.agent") + " " + javaVersion;

So you can replace that variable with this one or with the name of your application or with any other string you like (since the resulting string is not the User-Agent of a common browser I assume that no JavaScript or any other code will check for it).


text:
Q: Django rest framework: CreateAPIView, when the data is stored I want to use the primary key I'm pretty new to django and python and could use some help. Currently an API-call can be made to my app, which stores the data. But I need to do some business logic after the storage. How do I do this.
my view:
class ProcList(generics.CreateAPIView):
    queryset = Proc.objects.all()
    serializer_class = ProcSerializer
    permission_classes = (IsAdminOrReadOnly,)
    lookup_url_kwarg = 'proc_id' # primary key

my serializers:
class BlobSerializer(serializers.ModelSerializer): # Child (Old Avatar)
    key = serializers.CharField()
    value = serializers.CharField()
    class Meta:
        model = Blob
        fields = ('pk', 'key', 'value')

class ProcSerializer(WritableNestedModelSerializer): # Father (Old profile)
    blobs = BlobSerializer(many=True)
    class Meta:
        model = Proc
        fields = (
            'pk',
            .... Hidden/removed for length purpuse
            'service',
            'country_code',
            'blobs'
        )

my model (only the Proc-one, since the Blob-model is not important)
class Proc(models.Model): # Father (Old profile)
    MY_SERVICES = (
        ("em", 'Email'),
        ("sm", 'SMS'),
        .... Hidden/removed for length purpuse
    )
    proc_id = models.AutoField(primary_key=True, help_text="Primary key")
    service = models.CharField(max_length=2, choices=MY_SERVICES, blank=True, default='mc', help_text='What service is desired, MyChoice is default')
    .... Hidden/removed for length purpuse
    country_code = models.CharField(max_length=255)
    created_at = models.DateTimeField(auto_now=True, name='created_at')

My desired outcome is that the API-post-call, stores to the Proc and Blob model as they do now. Given what the "service"-variable is, I want to pass on the primary key to another mode. Ex. Sms.proc(proc_id)
Example (ugly, sorry =)
class ProcList(generics.CreateAPIView):
    queryset = Proc.objects.all()
    serializer_class = ProcSerializer
    permission_classes = (IsAdminOrReadOnly,)
    lookup_url_kwarg = 'proc_id' # primary key

    queryset.get.service # somehow fetch the service-variable from the record created in Proc-model.
    queryset.get.proc_id # somehow fetch the primary key from the record created in Proc-model.

   if service == 'sms':
        Sms.store(proc_id) # Not really important what this looks like. Only how i can get the proc_id and do whatever I want
   elif service == 'email':
        Sms.store(proc_id)

THanks for your help!

A: With thanks to @drec4s i solved it:
class ProcList(generics.CreateAPIView): # Endast Create för att skapa en proc
    queryset = Proc.objects.all()
    serializer_class = ProcSerializer
    permission_classes = (IsAdminOrReadOnly,)
    lookup_url_kwarg = 'proc_id'

    def perform_create(self, serializer):
        q = serializer.save()
        TmpLogg(entry=q.service).save() # the other variable i need

I can now use service or proc_id how I like.