text:
Q: SplashScreenImage as Background: little jump at the start? I've the same image as SplashScreenImage and as background, the effect is nice but at the start, after the loading, my image slides a bit on the top..
It's pretty visible (and disturbing) as effect, because the image is the same..
I'm using the ApplicationBar (all visible), don't know if it's a problem.
I've setted the background image as "Uniform to fill" (tried all btw) in my LayoutRoot, I've a Pivot control.

A: The problem is really the ApplicationBar, if you set it opacity to something like "0.99" you problem should go away.
But the best result may be just by having a second image, with 480x728 (the ApplicationBar is 72px height, so 800 - 72 = 728)


text:
Q: SignalR + posting a message to a Hub via an action method I am using the hub- feature of SignalR (https://github.com/SignalR/SignalR) to publish messages to all subscribed clients:
public class NewsFeedHub : Hub
public void Send(string channel, string content)
{
    Clients[channel].addMessage(content);
}

This works fine when calling "Send" via Javascript, but I would also like the web application to publish messages (from within an ASP.NET MVC action method). I already tried instantiating a new object ob NewsFeedHub and calling the Send method, but this results in an error (as the underlying "Connection" of the Hub is not set). Is there a way to use the Hub without a connection?

A: Please note that the SignalR API has changed multiple times since this question was asked. There is a chance that some answers will become out of date. This does not mean that they should be down-voted as they were correct at the time of writing
There is another updated answer for this, as seen in the SignalR Wiki
c#
Public ActionResult MyControllerMethod()
{
    var context = GlobalHost.ConnectionManager.GetHubContext<MyHub>();
    context.Clients.All.methodInJavascript("hello world");
    // or
    context.Clients.Group("groupname").methodInJavascript("hello world");
}

vb.net
Public Function MyControllerMethod() As ActionResult
    Dim context = GlobalHost.ConnectionManager.GetHubContext(Of MyHub)()
    context.Clients.All.methodInJavascript("hello world")
    '' or
    context.Clients.Group("groupname").methodInJavascript("hello world")
End Function

Update
This code has been updated. Follow http://www.asp.net/signalr/overview/signalr-20/hubs-api/hubs-api-guide-server for changes.
If you are using DI container
If you are using a DI container to wire up your hubs, get IConnectionManager from your container, and call GetHubContext on that connectionManager.

A: 2018 February, Short and simple solution
For solving this I usually design my hubs in the following way:
public class NewsFeedHub : Hub
{
    private static IHubContext hubContext = GlobalHost.ConnectionManager.GetHubContext<NewsFeedHub>();

    // Call this from JS: hub.client.send(channel, content)
    public void Send(string channel, string content)
    {
        Clients.Group(channel).addMessage(content);
    }

    // Call this from C#: NewsFeedHub.Static_Send(channel, content)
    public static void Static_Send(string channel, string content)
    {
        hubContext.Clients.Group(channel).addMessage(content);
    }

}

So it's easy to call from Javascript and from back-end code as well. The two methods are resulting in the same event at the client.

A: I was looking for .NET Core solution and Google sent me here, seems like no one mentioned .NET Core solution, so here you go:
The Hub, nothing fancy here:
public class MyHub : Hub
{
    // ...
}

Inside your controller:
public class HomeController : Controller
{
    readonly IHubContext<MyHub> _hub;

    public HomeController(IHubContext<MyHub> hub)
    {
        _hub = hub;
    }

    public IActionResult Index()
    {
        // ...
        await _hub.Clients.All.SendAsync("ReceiveMessage", "Hello from HomeController");
        // ...
    }
}

A: Following on from DDan's answer you can create an overloaded static method and keep common logic in one method - I use this pattern
public class ChatHub : Hub
{
    private static IHubConnectionContext<dynamic> GetClients(ChatHub chatHub)
    {
        if (chatHub == null)
            return GlobalHost.ConnectionManager.GetHubContext<ChatHub>().Clients;
        else
            return chatHub.Clients;
    }

    // Call from JavaScript
    public void Send(string message)
    {
        Send(message, this);
    }

    // Call from C# eg: Hubs.ChatHub.Send(message, null);
    public static void Send(string message, ChatHub chatHub)
    {
        IHubConnectionContext<dynamic> clients = GetClients(chatHub);
        // common logic goes here
        clients.All.receiveSend(message);
    }
}

Then from your controller you can use
Hubs.ChatHub.Send(arg1, null);

A: update 2012: This answer is old, too! SignalR's public API is in constant flux, it seems. Tim B James has the new, proper API usage as of July 2012.
update 2019 Don't use this answer anymore. New versions of SignalR that work on AspNetCore should refer to the accepted answer by Tim B James, or other up-voted answers. I'm leaving this answer here for history's sake.

The currently accepted answer from Mike is old, and no longer works with the latest version of SignalR.
Here's an updated version that shows how to post a message to a hub from an MVC controller action:
public ActionResult MyControllerMethod()
{
     // Important: .Resolve is an extension method inside SignalR.Infrastructure namespace.
     var connectionManager = AspNetHost.DependencyResolver.Resolve<IConnectionManager>();
     var clients = connectionManager.GetClients<MyHub>();

     // Broadcast to all clients.
     clients.MethodOnTheJavascript("Good news!");

     // Broadcast only to clients in a group.
     clients["someGroupName"].MethodOnTheJavascript("Hello, some group!");

     // Broadcast only to a particular client.
     clients["someConnectionId"].MethodOnTheJavascript("Hello, particular client!");
 }

redpajama_set_name: RedPajamaStackExchange


text:
Q: List of FFMPEG audio formats and their file extensions I've tried to find information about this but to no avail.
What audio formats and their file extensions are supported by FFMPEG?
Is there a command that can list them all?

A: Unfortunately there is no list with extensions.
However you can look up common extensions per muxer.

*

*List all codecs. You can narrow it down with selecting only DEA (Decoding supported, Encoding supported, Audio codec)

ffmpeg -hide_banner -codecs | grep DEA
Now you get a long list.
Take e.g. DEA.LS dts         DCA (DTS Coherent Acoustics) (decoders: dca ) (encoders: dca )

*

*Now query the common extensions for dts:

ffmpeg -hide_banner -h muxer=dts
Result: Common extensions: dts.
(With other codecs you should also try demuxer=)


text:
Q: Switch shift by voltage At \$t=0\$ switch A opens, switch B closes when there is a voltage, U2. U is a DC voltage source \$> 0 \$ also is the circuit until \$t = 0 \$ in stationary state.
My question is whether switch B is open for \$t < 0\$? If yes, will it stay open after \$t=0\$? I mean the circuit isn't closed at \$t=0\$ or am I wrong?

A: Since there is no voltage across switch B in steady-state (the resistor discharges the capacitor to 0V) it should be open (the requirement is voltage >0).
Your second question is the point of this exercise-- if switch B is open, will the voltage across it be <0 or >0, given the direction of current U. BTW, this is a representation of a very common circuit configuration where the switches would be a transistor and a diode respectively.


text:
Q: Add multiple flags to windowmanager I have a WindowManager params set up like this:
  final WindowManager.LayoutParams params = new WindowManager.LayoutParams(
        WindowManager.LayoutParams.FILL_PARENT,
        WindowManager.LayoutParams.WRAP_CONTENT,
        WindowManager.LayoutParams.TYPE_SYSTEM_ALERT,
        WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE,
        WindowManager.LayoutParams.FLAG_WATCH_OUTSIDE_TOUCH,
        PixelFormat.TRANSLUCENT );

However, this is causing an error. It's fine if I remove on of the flags, but I want both. How can I do this?

A: Use a bit-wise OR for your flags to combine them bitwise: flag1 | flag2
final WindowManager.LayoutParams params = new WindowManager.LayoutParams(
    WindowManager.LayoutParams.FILL_PARENT,
    WindowManager.LayoutParams.WRAP_CONTENT,
    WindowManager.LayoutParams.TYPE_SYSTEM_ALERT,
    WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE |
    WindowManager.LayoutParams.FLAG_WATCH_OUTSIDE_TOUCH,
    PixelFormat.TRANSLUCENT );


text:
Q: Binary stream '226' does not contain a valid BinaryHeader - C# I've got a typical 'Binary stream 'x' does not contain a valid BinaryHeader', but all of the questions I've looked at online don't seem to solve my specific situation.
Issue details
The part of the program in question in it's most basic terms writes class data to a binary file. This works flawlessly 99.9% of the time, but we have recently discovered an obscure way to get the data to corrupt.
So the class which gets serialized is a public class called 'RecordEntry' marked with the [Serializable] attribute. The class inherits from an interface. 'RecordEntry' contains a bunch of variables with information, but the one that causes us an issue is an array of a class called 'EntryField'. This is an extremely simple class which holds 3 strings and is also marked as [Serializable].
If the array of 'EntryField' classes (lets call it 'EntryFieldArray'), has a length of 4, and the first string in each 'EntryField' has a length of 13, and the third string in each has a length of 1, then when trying to deserialize, I get the error in the title. There are probably a few more obscure ways to reproduce the same crash, but that's the one I've found right now.
Serialization code
Firstly, the 'RecordEntry' class is converted to bytes:
public static byte[] ToBytes(this object obj)
{
    using (var stream = new MemoryStream())
    {
        IFormatter formatter = new BinaryFormatter();
        formatter.Serialize(stream, obj);
        return stream.ToArray();
    }
}

That byte array is then added to the file as a block of data.
For reading the encrypted file back, firstly the bytes are read back in the defined blocks, and then decrypted using the following:
internal static T ObjectFromBytes<T>(this byte[] bytes)
{
    using (var stream = new MemoryStream(bytes))
    {
        IFormatter formatter = new BinaryFormatter();
        return (T)formatter.Deserialize(stream);
    }
}

Here's the important part of the stack-trace to track the error:

System.Runtime.Serialization.SerializationException : Binary stream '226' does not contain a valid BinaryHeader. Possible causes are invalid stream or object version change between serialization and deserialization.
   at System.Runtime.Serialization.Formatters.Binary.__BinaryParser.Run()
   at System.Runtime.Serialization.Formatters.Binary.ObjectReader.Deserialize(HeaderHandler handler, __BinaryParser serParser, Boolean fCheck, Boolean isCrossAppDomain, IMethodCallMessage methodCallMessage)
   at System.Runtime.Serialization.Formatters.Binary.BinaryFormatter.Deserialize(Stream serializationStream, HeaderHandler handler, Boolean fCheck, Boolean isCrossAppDomain, IMethodCallMessage methodCallMessage)
   at System.Runtime.Serialization.Formatters.Binary.BinaryFormatter.Deserialize(Stream serializationStream)
   at <ProjectName>.<ProjectFile>.ObjectFromBytes[T](Byte[] bytes)

I can't seem to trace the issue back, and some developers I've contacted about this said it could be an issue with the Microsoft serialization code. Any ideas on what could cause an issue like this?

A: You write of encryption... Perhaps there is some problem with how the encryption is done... The best thing you can do is add some checks to your serialized data.
// https://en.wikipedia.org/wiki/Jenkins_hash_function
public static uint JenkinsOneAtATimeHash(byte[] key, int start, int count)
{
    int i = start;
    int end = start + count;
    uint hash = 0;
    while (i != end)
    {
        hash += key[i++];
        hash += hash << 10;
        hash ^= hash >> 6;
    }
    hash += hash << 3;
    hash ^= hash >> 11;
    hash += hash << 15;
    return hash;
}

public static byte[] ToBytes(this object obj)
{
    using (var stream = new MemoryStream())
    {
        IFormatter formatter = new BinaryFormatter();

        // We will prepend the length of the serialized object, we leave some space
        stream.Position += sizeof(int);

        formatter.Serialize(stream, obj);

        // We append a Jenkins hash of the serialized object
        uint hash = JenkinsOneAtATimeHash(stream.GetBuffer(), 4, (int)stream.Length - sizeof(int));

        byte[] buffer = BitConverter.GetBytes(hash);
        stream.Write(buffer, 0, buffer.Length);

        // We prepend the length of the serialized object (max 2gb)
        buffer = BitConverter.GetBytes((int)stream.Length - sizeof(int) - sizeof(int));
        stream.Position = 0;
        stream.Write(buffer, 0, buffer.Length);

        return stream.ToArray();
    }
}

internal static T ObjectFromBytes<T>(this byte[] bytes)
{
    if (bytes.Length < sizeof(int) + sizeof(int))
    {
        throw new Exception(string.Format("Serialized length: {0} < {1}", bytes.Length, sizeof(int) + sizeof(int)));
    }

    int length = BitConverter.ToInt32(bytes, 0);

    if (length != bytes.Length - sizeof(int) - sizeof(int))
    {
        throw new Exception(string.Format("Serialized length should be {0}, is {1} (+ sizeof(int) * 2)", length, bytes.Length - sizeof(int) - sizeof(int)));
    }

    uint hash = BitConverter.ToUInt32(bytes, bytes.Length - 4);

    uint hash2 = JenkinsOneAtATimeHash(bytes, sizeof(int), bytes.Length - sizeof(int) - sizeof(int));

    if (hash != hash2)
    {
        throw new Exception("Wrong hash!");
    }

    using (var stream = new MemoryStream(bytes, sizeof(int), bytes.Length - sizeof(int) - sizeof(int)))
    {
        IFormatter formatter = new BinaryFormatter();
        return (T)formatter.Deserialize(stream);
    }
}

I've changed the serialization and deserialization methods. Now I prepend the length of the object and append a simple hash. It isn't a very strong hash, but it should be enough to detect changes to the data. Upon deserialization I make some checks on the length of the stream and on the hash.


text:
Q: AttributeError: module 'tensorflow._api.v1.initializers' has no attribute 'TruncatedNormal' I get the following error when I try to import sentence_transformers in python 3.6.7 and tensorflow==2.3.0. Can someone please help me with this? Seems like it's a bug in the transformers package.
import sentence_transformers
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/local/lib/python3.6/site-packages/sentence_transformers/__init__.py", line 3, in <module>
    from .datasets import SentencesDataset, SentenceLabelDataset, ParallelSentencesDataset
  File "/usr/local/lib/python3.6/site-packages/sentence_transformers/datasets/__init__.py", line 1, in <module>
    from .sampler import *
  File "/usr/local/lib/python3.6/site-packages/sentence_transformers/datasets/sampler/__init__.py", line 1, in <module>
    from .LabelSampler import *
  File "/usr/local/lib/python3.6/site-packages/sentence_transformers/datasets/sampler/LabelSampler.py", line 6, in <module>
    from ...datasets import SentenceLabelDataset
  File "/usr/local/lib/python3.6/site-packages/sentence_transformers/datasets/SentenceLabelDataset.py", line 8, in <module>
    from .. import SentenceTransformer
  File "/usr/local/lib/python3.6/site-packages/sentence_transformers/SentenceTransformer.py", line 11, in <module>
    import transformers
  File "/usr/local/lib/python3.6/site-packages/transformers/__init__.py", line 124, in <module>
    from .pipelines import (
  File "/usr/local/lib/python3.6/site-packages/transformers/pipelines.py", line 47, in <module>
    from .modeling_tf_auto import (
  File "/usr/local/lib/python3.6/site-packages/transformers/modeling_tf_auto.py", line 45, in <module>
    from .modeling_tf_albert import (
  File "/usr/local/lib/python3.6/site-packages/transformers/modeling_tf_albert.py", line 43, in <module>
    from .modeling_tf_utils import (
  File "/usr/local/lib/python3.6/site-packages/transformers/modeling_tf_utils.py", line 943, in <module>
    def get_initializer(initializer_range: float = 0.02) -> tf.initializers.TruncatedNormal:
  File "/usr/local/lib64/python3.6/site-packages/tensorflow/python/util/module_wrapper.py", line 194, in __getattr__
    attr = getattr(self._tfmw_wrapped_module, name)
AttributeError: module 'tensorflow._api.v1.initializers' has no attribute 'TruncatedNormal'

A: Try:
initializer = tf.keras.initializers.TruncatedNormal()

or
initializer = tf.compat.v1.keras.initializers.TruncatedNormal()

In tensorflow2.3.0,you can't find 'TruncatedNormal' in  module 'tensorflow._api.v1.initializers'.
Maybe this version has removed this attribute.


text:
Q: Bootstrap 4 carousel not working inside tabs Im having a hard time figuring out whats going on here. I need to show a different carousel based on a selected tab, but something seems to be in conflict as it starts breaking when switching between tabs.
Is this a library issue?

TAB1

TAB2

JS fiddle

A: Yes, this is an issue with Bootstrap 4. It is caused by the carousel indicator active class interfering with the tab-pane and carousel-item active class
The documentation vaguely mentions nesting, but it's not clear if they are referring to other components, or just carousels in general (I would assume the latter)

Please be aware that nested carousels are not supported, and carousels
  are generally not compliant with accessibility standards.
https://v4-alpha.getbootstrap.com/components/carousel/

There doesn't seem to be any way around this as removing the active class breaks the carousel.

A: My code manualy add and remove class .active to/from .nav-link and .tab-pane elements. And it's work.
HTML+Bootstrap-v4.0-beta

            Overview
            Characteristic

                        Previous

                        Next

The Gibson Les Paul is a solid body electric guitar that was first sold by the Gibson Guitar Corporation in 1952.[1] The Les Paul was designed by Gibson president Ted McCarty, factory manager John Huis and their team, along with guitarist/inventor Les Paul.

The Les Paul was originally offered with a gold finish and two P-90 pickups. In 1957, humbucking pickups were added, along with sunburst finishes in 1958. The sunburst 1958–1960 Les Paul – today one of the best-known electric guitar types in the world – was considered a failure, with low production and sales. For 1961, the Les Paul was redesigned into what is now known as the Gibson SG. This design continued as a separate guitar when the traditional single cutaway, carved top bodystyle was re-introduced in 1968. The Les Paul has been continually produced in countless versions and editions since. Along with Fender's Telecaster and Stratocaster, it was one of the first mass-produced electric solid-body guitars. Les Pauls have been used in many genres, including rock, country, pop, soul, rhythm and blues, blues, jazz, reggae, punk, and heavy metal.

                            Construction

                            Body type
                            Solid, Single cut

                            Neck joint
                            Sent-in

                            Scale
                            24.75"

                            Woods

                            Body
                            Mahogany, Maple top

                            Neck
                            Mahogany

                            Fretboard
                            Ebony

                            Hardware

                            Bridge
                            Tune-o-matic

                            Pickup(s)
                            A Burstbucker 3 humbucker at the bridge, P-90H at the neck, and a piezoelectric built into the bridge.

JavaScript
jQuery(document).ready(function() {

  let activeTab = $('#myTabs a').filter('.active');

  $('#myTabs a').click(function(e) {
    e.preventDefault();

    activeTab.removeClass('active');
    $(activeTab.attr('href')).removeClass('active');

    activeTab = $(this);

    activeTab.addClass("active");
    $(activeTab.attr('href')).addClass('active');
  });
});

CodePen

A: I had the same problem and found a workaround for my own project. I have 5 tabs, the first (home page) had a carousel in it, the other 4 were just standard pages. I don't have time to implement it for your example, but just briefly, this is how I fixed mine:
1.
Save the current page/tab id to a variable on load, by searching for the link with a class of active. Take off the hash so we can use it to target the newly clicked element.
var currentPage = $('.nav-item a').filter('.active');
var pId = $(currentPage).attr('href');
var currentPageId = pId.substring(1, pId.length);
var prevPageId;
var pageId;

2.
When a new tab is clicked, save the initial tab/page id as a variable (prevPageId), get the id of the current page, then manually reset and update the classes on the previous and current tabs. This is the part that Bootstrap is messing up. For me it was intermittently removing the 'fade' class, and sometimes having two tabs with 'active'. Also, when I clicked back to the carousel (tab 1), it was not adding a class of 'active' to the 1st carousel item, so I have to do this manually.
jQuery(document).ready(function() {

 $(".nav-item a").click(function(event) {

  prevPageId = currentPageId;
  var href = $(this).attr('href');
  pageId = href.substring(1, href.length);
  currentPageId = pageId;
  event.preventDefault();

  $('#' + prevPageId).removeClass('tab-pane fade show active');
  $('#' + prevPageId).addClass('tab-pane fade');
  $('#' + prevPageId).attr("aria-expanded","false");

  $('#' + currentPageId).removeClass('tab-pane fade');
  $('#' + currentPageId).addClass('tab-pane fade show active');
  $('#' + currentPageId).attr("aria-expanded","true");

  if (currentPageId === 'home') {
     $('.carousel-item:first').addClass('active');
  }

 });

});

I'm new-ish to this so the above code could be better I'm sure but it works, that's the main thing!

A: If you can compile the bootstrap from the source all you have to do is to exlude the '.carousel-item' selector. Edit '\js\src\tab.js' and just replace (line 151 at the time of writing):
const active = $(container).find(Selector.ACTIVE)[0]

with:
const active = $(container).find(Selector.ACTIVE).not('.carousel-item')[0]

A: Hi this is due to interference .active class tab with carousel
 $( ".carousel-inner .carousel-item" ).first().addClass( "active" );


text:
Q: PHP PDO Multiple update query inserts garbage into the table I am receiving a JSON object from my client side, which contains the attributes of a location in a random order.
Almost each component of the address can be either followed, or preceded by the other.
For example: the state may come before or after the, country, and the city may be anywhere in between.
So I've created a function, that dynamically binds the each parameter to the place where it belongs.
But for some reason, the only thing that I get in my DB, is garbage positive and negative integers.
simple debugging, by echo - ing the generated queries and the bound values didn't help much.
Here is the output for example(First the query, then the bound params in the following form:
 :param --- value) :
    [1]UPDATE locations SET active = :active,locality = :locality,local_area = :local_area,state = :state,state_short = :state_short,country_full = :country_full,country_short = :country_short,postal_code = :postal_code,ya = :ya,za = :za WHERE location_id = 385
    Params:
    :active --- true:locality --- Moscow:local_area --- gorod Moskva:state --- Moscow
    :state_short --- Moscow:country_full --- Russia:country_short --- RU:postal_code --- 121069:ya --- 55.7427928:za --- 37.61540089999994

    [2]UPDATE locations SET active = :active,street_number = :street_number,route = :route,locality = :locality,sub_local_area = :sub_local_area,local_area = :local_area,state = :state,state_short = :state_short,country_full = :country_full,country_short = :country_short,ya = :ya,za = :za WHERE location_id = 386+++:active --- true:street_number --- 31:route --- Glategny Esplanade:locality --- St Peter Port:sub_local_area --- St Peter Port:local_area --- Guernsey:state --- Bailiwick of Guernsey:state_short --- Bailiwick of Guernsey:country_full --- Grosney:country_short --- GG:ya --- 49.461137:za

 --- -2.5333570000000236

Code:
function updateMultipile($table, $data = array()){

    $update_query = array();
    $i = 0;
    foreach($data as $key => $value){
        $sql = "UPDATE $table SET ";
            foreach($value as $column => $updatedValue){
                $sql .= $column . " = :" . $column . ",";
            }
            $sql = rtrim($sql, ", ");

        $sql .= " WHERE location_id = " . intval($key);
        $update_query[$i] = $sql;
        $i++;
    }

    try{
        $conn = DBLink::getInstance();
        $j = 0;
        $success = 0;
        foreach($data as $fieldset => $value){
            echo('[1]');
            $sth = $conn->prepare($update_query[$j]);
            echo $update_query[$j] . "+++";
            foreach($value as $key => $myValue){
                $myKey = ':' . $key;
                $sth->bindValue($myKey, $myValue); //PDO::PARAM_STR);
                echo($myKey . " --- " . $myValue);
            }
            if($sth->execute()){
                $success++;
            }
            else{
                echo $sth->errorCode();
            }

            $j++;
        }
    }
    catch(PDOException $err){
        echo $err::getMessage;
    }

    return $success;
}

A: Mysql do not support multiple updates nor multiple queries (my default).
you need to run these updates separately
I see now you're running them separately already. You know it's hard to run a code using your head, not computer.
Apart from your problem with this code, why not to use some database wrapper? To make the code as simple as
function updateMultipile($table, $data = array())
{
    $db = DBLink::getInstance();
    foreach($data as $id => $update)
    {
        $sql = "UPDATE ?n SET ?u WHERE location_id = ?i";
        $db->query($table,$update,$id);
    }
}

A: Anyways, seems that the problem was that I was trying to execute the same statement several times, or perhaps that bindParam, doesn't work in a foreach loop when provided with a value ($myValue), I would've used $value[$myKey] instead, since this functions receives a reference and not a value.
anyway, I 've decided that for my needs in this case, bindValue is sufficient.
Works like a charm.
function updateMultipile($table, $data = array()){
    $update_query = array();
$i = 0;
    foreach($data as $key => $value){
        $sql = "UPDATE $table SET ";
            foreach($value as $column => $updatedValue){
                $sql .= $column . " = :" . $column . ",";
            }
            $sql = rtrim($sql, ", ");

        $sql .= " WHERE location_id = " . intval($key);
        $update_query[$i] = $sql;
        $i++;
    }

try{
    $conn = DBLink::getInstance();
    $j = 0;
    $success = 0;
    foreach($data as $fieldset => $value){
        $sth[$j] = $conn->prepare($update_query[$j]);
        foreach($value as $key => $myValue){
            $myKey = ':' . $key;
            $sth[$j]->bindValue($myKey, $myValue); //PDO::PARAM_STR);

        }
        if($sth[$j]->execute()){
            $success++;
        }
        else{
            echo $sth[$j]->errorCode();
        }

        $j++;
    }
}
catch(PDOException $err){
    echo $err::getMessage();
}

return $success;
}


text:
Q: String corrupted or preg_match bug? The NO-BREAK SPACE and many other UTF-8 symbols  need 2 bytes to its representation; so, in a supposed context of UTF8 strings, an isolated (not preceded by xC2) byte of non-ASCII (>127) is a non-recognized character... Ok, it is only a layout problem (!), but it corrupts the whole string?
How to avoid this "non-expected behaviour"? (it occurs in some functions and not in others).
Example (generating an non-expected behaviour with preg_match only):
  header("Content-Type: text/plain; charset=utf-8"); // same if text/html
  //PHP Version 5.5.4-1+debphp.org~precise+1
  //using a .php file enconded as UTF8.

  $s = "THE UTF-8 NO-BREAK\xA0SPACE"; // a non-ASCII byte
  preg_match_all('/[-\'\p{L}]+/u',$s,$m);
  var_dump($m);            // empty! (corrupted)
  $m=str_word_count($s,1);
  var_dump($m);            // ok

  $s = "THE UTF-8 NO-BREAK\xC2\xA0SPACE";  // utf8-encoded nbsp
  preg_match_all('/[-\'\p{L}]+/u',$s,$m);
  var_dump($m);            // ok!
  $m=str_word_count($s,1);
  var_dump($m);            // ok

A: This is not a complete answer because I not say why some PHP functions "fail entirely on invalidly encoded strings" and others not: see @deceze at question's comments and @hakre answer.
If you are looking for an PCRE-replacement  for str_word_count(), see my preg_word_count() below.
PS: about "PHP5's build-in-library behaviour uniformity" discussion, my conclusion is that PHP5 is not so bad, but we have create a lot of user-defined wrap (façade) functions (see diversity of PHP-framworks!)... Or wait for PHP6 :-)

Thanks @pebbl! If I understand your link, there are a lack of error messagens on PHP. So a possible workaround of my illustred problem is to add an error condition... I find the condition here (it ensures valid utf8!)... And thanks @deceze for remember that exists a build-in function for check this condition (I edited the code after).
Putting the issues together, a solution translated to a function (EDITED, thanks to @hakre comments!),
 function my_word_count($s,$triggError=true) {
   if ( preg_match_all('/[-\'\p{L}]+/u',$s,$m) !== false )
      return count($m[0]);
   else {
      if ($triggError) trigger_error(
         // not need mb_check_encoding($s,'UTF-8'), see hakre's answer,
         // so, I wrong, there are no 'misteious error' with preg functions
         (preg_last_error()==PREG_BAD_UTF8_ERROR)?
              'non-UTF8 input!': 'other error',
         E_USER_NOTICE
         );
      return NULL;
   }
 }

Now (edited after thinking around @hakre answer), about uniform behaviour: we can develop a reasonable function  with PCRE library that mimic the str_word_count behaviour, accepting bad UTF8. For this task I used the @bobince iconv tip:
 /**
  * Like str_word_count() but showing how preg can do the same.
  * This function is most flexible but not faster than str_word_count.
  * @param $wRgx the "word regular expression" as defined by user.
  * @param $triggError changes behaviour causing error event.
  * @param $OnBadUtfTryAgain mimic the str_word_count behaviour.
  * @return 0 or positive integer as word-count, negative as PCRE error.
  */
 function preg_word_count($s,$wRgx='/[-\'\p{L}]+/u', $triggError=true,
                          $OnBadUtfTryAgain=true) {
   if ( preg_match_all($wRgx,$s,$m) !== false )
      return count($m[0]);
   else {
      $lastError = preg_last_error();
      $chkUtf8 = ($lastError==PREG_BAD_UTF8_ERROR);
      if ($OnBadUtfTryAgain && $chkUtf8)
         return preg_word_count(
            iconv('CP1252','UTF-8',$s), $wRgx, $triggError, false
         );
      elseif ($triggError) trigger_error(
         $chkUtf8? 'non-UTF8 input!': "error PCRE_code-$lastError",
         E_USER_NOTICE
         );
      return -$lastError;
   }
 }

Demonstrating (try other inputs!):
 $s = "THE UTF-8 NO-BREAK\xA0SPACE"; // a non-ASCII byte
 print "\n-- str_word_count=".str_word_count($s,0);
 print "\n-- preg_word_count=".preg_word_count($s);

 $s = "THE UTF-8 NO-BREAK\xC2\xA0SPACE";  // utf8-encoded nbsp
 print "\n-- str_word_count=".str_word_count($s,0);
 print "\n-- preg_word_count=".preg_word_count($s);

A: Okay, I can somewhat feel your disappointment that things didn't worked easily out switching from str_word_count to preg_match_all.  However the way you ask the question is a bit imprecise, I try to answer it anyway. Imprecise, because you have a high amount of wrong assumptions that you obviously take for granted (it happens to the best of us). I hope I can correct this a little:
$s = "THE UTF-8 NO-BREAK\xA0SPACE"; // a non-ASCII byte
preg_match_all('/[-\'\p{L}]+/u',$s,$m);
var_dump($m);            // empty! (corrupted)

This code is wrong. You blame PHP here for not giving a warning or something, but I must admit, the only one to blame here is "you". PHP does allow you to check for the error. Before you judge so early that a warning has to be given in error handling, I have to remind you that there are different ways how to deal with errors. Some dealing is with giving messages, another type of dealing with errors is by telling about them with return values. And if we visit the manual page of preg_match_all and look for the documentation of the return value, we can find this:

Returns the number of full pattern matches (which might be zero), or FALSE if an error occurred.

The part at the end:

FALSE if an error occurred [Highlight by me]

is some common way in error handling to signal the calling code that some error occured. Let's review your code of which you think it does not work:
$s = "THE UTF-8 NO-BREAK\xA0SPACE"; // a non-ASCII byte
preg_match_all('/[-\'\p{L}]+/u',$s,$m);
var_dump($m);            // empty! (corrupted)

The only thing this code shows is that the person who typed it (I guess it was you), clearly decided to not do any error handling. That's fine unless that person as well protests that the code won't work.
The sad thing about this is, that this is a common user-error, if you write fragile code (e.g. without error handling), don't expect it to work in a solid manner. That will never happen.
So what does this require when you program? First of all you should know about the functions you use. That normally requires knowledge about the input parameters and the return values. You find that information normally documented. Use the manual. Second you actually need to care about return values and do the error handling your own. The function alone does not know what it means if an error occured. Is it an exception? Then you need to do the exception handling probably as in the demo example:
<?php
/**
 * @link http://stackoverflow.com/q/19316127/367456
 */

$s = "THE UTF-8 NO-BREAK\xA0SPACE"; // a non-ASCII byte
$result = preg_match_all('/[-\'\p{L}]+/u',$s,$m);

if ($result === FALSE) {
    switch (preg_last_error()) {
        case PREG_BAD_UTF8_ERROR:
            throw new InvalidArgumentException(
                'UTF-8 encoded binary string expected.'
            );
        default:
            throw new RuntimeException('preg error occured.');

    }
}

var_dump($m);            // nothing at all corrupted...

In any case it means you need to look what you do, learn about it and write more code. No magic. No bug. Just a bit of work.
The other part you've in front of you is perhaps to understand what characters in a software are, but that is more independent to concrete programming languages like PHP, for example you can take an introductory read here:

*

*A tutorial on character code issues

*The Absolute Minimum Every Software Developer Absolutely, Positively Must Know About Unicode and Character Sets (No Excuses!)
The first is a must read or perhaps must-bookmark, because it is a lot to read but it explains it all very good.


text:
Q: How to change already developed app into both orientations Landscape and portrait? I developed app(navigation + tabbar) in portrait mode.
But now I want that if user change its orientation to landscape or
portrait then all should be rotate in that orientation.

A: You need to set each view's control autoresizingmask. You can do it through xib as well as code as per your need and add below method in all viewControllers and it should work.
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
    // Overriden to allow any orientation.
    return YES;
}

Hope this help.

A: And have a look into your ".plist", you can define "Supported interface orientations" (UISupportedInterfaceOrientations) here.


text:
Q: Can't close the modal in Ionic-vue 5.5.2 in this version of @ionic/vue@0.5.5.2 I can't use a component and assign a reference (< Login ref="modal"/>) to it to close it in the Modal component (Login.vue), so I don't know how to close it from Login.vue. I leave my code:
Home.vue
<template>
<ion-page>
    <ion-header>
        <ion-toolbar>
            <ion-title>
                Title
            </ion-title>
        </ion-toolbar>
    </ion-header>

    <ion-content class="auth-form">

        <ion-grid>
            <ion-row>
                <ion-col align-self-center>
                    <ion-button @click="openModal" expand="block" color="primary">Registrarme</ion-button>

                    o

                    ¿Tienes una cuenta?

                    <ion-button @click="openModal" expand="block" color="danger">Iniciar sesión</ion-button>
                </ion-col>
            </ion-row>
        </ion-grid>

    </ion-content>

</ion-page>
</template>

And my Login.vue:
<template>
<ion-page>
    <ion-header translucent>
        <ion-toolbar>
            <ion-title>{{ title }}</ion-title>
            <ion-buttons slot="end">
                <ion-button @click="cerrarmodal">Cerrar</ion-button>
            </ion-buttons>
        </ion-toolbar>
    </ion-header>

    <ion-content>

        <ion-list>

            <ion-item>
                <ion-label>Email</ion-label>
                <ion-input type="text"></ion-input>
            </ion-item>

            <ion-item>
                <ion-label>Contraseña</ion-label>
                <ion-input type="password"></ion-input>
            </ion-item>

        </ion-list>

        <ion-button color="primary" expand="block">Ingresar</ion-button>

    </ion-content>

</ion-page>
</template>

I've tried $ emit and $ parent.closeModal () but no luck, thanks for your help in advance.

A: I confirm that the best and simple way to solve this is calling dismiss() function of modalController.
First we must import modalController in our modal component:
import { modalController } from "@ionic/vue";

Next we can close modal like this:
async function close() {
  await modalController.dismiss();
}

Important: I use await because dismiss return a promise so it's important use it.

A: I resolved it by passing a prop "close" with the function closeModal and defining the prop "close" in the modal component and then calling it with a this.close
this.modal = await modalController.create({
                component: Login,
                componentProps: {
                  title: 'Iniciar sesión',
                  close: () => this.closeModal()
              },

            })

In modal component:
props: {
        title: {
            type: String,
            default: 'Super Modal'
        },
        close: { type: Function }
    },

cerrarmodal() {
            this.$emit('close', {
                foo: 'bar'
            })
            this.close()

        },

A: I think you can call
modalController.dismiss()

to close any open dialog... also the emit should have worked, didn't see that code

A:

<template>
  <ion-header>
    <ion-toolbar>
      <ion-button shape="round" fill="clear" @click="modalController.dismiss()">
          <ion-icon slot="icon-only" :icon="arrowBackOutline" />
        </ion-button>
    </ion-toolbar>
  </ion-header>
  <ion-content class="ion-padding">
    {{ content }}
  </ion-content>
</template>


text:
Q: Book: suicidal girl is saved by a dragon in human form, dragon community faces internal strife Read this book several years ago for free on my Kindle.
It began with a girl's attempted suicide interrupted by a man. I believe he heals her?
We later find out he is a dragon. He lives with several others who are also dragons. He eventually tells her about them.
There is contention between the dragon people about her being brought into the fold. There is internal strife in the dragon community.
It ended like there would be subsequent books.


text:
Q: Connecting cell phone and computer audio through TRS and TRRS 3.5 mm audio jacks I am trying to connect the computer audio output to the cell phone audio input and vice versa. There are two connection designs because I need to be able to connect both to a desktop and a laptop which feature different audio interfaces.

Regarding the connection I have several questions:

*

*Are the pins correctly connected?

*Will the signal levels work as is or should I amplify/attenuate them?

*Can I only connect one channel and make away with the mixer? Obviously whatever comes out the other channel will be lost, but I am interested in knowing if it is safe to directly connect the audio output of one channel to mic/line in.

*Can you think of a way of mixing the audio channels with only passive components or removing the mixer in any other way?

*The desktop has both mic in (pink color) and line in (light blue color). Which of these inputs is better suited for my application? What do I need to do differently if I connect to one or the other?

Many thanks in advance.

A: *

*They seem to be correctly connected

*Mic levels are much lower than line levels. Some audio interfaces have selectable gain control to switch between line level input and mic level input, some don't. Output volume can be decreased to match mic input. It may be a good idea to attenuate the signal for the mic input.

*Yes, it is safe to use only one channel and connect directly, except for the attenuation for mic input.

*Simply use two resistors to mix audio channels together. Add third resistor for attenuating the output.

*You can simply plug a direct cable from line out to line in, that's what it is for. The voltage levels match and you get a good quality two channel stereo link, as mic inputs tend to be single channel mono and more noisy due to lower signal level and higher amplification gain inside the PC.


text:
Q: What is the difference between 'super' and 'extends' in Java Generics I am trying to learn Java generics. I am not clear when you will use <T extends Foo> and when you will use <T super Foo>. What do each one of these things mean about T? Lets say I have <T extends Comparable> and <T super Comparable>, what do each of these mean?
I've read several tutorials at sun.com but I'm still lost. Can somebody illustrate with examples?

A: If you are asking about type parameters, then there is no <T super X> construct in Java. Bounded parameter can only extend, but it can extend more than one type. E.g
public class MyClass< T extends Closeable & Runnable >
{
  // Closeable and Runnable are chosen for demonstration purposes only
}

In this case if you see MyClass< ConcreteT > then ConcreteT must be declared as
public class ConcreteT
  implements Closeable, Runnable
{
   ...
}

For bounded wildcards, read this article.  Read section on get-put principle. Basically, super corresponds to write semantics, and extends corresponds to read semantics.

A: Remember PECS - Producer Extends Consumer Support. Also, uncle Bob discusses it well in his craftsman series. Check out http://objectmentor.com/resources/articles/The_Craftsman_44__Brown_Bag_I.pdf

A: It depends which way on the inheritance hierarchy it allows.  Assume you have a class "Child" which inherits from "Parent" which inherits from "Grandparent".
<T extends Parent> accepts either Parent or Child while <T super Parent> accepts either Parent or Grandparent.

A: There are three types of wildcards:

*

*? extends Type: Denotes a family of subtypes of type Type. This is the most useful wildcard.

*? super Type: Denotes a family of supertypes of type Type.

*?: Denotes the set of all types or any.

A: See Effective Java 2nd Edition, Item 28:
PECS
Producer extends, Consumer super
If your parameter is a producer, it should be <? extends T>, if it's a consumer it has to be <? super T>.
Take a look at the Google Collections, they know how to use it, because they got Bloch ;)

A: For me the best answer came from @BSingh, when i read the article of Uncle Bob. I resume here, the conclusion of article.
Use List< T super Suit> whenever you are going to write into the list.

When you put an Object to the List, all you care about is that the object is of a type that is compatible with type held by the list. So you want the list to take the type of that object or any of the superclasses of that object.

Use List< T extends Suit> whenever you are going to read from a list.

On the other hand, when you read from a list, you want the type you are reading to be the type contained byt the list, or a derivative from that type.


text:
Q: Guzzle + Empty response I use Guzzle to consume data from an external WS. But, I'm encountering a problem to get the data.
$body = $response->getBody()->getContents();

With the above code, I get an empty response.
If I convert the body to a stream and use this code:
$body = $response->getBody();
$stream = Psr7\stream_for($body);
$results = $stream->read(1024);

I get data but these data are truncated (1024 characters).
Why the first code didn't return any data? Is there a solution to add an "unlimited" option for the '->read' function?
I have tested many solutions, without success:
$response->getBody()->rewind();
$response->getBody()->__toString();
(string) $response->getBody()...

Thanks for your help.

A: After several hours and many many posts.... I found the solution.
The WS is built on a windows server. So, I need to modify the encodage of these datas with this code :
$response = iconv("ISO-8859-1", "UTF-8", $response);

And now it's ok, I get the results.


text:
Q: Reading till end of file in python I am reading a .exe file in binary format in python. In this, the hex editor shows null after 3 bytes. After few bytes, there is data present. But, when I am using read() function it stops until the first null occurs. Being a beginner in python, I searched up but couldn't find a solution. Here is a screenshot of file in hex editor.
http://prntscr.com/e7ubkd
Thank you


text:
Q: Reset global variables in timeit.repeat Scenario
Let test be the module we run as __main__. This module contains one global variable named primes, which is initialized in the module with the following assignment.
primes = []

The module also contains a function named pi, which alters this global variable:
def pi(n):
    global primes
    """Some code that modifies the global 'primes' variable"""

I then want to time said function using the builtin timeit module. I want to use the timeit.repeat function and get the minimum value of the timing, as a way of improving the measurement's accuracy (instead of measuring just one time, which may be subject to slow-down due to unrelated processes).
print(min(timeit.repeat('test.pi(50000)',
                        setup="import test",
                        number=1, repeat=10)) * 1000)

The problem is that the pi function behaves differently depending on the value of primes: I expected that, for each repetition, the import test statement in the setup parameter would re-run the primes = [] statement in the test, thus 'resetting' primes so that the code being executed would be identical for each repetition. But, instead, the value of primes that resulted from the previous execution is used, so I had to add the statement test.primes = [] to the setup parameter:
print(min(timeit.repeat('test.pi(50000)',
                        setup="import test \n" + "test.primes = []",
                        number=1, repeat=10)) * 1000)

Question
This leads me to the question: is there a direct way (i.e. in one statement) to 'reset' the values of all the global variables to what they were when they were first assigned in the module?
In this specific scenario adding that one statement to manually 'reset' primes works fine, but consider a case in which there are a lot of global variables, and you want to 'reset' all of them.

Side quest-ion
Why doesn't the statement import test re-run the initial primes = [] assignment?

A: Let's start with your side question, because it turns out that it's actually central to everything:

Why doesn't the statement import test re-run the initial primes = [] assignment?"

Because, as explained in the docs on the import system and the import statement, what import test does is, loosely, this pseudocode:
if 'test' not in sys.modules:
    find, load (compiling if needed), and exec the module
    sys.modules['test'] = result
test = sys['test.modules']

OK, but why does it do that?

*

*If you have two modules that both import the same module, they expect to see the same globals. And remember that types, functions, etc. defined at the top level of a function are all globals. For example, if sortedlist.py imports collections.abc to class SortedList(collections.abc.Sequence):, and scraper.py imports collections.abc to isinstance(something, collections.abc.Sequence), you'd want a SortedList to pass that test—but it won't if those are two completely independent types because they came from two different module objects that happen to have the same name,

*If you have 12 modules that all import pandas as pd, you'd be running all the Pandas initialization code 12 times. Except that some of your modules also probably import each other, so they'd each be run multiple times, and import Pandas each time. How long do you think it would take to run all the Pandas initialization 60 times?

So, reusing existing modules is almost always what you want.
And when you don't, that's usually a sign that there's something wrong with your design (which may well be the case here).
But "almost always" isn't "always". So there are ways around it. None of them are usually a good idea for live code, but for things like unit tests and benchmarking, there are three basic options that are all fine, as long as the tradeoffs are the ones you want:

*

*del sys.modules['test']. This is obviously pretty hacky, but it actually does exactly what you want here. Any existing references to the old module are completely untouched, but the next time anyone does import test, they're going to get a brand-new test module.

*importlib.reload(test). This sounds great, but it may on the one hand be overkill (notice that it forces the module source to be recompiled, which you don't need), while on the other it may not be sufficient (it doesn't actually reset the globals—if your code does primes = [] at the top level, that line gets executed, so who cares, but if your code instead does, say, globals().setdefault('primes', []) inside the pi function, you care).

*Instead of import test, manually do all the steps up through executing the module (see the examples in the importlib docs), but don't store it in sys.modules['test'] or in test, just store it in a local variable you discard after each test. This is probably the cleanest, although it does mean 6 lines of code instead of 1.


text:
Q: Data Tables to load limited data on page load first time and get more data by ajax if required i'm looking suggestion based answer as I'm doing work with data tales in cakephp to display my data. corrently i'm using datatables to display data. but the issue is all data load on first load of page, i'm supposing if data is too much in database like 100,000 records then it will create issue because it will take long time to load in view(I suppose it is not a good approach). I wanna load 100 record first time then on click next more data should be.
Problem 2
I looked cakephp plugin it is nice but only to load data for same model and controller. If I load  model "A" in controller "B" , then it does not work to display model "A" data, it keep search for model "B".
I know one is pagination option to load limited data, but i'm looking for data tables, if it exist.

A:
I know one is pagination option to load limited data, but i'm looking
  for data tables, if it exist.

Are you sure your know what you're doing? Datatables is just a script that uses client side pagination through a script that gets data from a datasource. That script can get it's data through many sources, one is AJAX. What you want is in fact pagination:
Basic concept: The Datatables script makes an AJAX call, the server side returns the paginated data as JSON and the Datatables script will process it.
Read the manuals.

*

*AJAX Datasource for Datatables

*JSON in CakePHP

*Pagination in CakePHP


text:
Q: How to pass props i.e. screenProps with Authentication flow using react-navigation I want to pass this.props to screen components from app.js, below is my code.
I tried doing same but when I pass it as screenProp it shows as undefined in screen component.
App.js
import { createAppContainer, createSwitchNavigator, createStackNavigator } from 'react-navigation';
import HomeScreen from './HomeScreen';
import MapScreen from './MapScreen';
import LoginScreen from './LoginScreen';
import RegisterDeviceScreen from './RegisterDeviceScreen';
import React, { Component } from 'react';
import {
  AsyncStorage,
} from 'react-native';

class AuthLoadingScreen extends Component {
  componentDidMount() {
    this._bootstrapAsync();
  }

  _bootstrapAsync = async () => {
    const userToken = await AsyncStorage.getItem('sessionText');
    if (!userToken) {
      await AsyncStorage.clear();
    }
    await this.props.navigation.navigate(userToken ? 'App' : 'Auth');
  };

  render() {
    return <RegisterDeviceScreen screenProps={this.props} />;
  }
}

const AppStack = createStackNavigator(
  {
    HomeScreen: { screen: HomeScreen },
    MapScreen: { screen: MapScreen },
    LoginScreen: { screen: LoginScreen },
    RegisterDeviceScreen: { screen: RegisterDeviceScreen },
  },
  {
    navigationOptions: {
      gesturesEnabled: false,
    }
  });

const AuthStack = createStackNavigator(
  {
    LoginScreen: { screen: LoginScreen },
    RegisterDeviceScreen: { screen: RegisterDeviceScreen },
    HomeScreen: { screen: HomeScreen },
    MapScreen: { screen: MapScreen },
  },
  {
    navigationOptions: {
      gesturesEnabled: false,
    }
  });

const SwitchNavigator = createSwitchNavigator(
  {
    AuthLoading: AuthLoadingScreen,
    Auth: AuthStack,
    App: AppStack,
  },
  {
    initialRouteName: 'AuthLoading',
  }
);

const AppContainer = createAppContainer(SwitchNavigator);
export default AppContainer;

When I try to log it in componentdidmount() inside homescreen component it shows screenProp as undefined.


text:
Q: Django MultiValueKeyDictError while saving data for a multistep form
class multi_form(View):
    model=Customer
    template_name='index.html'

    def get(self, request):
       return render(request, 'customer/index.html')

    def post(self,request):
        if(request.method!="POST"):
            return HttpResponseRedirect(reverse(''))
        else:
            first_name=request.POST.get("fname")
            last_name=request.POST.get("lname")
            personal_email=request.POST.get("Pid")
            official_email=request.POST.get("Oid")
            current_address=request.POST.get("Cadd")
            permanent_address=request.POST.get("Padd")
            pan_card_number=request.POST.get("Pan")
            aadhar_card_number=request.POST.get("Aadhar")
            loan_amount=request.POST.get("LAmount")
            request.session['fname']=first_name
            request.session['lname']=last_name
            request.session['Pid']=personal_email
            request.session['Oid']=official_email
            request.session['Cadd']=current_address
            request.session['Padd']=permanent_address
            request.session['Pan']=pan_card_number
            request.session['Aadhar']=aadhar_card_number
            request.session['Lamount']=loan_amount
            personal_photo=request.FILES['PhotoAttachment']
            bank_statement=request.FILES['BankAttachment']
            salary_slip=request.FILES['SalaryAttachment']
            pan_card=request.FILES['PanAttachment']
            aadhar_card=request.FILES['AadharAttachment']
            try:
                CustomerForm1=CustomerInfo(first_name=first_name, last_name=last_name, personal_email= personal_email, official_email=official_email, current_address=current_address, permanent_address=permanent_address, pan_card_number=pan_card_number, aadhar_card_number=aadhar_card_number, loan_amount=loan_amount)
                CustomerForm2=Customer(first_name=first_name, last_name=last_name, personal_email= personal_email, official_email=official_email, current_address=current_address, permanent_address=permanent_address, pan_card_number=pan_card_number, aadhar_card_number=aadhar_card_number, loan_amount=loan_amount, personal_photo=personal_photo, bank_statement=bank_statement, salary_slip=salary_slip, pan_card=pan_card, aadhar_card=aadhar_card)
                CustomerForm1.save()
                CustomerForm2.save()
                messages.success(request, "Your Response has been recorded")
                return render(request, 'customer/index.html')
            except:
                return render(request, 'customer/index.html')

So, I was trying to save fields of a multi-step form. Upon submission after only the first step and skipping the second step altogether I am displayed this error.
MultiValueDictKeyError at /
('PhotoAttachment', None)

How do I resolve this and save data of first of this form ie. CustomerForm1. I want to save data in form fields of both the forms although they contain duplicate fields
Note: If I remove the submit button in first step and CustomerForm1 from views.py then I don't get this error implying forms works fine otherwise.


text:
Q: (How to) Use Windows file explorer to find an application? I would like to open programmaticaly an application.
First i used System.Diagnostics.Process.Start(@"C:\Program Files (x86)\Program1.exe") works fine, but the application always needs to  be on the same path (not always true because different computer)
And a simple way to find it  (with mouse & click, not programmaticaly though) is to use the windows file explorer, i enter the title of my application and i find it instantly.
I would like to code that.
I thought i could use the keyboard shortcut "Home + F" and simulate the word with SendKeys.Send("blabla") but the "Home key" doesn't seem to exist with c# (at least not here https://msdn.microsoft.com/fr-fr/library/ms127847(v=vs.110).aspx)
It's a little program for children i can't expect them to find manually the path (so forget the OpenFileDialog..)
Maybe thats a very bad idea and there are another solution to find a program without knowing his path, i don't know have you got better idea?!

A: You're trying to solve the problem the wrong way.  What you're trying to "program" is the setting oft the working directory when the program is run using Explorer.  The right way to do that is to use Process.Start by passing it all of the necessary info to start the process:
var startInfo = new ProcessStartInfo("Program1.exe");
startInfo.WorkingDirectory = @"C:\Program Files (x86)\";

Process proc = Process.Start(startInfo);


text:
Q: how to draw text in QQuickItem I've been searching the internet how to draw or render text on QQuickItem but to no avail. I opt not to use QQuickPaintedItem which uses QPainter paint() function. Aside from that there is also a known issue of QQuickPaintedItem on iOS retina display devices where the display is blurred and edges were not sharp.
Please advise any possible work-around on this.

A:
Since QtDeclarative has been deprecated already, I opt not to use
  QQuickPaintedItem which uses QPainter paint() function

That statement doesn't make a lot of sense. QtDeclarative is QtQuick1, QQuickPaintedItem is part of the QtQuick2 module and has nothing to do with QtDeclarative. Furthermore, even though it uses QPainter it is still hardware accelerated using OpenGL.
Overloading a custom QQuickItem to draw text in it manually, without assistance from QPainter or any other similar class will be a very complex task.
A QQuickItem is basically the class behind QML's Item element. QML also has a Text element. QML has been designed for rapid UI development, it is entirely pointless to draw the text manually. You don't need any C++ for this, only QML:
Item {
    Text {
        text: "something"
    }
}

Take a look at the Text element and its properties, you can specify font, color and whatnot. You can directly use the element as a source for graphics effects too.

A: You can use QPainter to draw on a QImage like a canvas.  Then you can turn this into a QSGTexture that can be assigned to a QSGSimpleTextureNode.
Here is an excerpt of code I recently wrote to do this:
QColor color("steelblue");
QRect rect(0,0,aw, ah);
for(auto ch: m_charList){
    QImage canvas(rect.width(), rect.height(), QImage::Format_RGBA8888);
    canvas.fill(QColor("transparent"));
    QPainter painter(&canvas);

    QFont font = painter.font();
    //font.setPixelSize(48);
    font.setPixelSize(rect.width());
    font.setBold(true);
    painter.setFont(font);
    painter.setPen(color);

    QRect bounding = QRect(0, 0, rect.width(), rect.height());
    painter.drawText(0, 0, rect.width(), rect.height(), Qt::AlignCenter, ch, &bounding);

    QSGTexture *texture = this->window()->createTextureFromImage(canvas);
    m_textureList[ch] = texture;
}

The repo with the full working code in context is here.
There are MANY reasons to want to render like this.  You can do rotations in 3D space to QSGNodes for one.


text:
Q: Factors/divisibility of monotonically-increasing integer polynomial For positive integers $n$ and $x$, let $f_n(x)$ be a polynomial in $x$ of degree $n-1$, such that $f_n(x)$ is monotonically increasing for increasing $x \ge 1$.
Now assume that there exist positive integers $k$ and $d$ such that
\begin{align}
f_n(16k+2) = (4k+1)d \qquad\text{and}\qquad f_n(16k+3) = (8k+1)d.
\end{align}
With no other information, can anything be determined about $f_n(x)$ or $k$ or $d$?

A: The only interesting case is $n=3$.  $n=1$ is vacuous, since there are no monotonic increasing polynomials of degree zero. For $n=2$ we can solve everything, yielding
$$
f_2(x) = 4kd\,x +d(1-4k-64k^2)
$$
For $n=3$, let $f_3(x) = a_2x^2+a_1s+a_0$.  Then subtracting the two given equations we obtain
$$
a_1 = 4kd - (32k+5)a_2
$$
which then lets us obtain
$$
f_3(x) = a_2 x^2 + [4kd-(32k+5)a_2]x + [(256k^2+80k+6)a_2-d(64k^2+4k-1)]
$$
So there is for a given $k$ and $d$ a 1-parameter family of polynomials that work, but we mjust start with a large enough leading coefficient, since the derivative, at $x=1$, needs to be positive:
$$
a_2 > \frac{4d}{32k+7}
$$
For $n>3$ the two equations seriously under-determine the $m$ coefficients, and the problem becomes uninteresting again.


text:
Q: Webpack doesn't resolve json file correctly I have defined following method in a Vue page:
getIsoCountryCode: function(country){
            console.log(countries);
            return "flag-icon-" + countries.getAlpha2Code(country, 'en');
        }

The function returns flag-icon-undefined, even though it works when I test it outside the Vue/Webpack environment.
Webpack config:
const { VueLoaderPlugin } = require("vue-loader");
const path = require("path");

module.exports = {
  entry: "./lib/team-page/team.js",
  devtool: "source-map",
  watch: true,
  resolve: {
    alias: {
      flag_icon_css: __dirname + "/node_modules/flag-icon-css/css/flag-icon.css"
    }
  },
  output: {
    path: path.resolve(__dirname, "public/lib"),
    filename: "team.js"
  },
  mode: "development",
  module: {
    rules: [{
      type: 'javascript/auto',
      test: /\.(json|html)/,
      exclude: /(node_modules|bower_components)/,
      use: [{
        loader: 'file-loader',
        options: { name: '[name].[ext]' },
      }]
    },
      {
        test: /\.vue$/,
        loader: "vue-loader"
      },
      {
        test: /\.scss$/,
        use: [
            {loader: "style-loader"},

          {
            loader: "css-loader"
          },
          {
            loader: "sass-loader"
          }
        ]
      },
      {
        test: /\.css$/,
        use: [
            {loader: "style-loader"},

          {
            loader: "css-loader"
          }
        ]
      },
      {
        test: /\.js$/,
        loader: "babel-loader"
      },
      {
        test: /\.svg$/,
        loader: 'file-loader',
        options: {
          name: '../assets/flags/[name].[ext]'
        }
      }
    ]
  },
  plugins: [new VueLoaderPlugin()]
 };

I checked in the debugger, and found this piece of code in the Webpack-compiled file:
var codes = __webpack_require__(/*! ./codes.json */ "./node_modules/i18n-iso-countries/codes.json");

It still points to the node_modules folder, even though I would have expected it to be in the bundle. (Edit: this doesn't seem to matter, axios is defined in the same way and that works as expected.)
I added the rule suggested here to my config file, but it still doesn't work.
Edit: to get it to work, you have to register the locale first. For English: countries.registerLocale(require("i18n-iso-countries/langs/en.json"));


text:
Q: qt app with opencv fails at shutdown (0xC000004B) Simple qt(4.7.3) and opencv(2.3.1) app running under debug in vs2008 terminates with messages:
...
The thread 'Win32 Thread' (0x2418) has exited with code 0 (0x0).
The thread 'Win32 Thread' (0x1cc4) has exited with code 0 (0x0).
The thread 'Win32 Thread' (0xd7c) has exited with code 0 (0x0).
The thread 'Win32 Thread' (0x2108) has exited with code 0 (0x0).
The thread 'Win32 Thread' (0x17a0) has exited with code -1073741749 (0xc000004b).
The program '[472] QtArrSurf.exe: Native' has exited with code 0 (0x0).

0xC000004B error code means STATUS_THREAD_IS_TERMINATING (An attempt was made to suspend a thread that has begun termination).
Program source code:
#include <QtGui>
#include <opencv2/features2d/features2d.hpp>
int main(int argc, char *argv[]) {
    QApplication a(argc, argv);
    QPushButton b("button");
    b.show();
    QFileDialog::getOpenFileNames(&b, "Dialog", "", "Files(*.png)"); // problem trigger
    cv::SURF detectorSURF;    // just to touch opencv
    return a.exec();
}

If comment dialog everything goes smoothly without 0xc000004b and there is only one thread in program.
When dialog is executed a number of threads are spawned, which does not close with dialog:
0 > 6192    Main Thread Main Thread main    Normal  0
0   8928    Worker Thread   Win32 Thread    77a01f36    Normal  0
0   4620    Worker Thread   Win32 Thread    77a01f36    Normal  0
0   9800    Worker Thread   Win32 Thread    77a01f36    Normal  0
0   7924    Worker Thread   Win32 Thread    77a0014d    Normal  0
0   3844    Worker Thread   Win32 Thread    77a01f36    Normal  0
0   2524    RPC Thread  RPC Callback Thread 779ffd81    Normal  0
0   3068    Worker Thread   Win32 Thread    77a00552    Normal  0
...

What these threads are about?
They have silent stacks, like this:

ntdll.dll!77a01f36()
          [Frames below may be incorrect and/or missing, no symbols loaded for ntdll.dll]
          ntdll.dll!77a01f36()
          ntdll.dll!77a2471e()
          kernel32.dll!7587339a()
          ntdll.dll!77a19ed2()
          ntdll.dll!77a19ea5()

The place of interest is CvModule static object in opencv dll.
OpenCV\2.3.1\modules\core\src\system.cpp:
 CvModule cxcore_module( &cxcore_info );

In fail case i do not reach its destructor, but in good (without dialog) do.
Is this situation with 0xC000004B real problem?
Any suggestion where to look for solution?
Thanks.

A: I believe your app is not failing.
The exit code of a thread can be anything, a non zero return value from a thread does not indicate an error, it just indicates that the thread returned that value when it exited, for whatever reason.
Unless you are experiencing a crash or some other problem on exit I think you can safely ignore that non zero return value. If you want to fully understand why the thread returns this value you will need to debug the QT code and determine which thread is doing this. If you find the thread you could put a breakpoint at its exit point, to see why the logic in this function decided to return this value.


text:
Q: qt virtual keyboard disable on certain TextInputs here is example code
TextField {
id:needKeyboard
}

TextField {
id:dontNeedKeyboard
}

if i focus to every above TextFields virtual keyboard will shown to me
I want to disable qt virtual keyboard popup on certain TextField or TextInput, how is it possible?


text:
Q: Showing a function $f$ cannot be surjective Good day all!
So I have a question about the problem:
Let $E$ be a set, and $f$ be a mapping from $E$ to $P(E)$.
Consider a set $A$ such that $x$ is in $E$ but $x$ in NOT in $f(x)$
Show $f$ cannot be surjective.
My question is: How is this?
I see that if $x$ is in $A$ then $x$ is not in $f(x)$ which means $x$ is not in $P(E)$.
How is $x$ in $E$ but $x$ not in $P(E)$?
Is my understanding flawed?

A: $A=\{x\in E,\, x\notin f(x)\}\in P(E)$. So if $f$ is surjective, then there exists $y\in E$ such that $f(y)=A$. Try to show that this leads to a contradiction.
See also: https://en.wikipedia.org/wiki/Cantor's_theorem

A: Ahh, this is Cantors Theorem.
Listed here:
Non-existence of a Surjective Function from a Set to Its Subsets (Cantor's theorem)
Thanks for the help everyone!

A: If I understand your question correctly, you ask how $x\in E$ and $x\notin P(E)$ can be true at the same time.
Well, that is easy to see with an example:
Be $E=\{1,2,\}$. Then $P(E)=\{\emptyset,\{1\},\{2\},\{1,2\}\}$.
Clearly in this case none of the elements of $E$ is in $P(E)$. Note that $1\ne\{1\}$.
However note that in other cases, elements of $E$ can be elements of $P(E)$. For example, consider $E=\{\emptyset\}$, then $P(E)=\{\emptyset,\{\emptyset\}\}$. Here the only element of $E$ ($\emptyset$) is also member of $P(E)$.


text:
Q: How to solve Maven JSF project : java: package org.primefaces.model.chart does not exist? this is my first time ever working on JavaEE project. I want to add primefaces so I can use it in a JSF xhtml page. I added the dependency to the Maven file as follows.
        <dependency>
            <groupId>org.primefaces</groupId>
            <artifactId>primefaces</artifactId>
            <version>10.0.0</version>
            <scope>compile</scope>
        </dependency>

the primefaces got indexed to IntelliJ, and I was able to import it in the java code and on the xhtml page. But when I run WildFly to build and deploy the project I got this error.
jee/bravo/web/beans/ResultsBean.java:6:34
java: package org.primefaces.model.chart does not exist

How to solve this error?

A: Try removing the line <scope>compile</scope>.
It means it will only be available at compile time, but not at runtime. So everything looks OK in IntelliJ (during compile) but it is still missing on the Application Server like WildFly (during runtime).


text:
Q: Cross platform NPM start script I'm building out an Electron app that will be developed by folks on both Windows and OS X. I'd like to create a cross-platform start script. So far, I've had exactly zero luck getting something that works. The issue, I think, is that I need to set the NODE_ENV environment variable and the syntax is slightly different.
I'm hoping there's a way that I just haven't found yet. My current scripts section follows:
"scripts": {
    "start:osx": "NODE_ENV=development electron ./app/",
    "start:win": "set NODE_ENV=development && electron ./app/"
}

I'd really like to create a single "start" script and eliminate the platform-specific variants. Is it possible?

A: Environment variables are a problem in Windows.
As stated Domenic Denicola (one of the main contributors to npm) :

This is not npm's job. You can run custom Node scripts to set environment variables using process.env if you'd like, or use something that isn't environment variables (like JSON).
...
You can write custom scripts to work around connect's limitations, e.g. in your tests modify process.env.
(Reference : this issue)

So we'll manage through a JS script (Solution inspired on this commit) :

*

*Create a exec.js file in a scripts directory

*Copy the following code in exec.js :
var exec = require('child_process').exec;

var command_line = 'electron ./app/';
var environ = (!process.argv[2].indexOf('development')) ? 'development' : 'production';

if(process.platform === 'win32') {
  // tricks : https://github.com/remy/nodemon/issues/184#issuecomment-87378478 (Just don't add the space after the NODE_ENV variable, just straight to &&:)
  command_line = 'set NODE_ENV=' + environ + '&& ' + command_line;
} else {
  command_line = 'NODE_ENV=' + environ + ' ' + command_line;
}

var command = exec(command_line);

command.stdout.on('data', function(data) {
  process.stdout.write(data);
});
command.stderr.on('data', function(data) {
  process.stderr.write(data);
});
command.on('error', function(err) {
  process.stderr.write(err);
});

*Update your package.json :

"scripts": {
    "start": "node scripts/exec.js development",
}

*Run npm script : npm run start
Edit 05.04.2016
There is a very useful npm package that allows manages this problem : cross-env. Run commands that set environment variables across platforms


text:
Q: python program structure and use of global variables I have a program completed that does the following:
1)Reads formatted data (a sequence of numbers and associated labels) from serial port in real time.
2)Does minor manipulations to data.
3)plots data in real time in a gui I wrote using pyqt.
4)Updates data stats in the gui.
5)Allows post analysis of the data after collection is stopped.
There are two dialogs (separate classes) that are called from within the main window in order to select certain preferences in plotting and statistics.
My question is the following:  Right now my data is read in and declared as several global variables that are appended to as data comes in 20x per second or so - a 2d list of values for the numerical values and 1d lists for the various associated text values.  Would it be better to create a class in which to store data and its various attributes, and then to use instances of this data class to make everything else happen - like the plotting of the data and the statistics associated with it?
I have a hunch that the answer is yes, but I need a bit of guidance on how to make this happen if it is the best way forward.  For instance, would every single datum be a new instance of the data class?  Would I then pass them one by one or as a list of instances to the other classes and to methods?  How should the passing most elegantly be done?
If I'm not being specific enough, please let me know what other information would help me get a good answer.

A: A reasonably good rule of thumb is that if what you are doing needs more than 20 lines of code it is worth considering using an object oriented design rather than global variables, and if you get to 100 lines you should already be using classes.  The purists will probably say never use globals but IMHO for a simple linear script it is probably overkill.
Be warned that you will probably get a lot of answers expressing horror that you are not already.
There are some really good, (and some of them free), books that introduce you to object oriented programming in python a quick google should provide the help you need.
Added Comments to the answer to preserve them:
So at 741 lines, I'll take that as a yes to OOP:) So specifically on the data class. Is it correct to create a new instance of the data class 20x per second as data strings come in, or is it more appropriate to append to some data list of an existing instance of the class? Or is there no clear preference either way? – TimoB
I would append/extend your existing instance. – seth
I think I see the light now. I can instantiate the data class when the "start data" button is pressed, and append to that instance in the subsequent thread that does the serial reading. THANKS! – TimoB


text:
Q: Flickr API: How to get URL for sharing each photo in Set In my local webserver, I'm trying to generate the text for pasting to my blog, followed by below question:
How to get static image url from flickr URL?
[][1]

I think it's good to use some API function and to designate $variables to:

*

*53067560@N00

*2658147888

*"Chou fleurs by Nicolas de Fontenay, on Flickr"

*"http://farm4.staticflickr.com/3221/2658147888_826edc8465.jpg"

*"500"

*"375"

*"Chou fleurs"

, but don't know how to code in detail. Ideally, a function
getFlickrImageURLforGrab(name of Set, # of photos)

ex.) getFlickrImageURLforGrab(myset1, 10) returns first 10 photo's URLs in the Set myset1 are displayed. Would you please show a simple php example?

A: The answers in the question you link to refer to flickr.photos.getSizes.  You also will want to look at the doc for flickr.photosets.getPhotos.
I don't use PHP with Flickr's API, but a search turns up phpFlickr, which might help you with some of the heavy lifting.


text:
Q: Write a function to count number of Palindrome substrings in given string? Given a string aaaabaabaaaa(s to be generic), how many possible palindrome of size > 2 (n to be generic) can be generated from this string?
I need to know how to count number of palindromes and to print those.
Eg. for above string  aaa, aaaa, aba, aba, aaa, aaaa, abaaba, aaaabaabaaaa.
-Question asked in SAP(hiring for java) interview

A:  public void palindrome(String string)
 {
    char[] charArray = string.toCharArray();

    count = 0;
    i = 0;
    while(i < charArray.lenght)
    {
       if(charArray[i] == charArray[charArray.lenght - i - 1])
       {
       }
       else
       {
           System.out.println("not a palindrome");
           break;
       }
    }
}

this is the basic logic to test if it is a palindrome.
if the length of the string is even then "" is a palindrome as well or if it is odd the middle char is also a palindrome. So if((string.length()%2) == 0) then it is even or else it is an odd.
I will let you figure the rest out.


text:
Q: What is humorous about calling people "mortals"? The following definition of mortal is from Oxford Dictionaries Online:

[humorous] a person contrasted with others regarded as being of higher status or ability

It gives this sentence as an example:

an ambassador had to live in a style which was not expected of lesser mortals

Where is the humorous point of it? I can't see it.

A: This sense is a play on the contrast between mortals and immortals (specifically, the gods). By calling ordinary people mortals and contrasting them to someone else (such as ambassadors), the speaker is implying that the "immortals" think they're like the gods.

A: We are all mortals, are we not? So, using a phrase like lesser mortals suggests some sort of hierarchy that doesn't really exist. It's not the kind of humor that would make you LOL, but it might bring an amused smile.
Here's another example:

LeBron James does things on the basketball court that mortals should not be able do.

That wording elevates James to an above-human status. It's a somehat "humorous" way of saying his talents are seemingly superhuman.


text:
Q: Perfectly Straight Vertical/Horizontal Line When Pressing the Shift Key (C++ and Qt 5.8) I am performing a task to implement a perfectly straight vertical/horizontal line when the shift key is pressed in a program called EasyPaint. I have no errors in my code, but unfortunately, it also has zero effect on the program itself. When I draw a line and press shift, it does absolutely nothing. The code below is my method shiftPressEvent and my other method isMod. I tried to do a calculation of degrees to try and specify when the line should snap to a vertical alignment or horizontal alignment, but obviously, it seems to not be doing its intended job. If another set of eyes could maybe analyze the code and see where the problem lies, I'd greatly appreciate it. Also, if any further information is needed, please comment below. I can easily post the entire class of LineInstrument, but it's a tad lengthy.
Added Methods in LineInstrument.cpp Before Edits
void LineInstrument::shiftPressEvent(QKeyEvent *event, ImageArea &imageArea){
if (imageArea.isPaint())
{
    imageArea.setImage(mImageCopy);
    double Y = mStartPoint.y() - mEndPoint.y();
    double X = mStartPoint.x() - mEndPoint.x();

    radianAngle = atan2(Y, X);
    degreeAngle = radianAngle * 180 / atan(1) * 4;

    if (isMod(event->key()))
    {
        if (abs(degreeAngle) >= 45 && abs(degreeAngle) <= 135)
        {
            mEndPoint.setX(mStartPoint.x());
        }

        else if (abs(degreeAngle) < 45 && abs(degreeAngle) > 135)
        {
            mEndPoint.setY(mStartPoint.y());
        }

        imageArea.update();
    }
}
}

bool LineInstrument::isMod(int key){
if (key == Qt::Key_Shift)
{
    return true;
}

return false;
}

Added Methods in LineInstrument.cpp After Edits
    void LineInstrument::shiftPressEvent(QKeyEvent *event, ImageArea &imageArea)
{
    if (imageArea.isPaint())
    {
        imageArea.setImage(mImageCopy);
        double Y = mStartPoint.y() - mEndPoint.y();
        double X = mStartPoint.x() - mEndPoint.x();

        if (isMod(event->key()) && fabs(X) > fabs(Y))
        {
            mEndPoint.setY(mStartPoint.y());
            paint(imageArea, false);
        }

        else if (isMod(event->key()) && fabs(Y) >= fabs(X))
        {
            mEndPoint.setX(mStartPoint.x());
            paint(imageArea, false);
        }

    }
}

    bool LineInstrument::isMod(int key)

{
    if (key == Qt::Key_Shift)
    {
        return true;
    }

    return false;
}

LineInstrument Header File Before Edits
#ifndef LINEINSTRUMENT_H
#define LINEINSTRUMENT_H

#include "abstractinstrument.h"

#include <QtCore/QObject>
#include <QKeyEvent>

/**
 * @brief Line instrument class.
 *
 */
class LineInstrument : public AbstractInstrument
{
    Q_OBJECT

public:
    explicit LineInstrument(QObject *parent = 0);

    void mousePressEvent(QMouseEvent *event, ImageArea &imageArea);
    void mouseMoveEvent(QMouseEvent *event, ImageArea &imageArea);
    void mouseReleaseEvent(QMouseEvent *event, ImageArea &imageArea);
    void shiftPressEvent(QKeyEvent *event, ImageArea &imageArea);
    bool isMod(int key);
protected:
    void paint(ImageArea &imageArea, bool isSecondaryColor = false, bool additionalFlag = false);

private:
    double radianAngle;
    double degreeAngle;
};

#endif // LINEINSTRUMENT_H

LineInstrument Header File After Edits
    #ifndef LINEINSTRUMENT_H
#define LINEINSTRUMENT_H

#include "abstractinstrument.h"

#include <QtCore/QObject>
#include <QKeyEvent>

/**
 * @brief Line instrument class.
 *
 */
class LineInstrument : public AbstractInstrument
{
    Q_OBJECT

public:
    explicit LineInstrument(QObject *parent = 0);

    void mousePressEvent(QMouseEvent *event, ImageArea &imageArea);
    void mouseMoveEvent(QMouseEvent *event, ImageArea &imageArea);
    void mouseReleaseEvent(QMouseEvent *event, ImageArea &imageArea);
    void shiftPressEvent(QKeyEvent *event, ImageArea &imageArea);
    bool isMod(int key);
protected:
    void paint(ImageArea &imageArea, bool isSecondaryColor = false, bool additionalFlag = false);
};

#endif // LINEINSTRUMENT_H

A: Part of the problem is that you aren't calculating the angle in degrees properly. This line doesn't do what you think it does:
degreeAngle = radianAngle * 180 / atan(1) * 4;

That's the same as:
degreeAngle = 4 * radianAngle * 180 / atan(1);

What you should do is create a proper named constant for pi by doing something like this:
const double kPi = atan(1.0) * 4.0;

And you should probably create a function to convert radians to degrees like this:
double toDegrees(double radians)
{
    return radians * 180.0 / kPi;
}

You can also figure out whether you want horizontal or vertical snapping much more easily by simply comparing the x delta and the y delta. If X is greater than Y, then you want a horizontal line, otherwise you want a vertical one. Something like this should do the trick:
if (fabs(X) > fabs(Y))
{
    mEndPoint.setY(mStartPoint.y());
}
else
{
    mEndPoint.setX(mStartPoint.x());
}

Now whether this will fix your problem or not depends on how your drawing actually happens.


text:
Q: When is a cyclotomic polynomial over a finite field a minimal polynomial? When is the cyclotomic polynomial $f(x)$ over a finite field $\mathrm{F}_q$ also the minimal polynomial of some element $\alpha \in \mathrm{F}_q$?

A: In general, a polynomial $f\in F[X]$ is the minimal polynomial of its roots over $F$ if and only if $f$ is irreducible over $F$. Cyclotomic polynomials provide no exception.
However, while cyclotomic polymomials are irreducible over $\mathbb Q$, not all of them are irreducible when considered as a polynomial over a finite field.
For example, over $\mathbb F_2$ the $7$th cyclotomic polynomial $\Phi_7 = X^6 + X^5 + X^4 + X^3 + X^2 + X + 1$ factors into two factors of degree $3$:
$$
\Phi_7 = (X^3 + X + 1)(X^3 + X^2 + 1)
$$
Hence $\Phi_7\in\mathbb F_2[X]$ is not irreducible and therefore not the minimal polynomial of its roots.
Note: This was written as a response to an earlier version of the question.

A: One can show that the cyclotomic polynomial $\Phi_n(X)$ is irreducible over $\mathbf F_p$ precisely when $p$ has multiplicative order $\varphi(n)$ modulo $n$. This follows from the theory of cyclotomic extensions of $\mathbf Q$.
In particular, if $(\mathbf Z/n\mathbf Z)^\times$ is not cyclic (i.e. unless $n$ is an odd prime power, twice an odd prime power, or $n=2$ or $4$), then $\Phi_n(X)$ is reducible modulo every prime $p$, despite being irreducible over $\mathbf Q$!


text:
Q: sql error with foreign key I have the error here:

The INSERT statement conflicted with the FOREIGN KEY constraint "FK_CHITIETDH__MaDH__4316F928". The conflict occurred in database [...]

But with the code here :
create database abc_1quanly111
use abc_1quanly111

create table abc_1nhacc
(
    MaNhaCC   varchar(10) primary key,
    TenNhaCC  varchar(50),
    DiaChiCC  varchar(50),
    Telephone varchar(50),
)

create table abc_1mamathang
(
    MaMH   varchar(10) primary key,
    TenMH  varchar(50) not null,
    DonGia  int check (DonGia>0),
    SoLuong int ,
    MaNhaCC varchar(10) foreign key references abc_1nhacc(MaNhaCC)
)
--Insert Nha CC --- Values -----
INSERT INTO abc_1nhacc VALUES('NC1','Phong Vu','123 NTMK ','0283232677')
INSERT INTO abc_1nhacc VALUES('NC2','Phong Hoang','123 NTD ','0290120217'),('NC3','THE GIOI DI DONG','12 LE VAN VIET ','028382901'),('NC4','NGUYEN KIM','23 LE DUAN ','01283232677'),('NC5','Phong KIM','13 LE LOI ','0288292677')
select * from abc_1nhacc
--Insert Mat Hang ---- Values ----
insert into abc_1mamathang values('M1','Laptop Sony',1000000,100,'NC1')
,
('M2','Laptop MSI GAMING',3200000,1,'NC2'),
('M3','Laptop ASUS',900000,10,'NC3'),
('M4','Laptop ACER',1340000,20,'NC4'),
('M5','Xperia A',10000,10,'NC5')
select * from abc_1nhacc
select * from abc_1mamathang

create table abc_1khachhang
(
    MaKhachHang      varchar(10) primary key,
    TenKhachHang     varchar(50),
    DiaChiKhachHang  varchar(50),
    PhoneKhachHang   varchar(10),
)
--Insert Khach Hang ---- Values ----
INSERT INTO abc_1khachhang values('KH1','Anh A','121 Le Duan Q1','09878721'),('KH2','Anh B','12 Quang Trung Q12','01878221'),('KH3','Anh C','331 Nguyen Thi Minh Khai','028787221'),('KH4','Anh D','23 Le Quang Dinh','09872321'),('KH5','Bac AD','','098787211')

create table abc_1dondathang
(
    MaSoDonDatHang varchar(10) primary key,
    NgayDatHang    DATE Default GetDate(),
    MaKhachHang varchar(10) foreign key references abc_1khachhang(MaKhachHang)
)
CREATE TABLE CHITIETDH
(
     MaDH varchar(10) foreign key references abc_1dondathang,
     MaMH varchar(10) foreign key references abc_1mamathang,
      Soluong int check (soluong>0)
      constraint pk_DHMH primary key(MaDH ,MaMH)
)

select * from abc_1dondathang
select * from abc_1mamathang
select * from CHITIETDH

insert into CHITIETDH values('DH1','MH1',12) // errors

select * from CHITIETDH

I don't know solution how to fix that, can anyone help me thanks.

A: Your table CHITIETDH has a foreign key in table abc_1dondathang.
You try to insert values to CHITIETDH while abc_1dondathang is empty. You must all the values under this column MaDH varchar(10) foreign key references abc_1dondathang will exist in abc_1dondathang before you insert something in CHITIETDH.
You can read here more.


text:
Q: Python wrapper to pass arguments to bash There is an application my company wrote (a little app to create CloudFormation templates) and passed the binary for all the teams to use.
In trying to automate this a bit I wrote a Python script that basically passes arguments to a Bash/Shell command. This is a wrapper so I am just making this so I can iterate over a bunch of config files to create CloudFormation stacks in AWS.
In shell, I would do
cfapp cfn create -p Namespace=namespace -p Env=env -p Team=team -p Region=region --spec-file file://partner/foobar.yaml
I wrote this in Python but I get a syntax error:
os.system("cfapp cfn create -p Pool=%s" % pool "-p Namespace=%s" % namespace "-p Env=%s" % env "-p Team=%s" % team "-r %s" % region "--spec-file file://partner/"+str(config)+".yaml")
      time.sleep(5)

I read that this was how to do it via python though, obv, my implementation is wrong.

A: Use subprocess instead:
subprocess.check_call([
    "cfapp", "cfn", "create",
    "-p", "Namespace=%s" % namespace,
    "-p", "Env=%s" % env,
    "-p", "Team=%s" % team,
    "-p", "Region=region",
    "--spec-file", spec_file,
])

In terms of your initial error, your string formatting syntax is incorrect:
>>> pool = "foo"
>>> namespace = "bar"
>>> "cfapp cfn create -p Pool=%s" % pool "-p Namespace=%s" % namespace
  File "<stdin>", line 1
    "cfapp cfn create -p Pool=%s" % pool "-p Namespace=%s" % namespace
                                                     ^
SyntaxError: invalid syntax
>>> "cfapp cfn create -p Pool=%s -p Namespace=%s" % (pool, namespace)
'cfapp cfn create -p Pool=foo -p Namespace=bar'


text:
Q: How to safely close stream when using threads I have thread with this code:
public void run() {

try {
    fileProcessor = new FileProcessor();
    fileProcessor.process();
  } catch (RuntimeException e) {
    // ...
  } finally {
    if (fileProcessor != null) {
      fileProcessor.close();
    }
  }
}

method fileProcessor.process(); run some new thread too:
protected void process() {
    this.writer = new Writer();
    final MyClient client = new MyClient();
    client.start();
}

this code sometimes thrown exception
Caused by: java.io.IOException: Stream closed
        at sun.nio.cs.StreamEncoder.ensureOpen(StreamEncoder.java:26)
        at sun.nio.cs.StreamEncoder.write(StreamEncoder.java:99)
        at sun.nio.cs.StreamEncoder.write(StreamEncoder.java:116)
        at java.io.OutputStreamWriter.write(OutputStreamWriter.java:203)
        at java.io.Writer.write(Writer.java:140)
        at java.io.Writer.append(Writer.java:210)

how I can safely close stream? Because with fileProcessor.close(); now probably I close this stream but there are still some thread which use it.

A: use thread.join() for all threads in fileProcessor. so that it will wait until all threads finish their task.
client.start();
client.join(); // this will make sure client thread finished before proceed to next step

Link to simple tutorial on thread.join for clear understanding

A: Don't start a new thread in your process() method, run the functionality synchronously instead.
Alternatively call your close() method from within your process() method.


text:
Q: Preventing Cross-Site Request Forgery Attacks With a Windows Client Application I develop an web application by web api2.
My client application is a windows application that developed by C# , .net 4.0.
The client application sends some Json data to the web api application and the application stores data in database.
Now the issue is sending the request with another method except my application and sending dump data to the server.I have authentication on the server but it isn't enough,I need some tokens for handling this issue.
After some searches i find this article and read it, but the client is a web application.
Could i use this method in my windows client app?how?

A: Bottom line: You shouldn't need to.
By definition, CSRF attacks can only affect client applications that share cookies across domains. e.g. if you visit www.bank.com with your browser and then open another tab to www.evil.com, if www.bank.com does not protect against CSRF then www.evil.com may be able to POST a form submission to www.bank.com while you are logged in and then transfer money by forging the request to the form's action URL on the transfer money page.
If your client is a Windows application, the HTTP client should not have cookies stored for any other service other than your web API.
Note that the above only applies to when cookies are used as the session management mechanism (i.e. not Kerberos, NTLM, Basic Auth, etc).

.I have authentication on the server but it isn't enough

This should be enough as an attacker cannot forge a HTTP request to your API that will be sent along with the victim's cookies as the cookies are separated due to there being different instances of web clients. Much like being logged into Google on Chrome, but then accessing Google on Firefox - you will not share the same logged in session.
Of course, protect your API with HTTPS so the information is encrypted whilst in transit. Note that this does not protect against decompilation of your source code, which is something that is not easy to prevent. At the end of the day you cannot trust clients that are not under your control. You can make it difficult, but not impossible to prevent someone working out or changing what is being sent to your API.

A: Cross site anti-forgery tokens are a form of authentication. It authenticates the client who's sending the request: the client has to visit a certain page to get the token from the server, so it cannot be any client who has not visited that page and some how just send random data to that server.
The purpose of authentication is for the server to authenticate the client (other way around is also possible, but let's forget that for the moment). You setup the system such that it is very difficult for others to pretend to be your Windows Form app. Note it can be very difficult, but theoretically it's always possible to fake. So the aim is to setup an auth such that an attacker considers it impractical to launch an attack.
This auth should not be mixed up with the authentication to verify the human user. They are different. An app can provide a UI for human users to login, but the app is not written by you. So you need to authenticate 2 things:

*

*the request actually comes from your app, if that succeeds, then

*the human user is who he claims he is, otherwise

*reject the request


text:
Q: Add href to  tag in nav menu for mobile I have a primary menu which is displayed for desktop
<?php
 //Show the navigation menu
   wp_nav_menu(array(
     'theme_location'    =>  'primary-nav',
      'menu_class'        =>  'navigation d-block',
      'walker'            =>  new My_Walker_Nav_Menu()
        ));
 ?>

And this is the menu for mobile
<?php
  //Show the navigation menu
  if(wp_is_mobile()) {
  wp_nav_menu(array(
  'theme_location' => 'mobile-menu',
  'menu_class' => 'main-ul'
  ));
  }
?>

How can I add a href="javascript:void(0)" for the mobile menu?
Menu is:
About ˅
-child
News
Contact
I want if in mobile when About is clicked to show the child and not link you to About page.

A: This is really a problem i think you should solve with javascript if you are looking to solve it with code. I would suggest that you could probably use the wp_is_mobile to add a class to your HTML tag
If that class exists on your html tag run some JS that binds to all the menu items in question's clicks using something like  $('.CUSTOM-CLASS-FOR-MENU-ITEM').click(e){ e.preventDefault();} and then the links on those menu items will do nothing.
although I think a much better simple solution, would be to add Custom link Items where the link is just a # mark which will do nothing as well but allow you to :focus it, :hover it etc. You already have two separate menu locations declared in wordpress why not build two different menus and replace that About menu Item with a custom link item and then there is no need for javascript whatsoever.


text:
Q: Using `mathastext` or `newtxmath` Is it more appropriate to use tgtermes with mathastext and option italic or to use newtxtext and newtxmath? I do not know if one of them is missing some functionality for math mode. I would like to have math mode typeset in times new roman, with italics. Both of the package options seem to support this, but I do not know which is more appropriate.

A: I took the testmath.tex file in the distribution of amsmath and first added
\usepackage{newtxtext,newtxmath}

This is a picture of one of its parts

Then I used
\usepackage{tgtermes}
\usepackage[italic]{mathastext}

getting

I find the latter unacceptable, given that getting the former is possible. Notably, Greek letters are in Computer Modern and the kerning is wrong. The partial derivative symbol is too wide for Times.
Of course one might not like the newtxmath integrals, but there is the option for substituting them (cmintegrals).
As a general rule, mathastext should be considered the last resort.


text:
Q: Prevent import of android.R How to prevent android.R package from autoimport in IntelliJ Idea?
It's really annoying when Idea import android.R package and you can't use R class from your project unless you delete "import android.R;" line in your code.
For example, I type this:
new ArrayAdapter<String>(getActivity(), android.R.layout.sim

then press Ctrl+Space and select first item in completion. My code now look like this:
new ArrayAdapter<String>(getActivity(), R.layout.simple_list_item_1

and the imports now have
import android.R;

When I continue typing, and reach that moment:
new ArrayAdapter<String>(getActivity(), R.layout.simple_list_item_1,
                         getResources().getStringArray(R.array.

R.array is actually android.R.array, but that's not what I expect.

A: You can try these options:

Disable Add unambiguous imports on the fly or add android.R to Exclude from Import and Completion.


text:
Q: Java Math Functions for BigDecimal
Possible Duplicate:
Java BigDecimal trigonometric methods

Are there complementary mathematical functions used in java.lang.Math that fully utilize the capabilities of BigDecimal? In other words, is there a log function that takes and returns a BigDecimal similar to how there is a log function that takes and returns a double?