text:
Q: Elixir changeset custom validation I'm having a bit of trouble trying to implement a custom changeset validation.
My schema is:
defenum(VersionStateEnum, ["draft", "active"])
schema "versions" do
  field :expires_at, :utc_datetime
  field :state, VersionStateEnum
end

The validation I'm trying to implement is: The expires_at can only be set if the state is draft (this should also be valid for updates, I should not be able to remove the expires_at if the state is still draft)
I tried the following:
defp validate_expires_at(changeset) do
    expires_at = get_change(changeset, :expires_at)
    cond do
      get_change(changeset, :state) == :draft ->
        case expires_at do
          nil -> add_error(changeset, :expires_at, "can't be blank when state is draft")
          _ -> changeset
        end
      get_change(changeset, :state) == :active ->
        case expires_at do
          nil -> changeset
          _ -> add_error(changeset, :expires_at, "cannot be set when state is not draft")
        end
      true ->
        changeset
    end
  end
end

But it doesn't really work as I can update the expires_at to nil even if the state is draft. Any help is appreciated.
Edit 1:
My changeset:
@required_fields [
    :state
  ]
@optional_fields [:expires_at]
def changeset(model, params \\ nil) do
  model
  |> cast(params, @required_fields ++ @optional_fields)
  |> validate_required(@required_fields)
  |> validate_expires_at()
end

Where it's being called:
def create_document(attrs \\ %{}) do
  %Document{}
  |> Document.changeset(attrs)
  |> Repo.insert()
end

A: If I understand your problem correctly, I think that to solve it you should probably consider the struct given to the changeset as well.
Because, the way your code is, you're only checking for the state from the changes in the changeset, but if you try to update the expires_at alone, the changes in the changeset will not include the state that might already be set to "draft", and therefore, the cond block in your validate_expires_at function will always match true, because the value will be nil.
One workaround could be to update the function like:
defp validate_expires_at(changeset) do
    state = get_field(changeset, :state)
    expires_at = get_change(changeset, :expires_at)
    case state do
      :draft ->
        case expires_at do
          nil -> add_error(changeset, :expires_at, "can't be blank when state is draft")
          _ -> changeset
        end
      :active ->
        case expires_at do
          nil -> changeset
          _ -> add_error(changeset, :expires_at, "cannot be set when state is not draft")
        end
      _ -> changeset
    end
  end
end

Using get_field instead of get_changewill try to get the field from the changes, but if it wasn't changed, it can be taken from the existing struct and the rest of your function should work normally

Not sure how the atom/String handling works when inserting and retrieving from the DB. You might need to check if state could be a String when taken from the changeset's data


text:
Q: Exist an event in Javascript when the user stop select the text of a input or textarea? I have this code in Javascript:
var lastTextSelected = "";
//BOTH ELEMENTS ARE TEXTAREA
jQuery('#ingredients').select(selectedText);
jQuery('#steps').select(selectedText);

and this is the selectedText function:
function selectedText() {
        lastTextSelected = window.getSelection().toString();
}

My current objective is when the user stops selecting the current selected text of the elements, empty the content of the variable named lastTextSelected = "";
Is there an event in jQuery or Javascript for that?

A: Try the onselect event like this:

function myFunction() {
    console.log('event fired')
}
textarea{
 height: 300px;
 width: 300px;
}
<textarea id="area" onselect="myFunction()">select me</textarea>

Every time now text is selected myFunction is fired.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Replace assignment with deferred assignment In my angular.js page I extend $scope with all attributes I need.
Before, I simply extended $scope with
angular.extend($scope,{
    myAttr : aService.getValues()
});

However, turns out I have to add a promise (angular file access) to aService.getValues. Hence, I cant keep the above syntax but have to replace it with
angular.extend($scope,{
myAttr : null
});
aService.getValues().then(function(values){$scope.myAttr = values;})

That's annoying because I have to replace quite a bit of code and am afraid to add bugs. Any alternatives?

A: The only thing I can suggest is a slightly prettier re-doing of your own solution:
aService.getValues().then(function(values) {
  angular.extend($scope, {
    myAttr: values
  })
});

Is it critical that $scope is extended synchronously? If it is, I don't see any way of feeding asynchronous data into it any other way.
EDIT
If you're reworking your logic, consider using $stateProvider with a resolve property: https://github.com/angular-ui/ui-router/wiki (Scroll down to the section that talks about resolve). Long story short, everything in the resolve must run before the state controller is initialized. This way you can do all your async operations in the resolve, and only let it load after you have everything you need.


text:
Q: Change CSS with JS / jQuery when hash value in URL changes I have 6 100vw and 100vh divs on a page and a right aligned fixed nav bar.
Each of these divs has an id# from 1 - 6
The nav bar has 6 list items links which point to the id of the div,
for example:

I am using scroll spy to nicely 'scroll' to the targeted div.
This nicely places the id value in the ur.
for example:
mywebsite.com/#1
or
mywebsite.com/#2
etc
What I would like to do however is IF the url contains #1 or #2 or whatever number it may be, the list item background changes color.
I originally tried an active/not active class, however, this is done on the scroll and click so a listener for a click won't always work.
I have seen quite a few examples from previous questions on here, however the the closest I could get would be something like this:
function locationChange() {
 if(location.hash == "#1") {
   $('#list-item-1').css('background-color', '#333333');
   $('#list-item-2').css('background-color', '#333333');
 } else {
   $('#list-item-1').css('background-color', '#ffffff');
   $('#list-item-2').css('background-color', '#ffffff');
 }
);
window.addEventListener("hashchange", locationChange(), false);

With the above code, the page sometimes loads with list item 1 changed, which is good, it picks up the #1 on page load, however when I click or scroll through the page, the others are not picked up.
(I have only supplied a small amount above, my actual code applies this to all list items.)
Any help / suggestions / example code would be greatly appreciated.

A: Without having a working example, I believe the issue is within this line:
window.addEventListener("hashchange", locationChange(), false);

Adding a listener is a right course of action, but you are calling your function when you are defining the listener.  Changing locationChange() to locationChange will not immediately invoke the function and instead pass a handle to the function:
function locationChange() {
 if(location.hash == "#1") {
   $('#list-item-1').css('background-color', '#333333');
   $('#list-item-2').css('background-color', '#333333');
 } else {
   $('#list-item-1').css('background-color', '#ffffff');
   $('#list-item-2').css('background-color', '#ffffff');
 }
);
window.addEventListener("hashchange", locationChange, false);


text:
Q: How do I stop DIV elements from moving when another opens? (menu and submenu) I want to have icons which do not move but load a submenu with more icons. However with my current code, the main icons are jumping when the menus open. I believe that my problem is in the CSS.
CSS
body {
    background: url("http://taqwamagazine.com/wp-content/uploads/2013/11/grey-striped-background-2072.png");
    background-size: cover;
}
#all{
  background: rgba(255, 255, 255, .7);
  position: relative;
  width: 1200px;
  margin: auto;
}
#icons {
background: -moz-linear-gradient(top, rgba(178,225,255,0.8) 0%, rgba(102,182,252,0.8) 100%); /* FF3.6+ */
background: -webkit-gradient(linear, left top, left bottom, color-stop(0%,rgba(178,225,255,0.8)), color-stop(100%,rgba(102,182,252,0.8))); /* Chrome,Safari4+ */
background: -webkit-linear-gradient(top, rgba(178,225,255,0.8) 0%,rgba(102,182,252,0.8) 100%); /* Chrome10+,Safari5.1+ */
background: -o-linear-gradient(top, rgba(178,225,255,0.8) 0%,rgba(102,182,252,0.8) 100%); /* Opera 11.10+ */
background: -ms-linear-gradient(top, rgba(178,225,255,0.8) 0%,rgba(102,182,252,0.8) 100%); /* IE10+ */
background: linear-gradient(to bottom, rgba(178,225,255,0.8) 0%,rgba(102,182,252,0.8) 100%); /* W3C */
filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#ccb2e1ff', endColorstr='#cc66b6fc',GradientType=0 ); /* IE6-9 */
  position: relative;
  top: 0;
  height: 120px;
  padding: 0px;
  width: 1200px;
  zindex: 3;
  border-bottom-left-radius: 10px;
  border-bottom-right-radius: 10px;
  border-top-right-radius: 10px;
  border-top-left-radius: 10px;
}
#tile {
  position: relative;
  top: 0px;
  padding: 2.5px;
  zindex: 3;
}
#icon {
background: url("http://mikefougnie.magix.net/mikefougnie/projects/testicon.png");
    background-size: 100px 100px;
    background-repeat: strech;
  position: relative;
  top: 5px;
  left: 5px;
  padding: 0px;
  margin: 0px 0px 10px 0px;
  width: 100px;
  height: 100px;
  border: 1px solid black;
  border-radius: 20px;
  zindex: 5;
}
#links1 {
background: -moz-linear-gradient(top, rgba(69,72,77,0.7) 0%, rgba(68,71,76,0.7) 1%, rgba(0,0,0,0.7) 100%); /* FF3.6+ */
background: -webkit-gradient(linear, left top, left bottom, color-stop(0%,rgba(69,72,77,0.7)), color-stop(1%,rgba(68,71,76,0.7)), color-stop(100%,rgba(0,0,0,0.7))); /* Chrome,Safari4+ */
background: -webkit-linear-gradient(top, rgba(69,72,77,0.7) 0%,rgba(68,71,76,0.7) 1%,rgba(0,0,0,0.7) 100%); /* Chrome10+,Safari5.1+ */
background: -o-linear-gradient(top, rgba(69,72,77,0.7) 0%,rgba(68,71,76,0.7) 1%,rgba(0,0,0,0.7) 100%); /* Opera 11.10+ */
background: -ms-linear-gradient(top, rgba(69,72,77,0.7) 0%,rgba(68,71,76,0.7) 1%,rgba(0,0,0,0.7) 100%); /* IE10+ */
background: linear-gradient(to bottom, rgba(69,72,77,0.7) 0%,rgba(68,71,76,0.7) 1%,rgba(0,0,0,0.7) 100%); /* W3C */
filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#b345484d', endColorstr='#b3000000',GradientType=0 ); /* IE6-9 */
  position: relative;
  top: -1px;
  left: -65px;
  padding: 10px;
  width: 242px;
  height: 440px;
  border: 2px solid black;
  border-bottom-left-radius: 10px;
  border-bottom-right-radius: 10px;
  border-top-right-radius: 10px;
  border-top-left-radius: 10px;
  text-color: transparent;
  zindex: 4;
  box-shadow: 1px 1px 2px black, 0 0 25px blue
}

#menugrid, td {
  position: relative;
  vertical-align: top;
  horizontal-align: center;
  padding: 0px;
  width: 1000px;
}

#menugrid, table{
  position: relative;
  vertical-align: top;
  horizontal-align: center;
  padding: 0px;
  width: 100;
}

#links1, h5 {
  text-align: center;
  color: #fefefe;
  font-weight: normal;
  text-size: 25px;
  padding: 0px;
  text-shadow: 1px 1px 2px black, 0 0 25px blue, 0 0 5px darkblue;
}

#arrow-up {
  position: relative;
  left: 35px;
    width: 0;
    height: 0;
    border-left: 25px solid transparent;
    border-right: 25px solid transparent;
    border-bottom: 25px solid black;
  align: center;
  zindex: 9;
}

HTML

Dock Ribbon

Menu  One Title

Menu Two Title

Menu Three Title

Menu Four Title

Menu Five Title

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Etiam lacus quam, hendrerit non tempus ac, dictum a elit. Aenean quis leo eu turpis congue tincidunt. Vivamus sagittis semper feugiat. Morbi ullamcorper felis in nibh fringilla efficitur. Maecenas massa justo, malesuada in porttitor ac, faucibus vel velit. Aenean bibendum, ante et tincidunt scelerisque, quam nunc accumsan leo, in fermentum nulla odio vel felis. Duis pulvinar convallis mi, accumsan tincidunt massa commodo eu. Pellentesque eleifend tellus vel leo fermentum, ac vestibulum lorem gravida.

Nam at odio mattis, pharetra nulla eu, feugiat arcu. Phasellus sed eros tristique, venenatis augue ut, gravida dolor. Quisque pharetra bibendum molestie. Phasellus finibus dui non dui cursus, id volutpat turpis accumsan. Donec scelerisque lorem eget varius blandit. Curabitur sit amet erat elit. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Maecenas venenatis purus ac venenatis imperdiet. Phasellus porta eros ut felis interdum, a tempus ante imperdiet. Phasellus nec efficitur felis, sodales viverra nibh. Nullam vulputate mauris lorem, nec pretium erat fringilla quis. Sed ac venenatis erat. Cras hendrerit venenatis accumsan. Aenean ornare dictum justo, at ultrices orci sodales nec. Interdum et malesuada fames ac ante ipsum primis in faucibus.

Morbi et laoreet velit. Suspendisse libero nunc, sodales a risus quis, eleifend congue elit. Ut dapibus lacinia quam, quis vehicula leo cursus at. Phasellus venenatis ante a urna finibus, vitae posuere tellus eleifend. Sed cursus risus quis efficitur luctus. Fusce ut mi sed risus dignissim pulvinar. Sed et augue id ipsum mollis feugiat. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Proin blandit justo id nulla pharetra, id dapibus ipsum tristique. Duis dictum eros a augue posuere rutrum ac et metus.

Fusce dignissim nunc ut enim scelerisque varius. Pellentesque auctor nisi sollicitudin libero aliquam feugiat. Fusce eget volutpat libero. Nam at finibus tortor. Curabitur vulputate posuere mattis. Nulla vitae semper urna. Nunc blandit, ipsum in scelerisque accumsan, neque lectus aliquet urna, ut rutrum tellus est in nisi. Cras vehicula orci sit amet nulla ultrices porttitor. Nulla at maximus velit. Aenean tempor nec mi a efficitur. Maecenas a pellentesque diam.

Nullam mollis nulla sed magna dapibus interdum. Sed cursus semper eros et rutrum. Duis vitae vehicula ligula. In tempor nisl leo. Duis at aliquam elit, vitae pharetra arcu. Praesent efficitur, sapien nec ornare tristique, sapien dolor elementum lectus, et dictum elit nisl sed augue. Donec suscipit nulla vel viverra aliquam. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. In in nisl ac magna semper gravida. Vivamus eros mi, bibendum nec ex a, mattis volutpat sapien. In non imperdiet elit. Suspendisse ullamcorper eros rutrum risus pharetra sollicitudin. Vestibulum imperdiet est eu sem egestas, ut auctor ante pharetra.

Javascript
function toggle_visibility(id) {
var e = document.getElementById(id);
e.style.display = ((e.style.display!='none') ? 'none' : 'block');
}

A: you need to add position:absolute to the div's which are being toggled i.e., the child div's

A: OK, just change you position in your tile id to absolute. However you may want to spread them out more or submenus overlap.

A: There's no need to absolutely position those items.
They're jumping because the container your dropdowns are being opened into have
width: auto;

Assign a static width to those menu items and you'll stop seeing any jumping.


text:
Q: Learning Haskell - How to simplify expressions? Is there any way to take the pain out of expression simplification?
For example, given this expression:
(+) <$> a <*> b $ 1

I would love to see a tool that would explain what it means. It's quite laborious  for beginners (finding correct instance function definition in sources, checking operator precedence) to simplify expressions with all steps involved:
fmap (+) a <*> b $ 1

See definition in Data.Functor
(.) (+) a <*> b $ 1

See fmap in Control.Monad.Instances for instance Functor ((->) r)
and so on.
EDIT: To clarify, I'm looking for a way to rewrite expression using actual function definitions so that newcomer could understand the outcome of this expression. How to tell that (<$>) = fmap here? I don't know how to find a particular instance definition (source) using hoogle and other tools.
EDIT: Changed incorrect original expression to match following reductions.

A: I find that the easy way is to use typed holes available in GHCi 7.8:
> (*10) <$> _a $ 1
Found hole '_a' with type: s0 -> b
Where: 's0' is an ambiguous type variable
       'b' is a rigid type variable bound by
           the inferred type of it :: b at <interactive>:4:1
Relevant bindings include it :: b (bound at <interactive>:4:1)
In the second argument of '(<$>)', namely '_a'
In the expression: (* 10) <$> _a
In the expression: (* 10) <$> _a $ 1

So this tells me that a :: s0 -> b.  Next is to figure out the order of operators:
> :i (<$>)
(<$>) :: Functor f => (a -> b) -> f a -> f b
infixl 4 <$>
> :i ($)
($) :: (a -> b) -> a -> b
infixr 0 $

So this says that $ is highly right-associative, and given it's type we see that it's first argument must be a function, so a must be a function (double confirmation).  This means that (*10) <$> a $ 1 is the same as ((*10) <$> a) $ 1, so we'll focus on (*10) <$> a first.
> :t ((*10) <$>)
((*10) <$>) :: (Num a, Functor f) => f a -> f a
> :t (<$> _a)
Found hole '_a' with type: f a
Where: 'a' is a rigid type variable bound by
           the inferred type of it :: (a -> b) -> f b at Top level
       'f' is a rigid type variable bound by
           the inferred type of it :: (a -> b) -> f b at Top level
In the second argument of '(<$>)', namely '_a'
In the expression: (<$> _a)

So we need a to be a functor.  What are available instances?
> :i Functor
class Functor (f :: * -> *) where
  fmap :: (a -> b) -> f a -> f b
  (<$) :: a -> f b -> f a
        -- Defined in 'GHC.Base'
instance Functor Maybe -- Defined in 'Data.Maybe'
instance Functor (Either a) -- Defined in 'Data.Either'
instance Functor ZipList -- Defined in 'Control.Applicative'
instance Monad m => Functor (WrappedMonad m)
  -- Defined in 'Control.Applicative'
instance Control.Arrow.Arrow a => Functor (WrappedArrow a b)
  -- Defined in 'Control.Applicative'
instance Functor (Const m) -- Defined in 'Control.Applicative'
instance Functor [] -- Defined in 'GHC.Base'
instance Functor IO -- Defined in 'GHC.Base'
instance Functor ((->) r) -- Defined in 'GHC.Base'
instance Functor ((,) a) -- Defined in 'GHC.Base'

So (->) r happens to be one, which is awesome because we know a has to be a function.  From the Num constraint, we can determine that r must be the same as Num a => a.  This means that (*10) <$> a :: Num a => a -> a.  From that we then apply 1 to it, and we'd get (*10) <$> a $ 1 :: Num a, where a is some unknown function.
All this is discoverable using GHCi using :t and :i, along with typed holes.  Sure, there's a fair number of steps involved, but it never fails when you're trying to break down a complex expression, just look at the types of different sub-expressions.

A: GHCi was wonderfully and correctly suggested, and I suggest it too.
I also want to suggest Hoogle, because with the instant search enabled (at the top sidebar at the right there's a button for it), you can search for functions very rapidly, it can provide much, much more information than GHCi, and the best part is that you don't have to mention modules to search in them1. This is in contrast to GHCi where you have to import first:
ghci> :t pure
<interactive>:1:1: Not in scope: 'pure'
ghci> :m +Control.Applicative
ghci> :t pure
pure :: Applicative f => a -> f a

The Hoogle link above is just one (from the Haskell.org site). Hoogle is a program which you can also install on your machine (cabal install hoogle) and execute queries from the command-line (hoogle your-query).
Sidenote: you'd have to run hoogle data to gather the information first. It requires wget/curl, so if you're on Windows you'd probably need to get this in your path first (or a curl for Windows, of course). On Linux it's almost always built-in (if you don't have it on Linux, just apt-get it). I never use Hoogle from the command-line by the way, it's simply not as accessible, but it can still be very helpful because some text-editors and their plugins can take advantage of it.
Alternatively you can use FPComplete's Hoogle which is sometimes more satisfying (because in my experience it has been aware of more 3rd party libraries. I only use it in those "Hoogling sessions").
There is also Hayoo! by the way.
1 In Hoogle you probably >95% of the time won't have to do this but +Module to import a module if for some reason it's not being searched for (which is the case sometimes for 3rd party libraries).
You can also filter away modules by -Module.
For instance: destroyTheWorld +World.Destroyer -World.Destroyer.Mercy to find destroyTheWorld and make sure you're not looking at the merciful way to do it (This comes very handy with modules with the same function names for different versions, like the ones in Data.ByteString & Data.ByteString.Lazy, Data.Vector & Data.Vector.Mutable, etc.).
Oh and one more awesome advantage of Hoogle is that not only it shows you the function's signature, it can also take you to the module's Haddock pages, so you also gain documentation + in those pages, when available, you can click on "Source" at the right of every function to see how it's being implemented for even more information.
This is outside the scope of the question, but Hoogle is also used to query for function signatures which is just.. mindblowingly helpful. If I want a function that takes an index number and a list and gives me the element in that index, and I wonder if it's already built in, I can search for it within seconds.
I know that the function takes a number and a list, and gives me an element of the list so the function signature must look something along these lines: Int -> [a] -> a (or generically: Num a => a -> [b] -> b), and both instances show up that there really is a function for that ((!!) and genericIndex).
Where GHCi has the upperhand is that you can toy with the expressions, explore them, etc. A lot of times when dealing with abstract functions that means a lot.
Being able to :l(oad) is very very helpful as-well.
If you're just looking for function signatures, you can combine both Hoogle and GHCi.
In GHCi you can type :! cmd, and GHCi will execute cmd in the command-line, and print the results. That means you can Hoogle inside GHCi too, e.g. :! hoogle void.

A: Start ghci, :cd to the base directory of the source you're reading, :load the module you're interested in, and use the :i command to get the info:
ghci> :i <$>
(<$>) :: Functor f => (a -> b) -> f a -> f b
    -- Defined in `Data.Functor'
infixl 4 <$>
ghci> :i $
($) :: (a -> b) -> a -> b   -- Defined in `GHC.Base'
infixr 0 $
ghci> :i .
(.) :: (b -> c) -> (a -> b) -> a -> c   -- Defined in `GHC.Base'
infixr 9 .

That tells you the type, where it's defined, the associativity (infixl or infixr) and the precedence (the number; higher is tighter).  So (*10) <$> a $ 1 is read as ((*10) <$> a) $ 1.
When you :load a module, all of the names that are in scope inside that module will be in scope inside ghci.  The one place where this can get annoying is if you have an error in the code, then you can't :i anything inside it.  In these cases, you can comment lines out, use undefined, and probably also use typed holes as behlkir suggests (haven't played with those too much yet).
While you're at it, try the :? command in ghci.


text:
Q: Comment Banner/Header best practices/examples? Long ago, I got a quick glance at some  code (PERL... urp) one of my managers was writing and was stunned by the banner/heading system he used in his code.  I didn't get a chance to delve into his code in detail, but just from the banner comments on the screen I could easily tell what the code was meant to do, even from far away.
Unfortunately that was long ago and our conversation at the time did not lend itself to me saying, "Yeah, well forget about our dot-com startup going down the toilet, can I take notes on your coding style?"
Years later, I've not yet achieved a high-level comment style that has the clarity as the (probably now mythical) code I saw that day.
When I say, "banners", I'm referring to the high-level block divisions/headers many coders use to create higher-level devisions in their code.  They're usually made up of simple ASCII dashes, slashes, equal signs, etc.  In my current daily-use language, one code banner/header hierarchy might be:
# ========================================================
# = Header 1
# ========================================================

# --------------------------------------------------------
# - Header 2
#---------------------------------------------------------

# == Header 3 ============================================

# -- Header 4 --------------------------------------------

# Header 5

and all the usual variations.
Although my searches have turned up nothing noteworthy, surely somewhere on the web someone's attempted to collect examples of these and present them in a systematic manner?
Can someone point to banner comment style "systems" they've found useful?  I'm not thinking of "Oh, I like the ones using asterisks", but more of an overall strategy of styles that makes high-level code construction quick and easy to understand as well as easy on the eyes?  Picking a preferred system from examples would be easier than comparing descriptions, obviously.
Note: I'm not interested in the contents of the comments per se, but the "flair" used on the comments to provide a clear indications of overall code content and organization.

A: One of the best ways I have found of verifying the style of commenting is to use a code documentation tool such as doxygen, there is a list of others here, and then see what the output was like - the clearer the output the better the comments.
I would say that the single biggest points are consistency and a clear indication of ranking, followed by completeness and conciseness, i.e. Once you have looked at one you should know what the others will look like and how significant the one you are looking at is.  This forces you to have a good design as without it you don't know how significant things are.
Next all the information you need should be present but it should be short enough to take in at a glance - however satisfying both these forces you to change your coding style so that objects/code is not too large, is well named, doesn't have too many parameters, etc., all the things that tools like lint try to teach us.
For python code the style summary at PEP-257 provides a lot of useful guidelines and some examples.
A quick look for some "Good" code on my machine turned up Andrea Gavana's Aquabutton.py I have included a section of the code below but you can see the full code here - I have to say that this was the first module of Andrea's that I opened, being early in the alphabet but I am sure any would have done.
# --------------------------------------------------------------------------------- #
# AQUABUTTON wxPython IMPLEMENTATION
#
# Andrea Gavana, @ 07 October 2008
# Latest Revision: 24 Nov 2011, 22.00 GMT
#
#
# TODO List
#
# 1) Anything to do?
#
#
# For all kind of problems, requests of enhancements and bug reports, please
# write to me at:
#
# andrea.gavana@gmail.com
# andrea.gavana@maerskoil.com
#
# Or, obviously, to the wxPython mailing list!!!
#
#
# End Of Comments
# --------------------------------------------------------------------------------- #

"""
:class:`AquaButton` is another custom-drawn button class which *approximatively* mimics
the behaviour of Aqua buttons on the Mac.

Description
===========

:class:`AquaButton` is another custom-drawn button class which *approximatively* mimics
the behaviour of Aqua buttons on the Mac. At the moment this class supports:

* Bubble and shadow effects;
* Customizable background, foreground and hover colours;
* Rounded-corners buttons;
* Text-only or image+text buttons;
* Pulse effect on gaining focus.

And a lot more. Check the demo for an almost complete review of the functionalities.

Usage
=====

Sample usage::

    import wx
    import wx.lib.agw.aquabutton as AB

    app = wx.App(0)

    frame = wx.Frame(None, -1, "AquaButton Test")

    mainPanel = wx.Panel(frame)
    mainPanel.SetBackgroundColour(wx.WHITE)

    # Initialize AquaButton 1 (with image)
    bitmap = wx.Bitmap("my_button_bitmap.png", wx.BITMAP_TYPE_PNG)
    btn1 = AB.AquaButton(mainPanel, -1, bitmap, "AquaButton")

    # Initialize AquaButton 2 (no image)
    btn2 = AB.AquaButton(mainPanel, -1, None, "Hello World!")

    frame.Show()

    app.MainLoop()

Supported Platforms
===================

AquaButton has been tested on the following platforms:
  * Windows (Windows XP);
  * Linux Ubuntu (10.10).

Window Styles
=============

`No particular window styles are available for this class.`

Events Processing
=================

This class processes the following events:

================= ==================================================
Event Name        Description
================= ==================================================
``wx.EVT_BUTTON`` Process a `wxEVT_COMMAND_BUTTON_CLICKED` event, when the button is clicked.
================= ==================================================

License And Version
===================

:class:`AquaButton` control is distributed under the wxPython license.

Latest Revision: Andrea Gavana @ 22 Nov 2011, 22.00 GMT

Version 0.4

"""

import wx

# Constants for the hovering and clicking effects
HOVER = 1
""" Indicates that the mouse is hovering over :class:`AquaButton` """
CLICK = 2
""" Indicates that :class:`AquaButton` has been clicked """

class AquaButtonEvent(wx.PyCommandEvent):
    """ Event sent from the :class:`AquaButton` buttons when the button is activated. """

    def __init__(self, eventType, eventId):
        """
        Default class constructor.

        :param integer `eventType`: the event type;
        :param integer `eventId`: the event identifier.
        """

        wx.PyCommandEvent.__init__(self, eventType, eventId)
        self.isDown = False
        self.theButton = None

    def SetButtonObj(self, btn):
        """
        Sets the event object for the event.

        :param `btn`: the button object, an instance of :class:`AquaButton`.
        """

        self.theButton = btn

snip
class AquaButton(wx.PyControl):
    """ This is the main class implementation of :class:`AquaButton`. """

    def __init__(self, parent, id=wx.ID_ANY, bitmap=None, label="", pos=wx.DefaultPosition,
                 size=wx.DefaultSize, style=wx.NO_BORDER, validator=wx.DefaultValidator,
                 name="aquabutton"):
        """
        Default class constructor.

        :param Window `parent`: parent window. Must not be ``None``;
        :param integer `id`: window identifier. A value of -1 indicates a default value;
        :param Bitmap `bitmap`: the button bitmap (if any);
        :param string `label`: the button text label;
        :param `pos`: the control position. A value of (-1, -1) indicates a default position,
         chosen by either the windowing system or wxPython, depending on platform;
        :type `pos`: tuple or :class:`Point`
        :param `size`: the control size. A value of (-1, -1) indicates a default size,
         chosen by either the windowing system or wxPython, depending on platform;
        :type `size`: tuple or :class:`Size`
        :param integer `style`: the button style (unused);
        :param Validator `validator`: the validator associated to the button;
        :param string `name`: the button name.
        """

        wx.PyControl.__init__(self, parent, id, pos, size, style, validator, name)

        self.SetBackgroundStyle(wx.BG_STYLE_CUSTOM)

        self.Bind(wx.EVT_PAINT, self.OnPaint)
        self.Bind(wx.EVT_ERASE_BACKGROUND, lambda event: None)
        self.Bind(wx.EVT_SIZE, self.OnSize)
        self.Bind(wx.EVT_LEFT_DOWN, self.OnLeftDown)
        self.Bind(wx.EVT_LEFT_UP, self.OnLeftUp)
        self.Bind(wx.EVT_LEAVE_WINDOW, self.OnMouseLeave)
        self.Bind(wx.EVT_ENTER_WINDOW, self.OnMouseEnter)
        self.Bind(wx.EVT_SET_FOCUS, self.OnGainFocus)
        self.Bind(wx.EVT_KILL_FOCUS, self.OnLoseFocus)
        self.Bind(wx.EVT_KEY_DOWN, self.OnKeyDown)
        self.Bind(wx.EVT_KEY_UP, self.OnKeyUp)
        self.Bind(wx.EVT_TIMER, self.OnPulseTimer)

        if "__WXMSW__" in wx.PlatformInfo:
            self.Bind(wx.EVT_LEFT_DCLICK, self.OnLeftDown)

        self._mouseAction = None
        self.SetBitmapLabel(bitmap)
        self._hasFocus = False
        self._saveBitmap = True
        self._storedBitmap = wx.NullBitmap
        self._pulseOnFocus = False
        self._gammaFactor = 1.0
        self._gammaIncrement = 0.1

        self._timer = wx.Timer(self, wx.ID_ANY)

        self.SetLabel(label)
        self.InheritAttributes()
        self.SetInitialSize(size)

        # The following defaults are better suited to draw the text outline
        if "__WXMAC__" in wx.PlatformInfo:
            self._backColour = wx.Colour(147, 202, 255)
            self._hoverColour = self.LightColour(self._backColour, 30)
            self._disableColour = self.LightColour(self._backColour, 70)
            self._textColour = wx.BLACK
        else:
            self._backColour = wx.SystemSettings.GetColour(wx.SYS_COLOUR_ACTIVECAPTION)
            self._hoverColour = self.LightColour(self._backColour, 30)
            self._disableColour = self.LightColour(self._backColour, 70)
            self._textColour = wx.WHITE

    def SetBitmapLabel(self, bitmap):
        """
        Sets the bitmap label for the button.

        :param `bitmap`: the bitmap label to set, an instance of :class:`Bitmap`.
        """

        self._bitmap = bitmap
        self.Refresh()


text:
Q: Error in XML Layout in android Error in below xml
<?xml version="1.0" encoding="utf-8"?>
<!-- row.xml -->
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent" android:layout_height="45dp"
    android:gravity="center" android:background="@color/list_bg">

    <TableLayout android:layout_width="fill_parent"
        android:layout_height="wrap_content">

        <TableRow>

            <ImageView android:id="@+id/t1" android:layout_width="wrap_content"
                android:layout_height="wrap_content" />

            <TextView android:id="@+id/t2" android:typeface="normal"
                android:singleLine="true" android:textSize="14sp" android:textStyle="normal"
                android:layout_width="wrap_content" android:textColor="#000000"
                android:layout_height="wrap_content" />
            <TextView android:id="@+id/t10" android:typeface="normal"
                android:singleLine="true" android:text=" " android:textSize="14sp"
                android:textStyle="normal" android:layout_width="wrap_content"
                android:textColor="#000000" android:layout_height="wrap_content" />
            <TextView android:id="@+id/t4" android:typeface="normal"
                android:visibility="gone" android:singleLine="true" android:text="("
                android:textSize="14sp" android:textStyle="normal"
                android:layout_width="wrap_content" android:textColor="#000000"
                android:layout_height="wrap_content" />
            <TextView android:id="@+id/t5" android:typeface="normal"
                android:visibility="gone" android:singleLine="true"
                android:textSize="14sp" android:textStyle="normal"
                android:layout_width="wrap_content" android:textColor="#000000"
                android:layout_height="wrap_content" />
            <TextView android:id="@+id/t6" android:typeface="normal"
                android:visibility="gone" android:singleLine="true" android:text=")"
                android:textSize="14sp" android:textStyle="normal"
                android:layout_width="wrap_content" android:textColor="#000000"
                android:layout_height="wrap_content" />
            <ImageView android:id="@+id/t3" android:layout_width="wrap_content"
                android:layout_height="wrap_content" />

        </TableRow>

    </TableLayout>

</RelativeLayout>

Error is:
Multiple annotations found at this line:
    - The processing instruction target matching "[xX][mM][lL]" is not
     allowed.
    - No grammar constraints (DTD or XML schema) detected for the
     document.
Please help...

A: 1)  Make sure you don't have any comment or white space or empty line before
<?xml version="1.0" encoding="utf-8"?>

That declaration should be on top

A: I found my mistake there was a extra line before first line of my xml I have removed it and now its working fine.

A: Not seeing any error when copied to my eclipse. Using Eclipse Juno and SDK 20, ADT version 20.0.1


text:
Q: Sum of different numbers in an array I want to have a function that returns the sum of different (non duplicate) values from an array: if I have {3, 3, 1, 5}, I want to have sum of 3 + 1 + 5 = 9.
My attempt was:
int sumdiff(int* t, int size){
    int sum=0;
    for (int i=0; i<=size;i++){
        for(int j=i; j<=size;j++){
            if(t[i]!=t[j])
            sum=sum+t[i];
        }
    }
    return sum;
}

int main()
{
    int t[4]={3, 3, 1, 5};
    cout << sumdiff(t, 4);
}

It returns 25 and I think I know why, but I do not know how to improve it. What should I change?

A: Put all the items in a set, then count them.
Sets are data structures that hold only one element of each value (i.e., each of their elements is unique; if you try to add the same value more than once, only one instance will be count).
You can take a look in this interesting question about the most elegant way of doing that for ints.

A: First of all, your loop should be for (int i=0; i<size;i++). Your actual code is accessing out of the bounds of the array.
Then, if you don't want to use STL containers and algorithms (but you should), you can modify your code as follows:
int sumdiff(int* t, int size){
    int sum=0;
    for (int i=0; i<size;i++){

        // check if the value was previously added

        bool should_sum = true;

        for(int j=0; should_sum && j<i;j++){
            if(t[i]==t[j])
                should_sum = false;
        }

        if(should_sum)
            sum=sum+t[i];
    }
    return sum;
}

int main()
{
    int t[4]={3, 3, 1, 5};
    cout << sumdiff(t, 4);
}

A: You could:

*Store your array contents into an std::unordered_set first. By doing so, you'd essentially get rid of the duplicates automatically.

*Then call std::accumulate to compute the sum

A: **wasthishelpful's answer was exactly what i was talking about. I saw his post after i posted mine.
So, you're trying to check the duplicate number using your inner loop.
However, your outer loop will loop 4 times no matter what which gives you wrong result.
Try,

*

*Do only checking in inner loop. (use a flag to record if false)

*Do your sum outside of inner loop. (do the sum when flag is true)

A: Insert array elements into a set and use the std::accumulate function:
#include <iostream>
#include <numeric>
#include <set>

int main()
{
    int t[4] = { 3, 3, 1, 5 };
    std::set<int> mySet(std::begin(t), std::end(t));
    int mySum = std::accumulate(mySet.begin(), mySet.end(), 0);
    std::cout << "The sum is: " << mySum << std::endl;
    return 0;
}

A: Here is another solution using std::accumulate, but it iterates over the original elements in the call to std::accumulate, and builds the set and keeps a running total as each number in the array is encountered:
#include <iostream>
#include <numeric>
#include <set>

int main()
{
    int t[4] = { 3, 3, 1, 5 };
    std::set<int> mySet;
    int mySum = std::accumulate(std::begin(t), std::end(t), 0,
         [&](int n, int n2){return n += mySet.insert(n2).second?n2:0;});
    std::cout << "The sum is: " << mySum << std::endl;
    return 0;
}

The way it works is that std::insert() will return a pair tbat determines if the item was inserted. The second of the pair is a bool that denotes whether the item was inserted in the set.  We only add onto the total if the insertion is successful, otherwise we add 0.
Live Example


text:
Q: How to retrieve EventDetails in EventBridge? Using AWS .NET SDK, I tried to put event with EventBridge and then track it with CloudWatch.
How I put event:
using (var eventClient = new AmazonEventBridgeClient(credentials, RegionEndpoint.USEast1))
            {
                PutEventsResponse result = await eventClient.PutEventsAsync( new PutEventsRequest
                {
                    Entries = new List<PutEventsRequestEntry>
                    {
                        new PutEventsRequestEntry
                        {
                            DetailType = "TestEvent",
                            EventBusName = "default",
                            Source = "mySource",
                            Detail = JsonConvert.SerializeObject(new TestClass{ Message = "myMessage"}),
                            Time = DateTime.UtcNow
                        }
                    }
                });
            }

And what I see in logs

Can somebody explain me, why I don't see the Detail and DetailType I defined? Maybe I do something wrong?
Thank you in advance

A: Okey, I finally found solution. All, what I need, was to configure input to my rule target

Here I chose Part of the matched event and defined what I want to receive. But, this variant isn't available for CloudWatch Logs Target, so this answer isn't complete at all.


text:
Q: Python Installation Problems I have installed python on my computer in the AppData\local\programs\python location on my computer. I got the installation file from the python website. I cannot use the installation packages from the Microsoft store due to an authorization error (even though I unchecked the boxes in the App Execution Aliases page in settings). I am on my personal computer on which there are no other users.
When I go into my command prompt, and run the command:
python --versions

I get an error saying:
Python was not found; run without arguments to install from the Microsoft Store, or
disable this shortcut from Settings > Manage App Execution Aliases.

either I do not understand what this error is requiring me to do, or there is something else I am doing wrong.

A: Try running just "python" in the command prompt. If it doesn't work just install it through https://www.python.org/downloads/.

A: You must add python to global variables.


text:
Q: Creation of collection via FXCollections from FXML There are dozens of examples with creation of collections via FXCollections from FXML like this (from here):
<FXCollections fx:factory="observableArrayList">
    <String fx:value="A"/>
    <String fx:value="B"/>
    <String fx:value="C"/>
</FXCollections>

But I can not understand how it works. After all, factory method is no-arg method, so where do String-elements go? I have thought it is default property, but FXCollections has no default property. There is overloaded version of observableArrayList() factory method which takes vararg of collection's elements in docs and source code. But why does FXML use this method? It is not specified in documentation (or I can not find it). All what I found in docs is:

The fx:factory attribute is another means of creating objects whose classes do not have a default constructor. The value of the attribute is the name of a static, no-arg factory method for producing class instances. For example, the following markup creates an instance of an observable array list, populated with three string values:

I feel it is stupid question. But could anyone make it clear for me?
Thank you in advance
P.S. Sorry for my english

A:
There is overloaded version of observableArrayList() factory method which takes vararg of collection's elements in docs and source code. But why does FXML use this method?

It doesn't. FXCollections.observableArrayList() is used to create the list and since the surrounding element to the <String> elements is a List, those elements are added to the list. The java code to produce the same result would be
ObservableList list = FXCollections.observableArrayList();
list.add("A");
list.add("B");
list.add("C");

The list is treated the same way read-only list properties are, even though the documentation does not explicitly state this.


text:
Q: jQuery mobile slider bar firing different event depending on its value Quick question.
I use jqmobile ver.1.2.0 with vertical slider plugin(http://www.elmundio.net/blog/jquery-mobile-vertical-slider/).
How do I launch some functions depending on its value.
Ex. at value 50, change somewhere else's class name, at value 100 redirect the page to new URL.
I am gonna make some sample page afterwards.
Here's sample.
jsfiddle.net/nori2tae/zT2ZH/
Thanks.

A: i guess this is what you need
function anotherfunction() {
    alert('another function is fired');
}
$(document).ready(function() {
    //do something
    $('.container').change(function() {
        if ($(this).children('input').val()==50) {
            $('.changeThis').addClass('changed');
            $('.changed').removeClass('changeThis');
            alert("at 50 and changeThis now have [" + $('.changed').attr("class") + "] classes");
        } else if($(this).children('input').val()==100) {
            // another function here
            anotherfunction();
        }
    });
});

jsfiddle: http://jsfiddle.net/BerkerYuceer/5ZHue/
you can also try in mobile debugging mode..


text:
Q: Unknown CMake command "compileTargetAsC99", C-Logging I'm trying to make ctest work on my Ubuntu installation, and for that I need c-logging (https://github.com/Azure/c-logging). When I clone the repository and attempt to cmake .., I get the error
CMake Error at CMakeLists.txt:167 (compileTargetAsC99):
  Unknown CMake command "compileTargetAsC99".

Here is a pastebin of CMake error file: https://pastebin.com/1WE6B3y0
Thanks


text:
Q: How to order by value enumeration statuses? I have this foreach and how can i order by so that i get last item on first palce and the others to stay where they are?
  foreach (Statuses val in Enum.GetValues(typeof(Statuses)))
    {
       Status.Add(new StatusModel()
         {
            Value = (string)val.ToString(),
            TransKey = val.ToString()
         });
    }

A: You can use this dirty trick:
var ordered = Status
    .OrderByDescending(s => s.TransKey == "ValueYouWantAtTheTop");

Probably more efficient option:
var toMoveToTop = Status.First(s => s.TransKey == "ValueYouWantAtTheTop");
Status.Remove(toMoveToTop);
Status.Insert(0, toMoveToTop);


text:
Q: The return keyword acts strange I'm working on a project in JS(Electron,Node.js)that needs to check if a key in the Windows registry is present.
Here is my code:
function IsSettedUp() {
regedit.list('HKCU\\SOFTWARE')
    .on('data', function (entry) {
        //Returns Keys
        console.log(entry.data.keys)

        //Checks if "WinXSoft" appears in the entry.data.keys array
        var key = $.inArray("WinXSoft", entry.data.keys)

        console.log(key)

        //Returns false if WinXSoft wasn't found
        if (key == -1) {

            return false
        }
        //Returns true if WinXSoft was found
        else {
            return true
        }
    })

    }
    //Should be true or false according to the WinXSoft key
    var z = IsSettedUp();
    console.log(z)

When I create the key and run the code,this is the output:
console.log(entry.data.keys) outputs Array(42).(Expected)
console.log(key) ouputs  13(Expected)
console.log(z) outputs undefined(???,Should be true)
So yeah,do you guys know how I can fix this?

A: Try to return value out of the on function
function IsSettedUp() {
     var result = false;
     regedit.list('HKCU\\SOFTWARE').on('data', function (entry) {
        //Returns Keys
        console.log(entry.data.keys)

        //Checks if "WinXSoft" appears in the entry.data.keys array
        var key = $.inArray("WinXSoft", entry.data.keys)

        console.log(key)

        //Returns false if WinXSoft wasn't found
        if (key == -1) {

            result = true;
        }
        //Returns true if WinXSoft was found
        else {
            result = false;
        }
    });
    return result;
 }

A: that is because z is the value of IsSettedUp return , which is not there and hence undefined.
true is the return value for the callback provided to on function.

function IsSettedUp() {
regedit.list('HKCU\\SOFTWARE')
    .on('data', function (entry) {
        //Returns Keys
        console.log(entry.data.keys)

        //Checks if "WinXSoft" appears in the entry.data.keys array
        var key = $.inArray("WinXSoft", entry.data.keys)

        console.log(key)

        //Returns false if WinXSoft wasn't found
        if (key == -1) {

            return false
        }
        //Returns true if WinXSoft was found
        else {
            return true
        }
    })
    return 'test' // ADD THIS RETURN
    }
    //Should be true or false according to the WinXSoft key
    var z = IsSettedUp();
    console.log(z)

try this edited code and see what the value of z comes out now, one line is added at the end of your function

A: True or false is returned for inside function (entry) {. Nothing is returned for outside function IsSettedUp() {, so return value is the default undefined.Formatting code could make function scope clear.

A: I didn't found a solution for this problem so I decided to us another library that works fine now.


text:
Q: ComboBoxText in Glade / GTK+3 / Python - disappears when displayed 2nd time I'm trying to implement a drop down list in an Ubuntu app using Glade (GTK+3) and Python.
I can get the ComboBoxText to display, populated with strings. However when I close the window it is contained in and then re-open it, the combobox is not there, just a completely blank window.
I added the ComboBoxText widget in question to a window in Glade.
I then added this code in my Python programme:
def on_button_edit_clicked(self, widget):
    """ display list of events already stored, and allow deletion """

    self.combo = self.builder.get_object('combo_box')
    self.store = Gtk.ListStore(str)

    self.store.append(['hello'])
    self.store.append(['goodbye'])
    self.combo.set_model(self.store)

    event_editor = self.builder.get_object("event_editor")
    event_editor.show()

I even tried destroying the widget to see if that helps:
def on_event_editor_destroy(self, widget):
    self.combo.destroy()
    self.store = Gtk.ListStore(str)
    self.combo.set_model(self.store)

EDIT:
I have since tried some alternative code, that included a CellRendererText object, but still no luck.
These are my sources:
I created a Gtk.ListStore(), then I created a Gtk.CellRendererText(), then I created a Gtk.ComboBox().
This was all in-line with example 13.3 here.
Nothing works. When I open the combobox window a 2nd time, it is just a blank window. Can anyone help please?

A: I've found a solution. I was closing the window using the x button, which must have been destroying the widget and it's associated list store. Instead I am now using a custom button that merely hides the window.

A: The title says, "ComboBoxText in Glade / GTK+3 / Python..." then u try to implement a GtkComboBox, not a GtkComboBoxText. Why torture yourself with a GtkComboBox.
Glade file (snippet)
<object class="GtkComboBoxText" id="comboboxtextEventEditor">
    <property name="visible">True</property>
    <property name="can_focus">False</property>
    <property name="halign">end</property>
    <property name="margin_right">10</property>
    <property name="hexpand">True</property>
    <property name="entry_text_column">0</property>
    <property name="id_column">1</property>
    <signal name="changed" handler="on_changed_event_editor" swapped="no"/>
</object>

Notice no GtkListStore is needed for a GtkComboBoxText. Now some class methods
from __future__ import print_function
from gi.repository import Gtk
import os

def TheClass(Gtk.ApplicationWindow):
    #class variable
    UI_FILE = "preference.glade"

    @staticmethod
    def get_id():
        return "windowTheClass"

    def __init__(self, app):
        """ Constructor"""
        # Initialize class variables.
        #app is an instance of a class which extends Gtk.Application
        #Hardcode to have a working example code
        self.ui_path = os.path.join("home", "useraccount", "Documents", "example")
        #self.app = app
        #self.ui_path = self.app.ui_path
        # Load ui
        self.__load_ui()
        self.__initialize_event_editor_combobox()

    def __load_ui(self):
        self.builder = Gtk.Builder()
        try:
            strUIFile = os.path.join(self.ui_path, self.UI_FILE)
            self.builder.add_from_file( strUIFile )
            del strUIFile
            self.win = self.builder.get_object( self.__class__.get_id() )
            # This is not useful until Gtk version 3.6
            #self.app.add_window(self.win)
            self.builder.connect_signals(self)
        except:
            print(self.__class__.__name__ + ".__load_ui error",  sys.exc_info()[1])

    def __initialize_event_editor_combobox(self):
        """ Populate event editor comboboxtext"""
        combobox = self.builder.get_object("comboboxtextEventEditor")
        combobox.remove_all()
        # Args [position, id, text]
        combobox.insert(0,"0", "Hello")
        combobox.insert(0,"1", "goodbye")
        combobox.set_active_id("1")
        del combobox

    def on_changed_event(self, widget, data=None):
        """ combobox value selected. Refresh combobox"""
        strSelectedEntry = widget.get_active_text()
        print(self.__class__.__name__ + ".on_changed_event", strSelectedEntry)
        #self.initialize_something_else(strSelectedEntry)
        del strSelectedEntry


text:
Q: Secure centralized HMAC-based authentication service I need to centralize authentication to my rest web services and make this authentication the same for all of our webservices. So I started writing an external web service to take care about the authentication.
To keep compatibility, since the authentication was performed using a HMAC signature (signed using a private key) alongside the single request (so there is no token of any sort) I thought to make all web services to send the HMAC included inside the incoming request and the StringToSign (a representation of data used to generate the HMAC).
So the Authorization service can (knowing the private key) try to compose the same signature, if it matches then answers with 200 OK and with a JSON object saying "authorized".
All this communication happens over HTTPS, but I'm trying to figure out what could happen if someone would intercept or modify this answer, making a 403 Forbidden to become 200 OK...
Should I use some sort of way to recognize this is the original answer? If so, what could I do?
I do agree that ssl certificates released by CA's are secure, but how could I make sure my HTTPS layer has not been compromised allowing an attacker to modify authorization responses?
P.S. please provide some standard solution if any, I don't want it to be related to the technology I'm using right now, since each service may use its own stack and I don't really want it to be .NET or something else because there's a proprietary implementation for the authentication mechanism.

A:
All this communication happens over HTTPS, but I'm trying to figure
  out what could happen if someone would intercept or modify this answer

This is what the S in HTTPS is for: SSL guarantees integrity of the message. If the attacker forges the request, the client will notice it.
You can ask the experts at #security.


text:
Q: how to insert jtable only one column data into DB mysql? I need to insert only one column data from jtable to DB mysql,I found a way to do it but i'm facing a problem which occur when i inserted less data than expected eg: insert 2 rows instead of 3 rows; Error:java.lang.arrayindexoutofboundsexception 2>=2
How do I get rid of this ?
You can check out my code down ...Thanks
try
        {
            //String product3 = "null";
           int rows = jTable1.getRowCount();
           int cols = jTable1.getColumnCount();
           String salesql = "insert into salling(orderid,saledate,prod1,prod2,prod3,tax,subtotal,total) values(?,?,?,?,?,?,?,?)";
           pst = conn.prepareStatement(salesql);
           pst.setString(1, jTextFieldOrderNo.getText());
           pst.setString(2, jTextFieldDate.getText());

           for(int row =0; row <= rows; row++)
           {
               String product1 = (String)jTable1.getValueAt(0, 0);
               String product2 = (String)jTable1.getValueAt(1, 0);
               String product3 = (String)jTable1.getValueAt(2, 0);
              // String product3 = (String)jTable1
               pst.setString(3, product1);
               pst.setString(4, product2);
               pst.setString(5, product3);
           }
          pst.setString(6, jTextFieldTax.getText());
          pst.setString(7, jTextFieldSuTotal.getText());
          pst.setString(8, jTextFieldTotal.getText());

          pst.execute();
          JOptionPane.showMessageDialog(null, "Data saved...");

        }catch(Exception e)
        {
            JOptionPane.showMessageDialog(null, e);
        }

    }


text:
Q: MySQL - How to select data by date range one month? I have a issue, how to get data by range date from one month
Example result
Name | start_date | endate
BEN  | 2016-02-13 | 2016-03-13
JONY | 2016-10-12 | 2016-11-12
JHON | 2016-11-04 | 2016-12-04

A: Try DATE_ADD in mysql
select name, start_date, DATE_ADD(start_date,INTERVAL 1 month) as endate from yourtable

A: Just use these simple code to get the data from the table
by mentioning the right interval to get records added in last one month:
select * from my_table where  date >= DATE_SUB(CURDATE(), INTERVAL 1 MONTH)
hope this helps


text:
Q: Remove multiple line breaks between string and replace with single line breaks in java I have string
String description = a
\n
\n
\n
\n
\n
b

I want to remove the line break to be just 1 line break.
Remove more than 2 line break to be just 1 line break.
I have tried this
String descResult = description.replaceAll("([\n]){2,}", "");

but it doesn't work.

A: In addition to new lines, you seem to be having surrounding spaces too, so you need to use a regex that optionally captures optional spaces too. Try this Java code,
String s = "a \n \n \n \n \n b";
System.out.println("Before: " + s);
System.out.println("After: " + s.replaceAll("( *\n *){2,}", "\n"));

Prints,
Before: a

 b
After: a
b

A: Try it, replacement must be \n
String descResult = description.replaceAll("([\n]){2,}", "\n");


text:
Q: cellpadding is missing on FACEBOX I'm using facebox ( https://github.com/defunkt/facebox ) with same code downloaded from github without any modification except remote.html
I JUST added this code in remote.htmlTABLE in facebox window with this code:

        Hello
        World

        I'm remote.html, a different file loaded with ajax.
        I'm remote.html, a different file loaded with ajax.

PROBLEM: There is NO CELLPADDING on facebox window.
How can I solve this problem?
OR ANY OTHER SOLUTION TO REPLACE WITH FACEBOX?
Regards,
Nuri Akman

A: It's because the facebox.css file contains this:
#facebox table {
   border-collapse: collapse;
}

Remove it or override it with other CSS.

A: On version Facebox 1.3 add this code in facebox.css:
 #facebox .content table tr td { padding: 4px; }
 #facebox .content table tr th { padding: 4px; }
 #facebox .content table { border-collapse: separate; border-spacing: 1px; }


text:
Q: Changing the Range of a UISlider Programmatically How is it possible to set the min max ranges of the UISlider programmatically?
For example (dummy code)
UISlider* slider = [[UISlider alloc] init];
slider.min = -3;
slider.max = 3;

EDIT:
So I have the following:
sl.minimumValue = 5;
NSLog(@"MIN VAL: %d", sl.minimumValue);

This doesn't work, I still get it logging the value 0. Is this because I have set values in interface builder?

A: In the case updating selected values of IBOutlet-ed RangeSeekSlider
rangeSeekSlider.selectedMinValue = 10.0
rangeSeekSlider.selectedMaxValue = 100.0
rangeSeekSlider.setNeedsLayout()

A: Here is it.
UISlider* slider = [[UISlider alloc] init];
slider.minimumValue = -3.0f;
slider.maximumValue = 3.0f;

A: // Add a frame where you want to place the slider. This will place it at (x,y) = 0,0
with a height of 10 and width of 200

CGRect frame = CGRectMake(0.0, 0.0, 200.0, 10.0);

// sliderAction will respond to the updated slider value
UISlider *slider = [[UISlider alloc] initWithFrame:frame];
[slider addTarget:self action:@selector(sliderAction:) forControlEvents:UIControlEventValueChanged];

// Set minimum and maximum value
slider.minimumValue = 0.0;
slider.maximumValue = 50.0;
slider.continuous = YES;

// Initial value
slider.value = 25.0;

// Add slider to view
[self.view addSubview:slider];

A: Swift 5 :
self.yourSlider.minimumValue = 0.0
self.yourSlider.maximumValue = 4
self.yourSlider.value = 0


text:
Q: GoogleSheets API:"Invalid JSON payload received. Unknown name "Number" at 'data.values[0]': Cannot find field I am trying to copy contents of a spreadsheet into another spreadsheet but the error keeps popping up.
Could you help to figure out why is it not copying over the data from one sheet to the other?
This is the dummy data I am experimenting on in the original sheet:
1   CHANGED London
2   5   Budapest
3   4   Prague
4   11  Madrid
4   11  Madrid

This is how the destination sheet looks like:
2   5   Budapest
2   5   Budapest
2   5   Budapest

This is part of the error I get:
Invalid JSON payload received. Unknown name "Weather" at 'data.values[0]': Cannot find field.
Invalid JSON payload received. Unknown name "City" at 'data.values[0]': Cannot find field.
Invalid JSON payload received. Unknown name "Number" at 'data.values[1]': Cannot find field.
Invalid JSON payload received. Unknown name "Weather" at 'data.values[1]': Cannot find field.
Invalid JSON payload received. Unknown name "City" at 'data.values[1]': Cannot find field.
Invalid JSON payload received. Unknown name "Number" at 'data.values[2]': Cannot find field.

And this is the script:
from oauth2client.service_account import ServiceAccountCredentials
from pprint import pprint
from googleapiclient import discovery
scope = ["https://spreadsheets.google.com/feeds",'https://www.googleapis.com/auth/spreadsheets',"https://www.googleapis.com/auth/drive.file","https://www.googleapis.com/auth/drive"]
creds = ServiceAccountCredentials.from_json_keyfile_name("creds.json", scope )
client = gspread.authorize(creds)

LT = client.open("LetsTry").sheet1
LT_data = LT.get_all_records()
NQ_all = client.open("NQ_all").sheet1
NQ_all_data = NQ_all.get_all_records()

service = discovery.build('sheets', 'v4', credentials=creds)
spreadsheetId = 'xyz'
range = 'Sheet1!A1:C11'
body = {
    'values': LT_data
}
result = service.spreadsheets().values().append(
    spreadsheetId=spreadsheetId,
    range = range,
    valueInputOption= 'RAW',
    body=body).execute()
print('{0} cells updated.'.format(result.get('updatedCells')))

A: I had the same problem and I recognized that it's because of encoding.
I just set all data to utf8 and the error is fixed.
utf8_encode($yourValue);

Here is the utf encoding :
https://www.php.net/manual/tr/function.utf8-encode.php

A: How about this answer?
In your script, the values retrieved by LT_data = LT.get_all_records() are used to the request body of the method of spreadsheets.values.append in Sheets API. In this case of LT_data, the retrieved value is JSON object. But values of the request body is required to be 2 dimensional array. I think that the reason of your error message is this.
In order to avoid this error, how about the following modification?
Modified script:
When your script is modified, please modify as follows.

From:

LT_data = LT.get_all_records()

To:

LT_data = LT.get_all_values()

*

*The value retrieved by get_all_values() is 2 dimensional array. So in this case, it can be used for body = {'values': LT_data}.

Note:

*

*This answer supposes that you have already been able to get and put values for Google Spreadsheet using gspread and googleapis for python with the service account.

*In your case, the Spreadsheets of client.open("LetsTry") and spreadsheetId = 'xyz' are required to be able to be accessed with the service account. Please be careful this.

References:

*

*Method: spreadsheets.values.append

*get_all_records()

*get_all_values()
If I misunderstood your question and this was not the result you want, I apologize.


text:
Q: Parcelable - ArrayList NullPointerException I'm making my object parcelable so I can use it with Intents. I'm getting a NullPointerException when, once received, I'm reading my object's content. Most exactly the content of my ArrayList<String>. When iterating over my ArrayList<String> it has null value in all positions, therefore my NullPointerException.
Here's my Parcelable class:
public class PhoneBackup implements Parcelable{

public Integer id;
public Long ts;
public String device_name;
public String device_manufacturer;
public String device_model;
public Integer backup_contacts_count;
public String description;
public ArrayList<String> backup_contacts;

public PhoneBackup()
{

}

public PhoneBackup(Parcel pc){
//      backup_contacts = new ArrayList<String>(); // Tried this way, still NPE

    id = pc.readInt();
    ts =  pc.readLong();
    device_name = pc.readString();
    device_manufacturer = pc.readString();
    device_model = pc.readString();
    backup_contacts_count = pc.readInt();
    description = pc.readString();
//      pc.readStringList(backup_contacts); // Tried this way, still NPE
    backup_contacts = pc.createStringArrayList();
}

// (getters and setters)

@Override
public int describeContents() {
    return 0;
}

@Override
public void writeToParcel(Parcel dest, int flags) {
    dest.writeInt(id);
    dest.writeLong(ts);
    dest.writeString(device_name);
    dest.writeString(device_manufacturer);
    dest.writeString(device_model);
    dest.writeInt(backup_contacts_count);
    dest.writeString(description);
    dest.writeList(backup_contacts);

}

/** Static field used to regenerate object, individually or as arrays */
public static final Parcelable.Creator<PhoneBackup> CREATOR = new Parcelable.Creator<PhoneBackup>() {
    public PhoneBackup createFromParcel(Parcel pc) {
        return new PhoneBackup(pc);
    }
    public PhoneBackup[] newArray(int size) {
        return new PhoneBackup[size];
    }
};

The NullPointerException is with my backup_contacts. But backup_contacts has the correct size but the containts are all null and as I need to read the contents of backup_contacts using get(position) I receive a null value and not a String.
Question is, why is the Parcelable passing null values to the ArrayList<String> and not he actual Strings? How can I fix it?

A: To read a list it should be
backup_contacts = new ArrayList<String>();
in.readList(backup_contacts, null);

Here is the documentation.
The documentation for createStringArrayList  says:

Read and return a new ArrayList containing String objects from the
  parcel that was written with writeStringList(List)

A: I think the problem might be in the writing to the parcel :
dest.writeList(backup_contacts);

should be
dest.writeStringList(backup_contacts);

public final void writeStringList (List val) Added in API
  level 1
Flatten a List containing String objects into the parcel, at the
  current dataPosition() and growing dataCapacity() if needed. They can
  later be retrieved with createStringArrayList() or
  readStringList(List).


text:
Q: Magento 2 is not generating the db_schema_whitelist.json file via CLI I'm updating a module to Magento 2.3 and need to migrate the old setup install scripts to the new db_schema.xml file (the new declarative schema). The db_schema.xml file was correctly generated after running:
php bin/magento setup:install --convert-old-scripts=1
But now I need to generate the db_schema_whitelist.json file and running the following command does nothing:
php bin/magento setup:db-declaration:generate-whitelist --module-name=[module_name]

I followed all the steps outlined in the docs and checked the permissions of the etc folder.
But the result is always the same: no errors, no response, nothing. Any ideas?

A: The db_schema_whitelist.json will also not be created if you enter a wrong module name or have any typo in the CLI command:
php bin/magento setup:db-declaration:generate-whitelist --module-name=Vendor_Module
In this case, the command will not throw any errors in cli.

A: Before run below command for generate db_schema_whitelist.json
php bin/magento setup:db-declaration:generate-whitelist --module-name=Vendor_Module

you have to enable module in which your "db_schema.xml" file exists by running below CLI command
bin/magento module:enable Vendor_Module

and of course clean cache.

A: Found my own answer. Turns out the db_schema.xml file generated automatically by Magento had an error. The line that declares the name of the table was missing the resource value.
This is how the  tag was generated after running the CLI command:

And this is how it should be:

resource should contain the database shard on which to install the table. This value must be default, quote, or sales. In my case, adding default did the trick.
Edit (04/25/2019):
Whenever the db_whitelist_schema.json file is not created automatically when running the bin/magento setup:db-declaration:generate-whitelist --module-name=Vendor_Modulename command you can safely assume there's an error in the etc/db_schema.xml file of your module.
Since the terminal won't return an error msg to help you fix the issue, you can resort to the following hack to discover the missing piece in your db_schema file.
1) Open the following core file: vendor/magento/framework/Setup/Declaration/Schema/SchemaConfig.php
2) Locate the getDeclarationConfig() method and add a try-catch like this:
/**
 * @inheritdoc
 */
public function getDeclarationConfig()
{
    try {
        $schema = $this->schemaFactory->create();
        $data = $this->readerComposite->read(FileResolverByModule::ALL_MODULES);
        $this->declarativeSchemaBuilder->addTablesData($data['table']);
        $schema = $this->declarativeSchemaBuilder->build($schema);
        return $schema;
    } catch (\Exception $e) {
        $writer = new \Zend\Log\Writer\Stream(BP . '/var/log/schema.log');
        $logger = new \Zend\Log\Logger();
        $logger->addWriter($writer);
        $logger->info($e->getMessage());
    }
}

3) Now run the bin/magento setup:db-declaration:generate-whitelist
4) Check for any errors in var/log/schema.log
5) Rinse and repeat until you fix all the errors in your db_schema.xml file
6) Don't forget to remove the temporary changes you made to the core file!

A: Based on the OP's own answer EDIT, I propose a more global way to debug executing the bin/magento setup:db-declaration:generate-whitelist --module-name=Vendor_Modulename command, which should work for all kind of error, not only ones about errors in db_schema.xml:

*

*Open the file that defines the setup:db-declaration:generate-whitelist command in vendor/magento/module-developer/Console/Command/TablesWhitelistGenerateCommand.php

*Locate the execute(...) method, and add the following code:
/**
 * @inheritdoc
 */
protected function execute(InputInterface $input, OutputInterface $output): int
{
    // ...
    try {
        // Original code
    } catch (ConfigurationMismatchException $e) {
        // Original code
    } catch (\Exception $e) {
        // ADD FOLLOWING LINE:
        $output->writeln('<error>' . $e->getMessage() . '</error>');
        return \Magento\Framework\Console\Cli::RETURN_FAILURE;
    }
    // ...
}

This way, you won't have to manually check a log file, as the error will be displayed in the CLI.

(In my opinion, this simple line of code should already be in the code base, anyway...)
EDIT: Actually, this exact line of code has been added in the core code. I was simply not up-to-date...

A: One really quick thing I've found worth checking. If Magento 2 is not generating your db_schema_whitelist.json, make sure your module is actually enabled by checking bin/magento mod:status module where module is the name of your module, and then bin/magento mod:ena module to enable your module. It's super easy to create a module and forget to enable it before trying to use it. This issue applies to more than just db_schema_whitelist.json, of course.

A: For me It only works after I run s:up first then the module installed and after that the whitelist json was added just fine.

A: The answer provided by @Danial is great but still if it is not working then check the below point as well
1- Check if module is enable or enable it using
bin/magento module:enable Vendor_Module

2- Check if you have the correct permission, maybe the file is not generating because you do not have the required permission.

A: php bin/magento setup:db-declaration:generate-whitelist --module-name=Ced_Commerce


text:
Q: php : multi-sort a multi-dimensional array I'd like to multi-sort a multi-dimensional array. Here's a sample of my array:
Array
(
    [0] => Array
        (
            [level] => beg01
            [start] => 09/10
            [finish] => 15/11
            [other] => blah blah
            [things] => blah blah
            [quite] => blah blah
            [a lot] => blah blah
            [actually] => blah blah
        )
    [1] => Array
        (
            [level] => beg01
            [start] => 01/10
            [finish] => 10/11
            [other] => blah blah
            [things] => blah blah
            [quite] => blah blah
            [a lot] => blah blah
            [actually] => blah blah
        )
........
}

I want the result to be sorted by the key 'level' and among each level, I want the items to be sorted by the key 'start'. Like this:
level 1 : 01/01
level 1 : 01/02
level 1 : 02/03

level 2 : 01/02
level 2 : 02/02
level 2 : 03/02
....

so far here's what I did: I pass my array twice trough this function:
function sort_one($arr,$index) {
                $b = array();
                $c = array();
                foreach ($arr as $key => $value) {
                    $b[$key] = $value[$index];
                }
                asort($b);

                foreach ($b as $key => $value) {
                    $c[] = $arr[$key];
                }

                return $c;
}

with index level and start. I get two new arrays $by_level and $by_date.
then I multisort them:
array_multisort($by_level, $by_date);

It works almost but some elements are not in place so I think I am doing something wrong.
edit: Found a working solution:
$sort = array();
foreach($query_result as $k=>$v) {
    $sort['level'][$k] = $v['level'];
    $sort['start'][$k] = $v['start'];
}
array_multisort($sort['level'], SORT_ASC, $sort['start'], SORT_ASC,$query_result);

A: You can achieve this in one pass by using usort with a callback which compares the level first, then compares the start only if the levels are equal:
usort($query_result, function($lhs, $rhs) {
     if ( $lhs['level'] == $rhs['level'] ) {
           return strcmp($lhs['start'], $rhs['start']);
     } else {
           return strcmp($lhs['level'], $rhs['level']);
     }
 });


text:
Q: Suspects found dead? Murder suspects found dead.
Is dead in this sentence an adjective or an adverb? Why ? Can you explain with examples ?

A: "find" is verb that can take an object and a complement. The complement may be an adjective that describes the object.

I found Joe happy and contented.

In a passive form the object becomes the subject

Joe was found happy and contented.

And in headlines, the linking verb "was" is sometimes omitted

Joe found happy and contented

Murder suspects found dead

Dead is an adjective that describes the murder suspects.

A: The detective fell over the edge of a cliff and fell right onto the murder suspects. He found them dead, because he fell over 100 feet (adverb). He found them dead because they were hit by the detective falling from great height (adjective).
It is an adjective referring to the suspects. I tried hard to create a sentence where the person finding them was dead (adverb).
And usually adverbs are formed by adding -ly. However, deadly has a different meaning.


text:
Q: Commands to start and stop Nginx and how many nginx processes will be created? I am new in using Nginx. I have two questions:
(a) I noticed that are two sets of commands to start and stop Nginx:
$ sudo nginx
$ sudo nginx -s stop

and
$ sudo service nginx start
$ sudo service nginx stop

What are the differences between them?
(b) Once Nginx is started, there are a number of its processes running. So, how many copies will be created and how does the system determine the number of processes to create?

A: A - In the first way you are using nginx executable to restart it, the second one uses built-in (I typically use it on Centos) operating system util which handles service scripts.
B - It is configured in nginx.conf, by default it is (as far as I remember) set to 2 working processes. Nginx always creates one master process as well
http://nginx.org/en/docs/beginners_guide.html


text:
Q: Holomorphic function which is injective Let $f$ be holomorphic in the upper half plane $\{\operatorname{Im}  z> 0\}$. Suppose that $\operatorname{Im} f'(z)> 0$ for all $z$ in the half plane. Show that $f$ is 1-to-1.

A: Given $z,w$ in the upper half plane with $z\ne w$, we have:
$$\frac{f(w)-f(z)}{w-z}=\int_0^1f'(z+t(w-z))dt.\tag{1}$$
Since $\mathrm{Im}\,f'>0$, the imaginary part of the right hand side is positive, which implies $f(z)\ne f(w)$.


text: Q: Wordpress menu showing all pages except on home page I have made a WordPress site. Here, I have added a menu bar for all pages. But the menu bar is shown on all pages except the home page. How can I fix it?


text:
Q: Migrated questions are loaded in newest questions via WebSockets, but disappear after refreshing I've just had the following situation on Meta Stack Overflow:

*

*I was on the newest questions page.

*"1 new question" appeared. I clicked that, and this question, which was migrated from Meta Stack Exchange, was added at the top of the question list.

*After refreshing the page, the question disappeared from the list. Now it's on the 17th page (when displaying 50 questions per page), along with other questions which was asked on August 29th.

I think that this question either shouldn't be displayed in the newest questions at all, or it should stay there after refreshing the page.


text:
Q: blazy and facebook share/like I am using a script, blazy, to change my page's images as the user scrolls down. It works fine, and I would like the user to have the possibility to share each image to his friends on Facebook. I managed to link the url to an anchor to the image. When sharing a link, a little thumbnail is displayed with the link with a short description of the image. My problem is that only the logo of my website is displayed and not the image the user wants to share.

Looking at The Open Graph protocol, I tried to create a meta tag when clicking on the Facebook share button. The result is the same -- the image I want to share is not displayed, this is because Facebook linter only looks at the HTML in the response and does not run any scripts. The content of my page always changes, I cannot write the meta tags "by hand".
<a class="facebook_share" href="actualites.php#237" onclick="
$('meta[name=og:image]').remove();
                      $('head').append('<meta name=\'og:image\' content=\'***/content/posts/237/449_thumb.png\'>');
window.open(...[see above]);


text:
Q: Is there a way to tell which exact enum I'm working with at run-time? I have two enums and a generic method. The generic type T could be either one of the enums.
    public enum myEnumA
    {
        a,
        b
    }

    public enum myEnumB
    {
        c,
        d
    }

    public void myMethod<T>()
    {
        if (typeof(T) is myEnumA)
        {
            //do something
        }
        else if (typeof (T) is myEnumB)
        {
            //do something else
        }
    }

The compiler tells me "the given expression is never of the provided type" regarding the if check.
Is there a way to tell which exact enum it is at run time?

A: You want:
if (typeof(T) == typeof(MyEnumA))

to compare the types. The is operator is for testing whether a value is of a particular type.
Note that having to test for particular types within a generic method suggests that it might not really be very generic after all - consider using overloads or just entirely separate methods instead.

A: Because typeof returns a Type instance and that will never be compatible with your enum types. So is will return always false. Instead you need
if (typeof(T) == typeof(myEnumA))

A: You can do
if (typeof(T) == typeof(myEnumA))

Your types are enums, which are sealed.  Were your types not sealed, you might need to use the IsAssignableFrom method, to check for subclassing, e.g.:
if (typeof(BaseTypeA).IsAssignableFrom(typeof(T))


text:
Q: Restrict access from IP when using Galera Cluster shared for pre-production and production webapplication servers At the moment we use a MariaDB + Galera Cluster for a production and pre-production environment.
All DB users on the pre-production and on the production application Servers have a wild card set for the host like this one:
CREATE USER 'user'@'%' IDENTIFIED BY '***';
GRANT ALL PRIVILEGES ON *.* TO 'user'@'%' IDENTIFIED BY '***'
 WITH GRANT OPTION MAX_QUERIES_PER_HOUR 0 MAX_CONNECTIONS_PER_HOUR 0
 MAX_UPDATES_PER_HOUR 0 MAX_USER_CONNECTIONS 0;

Is it somehow possible to restrict users from pre-production to access production databases?
We could set up a pre-prod and prod Galera cluster and MariaDB, but that is not an option in the moment.
The Galera cluster seems to need the wildcard to work with the MariaDB.
So when someone copies a db config from prod to pre-prod - which already happened, the prod db could be messed up.
Any hint how this could be more restrictive?
At the moment we are trying to setup some measurements to avoid using an prod db config on a pre-prod server.


text:
Q: What is the mean about "mysql+pymysql" in flask I want to use MySQL in flask, and one config is
app.config['SQLALCHEMY_DATABASE_URI'] = "mysql+pymysql://user:password@127.0.0.1:3306/db"

If I use mysql+pymysql, it can work
But when I only use mysql, the erroe message like this
Internal Server Error
The server encountered an internal error and was unable to complete your request. Either the server is overloaded or there is an error in the application.

But in my code, I don't import  pymysql, so what is the pymysql and why need use that can work

I know pymysql is a moudle

Thanks your reply!

A: The create_engine function (which is what uses the URL given in the config), requires you to give it a "dialect". A "dialect" is the name of the underlying database engine that SQLAlchemy is connecting to.
However, since many databases have multiple different clients (in Python these implement DBAPI), so in many cases (such as for the mysql dialect) you're required to give the name of the client you want SQLAlchemy to use. In this case, you're asking it to use the pymysql library to actually handle connectivity with MySQL.
SQLAlchemy 1.3 supports the following dialect/DBAPI-libraries for connecting to MySQL:

*

*mysqlclient (maintained fork of MySQL-Python)

*PyMySQL

*MySQL Connector/Python

*CyMySQL

*OurSQL

*Google Cloud SQL

*PyODBC

*zxjdbc for Jython


text:
Q: Creating a table in C# (table Layout Panel) I was wondering what the best way to do this is,
i have an array/list with some thing like the following
String[] _array

_array[1] = "number of Cups", "numcups";
_array[2] = "number of spoons", "numspoons";
_array[3] = "number of forks", "numforks";

I want to pass this to a method along with a number and create a table on a form that is some thing like
lets assume the number is 2
| Number of cups  | Number of Spoons | Number of Forks    |
| texbox.numbcups1| texbox.numspoons1| textbox.numforks1  |
| texbox.numbcups2| texbox.numspoons2| textbox.numforks3  |
so use the first array value as the title of the column and then the second value as the base name of a text box that the user will be able to enter data into.
So is the TableLayoutPanel the best choice for this, or is there a better function in forms to create this.
I hope you get the idea of what I am trying to create, a table with headed columns, and multiple rows that user can enter data into.


text:
Q: Guardar datos de archivo en ArrayList y desplegarlo de mayor a menor. Estoy trabajando en un programa que obtenga datos de un archivo de texto, que obtenga solo los primeros 100 y tener un metodo que ordene del primero al ultimo o viceversa y otro que busque un nombre especifico en el archivo.
 Esto es lo que tengo por el momento.
 import java.util.ArrayList;
 import java.util.Scanner;
 import java.io.File;

public class distritos
{

    public static void main(String[] args)
    {
        Scanner entrada;
        File archivo;
        String a;
        String linea;
        ArrayList<Double> array = new ArrayList<Double>();
        try
        {
            entrada = new Scanner("Texto.txt");
            a = entrada.nextLine();
            archivo = new File(a);
            entrada = new Scanner(archivo);

            int comienzo = 0;
            while(entrada.hasNextLine() && comienzo < 100)
            {

                linea = entrada.nextLine();
                System.out.println(linea);
                comienzo++;
            }
        }
        catch(Exception e)
        {

        }
    }
}

Lo probe y funciona bien, obtiene las primeras 100 lineas y las imprime, sin embargo, tengo problemas a la hora de ordernarlo y no se por donde empezar.

A: Antes de imprimir las lineas, tienes que ordenarlas, para esto puedes usar un ArrayList e introducir los valores de cada linea que contiene el archivo
    ...
    ...
    ArrayList<String> lista = new ArrayList<String>();

    int comienzo = 0;
     while(entrada.hasNextLine() && comienzo < 100)
     {

         linea = entrada.nextLine();
        // System.out.println(linea);
         lista.add(linea); //Agrega valor a ArrayList
         comienzo++;
     }
     ...
     ...

Posteriormente puedes usar para ordenar alfabéticamente el arraylist Collections.sort() y posteriormente imprimir los valores ordenados, de esta forma:
        Collections.sort(lista);
        //Ahora imprime valores ordenados
        for(String valor: lista){
            System.out.println(valor);
        }

De acuerdo a el código de tu pregunta, esta sería la forma de realizarlo:
    Scanner entrada;
    File archivo;
    String a;
    String linea;
   // ArrayList<Double> array = new ArrayList<Double>();
    ArrayList<String> lista = new ArrayList<String>();
    try
    {
        entrada = new Scanner("Texto.txt");
        a = entrada.nextLine();
        archivo = new File(a);
        entrada = new Scanner(archivo);

        int comienzo = 0;
        while(entrada.hasNextLine() && comienzo < 100)
        {

            linea = entrada.nextLine();
           // System.out.println(linea);
            lista.add(linea); //Agrega valor a ArrayList
            comienzo++;
        }

        //Despues de agregar a ArrayList, ordena.
        Collections.sort(lista);
        //Ahora imprime los valores ordenados.
        for(String valor: lista){
            System.out.println(valor);
        }

    }
    catch(Exception e)
    {
        System.out.println(e.getMessage());
    }


text:
Q: Category and tags goes 404 I made a custom theme for a website and I'm having some trouble with the category and tag pages, since they redirect to pages with the same slug or to 404 (when there is no pages).
On my website I have 3 custom type posts, each with about two customs taxonomies (none of then with category or tag as name).
Besides that I also using the custom permalink %postname% and all the site beside that two pages are working fine.
My .htaccess look like this:
    <IfModule mod_rewrite.c>
    RewriteEngine On
    RewriteBase /brazcubas/
    RewriteRule ^index\.php$ - [L]
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule . /brazcubas/index.php [L]
    </IfModule>

I don't know what I'm maybe doing wrong.
What I've already tried was:

*

*Disable and Enable the permalink structure.

*Create custom category pages

*Create custom archives pages

*Change to other theme.

Even with other themes the error still going.
What could it be?


text:
Q: spaCy similarity - Setting sense2vec or word2vec as default I came across one of spaCy's blog's post which introduces the sense2vec idea and there's also an online interface to play with it's most similar function while there's also an online tool to play with the similarity function, brought by spaCy.
I just couldn't understand if those tools are based on the sense2vec algorithm or just normal pre-trained word2vec model (I'm talking about the large English model).
Is there a way to define with which model to I would like to work with?
The point is that

A: You can load your own vectors by following these instructions in the docs. Using that process, you should be able to load in the sense2vec vectors.
The models that are used for the .similarity() methods are either the full word2vec model or tensors, depending on whether you're using the large or small model. The sentence similarity tool you linked to describes this:

By default, spaCy uses an average-of-vectors algorithm, using pre-trained vectors if available (e.g. the en_core_web_lg model). If not, the doc.tensor attribute is used, which is produced by the tagger, parser and entity recognizer. This is how the en_core_web_sm model provides similarities. Usually the .tensor-based similarities will be more structural, while the word vector similarities will be more topical. You can also customize the .similarity() method, to provide your own similarity function, which can be trained using supervised techniques.


text:
Q: [Terraform]│ The given key does not identify an element in this collection value Trying to understand what exactly am I missing here in my terraform module(Cloudflare).
Currently developing it but I've hit a stone with this one:
Code:
## Variables
variable "filters" {
  description = "required filters for the firwall rules"
  type = map(object({
    description = string
    expression = string
  }))
  default = {
    "filters1" = {
      description = "test-rule"
      expression = "test-exps"
    }
  }

}
variable "firewall-rules" {
    description = "A set of Firewall rules"
    type = map(object({
      description = string
      action = string
    }))
    default = {
     "rules1" = {
        description = "value"
        action = "value"
      }
    }

## Resources
resource "cloudflare_filter" "firewall-filters" {
  zone_id = var.zone_id
  for_each = var.filters
  description = each.value["description"]
  expression = each.value["expression"]

}
resource "cloudflare_firewall_rule" "firewall-rules" {
  zone_id = var.zone_id
  for_each = var.firewall-rules
  filter_id = cloudflare_filter.firewall-filters
  description = each.value["description"]
  action = each.value["action"]
}

Ignore "value" it's for testing purpose.
Technically shouldn't the for_each work fine, while filter_id points to
"cloudflare_filter.firewall-filters", which inherits the values from the variable "filters".

Thank you in advance!


text:
Q: strftime adding +1 day also removes 5 minutes Somehow, using strtotime and adding "+1 day" not only adds the day, but also removes 5 minutes.
In the following example I expect '2013-10-02 08:15:00', but get '2013-10-02 08:10:00':
$myDate = '2013-10-01 08:15:00';
$newDate = strtotime($myDate . ' +1 day');
$newDate = strftime("%Y-%m-%d %H:%m:00", $newDate);
debug($newDate);

//'2013-10-02 08:10:00'

BUT - if I use date() instead of strftime(), it works fine
$myDate = '2013-10-01 08:15:00';
$newDate = strtotime($myDate . ' +1 day');
$newDate = date("Y-m-d H:i:s", $newDate);
debug($newDate);

//'2013-10-02 08:15:00'

A: Needed a capital M instead of m.
Check http://php.net/manual/en/function.strftime.php
$myDate = '2013-10-01 08:15:00';
$newDate = strtotime($myDate . ' +1 day');
$newDate = strftime("%Y-%m-%d %H:%M:00", $newDate);
debug($newDate);


text:
Q: passing section id in mvc using @Url.Action so that user will be scrolled to a particular section after redirecting I am a web designer but I am told to design static pages in mvc where rather then using href="some url" I have to use href="@Url.Action("Controller", View)" Now I want to pass a section id in the url so when the user redirects it will be scrolled down to that specific section usually in html this is the syntax I use
href="index.html#mysectionid"

in Html I have something Like this

I want to Know How I am gonna do this thing in mvc. Thanks

A: You can mix C# code with normal html in Razor:
Test


text:
Q: Running some parts of a script as an unprivileged user with shell environment I am creating an instance configuration script that sets up a machine.
I am running the script via sudo i.e. sudo run.sh. Most of the steps require root access but some of the script's steps do no require root access and I prefer running them as the unprivileged user who ran the sudo.
Inside the script running with sudo, I am trying to do
sudo -i -u username sh -c 'echo $MY_ENV'

Since .bashrc contains export MY_ENV=something I expect the above command to print "something"
How can I temporarily switch inside the script to the other user to run commands that include the user's shell env ?

A: .bashrc is executed only by interactive shells, not by scripts¹. It's the wrong place to define environment variables. See Is there a ".bashrc" equivalent file read by all shells? and the Ubuntu wiki.
You can tell bash to read .bashrc explicitly. Of course you'll have to execute bash, not sh which could be a different shell:
sudo -i -u username bash -c '. `~/.bashrc; echo "$MY_ENV"'

But it's a bad idea because .bashrc files are likely to contain things that assume that they're executed on a terminal and that spend time setting up key bindings, aliases, prompts, etc.
The sane solution is to put environment variable definitions where they belong, in ~/.profile or ~/.pam_environment.
¹  Except when bash is called by sshd for some weird reason.


text:
Q: Reference concerning weak-type (1,1) operator in $\mathbb{R}^d$ I wish someone give me some reference on weak-type (1,1) operator in the d-dimensional Euclidean space. Thanks for any kind help.

A: Let $(X, \mathcal{X}, \mu)$ and $(Y, \mathcal{Y}, \nu)$ be measure spaces, and suppose that $T$ is an operator mapping measurable functions defined on $X$ to measurable functions defined on $Y$.  Let $1 \le p, q \le \infty$.  We say that $T$ is of strong-type (p,q) if there is an absolute constant $C > 0$ such that $||Tf||_q \le C ||f||_p$, for all $f$ for which $T$ is defined.  In applications, we frequently begin with $T$ defined on some dense subclass of $L^p(X)$ (say $X$ and $Y$ are Euclidean spaces with Lebesgue measure and $T$ is a sublinear operator defined on the Schwartz class or for continuous functions of compact support).  In this case, an a priori estimate of this form guarantees that $T$ may be uniquely and meaningfully extended to all of $L^p$.
Define the distribution function of f by $\lambda_f(t) := \mu(\{x \in X: |f(x)| > t\})$.  Then we have $\displaystyle ||f||_p^p = \int_X |f|^p \ge \int _{|f| > t} |f|^p \ge t^p \lambda_f(t) $, which is Chebyshev's inequality.
That is, $\lambda_f(t) \le \frac{||f||_p^p}{t^p}$.  So, if $T$ satisfies the strong (p,q) bound, we get from Chebyshev that $\lambda_{Tf}(t) \le C \frac{||f||_p^q}{t^q}$.  We say that $T$ is of weak type (p,q) if it satisfies this weaker bound.  So a strong type (p,q) operator is of weak type (p,q), but this implication cannot be reversed in general.
One reason we care about weak type bounds is because there are a series of results (such as the Marcinkiewicz interpolation result, which you can read about in this blog post by Terry Tao http://terrytao.wordpress.com/2009/03/30/245c-notes-1-interpolation-of-lp-spaces/) which essentially say that, under some mild conditions, two weak type bounds $(p_1, q_1), (p_2, q_2)$ imply intermediary strong type bounds.


text:
Q: Sentence classification subjectivity/objectivity I want to classify sentences as objective or subjective.
For example :
Objective: Taipei 101 is the world's tallest building.
Subjective: Venus Williams is the greatest athlete of this decade.
I was thinking of using Naive Bayes as my classifier.
What data should I use for training?
I was thinking of news articles and wiki articles for objective sentences.
For subjectivity, I was thinking of using a lot of books (since books tend to be more subjective).
Is this likely to work or am I thinking about this wrong? What accuracy can I expect? Which data will work best for training objective and subjective?

A: The best training data will be the same kind of data that you will really be classifying (from the same source). If you train on news article titles (as "objective") and book sentences (as "subjective"), then really you're learning a model to distinguish between news article titles and book sentences. If you then use this model to classify tweets (for example) as "subjective" or "objective", then you shouldn't expect good performance.
I would suggest that you manually label 1000 sentences from the actual kind of data that you will classify as being "subjective" or "objective". This will give you relevant and accurate training data, and may also teach you about your data and your problem. Then start with those 1000 sentences as training data, and measure your performance.