Programs & Examples On #Iscriptcontrol

What is the current choice for doing RPC in Python?

We are developing Versile Python (VPy), an implementation for python 2.6+ and 3.x of a new ORB/RPC framework. Functional AGPL dev releases for review and testing are available. VPy has native python capabilities similar to PyRo and RPyC via a general native objects layer (code example). The product is designed for platform-independent remote object interaction for implementations of Versile Platform.

Full disclosure: I work for the company developing VPy.

Configure cron job to run every 15 minutes on Jenkins

1) Your cron is wrong. If you want to run job every 15 mins on Jenkins use this:

H/15 * * * *

2) Warning from Jenkins Spread load evenly by using ‘...’ rather than ‘...’ came with JENKINS-17311:

To allow periodically scheduled tasks to produce even load on the system, the symbol H (for “hash”) should be used wherever possible. For example, using 0 0 * * * for a dozen daily jobs will cause a large spike at midnight. In contrast, using H H * * * would still execute each job once a day, but not all at the same time, better using limited resources.

Examples:

  • H/15 * * * * - every fifteen minutes (perhaps at :07, :22, :37, :52):
  • H(0-29)/10 * * * * - every ten minutes in the first half of every hour (three times, perhaps at :04, :14, :24)
  • H 9-16/2 * * 1-5 - once every two hours every weekday (perhaps at 10:38 AM, 12:38 PM, 2:38 PM, 4:38 PM)
  • H H 1,15 1-11 * - once a day on the 1st and 15th of every month except December

javascript close current window

you can try

_x000D_
_x000D_
function closed(){_x000D_
 _x000D_
 setTimeout("window.close()", 500);_x000D_
 }
_x000D_
_x000D_
_x000D_

git switch branch without discarding local changes

There are a bunch of different ways depending on how far along you are and which branch(es) you want them on.

Let's take a classic mistake:

$ git checkout master
... pause for coffee, etc ...
... return, edit a bunch of stuff, then: oops, wanted to be on develop

So now you want these changes, which you have not yet committed to master, to be on develop.

  1. If you don't have a develop yet, the method is trivial:

    $ git checkout -b develop
    

    This creates a new develop branch starting from wherever you are now. Now you can commit and the new stuff is all on develop.

  2. You do have a develop. See if Git will let you switch without doing anything:

    $ git checkout develop
    

    This will either succeed, or complain. If it succeeds, great! Just commit. If not (error: Your local changes to the following files would be overwritten ...), you still have lots of options.

    The easiest is probably git stash (as all the other answer-ers that beat me to clicking post said). Run git stash save or git stash push,1 or just plain git stash which is short for save / push:

    $ git stash
    

    This commits your code (yes, it really does make some commits) using a weird non-branch-y method. The commits it makes are not "on" any branch but are now safely stored in the repository, so you can now switch branches, then "apply" the stash:

    $ git checkout develop
    Switched to branch 'develop'
    $ git stash apply
    

    If all goes well, and you like the results, you should then git stash drop the stash. This deletes the reference to the weird non-branch-y commits. (They're still in the repository, and can sometimes be retrieved in an emergency, but for most purposes, you should consider them gone at that point.)

The apply step does a merge of the stashed changes, using Git's powerful underlying merge machinery, the same kind of thing it uses when you do branch merges. This means you can get "merge conflicts" if the branch you were working on by mistake, is sufficiently different from the branch you meant to be working on. So it's a good idea to inspect the results carefully before you assume that the stash applied cleanly, even if Git itself did not detect any merge conflicts.

Many people use git stash pop, which is short-hand for git stash apply && git stash drop. That's fine as far as it goes, but it means that if the application results in a mess, and you decide you don't want to proceed down this path, you can't get the stash back easily. That's why I recommend separate apply, inspect results, drop only if/when satisfied. (This does of course introduce another point where you can take another coffee break and forget what you were doing, come back, and do the wrong thing, so it's not a perfect cure.)


1The save in git stash save is the old verb for creating a new stash. Git version 2.13 introduced the new verb to make things more consistent with pop and to add more options to the creation command. Git version 2.16 formally deprecated the old verb (though it still works in Git 2.23, which is the latest release at the time I am editing this).

How do I clear inner HTML

The problem appears to be that the global symbol clear is already in use and your function doesn't succeed in overriding it. If you change that name to something else (I used blah), it works just fine:

Live: Version using clear which fails | Version using blah which works

<html>
<head>
    <title>lala</title>
</head>
<body>
    <h1 onmouseover="go('The dog is in its shed')" onmouseout="blah()">lalala</h1>
    <div id="goy"></div>
    <script type="text/javascript">
    function go(what) {
        document.getElementById("goy").innerHTML = what;
    }
    function blah() {
        document.getElementById("goy").innerHTML = "";
    }
    </script>
</body>
</html>

This is a great illustration of the fundamental principal: Avoid global variables wherever possible. The global namespace in browsers is incredibly crowded, and when conflicts occur, you get weird bugs like this.

A corollary to that is to not use old-style onxyz=... attributes to hook up event handlers, because they require globals. Instead, at least use code to hook things up: Live Copy

<html>
<head>
    <title>lala</title>
</head>
<body>
    <h1 id="the-header">lalala</h1>
    <div id="goy"></div>
    <script type="text/javascript">
      // Scoping function makes the declarations within
      // it *not* globals
      (function(){
        var header = document.getElementById("the-header");
        header.onmouseover = function() {
          go('The dog is in its shed');
        };
        header.onmouseout = clear;

        function go(what) {
          document.getElementById("goy").innerHTML = what;
        }
        function clear() {
          document.getElementById("goy").innerHTML = "";
        }
      })();
    </script>
</body>
</html>

...and even better, use DOM2's addEventListener (or attachEvent on IE8 and earlier) so you can have multiple handlers for an event on an element.

How to remove line breaks (no characters!) from the string?

$str = "
Dear friends, I just wanted so Hello. How are you guys? I'm fine, thanks!<br />
<br />
Greetings,<br />
Bill";

echo str_replace(array("\n", "\r"), '', $str);  // echo $str in a single line

Passing parameters to a Bash function

If you prefer named parameters, it's possible (with a few tricks) to actually pass named parameters to functions (also makes it possible to pass arrays and references).

The method I developed allows you to define named parameters passed to a function like this:

function example { args : string firstName , string lastName , integer age } {
  echo "My name is ${firstName} ${lastName} and I am ${age} years old."
}

You can also annotate arguments as @required or @readonly, create ...rest arguments, create arrays from sequential arguments (using e.g. string[4]) and optionally list the arguments in multiple lines:

function example {
  args
    : @required string firstName
    : string lastName
    : integer age
    : string[] ...favoriteHobbies

  echo "My name is ${firstName} ${lastName} and I am ${age} years old."
  echo "My favorite hobbies include: ${favoriteHobbies[*]}"
}

In other words, not only you can call your parameters by their names (which makes up for a more readable core), you can actually pass arrays (and references to variables - this feature works only in Bash 4.3 though)! Plus, the mapped variables are all in the local scope, just as $1 (and others).

The code that makes this work is pretty light and works both in Bash 3 and Bash 4 (these are the only versions I've tested it with). If you're interested in more tricks like this that make developing with bash much nicer and easier, you can take a look at my Bash Infinity Framework, the code below is available as one of its functionalities.

shopt -s expand_aliases

function assignTrap {
  local evalString
  local -i paramIndex=${__paramIndex-0}
  local initialCommand="${1-}"

  if [[ "$initialCommand" != ":" ]]
  then
    echo "trap - DEBUG; eval \"${__previousTrap}\"; unset __previousTrap; unset __paramIndex;"
    return
  fi

  while [[ "${1-}" == "," || "${1-}" == "${initialCommand}" ]] || [[ "${#@}" -gt 0 && "$paramIndex" -eq 0 ]]
  do
    shift # First colon ":" or next parameter's comma ","
    paramIndex+=1
    local -a decorators=()
    while [[ "${1-}" == "@"* ]]
    do
      decorators+=( "$1" )
      shift
    done

    local declaration=
    local wrapLeft='"'
    local wrapRight='"'
    local nextType="$1"
    local length=1

    case ${nextType} in
      string | boolean) declaration="local " ;;
      integer) declaration="local -i" ;;
      reference) declaration="local -n" ;;
      arrayDeclaration) declaration="local -a"; wrapLeft= ; wrapRight= ;;
      assocDeclaration) declaration="local -A"; wrapLeft= ; wrapRight= ;;
      "string["*"]") declaration="local -a"; length="${nextType//[a-z\[\]]}" ;;
      "integer["*"]") declaration="local -ai"; length="${nextType//[a-z\[\]]}" ;;
    esac

    if [[ "${declaration}" != "" ]]
    then
      shift
      local nextName="$1"

      for decorator in "${decorators[@]}"
      do
        case ${decorator} in
          @readonly) declaration+="r" ;;
          @required) evalString+="[[ ! -z \$${paramIndex} ]] || echo \"Parameter '$nextName' ($nextType) is marked as required by '${FUNCNAME[1]}' function.\"; " >&2 ;;
          @global) declaration+="g" ;;
        esac
      done

      local paramRange="$paramIndex"

      if [[ -z "$length" ]]
      then
        # ...rest
        paramRange="{@:$paramIndex}"
        # trim leading ...
        nextName="${nextName//\./}"
        if [[ "${#@}" -gt 1 ]]
        then
          echo "Unexpected arguments after a rest array ($nextName) in '${FUNCNAME[1]}' function." >&2
        fi
      elif [[ "$length" -gt 1 ]]
      then
        paramRange="{@:$paramIndex:$length}"
        paramIndex+=$((length - 1))
      fi

      evalString+="${declaration} ${nextName}=${wrapLeft}\$${paramRange}${wrapRight}; "

      # Continue to the next parameter:
      shift
    fi
  done
  echo "${evalString} local -i __paramIndex=${paramIndex};"
}

alias args='local __previousTrap=$(trap -p DEBUG); trap "eval \"\$(assignTrap \$BASH_COMMAND)\";" DEBUG;'

how to rotate a bitmap 90 degrees

By default the rotation point is the Canvas's (0,0) point, and my guess is that you may want to rotate it around the center. I did that:

protected void renderImage(Canvas canvas)
{
    Rect dest,drawRect ;

    drawRect = new Rect(0,0, mImage.getWidth(), mImage.getHeight());
    dest = new Rect((int) (canvas.getWidth() / 2 - mImage.getWidth() * mImageResize / 2), // left
                    (int) (canvas.getHeight()/ 2 - mImage.getHeight()* mImageResize / 2), // top
                    (int) (canvas.getWidth() / 2 + mImage.getWidth() * mImageResize / 2), //right
                    (int) (canvas.getWidth() / 2 + mImage.getHeight()* mImageResize / 2));// bottom

    if(!mRotate) {
        canvas.drawBitmap(mImage, drawRect, dest, null);
    } else {
        canvas.save(Canvas.MATRIX_SAVE_FLAG); //Saving the canvas and later restoring it so only this image will be rotated.
        canvas.rotate(90,canvas.getWidth() / 2, canvas.getHeight()/ 2);
        canvas.drawBitmap(mImage, drawRect, dest, null);
        canvas.restore();
    }
}

How to remove td border with html?

To remove borders between cells, while retaining the border around the table, add the attribute rules=none to the table tag.

There is no way in HTML to achieve the rendering specified in the last figure of the question. There are various tricky workarounds that are based on using some other markup structure.

java- reset list iterator to first element of the list

Best would be not using LinkedList at all, usually it is slower in all disciplines, and less handy. (When mainly inserting/deleting to the front, especially for big arrays LinkedList is faster)

Use ArrayList, and iterate with

int len = list.size();
for (int i = 0; i < len; i++) {
  Element ele = list.get(i);
}

Reset is trivial, just loop again.
If you insist on using an iterator, then you have to use a new iterator:

iter = list.listIterator();

(I saw only once in my life an advantage of LinkedList: i could loop through whith a while loop and remove the first element)

SQL set values of one column equal to values of another column in the same table

I don't think that other example is what you're looking for. If you're just updating one column from another column in the same table you should be able to use something like this.

update some_table set null_column = not_null_column where null_column is null

Sending data back to the Main Activity in Android

FirstActivity uses startActivityForResult:

Intent intent = new Intent(MainActivity.this,SecondActivity.class);
startActivityForResult(intent, int requestCode); // suppose requestCode == 2

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
    super.onActivityResult(requestCode, resultCode, data);
    if (requestCode == 2)
    {
        String message=data.getStringExtra("MESSAGE");
    }
}

On SecondActivity call setResult() onClick events or onBackPressed()

Intent intent=new Intent();
intent.putExtra("MESSAGE",message);
setResult(Activity.RESULT_OK, intent);

return, return None, and no return at all?

On the actual behavior, there is no difference. They all return None and that's it. However, there is a time and place for all of these. The following instructions are basically how the different methods should be used (or at least how I was taught they should be used), but they are not absolute rules so you can mix them up if you feel necessary to.

Using return None

This tells that the function is indeed meant to return a value for later use, and in this case it returns None. This value None can then be used elsewhere. return None is never used if there are no other possible return values from the function.

In the following example, we return person's mother if the person given is a human. If it's not a human, we return None since the person doesn't have a mother (let's suppose it's not an animal or something).

def get_mother(person):
    if is_human(person):
        return person.mother
    else:
        return None

Using return

This is used for the same reason as break in loops. The return value doesn't matter and you only want to exit the whole function. It's extremely useful in some places, even though you don't need it that often.

We've got 15 prisoners and we know one of them has a knife. We loop through each prisoner one by one to check if they have a knife. If we hit the person with a knife, we can just exit the function because we know there's only one knife and no reason the check rest of the prisoners. If we don't find the prisoner with a knife, we raise an alert. This could be done in many different ways and using return is probably not even the best way, but it's just an example to show how to use return for exiting a function.

def find_prisoner_with_knife(prisoners):
    for prisoner in prisoners:
        if "knife" in prisoner.items:
            prisoner.move_to_inquisition()
            return # no need to check rest of the prisoners nor raise an alert
    raise_alert()

Note: You should never do var = find_prisoner_with_knife(), since the return value is not meant to be caught.

Using no return at all

This will also return None, but that value is not meant to be used or caught. It simply means that the function ended successfully. It's basically the same as return in void functions in languages such as C++ or Java.

In the following example, we set person's mother's name and then the function exits after completing successfully.

def set_mother(person, mother):
    if is_human(person):
        person.mother = mother

Note: You should never do var = set_mother(my_person, my_mother), since the return value is not meant to be caught.

Detecting Back Button/Hash Change in URL

I do the following, if you want to use it then paste it in some where and set your handler code in locationHashChanged(qs) where commented, and then call changeHashValue(hashQuery) every time you load an ajax request. Its not a quick-fix answer and there are none, so you will need to think about it and pass sensible hashQuery args (ie a=1&b=2) to changeHashValue(hashQuery) and then cater for each combination of said args in your locationHashChanged(qs) callback ...

// Add code below ...
function locationHashChanged(qs)
{
  var q = parseQs(qs);
  // ADD SOME CODE HERE TO LOAD YOUR PAGE ELEMS AS PER q !!
  // YOU SHOULD CATER FOR EACH hashQuery ATTRS COMBINATION
  //  THAT IS PASSED TO changeHashValue(hashQuery)
}

// CALL THIS FROM YOUR AJAX LOAD CODE EACH LOAD ...
function changeHashValue(hashQuery)
{
  stopHashListener();
  hashValue     = hashQuery;
  location.hash = hashQuery;
  startHashListener();
}

// AND DONT WORRY ABOUT ANYTHING BELOW ...
function checkIfHashChanged()
{
  var hashQuery = getHashQuery();
  if (hashQuery == hashValue)
    return;
  hashValue = hashQuery;
  locationHashChanged(hashQuery);
}

function parseQs(qs)
{
  var q = {};
  var pairs = qs.split('&');
  for (var idx in pairs) {
    var arg = pairs[idx].split('=');
    q[arg[0]] = arg[1];
  }
  return q;
}

function startHashListener()
{
  hashListener = setInterval(checkIfHashChanged, 1000);
}

function stopHashListener()
{
  if (hashListener != null)
    clearInterval(hashListener);
  hashListener = null;
}

function getHashQuery()
{
  return location.hash.replace(/^#/, '');
}

var hashListener = null;
var hashValue    = '';//getHashQuery();
startHashListener();

Use 'class' or 'typename' for template parameters?

In response to Mike B, I prefer to use 'class' as, within a template, 'typename' has an overloaded meaning, but 'class' does not. Take this checked integer type example:

template <class IntegerType>
class smart_integer {
public: 
    typedef integer_traits<Integer> traits;
    IntegerType operator+=(IntegerType value){
        typedef typename traits::larger_integer_t larger_t;
        larger_t interm = larger_t(myValue) + larger_t(value); 
        if(interm > traits::max() || interm < traits::min())
            throw overflow();
        myValue = IntegerType(interm);
    }
}

larger_integer_t is a dependent name, so it requires 'typename' to preceed it so that the parser can recognize that larger_integer_t is a type. class, on the otherhand, has no such overloaded meaning.

That... or I'm just lazy at heart. I type 'class' far more often than 'typename', and thus find it much easier to type. Or it could be a sign that I write too much OO code.

Validate SSL certificates with Python

From release version 2.7.9/3.4.3 on, Python by default attempts to perform certificate validation.

This has been proposed in PEP 467, which is worth a read: https://www.python.org/dev/peps/pep-0476/

The changes affect all relevant stdlib modules (urllib/urllib2, http, httplib).

Relevant documentation:

https://docs.python.org/2/library/httplib.html#httplib.HTTPSConnection

This class now performs all the necessary certificate and hostname checks by default. To revert to the previous, unverified, behavior ssl._create_unverified_context() can be passed to the context parameter.

https://docs.python.org/3/library/http.client.html#http.client.HTTPSConnection

Changed in version 3.4.3: This class now performs all the necessary certificate and hostname checks by default. To revert to the previous, unverified, behavior ssl._create_unverified_context() can be passed to the context parameter.

Note that the new built-in verification is based on the system-provided certificate database. Opposed to that, the requests package ships its own certificate bundle. Pros and cons of both approaches are discussed in the Trust database section of PEP 476.

Eclipse interface icons very small on high resolution screen in Windows 8.1

I had this problem when I changed my default Windows 10 language from Eng to Italian, with Eclipse being installed when default language was Eng. Reverting Windows language to Eng and rebooting solved the problem. I don’t know what’s happened, Windows rename some folders like C:\Users translating it in your default language (i.e. C:\Utenti) and maybe this is causing problems.

How to filter by string in JSONPath?

The browser testing tools while convenient can be a bit deceiving. Consider:

{
  "resourceType": "Encounter",
  "id": "EMR56788",
  "text": {
    "status": "generated",
    "div": "Patient admitted with chest pains</div>"
  },
  "status": "in-progress",
  "class": "inpatient",
  "patient": {
    "reference": "Patient/P12345",
    "display": "Roy Batty"
  }
}

Most tools returned this as false:

$[?(@.class==inpatient)]

But when I executed against

<dependency>
    <groupId>com.jayway.jsonpath</groupId>
    <artifactId>json-path</artifactId>
    <version>1.2.0</version>
</dependency>

It returned true. I recommend writing a simple unit test to verify rather than rely on the browser testing tools.

Why is processing a sorted array faster than processing an unsorted array?

This question has already been answered excellently many times over. Still I'd like to draw the group's attention to yet another interesting analysis.

Recently this example (modified very slightly) was also used as a way to demonstrate how a piece of code can be profiled within the program itself on Windows. Along the way, the author also shows how to use the results to determine where the code is spending most of its time in both the sorted & unsorted case. Finally the piece also shows how to use a little known feature of the HAL (Hardware Abstraction Layer) to determine just how much branch misprediction is happening in the unsorted case.

The link is here: A Demonstration of Self-Profiling

What is the difference between Builder Design pattern and Factory Design pattern?

Builder and Abstract Factory

The Builder design pattern is very similar, at some extent, to the Abstract Factory pattern. That's why it is important to be able to make the difference between the situations when one or the other is used. In the case of the Abstract Factory, the client uses the factory's methods to create its own objects. In the Builder's case, the Builder class is instructed on how to create the object and then it is asked for it, but the way that the class is put together is up to the Builder class, this detail making the difference between the two patterns.

Common interface for products

In practice the products created by the concrete builders have a structure significantly different, so if there is not a reason to derive different products a common parent class. This also distinguishes the Builder pattern from the Abstract Factory pattern which creates objects derived from a common type.

From: http://www.oodesign.com/builder-pattern.html

Creating an XmlNode/XmlElement in C# without an XmlDocument?

You need Linq - System.Xml.Linq to be precise.

You can create XML using XElement from scratch - that should pretty much sort you out.

SQL Server 2008 - IF NOT EXISTS INSERT ELSE UPDATE

You need to replace it as WHERE clockDate = { fn CURRENT_DATE() } AND userName = 'test'. Please remove extra ")" from { fn CURRENT_DATE() })

Vector erase iterator

Do not erase and then increment the iterator. No need to increment, if your vector has an odd (or even, I don't know) number of elements you will miss the end of the vector.

ld cannot find an existing library

As just formulated by grepsedawk, the answer lies in the -l option of g++, calling ld. If you look at the man page of this command, you can either do:

  • g++ -l:libmagic.so.1 [...]
  • or: g++ -lmagic [...] , if you have a symlink named libmagic.so in your libs path

Adding onClick event dynamically using jQuery

let a = $("<a>bfCaptchaEntry</a>");
a.attr("onClick", "function(" + someParameter+ ")");

How to replace all double quotes to single quotes using jquery?

Use double quote to enclose the quote or escape it.

newTemp = mystring.replace(/"/g, "'");

or

newTemp = mystring.replace(/"/g, '\'');

How to trigger event when a variable's value is changed?

Seems to me like you want to create a property.

public int MyProperty
{
    get { return _myProperty; }
    set
    {
        _myProperty = value;
        if (_myProperty == 1)
        {
            // DO SOMETHING HERE
        }
    }
}

private int _myProperty;

This allows you to run some code any time the property value changes. You could raise an event here, if you wanted.

SQL Transaction Error: The current transaction cannot be committed and cannot support operations that write to the log file

Had the exact same error in a procedure. It turns out the user running it (a technical user in our case) did not have sufficient rigths to create a temporary table.

EXEC sp_addrolemember 'db_ddladmin', 'username_here';

did the trick

iOS8 Beta Ad-Hoc App Download (itms-services)

I was struggling with this, my app was installing but not complete (almost 60% I can say) in iOS8, but in iOS7.1 it was working as expected. The error message popped was:

"Cannot install at this time". 

Finally Zillan's link helped me to get apple documentation. So, check:

  1. make sure the internet reachability in your device as you will be in local network/ intranet.
  2. Also make sure the address ax.init.itunes.apple.com is not getting blocked by your firewall/proxy (Just type this address in safari, a blank page must load).

As soon as I changed the proxy it installed completely. Hope it will help someone.

Check if a string isn't nil or empty in Lua

One simple thing you could do is abstract the test inside a function.

local function isempty(s)
  return s == nil or s == ''
end

if isempty(foo) then
  foo = "default value"
end

Python extending with - using super() Python 3 vs Python 2

Another python3 implementation that involves the use of Abstract classes with super(). You should remember that

super().__init__(name, 10)

has the same effect as

Person.__init__(self, name, 10)

Remember there's a hidden 'self' in super(), So the same object passes on to the superclass init method and the attributes are added to the object that called it. Hence super()gets translated to Person and then if you include the hidden self, you get the above code frag.

from abc import ABCMeta, abstractmethod
class Person(metaclass=ABCMeta):
    name = ""
    age = 0

    def __init__(self, personName, personAge):
        self.name = personName
        self.age = personAge

    @abstractmethod
    def showName(self):
        pass

    @abstractmethod
    def showAge(self):
        pass


class Man(Person):

    def __init__(self, name, height):
        self.height = height
        # Person.__init__(self, name, 10)
        super().__init__(name, 10)  # same as Person.__init__(self, name, 10)
        # basically used to call the superclass init . This is used incase you want to call subclass init
        # and then also call superclass's init.
        # Since there's a hidden self in the super's parameters, when it's is called,
        # the superclasses attributes are a part of the same object that was sent out in the super() method

    def showIdentity(self):
        return self.name, self.age, self.height

    def showName(self):
        pass

    def showAge(self):
        pass


a = Man("piyush", "179")
print(a.showIdentity())

Executing a batch file in a remote machine through PsExec

You have an extra -c you need to get rid of:

psexec -u administrator -p force \\135.20.230.160 -s -d cmd.exe /c "C:\Amitra\bogus.bat"

Using CSS to affect div style inside iframe

Yes. Take a look at this other thread for details: How to apply CSS to iframe?

var cssLink = document.createElement("link");
cssLink.href = "style.css";  
cssLink.rel = "stylesheet";  
cssLink.type = "text/css";  
frames['frame1'].document.body.appendChild(cssLink); 

How to resize an Image C#

This is the code that I worked out for a specific requirement ie: the destination is always in landscape ratio. It should give you a good start.

public Image ResizeImage(Image source, RectangleF destinationBounds)
{
    RectangleF sourceBounds = new RectangleF(0.0f,0.0f,(float)source.Width, (float)source.Height);
    RectangleF scaleBounds = new RectangleF();

    Image destinationImage = new Bitmap((int)destinationBounds.Width, (int)destinationBounds.Height);
    Graphics graph = Graphics.FromImage(destinationImage);
    graph.InterpolationMode =
        System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;

    // Fill with background color
    graph.FillRectangle(new SolidBrush(System.Drawing.Color.White), destinationBounds);

    float resizeRatio, sourceRatio;
    float scaleWidth, scaleHeight;

    sourceRatio = (float)source.Width / (float)source.Height;

    if (sourceRatio >= 1.0f)
    {
        //landscape
        resizeRatio = destinationBounds.Width / sourceBounds.Width;
        scaleWidth = destinationBounds.Width;
        scaleHeight = sourceBounds.Height * resizeRatio;
        float trimValue = destinationBounds.Height - scaleHeight;
        graph.DrawImage(source, 0, (trimValue / 2), destinationBounds.Width, scaleHeight);
    }
    else
    {
        //portrait
        resizeRatio = destinationBounds.Height/sourceBounds.Height;
        scaleWidth = sourceBounds.Width * resizeRatio;
        scaleHeight = destinationBounds.Height;
        float trimValue = destinationBounds.Width - scaleWidth;
        graph.DrawImage(source, (trimValue / 2), 0, scaleWidth, destinationBounds.Height);
    }

    return destinationImage;

}

Find file in directory from command line

locate <file_pattern>

*** find will certainly work, and can target specific directories. However, this command is slower than the locate command. On a Linux OS, each morning a database is constructed that contains a list of all directory and files, and the locate command efficiently searches this database, so if you want to do a search for files that weren't created today, this would be the fastest way to accomplish such a task.

Convert a List<T> into an ObservableCollection<T>

The Observable Collection constructor will take an IList or an IEnumerable.

If you find that you are going to do this a lot you can make a simple extension method:

    public static ObservableCollection<T> ToObservableCollection<T>(this IEnumerable<T> enumerable)
    {
        return new ObservableCollection<T>(enumerable);
    }

How can I convert a DOM element to a jQuery element?

var elm = document.createElement("div");
var jelm = $(elm);//convert to jQuery Element
var htmlElm = jelm[0];//convert to HTML Element

How to load local html file into UIWebView

if let htmlFile = NSBundle.mainBundle().pathForResource("aa", ofType: "html"){
    do{
        let htmlString = try NSString(contentsOfFile: htmlFile, encoding:NSUTF8StringEncoding )
        webView.loadHTMLString(htmlString as String, baseURL: nil)
    }
    catch _ {
    }
}

Java JDBC connection status

The low-cost method, regardless of the vendor implementation, would be to select something from the process memory or the server memory, like the DB version or the name of the current database. IsClosed is very poorly implemented.

Example:

java.sql.Connection conn = <connect procedure>;
conn.close();
try {
  conn.getMetaData();
} catch (Exception e) {
  System.out.println("Connection is closed");
}

header location not working in my php code

It took me some time to figure this out: My php-file was encoded in UTF-8. And the BOM prevented header location to work properly. In Notepad++ I set the file encoding to "UTF-8 without BOM" and the problem was gone.

Docker how to change repository name or rename image?

To rename an image, you give it a new tag, and then remove the old tag using the ‘rmi’ command:

$ docker tag $ docker rmi

This second step is scary, as ‘rmi’ means “remove image”. However, docker won’t actually remove the image if it has any other tags. That is, if you were to immediately follow this with: docker rmi , then it would actually remove the image (assuming there are no other tags assigned to the image)

How to set the context path of a web application in Tomcat 7.0

I faced this problem for one month,Putting context tag inside server.xml is not safe it affect context elements deploying for all other host ,for big apps it take connection errors also not good isolation for example you may access other sites by folder name domain2.com/domain1Folder !! also database session connections loaded twice ! the other way is put ROOT.xml file that has context tag with full path such :

 <Context path="" docBase="/var/lib/tomcat7/webapps/ROOT" />

in conf/catalina/webappsfoldername and deploy war file as ROOT.war inside webappsfoldername and also specify host such

 <Host name="domianname"  appBase="webapps2" unpackWARs="true"  autoDeploy="true"  xmlValidation="false" xmlNamespaceAware="false" >

        <Logger className="org.apache.catalina.logger.FileLogger"
               directory="logs"  prefix="localhost_log." suffix=".txt"
          timestamp="true"/>
</Host>

In this approach also for same type apps user sessions has not good isolation ! you may inside app1 if app1 same as app2 you may after login by server side session automatically can login to app2 ?! So you have to keep users session in client side cache and not with jsessionid ! we may change engine name from localhost to solve it. but let say playing with tomcat need more time than play with other cats!

Same font except its weight seems different on different browsers

Be sure the font is the same for all browsers. If it is the same font, then the problem has no solution using cross-browser CSS.

Because every browser has its own font rendering engine, they are all different. They can also differ in later versions, or across different OS's.

UPDATE: For those who do not understand the browser and OS font rendering differences, read this and this.

However, the difference is not even noticeable by most people, and users accept that. Forget pixel-perfect cross-browser design, unless you are:

  1. Trying to turn-off the subpixel rendering by CSS (not all browsers allow that and the text may be ugly...)
  2. Using images (resources are demanding and hard to maintain)
  3. Replacing Flash (need some programming and doesn't work on iOS)

UPDATE: I checked the example page. Tuning the kerning by text-rendering should help:

text-rendering: optimizeLegibility; 

More references here:

  1. Part of the font-rendering is controlled by font-smoothing (as mentioned) and another part is text-rendering. Tuning these properties may help as their default values are not the same across browsers.
  2. For Chrome, if this is still not displaying OK for you, try this text-shadow hack. It should improve your Chrome font rendering, especially in Windows. However, text-shadow will go mad under Windows XP. Be careful.

Setting property 'source' to 'org.eclipse.jst.jee.server:JSFTut' did not find a matching property

I thought I'd add that for Tomcat 7.x, <Context> is not in the server.xml, but in the context.xml. Removing and re-adding the project did not seem to help my similar issue, which was a web.xml issue, which I found out by checking the context.xml which had this line in the <Context> section:

<WatchedResource>WEB-INF/web.xml</WatchedResource>

The solution in WARNING: Setting property 'source' to 'org.eclipse.jst.jee.server:appname' did not find a matching property brought me closer to my answer, as the change of publishing into a separate XML did resolve the error reported above for me, but unfortunately it generated a second error that I'm still investigating.

WARNING: [SetContextPropertiesRule]{Context} Setting property 'source' to 'org.eclipse.jst.jee.server:myproject' did not find a matching property.

How to center a window on the screen in Tkinter?

Tk provides a helper function that can do this as tk::PlaceWindow, but I don't believe it has been exposed as a wrapped method in Tkinter. You would center a widget using the following:

from tkinter import *

app = Tk()
app.eval('tk::PlaceWindow %s center' % app.winfo_pathname(app.winfo_id()))
app.mainloop()

This function should deal with multiple displays correctly as well. It also has options to center over another widget or relative to the pointer (used for placing popup menus), so that they don't fall off the screen.

Eclipse CDT: Symbol 'cout' could not be resolved

I have created the Makefile project using cmake on Ubuntu 16.04.

When created the eclipse project for the Makefiles which cmake generated I created the new project like so:

File --> new --> Makefile project with existing code.

Only after couple of times doing that I have noticed that the default setting for the "Toolchain for indexer settings" is none. In my case I have changed it to Linux GCC and all the errors disappeared.

Hope it helps and let me know if it is not a legit solution.

Cheers,

Guy.

How to programmatically disable page scrolling with jQuery

I've written a jQuery plugin to handle this: $.disablescroll.

It prevents scrolling from mousewheel, touchmove, and keypress events, such as Page Down.

There's a demo here.

Usage:

$(window).disablescroll();

// To re-enable scrolling:
$(window).disablescroll("undo");

Updating state on props change in React Form

I think use ref is safe for me, dont need care about some method above.

class Company extends XComponent {
    constructor(props) {
        super(props);
        this.data = {};
    }
    fetchData(data) {
        this.resetState(data);
    }
    render() {
        return (
            <Input ref={c => this.data['name'] = c} type="text" className="form-control" />
        );
    }
}
class XComponent extends Component {
    resetState(obj) {
        for (var property in obj) {
            if (obj.hasOwnProperty(property) && typeof this.data[property] !== 'undefined') {
                if ( obj[property] !== this.data[property].state.value )
                    this.data[property].setState({value: obj[property]});
                else continue;
            }
            continue;
        }
    }
}

Difference between git stash pop and git stash apply

Quick Answer:

git stash pop -> remove from the stash list

git stash apply -> keep it in the stash list

The most efficient way to remove first N elements in a list?

Python lists were not made to operate on the beginning of the list and are very ineffective at this operation.

While you can write

mylist = [1, 2 ,3 ,4]
mylist.pop(0)

It's very inefficient.


If you only want to delete items from your list, you can do this with del:

del mylist[:n]

Which is also really fast:

In [34]: %%timeit
help=range(10000)
while help:
    del help[:1000]
   ....:
10000 loops, best of 3: 161 µs per loop

If you need to obtain elements from the beginning of the list, you should use collections.deque by Raymond Hettinger and its popleft() method.

from collections import deque

deque(['f', 'g', 'h', 'i', 'j'])

>>> d.pop()                          # return and remove the rightmost item
'j'
>>> d.popleft()                      # return and remove the leftmost item
'f'

A comparison:

list + pop(0)

In [30]: %%timeit
   ....: help=range(10000)
   ....: while help:
   ....:     help.pop(0)
   ....:
100 loops, best of 3: 17.9 ms per loop

deque + popleft()

In [33]: %%timeit
help=deque(range(10000))
while help:
    help.popleft()
   ....:
1000 loops, best of 3: 812 µs per loop

Converting NSString to NSDate (and back again)

NSString to NSDate or NSDate to NSString

//This method is used to get NSDate from string 
//Pass the date formate ex-"dd-MM-yyyy hh:mm a"
+ (NSDate*)getDateFromString:(NSString *)dateString withFormate:(NSString *)formate  {

    // Converted date from date string
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setLocale:[[NSLocale alloc] initWithLocaleIdentifier:@"en_US"]];
    [dateFormatter setDateFormat:formate];
    NSDate *convertedDate         = [dateFormatter dateFromString:dateString];
    return convertedDate;
}

//This method is used to get the NSString for NSDate
//Pass the date formate ex-"dd-MM-yyyy hh:mm a"
+ (NSString *)getDateStringFromDate:(NSDate *)date withFormate:(NSString *)formate {

    // Converted date from date string
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    //[dateFormatter setLocale:[[NSLocale alloc] initWithLocaleIdentifier:@"en_US"]];
    [dateFormatter setDateFormat:formate];
    NSString *convertedDate         = [dateFormatter stringFromDate:date];
    return convertedDate;
}

How to convert a .eps file to a high quality 1024x1024 .jpg?

Maybe you should try it with -quality 100 -size "1024x1024", because resize often gives results that are ugly to view.

in angularjs how to access the element that triggered the event?

I'm not sure which version you had, but this question was asked for long time ago. Currently with Angular 1.5, I can use the ng-keypress event and debounce function from Lodash to emulate similar behavior like ng-change, so I can capture the $event

<input type="text" ng-keypress="edit($event)" ng-model="myModel">

$scope.edit = _.debounce(function ($event) { console.log("$event", $event) }, 800)

Any tools to generate an XSD schema from an XML instance document?

If all you want is XSD, LiquidXML has a free version that does XSDs, and its got a GUI to it so you can tweak the XSD if you like. Anyways nowadays I write my own XSDs by hand, but its all thanks to this app.

http://www.liquid-technologies.com/

Activating Anaconda Environment in VsCode

If you need an independent environment for your project: Install your environment to your project folder using the --prefix option:

conda create --prefix C:\your\workspace\root\awesomeEnv\ python=3

In VSCode launch.json configuration set your "pythonPath" to:

"pythonPath":"${workspaceRoot}/awesomeEnv/python.exe"

wordpress contactform7 textarea cols and rows change in smaller screens

Code will be As below.

[textarea id:message 0x0 class:custom-class "Insert text here"]<!-- No Rows No columns -->

[textarea id:message x2 class:custom-class "Insert text here"]<!-- Only Rows -->

[textarea id:message 12x class:custom-class "Insert text here"]<!-- Only Columns -->

[textarea id:message 10x2 class:custom-class "Insert text here"]<!-- Both Rows and Columns -->

For Details: https://contactform7.com/text-fields/

javascript: using a condition in switch case

switch (true) {
  case condition0:
    ...
    break;
  case condition1:
    ...
    break;
}

will work in JavaScript as long as your conditions return proper boolean values, but it doesn't have many advantages over else if statements.

Extract first item of each sublist

Your code is almost correct. The only issue is the usage of list comprehension.

If you use like: (x[0] for x in lst), it returns a generator object. If you use like: [x[0] for x in lst], it return a list.

When you append the list comprehension output to a list, the output of list comprehension is the single element of the list.

lst = [["a","b","c"], [1,2,3], ["x","y","z"]]
lst2 = []
lst2.append([x[0] for x in lst])
print lst2[0]

lst2 = [['a', 1, 'x']]

lst2[0] = ['a', 1, 'x']

Please let me know if I am incorrect.

How to deal with "java.lang.OutOfMemoryError: Java heap space" error?

VM arguments worked for me in eclipse. If you are using eclipse version 3.4, do the following

go to Run --> Run Configurations --> then select the project under maven build --> then select the tab "JRE" --> then enter -Xmx1024m.

Alternatively you could do Run --> Run Configurations --> select the "JRE" tab --> then enter -Xmx1024m

This should increase the memory heap for all the builds/projects. The above memory size is 1 GB. You can optimize the way you want.

Deny access to one specific folder in .htaccess

For some reasons which I did not understand, creating folder/.htaccess and adding Deny from All failed to work for me. I don't know why, it seemed simple but didn't work, adding RedirectMatch 403 ^/folder/.*$ to the root htaccess worked instead.

source command not found in sh shell

Bourne shell (sh) uses PATH to locate in source <file>. If the file you are trying to source is not in your path, you get the error 'file not found'.

Try:

source ./<filename>

How to check if X server is running?

The bash script solution:

if ! xset q &>/dev/null; then
    echo "No X server at \$DISPLAY [$DISPLAY]" >&2
    exit 1
fi

Doesn't work if you login from another console (Ctrl+Alt+F?) or ssh. For me this solution works in my Archlinux:

#!/bin/sh
ps aux|grep -v grep|grep "/usr/lib/Xorg"
EXITSTATUS=$?
if [ $EXITSTATUS -eq 0 ]; then
  echo "X server running"
  exit 1
fi

You can change /usr/lib/Xorg for only Xorg or the proper command on your system.

Adding a directory to the PATH environment variable in Windows

WARNING: This solution may be destructive to your PATH, and the stability of your system. As a side effect, it will merge your user and system PATH, and truncate PATH to 1024 characters. The effect of this command is irreversible. Make a backup of PATH first. See the comments for more information.

Don't blindly copy-and-paste this. Use with caution.

You can permanently add a path to PATH with the setx command:

setx /M path "%path%;C:\your\path\here\"

Remove the /M flag if you want to set the user PATH instead of the system PATH.

Notes:

  • The setx command is only available in Windows 7 and later.
  • You should run this command from an elevated command prompt.

  • If you only want to change it for the current session, use set.

How to store the hostname in a variable in a .bat file?

I usually read command output in to variables using the FOR command as it saves having to create temporary files. For example:

FOR /F "usebackq" %i IN (`hostname`) DO SET MYVAR=%i

Note, the above statement will work on the command line but not in a batch file. To use it in batch file escape the % in the FOR statement by putting them twice:

FOR /F "usebackq" %%i IN (`hostname`) DO SET MYVAR=%%i
ECHO %MYVAR%

There's a lot more you can do with FOR. For more details just type HELP FOR at command prompt.

How do I determine whether an array contains a particular value in Java?

Instead of using the quick array initialisation syntax too, you could just initialise it as a List straight away in a similar manner using the Arrays.asList method, e.g.:

public static final List<String> STRINGS = Arrays.asList("firstString", "secondString" ...., "lastString");

Then you can do (like above):

STRINGS.contains("the string you want to find");

The import org.apache.commons cannot be resolved in eclipse juno

You could just add one needed external jar file to the project. Go to your project-->java build path-->libraries, add external JARS.Then add your downloaded file from the formal website. My default name is commons-codec-1.10.jar

How to loop through Excel files and load them into a database using SSIS package?

I ran into an article that illustrates a method where the data from the same excel sheet can be imported in the selected table until there is no modifications in excel with data types.

If the data is inserted or overwritten with new ones, importing process will be successfully accomplished, and the data will be added to the table in SQL database.

The article may be found here: http://www.sqlshack.com/using-ssis-packages-import-ms-excel-data-database/

Hope it helps.

MatPlotLib: Multiple datasets on the same scatter plot

I came across this question as I had exact same problem. Although accepted answer works good but with matplotlib version 2.1.0, it is pretty straight forward to have two scatter plots in one plot without using a reference to Axes

import matplotlib.pyplot as plt

plt.scatter(x,y, c='b', marker='x', label='1')
plt.scatter(x, y, c='r', marker='s', label='-1')
plt.legend(loc='upper left')
plt.show()

Hosting ASP.NET in IIS7 gives Access is denied?

In my case running c:\windows\Microsoft.Net\Framework64\v4.0.30319\aspnet_regiis.exe /i resolved the 403 access denied issue.

How to use both onclick and target="_blank"

Just use window.open():

window.open('Prosjektplan.pdf')

Anyway, what guys are saying on comments is true. You better use <a target="_blank"> instead of click events.

How to create a hidden <img> in JavaScript?

This question is vague, but if you want to make the image with Javascript. It is simple.

function loadImages(src) {
  if (document.images) {
    img1 = new Image();
    img1.src = src;
}
loadImages("image.jpg");

The image will be requested but until you show it it will never be displayed. great for pre loading images you expect to be requests but delaying it until the document is loaded.

Example

How do I set a VB.Net ComboBox default value

Another good method for setting a DropDownList style combobox:

Combox1.SelectedIndex = Combox1.FindStringExact("test1")

Send JSON data via POST (ajax) and receive json response from Controller (MVC)

Your PersonSheets has a property int Id, Id isn't in the post, so modelbinding fails. Make Id nullable (int?) or send atleast Id = 0 with the POst .

How do I accomplish an if/else in mustache.js?

This is something you solve in the "controller", which is the point of logicless templating.

// some function that retreived data through ajax
function( view ){

   if ( !view.avatar ) {
      // DEFAULTS can be a global settings object you define elsewhere
      // so that you don't have to maintain these values all over the place
      // in your code.
      view.avatar = DEFAULTS.AVATAR;
   }

   // do template stuff here

}

This is actually a LOT better then maintaining image url's or other media that might or might not change in your templates, but takes some getting used to. The point is to unlearn template tunnel vision, an avatar img url is bound to be used in other templates, are you going to maintain that url on X templates or a single DEFAULTS settings object? ;)

Another option is to do the following:

// augment view
view.hasAvatar = !!view.avatar;
view.noAvatar = !view.avatar;

And in the template:

{{#hasAvatar}}
    SHOW AVATAR
{{/hasAvatar}}
{{#noAvatar}}
    SHOW DEFAULT
{{/noAvatar}}

But that's going against the whole meaning of logicless templating. If that's what you want to do, you want logical templating and you should not use Mustache, though do give it yourself a fair chance of learning this concept ;)

How to insert text in a td with id, using JavaScript

append a text node as follows

var td1 = document.getElementById('td1');
var text = document.createTextNode("some text");
td1.appendChild(text);

Generate random numbers using C++11 random library

I red all the stuff above, about 40 other pages with c++ in it like this and watched the video from Stephan T. Lavavej "STL" and still wasn't sure how random numbers works in praxis so I took a full Sunday to figure out what its all about and how it works and can be used.

In my opinion STL is right about "not using srand anymore" and he explained it well in the video 2. He also recommend to use:

a) void random_device_uniform() -- for encrypted generation but slower (from my example)

b) the examples with mt19937 -- faster, ability to create seeds, not encrypted


I pulled out all claimed c++11 books I have access to and found f.e. that german Authors like Breymann (2015) still use a clone of

srand( time( 0 ) );
srand( static_cast<unsigned int>(time(nullptr))); or
srand( static_cast<unsigned int>(time(NULL))); or

just with <random> instead of <time> and <cstdlib> #includings - so be careful to learn just from one book :).

Meaning - that shouldn't be used since c++11 because:

Programs often need a source of random numbers. Prior to the new standard, both C and C++ relied on a simple C library function named rand. That function produces pseudorandom integers that are uniformly distributed in the range from 0 to a system- dependent maximum value that is at least 32767. The rand function has several problems: Many, if not most, programs need random numbers in a different range from the one produced by rand. Some applications require random floating-point numbers. Some programs need numbers that reflect a nonuniform distribution. Programmers often introduce nonrandomness when they try to transform the range, type, or distribution of the numbers generated by rand. (quote from Lippmans C++ primer fifth edition 2012)


I finally found a the best explaination out of 20 books in Bjarne Stroustrups newer ones - and he should know his stuff - in "A tour of C++ 2019", "Programming Principles and Practice Using C++ 2016" and "The C++ Programming Language 4th edition 2014" and also some examples in "Lippmans C++ primer fifth edition 2012":

And it is really simple because a random number generator consists of two parts: (1) an engine that produces a sequence of random or pseudo-random values. (2) a distribution that maps those values into a mathematical distribution in a range.


Despite the opinion of Microsofts STL guy, Bjarne Stroustrups writes:

In , the standard library provides random number engines and distributions (§24.7). By default use the default_random_engine , which is chosen for wide applicability and low cost.

The void die_roll() Example is from Bjarne Stroustrups - good idea generating engine and distribution with using (more bout that here).


To be able to make practical use of the random number generators provided by the standard library in <random> here some executable code with different examples reduced to the least necessary that hopefully safe time and money for you guys:

    #include <random>     //random engine, random distribution
    #include <iostream>   //cout
    #include <functional> //to use bind

    using namespace std;


    void space() //for visibility reasons if you execute the stuff
    {
       cout << "\n" << endl;
       for (int i = 0; i < 20; ++i)
       cout << "###";
       cout << "\n" << endl;
    }

    void uniform_default()
    {
    // uniformly distributed from 0 to 6 inclusive
        uniform_int_distribution<size_t> u (0, 6);
        default_random_engine e;  // generates unsigned random integers

    for (size_t i = 0; i < 10; ++i)
        // u uses e as a source of numbers
        // each call returns a uniformly distributed value in the specified range
        cout << u(e) << " ";
    }

    void random_device_uniform()
    {
         space();
         cout << "random device & uniform_int_distribution" << endl;

         random_device engn;
         uniform_int_distribution<size_t> dist(1, 6);

         for (int i=0; i<10; ++i)
         cout << dist(engn) << ' ';
    }

    void die_roll()
    {
        space();
        cout << "default_random_engine and Uniform_int_distribution" << endl;

    using my_engine = default_random_engine;
    using my_distribution = uniform_int_distribution<size_t>;

        my_engine rd {};
        my_distribution one_to_six {1, 6};

        auto die = bind(one_to_six,rd); // the default engine    for (int i = 0; i<10; ++i)

        for (int i = 0; i <10; ++i)
        cout << die() << ' ';

    }


    void uniform_default_int()
    {
       space();
       cout << "uniform default int" << endl;

       default_random_engine engn;
       uniform_int_distribution<size_t> dist(1, 6);

        for (int i = 0; i<10; ++i)
        cout << dist(engn) << ' ';
    }

    void mersenne_twister_engine_seed()
    {
        space();
        cout << "mersenne twister engine with seed 1234" << endl;

        //mt19937 dist (1234);  //for 32 bit systems
        mt19937_64 dist (1234); //for 64 bit systems

        for (int i = 0; i<10; ++i)
        cout << dist() << ' ';
    }


    void random_seed_mt19937_2()
    {
        space();
        cout << "mersenne twister split up in two with seed 1234" << endl;

        mt19937 dist(1234);
        mt19937 engn(dist);

        for (int i = 0; i < 10; ++i)
        cout << dist() << ' ';

        cout << endl;

        for (int j = 0; j < 10; ++j)
        cout << engn() << ' ';
    }



    int main()
    {
            uniform_default(); 
            random_device_uniform();
            die_roll();
            random_device_uniform();
            mersenne_twister_engine_seed();
            random_seed_mt19937_2();
        return 0;
    }

I think that adds it all up and like I said, it took me a bunch of reading and time to destill it to that examples - if you have further stuff about number generation I am happy to hear about that via pm or in the comment section and will add it if necessary or edit this post. Bool

Form Submission without page refresh

The problem is the Method 'POST' your form is submitting by using the "post" method, and in the AJAX you are using "GET".

How to set index.html as root file in Nginx?

For me, the try_files directive in the (currently most voted) answer https://stackoverflow.com/a/11957896/608359 led to rewrite cycles,

*173 rewrite or internal redirection cycle while internally redirecting

I had better luck with the index directive. Note that I used a forward slash before the name, which might or might not be what you want.

server {
  listen 443 ssl;
  server_name example.com;

  root /home/dclo/example;
  index /index.html;
  error_page 404 /index.html;

  # ... ssl configuration
}

In this case, I wanted all paths to lead to /index.html, including when returning a 404.

How to run Spyder in virtual environment?

Here is a quick way to do it in 2021 using the Anaconda Navigator. This is the most reliable way to do it, unless you want to create environments programmatically which I don't think is the case for most users:

  1. Open Anaconda Navigator.
  2. Click on Environments > Create and give a name to your environment. Be sure to change Python/R Kernel version if needed.

enter image description here

  1. Go "Home" and click on "Install" under the Spyder box.

enter image description here

  1. Click "Launch/Run"

There are still a few minor bugs when setting up your environment, most of them should be solved by restarting the Navigator.

If you find a bug, please help us posting it in the Anaconda Issues bug-tracker too! If you run into trouble creating the environment or if the environment was not correctly created you can double check what got installed: Clicking the "Environments" opens a management window showing installed packages. Search and select Spyder-related packages and then click on "Apply" to install them.

enter image description here

Launch programs whose path contains spaces

Set objShell = WScript.CreateObject("WScript.Shell")
objShell.Run("firefox")
Set objShell = Nothing

Please try this

javax.xml.bind.UnmarshalException: unexpected element. Expected elements are (none)

One of the reasons for this error is the use of the jaxb implementation from the jdk. I am not sure why such a problem can appear in pretty simple xml parsing situations. You may use the latest version of the jaxb library from a public maven repository:

http://mvnrepository.com

<dependency>
    <groupId>javax.xml.bind</groupId>
    <artifactId>jaxb-api</artifactId>
    <version>2.2.12</version>
</dependency>

missing FROM-clause entry for table

Because that gtab82 table isn't in your FROM or JOIN clause. You refer gtab82 table in these cases: gtab82.memno and gtab82.memacid

:: (double colon) operator in Java 8

In java-8 Streams Reducer in simple works is a function which takes two values as input and returns result after some calculation. this result is fed in next iteration.

in case of Math:max function, method keeps returning max of two values passed and in the end you have largest number in hand.

How do I create a list of random numbers without duplicates?

You can use Numpy library for quick answer as shown below -

Given code snippet lists down 6 unique numbers between the range of 0 to 5. You can adjust the parameters for your comfort.

import numpy as np
import random
a = np.linspace( 0, 5, 6 )
random.shuffle(a)
print(a)

Output

[ 2.  1.  5.  3.  4.  0.]

It doesn't put any constraints as we see in random.sample as referred here.

Hope this helps a bit.

Convert char to int in C and C++

It sort of depends on what you mean by "convert".

If you have a series of characters that represents an integer, like "123456", then there are two typical ways to do that in C: Use a special-purpose conversion like atoi() or strtol(), or the general-purpose sscanf(). C++ (which is really a different language masquerading as an upgrade) adds a third, stringstreams.

If you mean you want the exact bit pattern in one of your int variables to be treated as a char, that's easier. In C the different integer types are really more of a state of mind than actual separate "types". Just start using it where chars are asked for, and you should be OK. You might need an explicit conversion to make the compiler quit whining on occasion, but all that should do is drop any extra bits past 256.

How to split a string in two and store it in a field

I would suggest the following:

String[] parsedInput = str.split("\n"); String firstName = parsedInput[0].split(": ")[1]; String lastName = parsedInput[1].split(": ")[1]; myMap.put(firstName,lastName); 

How do I add options to a DropDownList using jQuery?

U can use direct

$"(.ddlClassName").Html("<option selected=\"selected\" value=\"1\">1</option><option value=\"2\">2</option>")

-> Here u can use direct string

Can I force pip to reinstall the current version?

If you want to reinstall packages specified in a requirements.txt file, without upgrading, so just reinstall the specific versions specified in the requirements.txt file:

pip install -r requirements.txt --ignore-installed

What is EOF in the C programming language?

EOF means end of file. It's a sign that the end of a file is reached, and that there will be no data anymore.

Edit:

I stand corrected. In this case it's not an end of file. As mentioned, it is passed when CTRL+d (linux) or CTRL+z (windows) is passed.

Python constructors and __init__

coonstructors are called automatically when you create a new object, thereby "constructing" the object. The reason you can have more than one init is because names are just references in python, and you are allowed to change what each variable references whenever you want (hence dynamic typing)

def func(): #now func refers to an empty funcion
    pass
...
func=5      #now func refers to the number 5
def func():
    print "something"    #now func refers to a different function

in your class definition, it just keeps the later one

libstdc++-6.dll not found

useful to windows users who use eclipse for c/c++ but run *.exe file and get an error: "missing libstdc++6.dll"

4 ways to solve it

  1. Eclipse ->"Project" -> "Properties" -> "C/C++ Build" -> "Settings" -> "Tool Settings" -> "MinGW C++ Linker" -> "Misscellaneous" -> "Linker flags" (add '-static' to it)

  2. Add '{{the path where your MinGW was installed}}/bin' to current user environment variable - "Path" in Windows, then reboot eclipse, and finally recompile.

  3. Add '{{the path where your MinGW was installed}}/bin' to Windows environment variable - "Path", then reboot eclipse, and finally recompile.

  4. Copy the file "libstdc++-6.dll" to the path where the *.exe file is running, then rerun. (this is not a good way)

Note: the file "libstdc++-6.dll" is in the folder '{{the path where your MinGW was installed}}/bin'

Disable back button in android

Apart form these two methods from answer above.

onBackPressed() (API Level 5, Android 2.0)

onKeyDown() (API Level 1, Android 1.0)

You can also override the dispatchKeyEvent()(API Level 1, Android 1.0) like this,

dispatchKeyEvent() (API Level 1, Android 1.0)

@Override
public boolean dispatchKeyEvent(KeyEvent event) {
    // TODO Auto-generated method stub
    if (event.getKeyCode() == KeyEvent.KEYCODE_BACK) {
        return true;
    }
    return super.dispatchKeyEvent(event);
}

How to give a Blob uploaded as FormData a file name?

For Chrome, Safari and Firefox, just use this:

form.append("blob", blob, filename);

(see MDN documentation)

How to make MySQL table primary key auto increment with some prefix

I know it is late but I just want to share on what I have done for this. I'm not allowed to add another table or trigger so I need to generate it in a single query upon insert. For your case, can you try this query.

CREATE TABLE YOURTABLE(
IDNUMBER VARCHAR(7) NOT NULL PRIMARY KEY,
ENAME VARCHAR(30) not null
);

Perform a select and use this select query and save to the parameter @IDNUMBER

(SELECT IFNULL
     (CONCAT('LHPL',LPAD(
       (SUBSTRING_INDEX
        (MAX(`IDNUMBER`), 'LHPL',-1) + 1), 5, '0')), 'LHPL001')
    AS 'IDNUMBER' FROM YOURTABLE ORDER BY `IDNUMBER` ASC)

And then Insert query will be :

INSERT INTO YOURTABLE(IDNUMBER, ENAME) VALUES 
(@IDNUMBER, 'EMPLOYEE NAME');

The result will be the same as the other answer but the difference is, you will not need to create another table or trigger. I hope that I can help someone that have a same case as mine.

How to lookup JNDI resources on WebLogic?

You should be able to simply do this:

Context context = new InitialContext();
dataSource = (javax.sql.DataSource) context.lookup("jdbc/myDataSource");

If you are looking it up from a remote destination you need to use the WL initial context factory like this:

Hashtable<String, String> h = new Hashtable<String, String>(7);
h.put(Context.INITIAL_CONTEXT_FACTORY, "weblogic.jndi.WLInitialContextFactory");
h.put(Context.PROVIDER_URL, pURL); //For example "t3://127.0.0.1:7001"
h.put(Context.SECURITY_PRINCIPAL, pUsername);
h.put(Context.SECURITY_CREDENTIALS, pPassword);

InitialContext context = new InitialContext(h);
dataSource = (javax.sql.DataSource) context.lookup("jdbc/myDataSource");

weblogic.jndi.WLInitialContextFactory

Python: Converting string into decimal number

You will need to use strip() because of the extra bits in the strings.

A2 = [float(x.strip('"')) for x in A1]

Hashing a string with Sha256

The shortest and fastest way ever. Only 1 line!

public static string StringSha256Hash(string text) =>
    string.IsNullOrEmpty(text) ? string.Empty : BitConverter.ToString(new System.Security.Cryptography.SHA256Managed().ComputeHash(System.Text.Encoding.UTF8.GetBytes(text))).Replace("-", string.Empty);

Warning "Do not Access Superglobal $_POST Array Directly" on Netbeans 7.4 for PHP

I agree with the other answerers that in most cases (almost always) it is necessary to sanitize Your input.

But consider such code (it is for a REST controller):

$method = $_SERVER['REQUEST_METHOD'];

switch ($method) {
            case 'GET':
                return $this->doGet($request, $object);
            case 'POST':
                return $this->doPost($request, $object);
            case 'PUT':
                return $this->doPut($request, $object);
            case 'DELETE':
                return $this->doDelete($request, $object);
            default:
                return $this->onBadRequest();
}

It would not be very useful to apply sanitizing here (although it would not break anything, either).

So, follow recommendations, but not blindly - rather understand why they are for :)

How to cherry pick a range of commits and merge into another branch?

I wrapped VonC's code into a short bash script, git-multi-cherry-pick, for easy running:

#!/bin/bash

if [ -z $1 ]; then
    echo "Equivalent to running git-cherry-pick on each of the commits in the range specified.";
    echo "";
    echo "Usage:  $0 start^..end";
    echo "";
    exit 1;
fi

git rev-list --reverse --topo-order $1 | while read rev 
do 
  git cherry-pick $rev || break 
done 

I'm currently using this as I rebuild the history of a project that had both 3rd-party code and customizations mixed together in the same svn trunk. I'm now splitting apart core 3rd party code, 3rd party modules, and customizations onto their own git branches for better understanding of customizations going forward. git-cherry-pick is helpful in this situation since I have two trees in the same repository, but without a shared ancestor.

Apply CSS style attribute dynamically in Angular JS

Directly from ngStyle docs:

Expression which evals to an object whose keys are CSS style names and values are corresponding values for those CSS keys.

<div ng-style="{'width': '20px', 'height': '20px', ...}"></div>

So you could do this:

<div ng-style="{'background-color': data.backgroundCol}"></div>

Hope this helps!

Access to build environment variables from a groovy script in a Jenkins build step (Windows)

The only way I could get this to work (on Linux) was to follow this advice:

https://wiki.jenkins-ci.org/display/JENKINS/Parameterized+System+Groovy+script

import hudson.model.*

// get current thread / Executor and current build
def thr = Thread.currentThread()
def build = thr?.executable

// if you want the parameter by name ...
def hardcoded_param = "FOOBAR"
def resolver = build.buildVariableResolver
def hardcoded_param_value = resolver.resolve(hardcoded_param)

println "param ${hardcoded_param} value : ${hardcoded_param_value}"

This is on Jenkins 1.624 running on CentOS 6.7

jQuery each loop in table row

Use immediate children selector >:

$('#tblOne > tbody  > tr')

Description: Selects all direct child elements specified by "child" of elements specified by "parent".

How do we control web page caching, across all browsers?

There's a bug in IE6

Content with "Content-Encoding: gzip" is always cached even if you use "Cache-Control: no-cache".

http://support.microsoft.com/kb/321722

You can disable gzip compression for IE6 users (check the user agent for "MSIE 6")

How do I get the position selected in a RecyclerView?

To complement @tyczj answer:

Generic Adapter Pseido code:

public abstract class GenericRecycleAdapter<T, K extends RecyclerView.ViewHolder> extends RecyclerView.Adapter{ 

private List<T> mList;
//default implementation code 

public abstract int getLayout();

@Override
    public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View v = LayoutInflater.from(parent.getContext())
                .inflate(getLayout(), parent, false);
        return getCustomHolder(v);
    }

    public Holders.TextImageHolder getCustomHolder(View v) {
        return new Holders.TextImageHolder(v){
            @Override
            public void onClick(View v) {
                onItem(mList.get(this.getAdapterPosition()));
            }
        };
    }

abstract void onItem(T t);

 @Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
    onSet(mList.get(position), (K) holder);

}

public abstract void onSet(T item, K holder);

}

ViewHolder:

public class Holders  {

    public static class TextImageHolder extends RecyclerView.ViewHolder implements View.OnClickListener{

        public TextView text;

        public TextImageHolder(View itemView) {
            super(itemView);
            text = (TextView) itemView.findViewById(R.id.text);
            text.setOnClickListener(this);


        }

        @Override
        public void onClick(View v) {

        }
    }


}

Adapter usage:

public class CategoriesAdapter extends GenericRecycleAdapter<Category, Holders.TextImageHolder> {


    public CategoriesAdapter(List<Category> list, Context context) {
        super(list, context);
    }

    @Override
    void onItem(Category category) {

    }


    @Override
    public int getLayout() {
        return R.layout.categories_row;
    }

    @Override
    public void onSet(Category item, Holders.TextImageHolder holder) {

    }



}

How to use particular CSS styles based on screen size / device

@media queries serve this purpose. Here's an example:

@media only screen and (max-width: 991px) and (min-width: 769px){
 /* CSS that should be displayed if width is equal to or less than 991px and larger 
  than 768px goes here */
}

@media only screen and (max-width: 991px){
 /* CSS that should be displayed if width is equal to or less than 991px goes here */
}

Nested ng-repeat

Create a dummy tag that is not going to rendered on the page but it will work as holder for ng-repeat:

<dummyTag ng-repeat="featureItem in item.features">{{featureItem.feature}}</br> </dummyTag>

Taking screenshot on Emulator from Android Studio

  1. In Android Studio, select View > Tool Windows > Logcat to open Logcat.
  2. Select the device and a process from the drop-down at the top of the window.
  3. Click Screen Capture on the left side of the window.

For more info Check this link

In Excel, how do I extract last four letters of a ten letter string?

No need to use a macro. Supposing your first string is in A1.

=RIGHT(A1, 4)

Drag this down and you will get your four last characters.

Edit: To be sure, if you ever have sequences like 'ABC DEF' and want the last four LETTERS and not CHARACTERS you might want to use trimspaces()

=RIGHT(TRIMSPACES(A1), 4)

Edit: As per brettdj's suggestion, you may want to check that your string is actually 4-character long or more:

=IF(TRIMSPACES(A1)>=4, RIGHT(TRIMSPACES(A1), 4), TRIMSPACES(A1))

simple HTTP server in Java using only Java SE API

Since Java SE 6, there's a builtin HTTP server in Sun Oracle JRE. The com.sun.net.httpserver package summary outlines the involved classes and contains examples.

Here's a kickoff example copypasted from their docs (to all people trying to edit it nonetheless, because it's an ugly piece of code, please don't, this is a copy paste, not mine, moreover you should never edit quotations unless they have changed in the original source). You can just copy'n'paste'n'run it on Java 6+.

package com.stackoverflow.q3732109;

import java.io.IOException;
import java.io.OutputStream;
import java.net.InetSocketAddress;

import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpHandler;
import com.sun.net.httpserver.HttpServer;

public class Test {

    public static void main(String[] args) throws Exception {
        HttpServer server = HttpServer.create(new InetSocketAddress(8000), 0);
        server.createContext("/test", new MyHandler());
        server.setExecutor(null); // creates a default executor
        server.start();
    }

    static class MyHandler implements HttpHandler {
        @Override
        public void handle(HttpExchange t) throws IOException {
            String response = "This is the response";
            t.sendResponseHeaders(200, response.length());
            OutputStream os = t.getResponseBody();
            os.write(response.getBytes());
            os.close();
        }
    }

}

Noted should be that the response.length() part in their example is bad, it should have been response.getBytes().length. Even then, the getBytes() method must explicitly specify the charset which you then specify in the response header. Alas, albeit misguiding to starters, it's after all just a basic kickoff example.

Execute it and go to http://localhost:8000/test and you'll see the following response:

This is the response


As to using com.sun.* classes, do note that this is, in contrary to what some developers think, absolutely not forbidden by the well known FAQ Why Developers Should Not Write Programs That Call 'sun' Packages. That FAQ concerns the sun.* package (such as sun.misc.BASE64Encoder) for internal usage by the Oracle JRE (which would thus kill your application when you run it on a different JRE), not the com.sun.* package. Sun/Oracle also just develop software on top of the Java SE API themselves like as every other company such as Apache and so on. Using com.sun.* classes is only discouraged (but not forbidden) when it concerns an implementation of a certain Java API, such as GlassFish (Java EE impl), Mojarra (JSF impl), Jersey (JAX-RS impl), etc.

Get last field using awk substr

You can also use:

    sed -n 's/.*\/\([^\/]\{1,\}\)$/\1/p'

or

    sed -n 's/.*\/\([^\/]*\)$/\1/p'

How to make a flat list out of list of lists?

This may not be the most efficient way but I thought to put a one-liner (actually a two-liner). Both versions will work on arbitrary hierarchy nested lists, and exploits language features (Python3.5) and recursion.

def make_list_flat (l):
    flist = []
    flist.extend ([l]) if (type (l) is not list) else [flist.extend (make_list_flat (e)) for e in l]
    return flist

a = [[1, 2], [[[[3, 4, 5], 6]]], 7, [8, [9, [10, 11], 12, [13, 14, [15, [[16, 17], 18]]]]]]
flist = make_list_flat(a)
print (flist)

The output is

[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18]

This works in a depth first manner. The recursion goes down until it finds a non-list element, then extends the local variable flist and then rolls back it to the parent. Whenever flist is returned, it is extended to the parent's flist in the list comprehension. Therefore, at the root, a flat list is returned.

The above one creates several local lists and returns them which are used to extend the parent's list. I think the way around for this may be creating a gloabl flist, like below.

a = [[1, 2], [[[[3, 4, 5], 6]]], 7, [8, [9, [10, 11], 12, [13, 14, [15, [[16, 17], 18]]]]]]
flist = []
def make_list_flat (l):
    flist.extend ([l]) if (type (l) is not list) else [make_list_flat (e) for e in l]

make_list_flat(a)
print (flist)

The output is again

[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18]

Although I am not sure at this time about the efficiency.

Should I use scipy.pi, numpy.pi, or math.pi?

>>> import math
>>> import numpy as np
>>> import scipy
>>> math.pi == np.pi == scipy.pi
True

So it doesn't matter, they are all the same value.

The only reason all three modules provide a pi value is so if you are using just one of the three modules, you can conveniently have access to pi without having to import another module. They're not providing different values for pi.

How can I pass a class member function as a callback?

That doesn't work because a member function pointer cannot be handled like a normal function pointer, because it expects a "this" object argument.

Instead you can pass a static member function as follows, which are like normal non-member functions in this regard:

m_cRedundencyManager->Init(&CLoggersInfra::Callback, this);

The function can be defined as follows

static void Callback(int other_arg, void * this_pointer) {
    CLoggersInfra * self = static_cast<CLoggersInfra*>(this_pointer);
    self->RedundencyManagerCallBack(other_arg);
}

How to set variables in HIVE scripts

Just in case someone needs to parameterize hive query via cli.

For eg:

hive_query.sql

SELECT * FROM foo WHERE day >= '${hivevar:CURRENT_DATE}'

Now execute above sql file from cli:

hive --hivevar CURRENT_DATE="2012-09-16" -f hive_query.sql

Could not insert new outlet connection: Could not find any information for the class named

I had the same problem. I realised than in X-Code Manual item was selected when I tried to create an outlet by control-drag

enter image description here

After I set it to automatic it worked

enter image description here

How to copy java.util.list Collection

Use the ArrayList copy constructor, then sort that.

List oldList;
List newList = new ArrayList(oldList);
Collections.sort(newList);

After making the copy, any changes to newList do not affect oldList.

Note however that only the references are copied, so the two lists share the same objects, so changes made to elements of one list affect the elements of the other.

jQuery - Illegal invocation

In my case, I just changed

Note: This is in case of Django, so I added csrftoken. In your case, you may not need it.

Added contentType: false, processData: false

Commented out "Content-Type": "application/json"

$.ajax({
    url: location.pathname, 
    type: "POST",
    crossDomain: true,
    dataType: "json",
    headers: {
        "X-CSRFToken": csrftoken,
        "Content-Type": "application/json"
    },
    data:formData,
    success: (response, textStatus, jQxhr) => {

    },
    error: (jQxhr, textStatus, errorThrown) => {

    }
})

to

$.ajax({
    url: location.pathname, 
    type: "POST",
    crossDomain: true,
    dataType: "json",
    contentType: false,
    processData: false,
    headers: {
        "X-CSRFToken": csrftoken
        // "Content-Type": "application/json",
    },
    data:formData,
    success: (response, textStatus, jQxhr) => {

    },
    error: (jQxhr, textStatus, errorThrown) => {

    }
})

and it worked.

Convert number to month name in PHP

adapt as required

$m='08';
$months = array (1=>'Jan',2=>'Feb',3=>'Mar',4=>'Apr',5=>'May',6=>'Jun',7=>'Jul',8=>'Aug',9=>'Sep',10=>'Oct',11=>'Nov',12=>'Dec');
echo $months[(int)$m];

shorthand If Statements: C#

Yes. Use the ternary operator.

condition ? true_expression : false_expression;

How do I determine k when using k-means clustering?

Basically, you want to find a balance between two variables: the number of clusters (k) and the average variance of the clusters. You want to minimize the former while also minimizing the latter. Of course, as the number of clusters increases, the average variance decreases (up to the trivial case of k=n and variance=0).

As always in data analysis, there is no one true approach that works better than all others in all cases. In the end, you have to use your own best judgement. For that, it helps to plot the number of clusters against the average variance (which assumes that you have already run the algorithm for several values of k). Then you can use the number of clusters at the knee of the curve.

How to save all console output to file in R?

  1. If you want to get error messages saved in a file

    zz <- file("Errors.txt", open="wt")
    sink(zz, type="message")
    

    the output will be:

    Error in print(errr) : object 'errr' not found
    Execution halted
    

    This output will be saved in a file named Errors.txt

  2. In case, you want printed values of console to a file you can use 'split' argument:

    zz <- file("console.txt", open="wt")
    sink(zz,  split=TRUE)
    print("cool")
    print(errr)
    

    output will be:

    [1] "cool"
    

    in console.txt file. So all your console output will be printed in a file named console.txt

Pure CSS multi-level drop-down menu

<div class="example" align="center">
    <div class="menuholder">
        <ul class="menu slide">
            <li><a href="index.php?id=1" class="blue">Home</a></li>
        <li><a href="index.php?id=14" class="blue">About Us</a></li>
            <li><a href="index.php?id=4" class="blue">Mens</a>
                <div class="subs">
                    <dl>
                        <dd><a href="index.php?id=15">Coats & Jackets</a></dd>
                        <dd><a href="index.php?id=22">Chinos</a></dd>
                        <dd><a href="index.php?id=23">Jeans</a></dd>
                        <dd><a href="index.php?id=24">Jumpers & Cardigans</a></dd>
                        <dd><a href="index.php?id=25">Linen</a></dd>
                    </dl>
                    <dl>
                        <dd><a href="index.php?id=26">Polo Shirts</a></dd>
                        <dd><a href="index.php?id=16">Shirts Casual</a></dd>
                        <dd><a href="index.php?id=27">Shirts Formal</a></dd>
                        <dd><a href="index.php?id=28">Shorts</a></dd>
                        <dd><a href="index.php?id=18">Sportswear</a></dd>
                    </dl>
                    <dl>
                        <dd><a href="index.php?id=19">Tops & T-Shirts</a></dd>
                        <dd><a href="index.php?id=20">Trousers Casual</a></dd>
                        <dd><a href="index.php?id=29">Trousers Formal</a></dd>
                        <dd><a href="index.php?id=30">Nightwear</a></dd>
                        <dd><a href="index.php?id=17">Socks</a></dd>
                    </dl>
                    <dl>
                        <dd><a href="index.php?id=21">Underwear</a></dd>
                        <dd><a href="index.php?id=31">Swimwear</a></dd>
                    </dl>
                </div>
            </li>
            <!--menu-->
                        <li><a href="index.php?id=5" class="blue">Ladie's</a>
                <div class="subs">
                    <dl>
                          <dd><a href="index.php?id=32">Coats & Jackets</a></dd>
                          <dd><a href="index.php?id=33">Dresses</a></dd>
                          <dd><a href="index.php?id=34">Jeans</a></dd>
                          <dd><a href="index.php?id=35">Jumpers & Cardigans</a></dd>
                          <dd><a href="index.php?id=36">Jumpsuits</a></dd>
                    </dl>
                    <dl>
                        <dd><a href="index.php?id=37">Leggings & Jeggings</a></dd>
                          <dd><a href="index.php?id=38">Linen</a></dd>
                          <dd><a href="index.php?id=39">Lingerie & Underwear</a></dd>
                          <dd><a href="index.php?id=40">Maternity Wear</a></dd>
                          <dd><a href="index.php?id=41">Nightwear</a></dd>
                    </dl>
                    <dl>
                     <dd><a href="index.php?id=42">Shorts</a></dd>
                          <dd><a href="index.php?id=43">Skirts</a></dd>
                          <dd><a href="index.php?id=44">Sportswear</a></dd>
                          <dd><a href="index.php?id=45">Suits & Tailoring</a></dd>
                          <dd><a href="index.php?id=46">Swimwear & Beachwear</a></dd>
                    </dl>
                    <dl>
                          <dd><a href="index.php?id=47">Thermals</a></dd>
                          <dd><a href="index.php?id=48">Tops & T-Shirts</a></dd>
                          <dd><a href="index.php?id=49">Trousers & Chinos</a></dd>
                          <dd><a href="index.php?id=50">Socks</a></dd>
                    </dl>
                </div>
            </li><!--menu end-->
                        <!--menu-->
                        <li><a href="index.php?id=7" class="blue">Girls</a>
                <div class="subs">
                    <dl>
                            <dd><a href="index.php?id=51">Coats & Jackets</a></dd>
                          <dd><a href="index.php?id=52">Dresses</a></dd>
                          <dd><a href="index.php?id=53">Jeans</a></dd>
                          <dd><a href="index.php?id=54">Joggers & Sweatshirts</a></dd>
                          <dd><a href="index.php?id=55">Jumpers & Cardigans</a></dd>
                    </dl>
                    <dl>
                                <dd><a href="index.php?id=56">Jumpsuits & Playsuits</a></dd>
                              <dd><a href="index.php?id=57">Leggings</a></dd>
                              <dd><a href="index.php?id=58">Nightwear</a></dd>
                              <dd><a href="index.php?id=59">Shorts</a></dd>
                              <dd><a href="index.php?id=60">Skirts</a></dd>
                    </dl>
                    <dl>
                              <dd><a href="index.php?id=61">Swimwear</a></dd>
                              <dd><a href="index.php?id=62">Tops & T-Shirts</a></dd>
                              <dd><a href="index.php?id=63">Trousers & Jeans</a></dd>
                              <dd><a href="index.php?id=64">Socks</a></dd>
                              <dd><a href="index.php?id=65">Underwear</a></dd>
                    </dl>
                    <dl>

                    </dl>
                </div>
            </li><!--menu end-->
                            <!--menu-->
                        <li><a href="index.php?id=8" class="blue">Boys</a>
                <div class="subs">
                    <dl>
                        <dd><a href="index.php?id=66">Coats & Jackets</a></dd>
                          <dd><a href="index.php?id=67">Jeans</a></dd>
                          <dd><a href="index.php?id=68">Joggers & Sweatshirts</a></dd>
                          <dd><a href="index.php?id=69">Jumpers & Cardigans</a></dd>
                          <dd><a href="index.php?id=70">Nightwear</a></dd>
                    </dl>
                    <dl>
                            <dd><a href="index.php?id=71">Shirts</a></dd>
                          <dd><a href="index.php?id=72">Shorts</a></dd>
                          <dd><a href="index.php?id=73">Sportswear</a></dd>
                          <dd><a href="index.php?id=74">Swimwear</a></dd>
                          <dd><a href="index.php?id=75">T-Shirts & Polo Shirts</a></dd>
                    </dl>
                    <dl>
                          <dd><a href="index.php?id=76">Trousers & Jeans</a></dd>
                          <dd><a href="index.php?id=77">Socks</a></dd>
                          <dd><a href="index.php?id=78">Underwear</a></dd>
                    </dl>
                    <dl>

                    </dl>
                </div>
            </li><!--menu end-->
            <!--menu-->
             <li><a href="index.php?id=9" class="blue">Toddlers</a>
                <div class="subs">
                    <dl>
                      <dd><a href="index.php?id=79">Newborn</a></dd>
                      <dd><a href="index.php?id=80">0-2 Years</a></dd>
                    </dl>                 
                </div>
            </li><!--menu end-->
            <!--menu-->
             <li><a href="index.php?id=10" class="blue">Accessories</a>
                <div class="subs">
                    <dl>
                          <dd><a href="index.php?id=81">Shoes</a></dd>
                          <dd><a href="index.php?id=82">Ties</a></dd>
                          <dd><a href="index.php?id=83">Caps</a></dd>
                          <dd><a href="index.php?id=84">Belts</a></dd>
                    </dl>                 
                </div>
            </li><!--menu end-->
            <li><a href="index.php?id=13" class="blue">Contact Us</a></li>
        </ul>
        <div class="back"></div>
        <div class="shadow"></div>
    </div>
    <div style="clear:both"></div>
</div>

CSS 3 Coding- Copy and Paste

<style>

body{margin:0px;}
.example {
    width:980px;
    height:40px;
    margin:0px auto;
 position:absolute;
 margin-bottom:60px;
 top:95px;
}

.menuholder {
    float:left;
    font:normal bold 11px/35px verdana, sans-serif;
    overflow:hidden;
    position:relative;
}
.menuholder .shadow {
    -moz-box-shadow:0 0 20px rgba(0, 0, 0, 1);
    -o-box-shadow:0 0 20px rgba(0, 0, 0, 1);
    -webkit-box-shadow:0 0 20px rgba(0, 0, 0, 1);
    background:#888;
    box-shadow:0 0 20px rgba(0, 0, 0, 1);
    height:10px;
    left:5%;
    position:absolute;
    top:-9px;
    width:100%;
    z-index:100;
}
.menuholder .back {
    -moz-transition-duration:.4s;
    -o-transition-duration:.4s;
    -webkit-transition-duration:.4s;
    background-color:rgba(0, 0, 0, 0.88);
    height:0;
    width:980px; /*100%*/
}
.menuholder:hover div.back {
    height:280px;
}
ul.menu {
    display:block;
    float:left;
    list-style:none;
    margin:0;
    padding:0 125px;
    position:relative;
}
ul.menu li {
    float:left;
    margin:0 10px 0 0;
}
ul.menu li > a {
    -moz-border-radius:0 0 10px 10px;
    -moz-box-shadow:2px 2px 4px rgba(0, 0, 0, 0.9);
    -moz-transition:all 0.3s ease-in-out;
    -o-border-radius:0 0 10px 10px;
    -o-box-shadow:2px 2px 4px rgba(0, 0, 0, 0.9);
    -o-transition:all 0.3s ease-in-out;
    -webkit-border-bottom-left-radius:10px;
    -webkit-border-bottom-right-radius:10px;
    -webkit-box-shadow:2px 2px 4px rgba(0, 0, 0, 0.9);
    -webkit-transition:all 0.3s ease-in-out;
    border-radius:0 0 10px 10px;
    box-shadow:2px 2px 4px rgba(0, 0, 0, 0.9);
    color:#eee;
    display:block;
    padding:0 10px;
    text-decoration:none;
    transition:all 0.3s ease-in-out;
}
ul.menu li a.red {
    background:#a00;
}
ul.menu li a.orange {
    background:#da0;
}
ul.menu li a.yellow {
    background:#aa0;
}
ul.menu li a.green {
    background:#060;
}
ul.menu li a.blue {
    background:#073263;
}
ul.menu li a.violet {
    background:#682bc2;
}
.menu li div.subs {
    left:0;
    overflow:hidden;
    position:absolute;
    top:35px;
    width:0;
}
.menu li div.subs dl {
    -moz-transition-duration:.2s;
    -o-transition-duration:.2s;
    -webkit-transition-duration:.2s;
    float:left;
    margin:0 130px 0 0;
    overflow:hidden;
    padding:40px 0 5% 2%;
    width:0;
}
.menu dt {
    color:#fc0;
    font-family:arial, sans-serif;
    font-size:12px;
    font-weight:700;
    height:20px;
    line-height:20px;
    margin:0;
    padding:0 0 0 10px;
    white-space:nowrap;
}
.menu dd {
    margin:0;
    padding:0;
    text-align:left;
}
.menu dd a {
    background:transparent;
    color:#fff;
    font-size:12px;
    height:20px;
    line-height:20px;
    padding:0 0 0 10px;
    text-align:left;
    white-space:nowrap;
    width:80px;
}
.menu dd a:hover {
    color:#fc0;
}
.menu li:hover div.subs dl {
    -moz-transition-delay:0.2s;
    -o-transition-delay:0.2s;
    -webkit-transition-delay:0.2s;
    margin-right:2%;
    width:21%;
}
ul.menu li:hover > a,ul.menu li > a:hover {
    background:#aaa;
    color:#fff;
    padding:10px 10px 0;
}
ul.menu li a.red:hover,ul.menu li:hover a.red {
    background:#c00;
}
ul.menu li a.orange:hover,ul.menu li:hover a.orange {
    background:#fc0;
}
ul.menu li a.yellow:hover,ul.menu li:hover a.yellow {
    background:#cc0;
}
ul.menu li a.green:hover,ul.menu li:hover a.green {
    background:#080;
}
ul.menu li a.blue:hover,ul.menu li:hover a.blue {
    background:#00c;
}
ul.menu li a.violet:hover,ul.menu li:hover a.violet {
background:#8a2be2;
}
.menu li:hover div.subs,.menu li a:hover div.subs {
    width:100%;
}

How to change the cursor into a hand when a user hovers over a list item?

Check the following. I get it from W3Schools.

_x000D_
_x000D_
.alias { cursor: alias; }
.all-scroll { cursor: all-scroll; }
.auto { cursor: auto; }
.cell { cursor: cell; }
.context-menu { cursor: context-menu; }
.col-resize { cursor: col-resize; }
.copy { cursor: copy; }
.crosshair { cursor: crosshair; }
.default { cursor: default; }
.e-resize { cursor: e-resize; }
.ew-resize { cursor: ew-resize; }
.grab {
  cursor: -webkit-grab;
  cursor: grab;
}
.grabbing {
  cursor: -webkit-grabbing;
  cursor: grabbing;
}
.help { cursor: help; }
.move { cursor: move; }
.n-resize { cursor: n-resize; }
.ne-resize { cursor: ne-resize; }
.nesw-resize { cursor: nesw-resize; }
.ns-resize { cursor: ns-resize; }
.nw-resize { cursor: nw-resize; }
.nwse-resize { cursor: nwse-resize; }
.no-drop { cursor: no-drop; }
.none { cursor: none; }
.not-allowed { cursor: not-allowed; }
.pointer { cursor: pointer; }
.progress { cursor: progress; }
.row-resize { cursor: row-resize; }
.s-resize { cursor: s-resize; }
.se-resize { cursor: se-resize; }
.sw-resize { cursor: sw-resize; }
.text { cursor: text; }
.url { cursor: url(myBall.cur), auto; }
.w-resize { cursor: w-resize; }
.wait { cursor: wait; }
.zoom-in { cursor: zoom-in; }
.zoom-out { cursor: zoom-out; }
_x000D_
<!DOCTYPE html>
<html>

<body>
  <h1>The cursor property</h1>
  <p>Mouse over the words to change the mouse cursor.</p>
  <p class="alias">alias</p>
  <p class="all-scroll">all-scroll</p>
  <p class="auto">auto</p>
  <p class="cell">cell</p>
  <p class="context-menu">context-menu</p>
  <p class="col-resize">col-resize</p>
  <p class="copy">copy</p>
  <p class="crosshair">crosshair</p>
  <p class="default">default</p>
  <p class="e-resize">e-resize</p>
  <p class="ew-resize">ew-resize</p>
  <p class="grab">grab</p>
  <p class="grabbing">grabbing</p>
  <p class="help">help</p>
  <p class="move">move</p>
  <p class="n-resize">n-resize</p>
  <p class="ne-resize">ne-resize</p>
  <p class="nesw-resize">nesw-resize</p>
  <p class="ns-resize">ns-resize</p>
  <p class="nw-resize">nw-resize</p>
  <p class="nwse-resize">nwse-resize</p>
  <p class="no-drop">no-drop</p>
  <p class="none">none</p>
  <p class="not-allowed">not-allowed</p>
  <p class="pointer">pointer</p>
  <p class="progress">progress</p>
  <p class="row-resize">row-resize</p>
  <p class="s-resize">s-resize</p>
  <p class="se-resize">se-resize</p>
  <p class="sw-resize">sw-resize</p>
  <p class="text">text</p>
  <p class="url">url</p>
  <p class="w-resize">w-resize</p>
  <p class="wait">wait</p>
  <p class="zoom-in">zoom-in</p>
  <p class="zoom-out">zoom-out</p>
</body>

</html>
_x000D_
_x000D_
_x000D_

How do I check if an element is hidden in jQuery?

1 • jQuery solution

Methods to determine if an element is visible in jQuery

<script>
if ($("#myelement").is(":visible")){alert ("#myelement is visible");}
if ($("#myelement").is(":hidden")){alert ("#myelement is hidden"); }
</script>

Loop on all visible div children of the element of id 'myelement':

$("#myelement div:visible").each( function() {
 //Do something
});

Peeked at source of jQuery

This is how jQuery implements this feature:

jQuery.expr.filters.visible = function( elem ) {
    return !!( elem.offsetWidth || elem.offsetHeight || elem.getClientRects().length );
};

2 • How to check if an element is off-screen - CSS

Using Element.getBoundingClientRect() you can easily detect whether or not your element is within the boundaries of your viewport (i.e. onscreen or offscreen):

jQuery.expr.filters.offscreen = function(el) {
  var rect = el.getBoundingClientRect();
  return (
           (rect.x + rect.width) < 0 
             || (rect.y + rect.height) < 0
             || (rect.x > window.innerWidth || rect.y > window.innerHeight)
         );
};

You could then use that in several ways:

// Returns all elements that are offscreen
$(':offscreen');

// Boolean returned if element is offscreen
$('div').is(':offscreen');

If you use Angular, check: Don’t use hidden attribute with Angular

"Cannot verify access to path (C:\inetpub\wwwroot)", when adding a virtual directory

I had this error because I hadn't installed ASP.NET through Server Roles and Features. Added that and it all worked as expected

Smart cast to 'Type' is impossible, because 'variable' is a mutable property that could have been changed by this time

For there to be a Smart Cast of the properties, the data type of the property must be the class that contains the method or behavior that you want to access and NOT that the property is of the type of the super class.


e.g on Android

Be:

class MyVM : ViewModel() {
    fun onClick() {}
}

Solution:

From: private lateinit var viewModel: ViewModel
To: private lateinit var viewModel: MyVM

Usage:

viewModel = ViewModelProvider(this)[MyVM::class.java]
viewModel.onClick {}

GL

C# Interfaces. Implicit implementation versus Explicit implementation

To quote Jeffrey Richter from CLR via C#
(EIMI means Explicit Interface Method Implementation)

It is critically important for you to understand some ramifications that exist when using EIMIs. And because of these ramifications, you should try to avoid EIMIs as much as possible. Fortunately, generic interfaces help you avoid EIMIs quite a bit. But there may still be times when you will need to use them (such as implementing two interface methods with the same name and signature). Here are the big problems with EIMIs:

  • There is no documentation explaining how a type specifically implements an EIMI method, and there is no Microsoft Visual Studio IntelliSense support.
  • Value type instances are boxed when cast to an interface.
  • An EIMI cannot be called by a derived type.

If you use an interface reference ANY virtual chain can be explicitly replaced with EIMI on any derived class and when an object of such type is cast to the interface, your virtual chain is ignored and the explicit implementation is called. That's anything but polymorphism.

EIMIs can also be used to hide non-strongly typed interface members from basic Framework Interfaces' implementations such as IEnumerable<T> so your class doesn't expose a non strongly typed method directly, but is syntactical correct.

Python error when trying to access list by index - "List indices must be integers, not str"

A list is a chain of spaces that can be indexed by (0, 1, 2 .... etc). So if players was a list, players[0] or players[1] would have worked. If players is a dictionary, players["name"] would have worked.

How to replace all occurrences of a string in Javascript?

These are the most common and readable methods.

var str = "Test abc test test abc test test test abc test test abc"

Method 1:

str = str.replace(/abc/g, "replaced text");

Method 2:

str = str.split("abc").join("replaced text");

Method 3:

str = str.replace(new RegExp("abc", "g"), "replaced text");

Method 4:

while(str.includes("abc")){
    str = str.replace("abc", "replaced text");
}

Output:

console.log(str);
// Test replaced text test test replaced text test test test replaced text test test replaced text

ListView with Add and Delete Buttons in each Row in android

on delete button click event

public void delete(View v){                

    ListView listview1;
    ArrayList<E> datalist;

    final int position = listview1.getPositionForView((View) v.getParent());
    datalist.remove(position);
    myAdapter.notifyDataSetChanged();

}

How to automatically generate getters and setters in Android Studio

You can use AndroidAccessors Plugin of Android Studio to generate getter and setter without m as prefix to methods

Ex: mId; Will generate getId() and setId() instead of getmId() and setmId()

plugin screenshot

"Submit is not a function" error in JavaScript

In fact, the solution is very easy...

Original:

    <form action="product.php" method="get" name="frmProduct" id="frmProduct"
enctype="multipart/form-data">
    <input onclick="submitAction()" id="submit_value" type="button" 
    name="submit_value" value="">
</form>
<script type="text/javascript">
    function submitAction()
    {
        document.frmProduct.submit();
    }
</script>

Solution:

    <form action="product.php" method="get" name="frmProduct" id="frmProduct" 
enctype="multipart/form-data">
</form>

<!-- Place the button here -->
<input onclick="submitAction()" id="submit_value" type="button" 
    name="submit_value" value="">

<script type="text/javascript">
    function submitAction()
    {
        document.frmProduct.submit();
    }
</script>

How to create loading dialogs in Android?

Today things have changed a little.

Now we avoid use ProgressDialog to show spinning progress:

enter image description here

If you want to put in your app a spinning progress you should use an Activity indicators:

http://developer.android.com/design/building-blocks/progress.html#activity

Sorting Directory.GetFiles()

You could write a custom IComparer interface to sort by creation date, and then pass it to Array.Sort. You probably also want to look at StrCmpLogical, which is what is used to do the sorting Explorer uses (sorting numbers correctly with text).

How do you stylize a font in Swift?

I am assuming this is a custom font. For any custom font this is what you do.

  1. First download and add your font files to your project in Xcode (The files should appear as well in “Target -> Build Phases -> Copy Bundle Resources”).

  2. In your Info.plist file add the key “Fonts provided by application” with type “Array”.

  3. For each font you want to add to your project, create an item for the array you have created with the full name of the file including its extension (e.g. HelveticaNeue-UltraLight.ttf). Save your “Info.plist” file.

label.font = UIFont (name: "HelveticaNeue-UltraLight", size: 30)

Webdriver findElements By xpath

Your questions:

Q 1.) I would like to know why it returns all the texts that following the div?
It should not and I think in will not. It returns all div with 'id' attribute value equal 'containter' (and all children of this). But you are printing the results with ele.getText() Where getText will return all text content of all children of your result.

Get the visible (i.e. not hidden by CSS) innerText of this element, including sub-elements, without any leading or trailing whitespace.
Returns:
The innerText of this element.

Q 2.) how should I modify the code so it just return first or first few nodes that follow the parent note
This is not really clear what you are looking for. Example:

<p1> <div/> </p1 <p2/> 

The following to parent of the div is p2. This would be:

 //div[@id='container'][1]/parent::*/following-sibling::* 

or shorter

 //div[@id='container'][1]/../following-sibling::* 

If you are only looking for the first one extent the expression with an "predicate" (e.g [1] - for the first one. or [position() &lt; 4]for the first three)

If your are looking for the first child of the first div:

//div[@id='container'][1]/*[1]

If there is only one div with id an you are looking for the first child:

   //div[@id='container']/*[1]

and so on.

Passing parameters in rails redirect_to

redirect_to :controller => "controller_name", :action => "action_name", :id => x.id

Why can't I inherit static classes?

A workaround you can do is not use static classes but hide the constructor so the classes static members are the only thing accessible outside the class. The result is an inheritable "static" class essentially:

public class TestClass<T>
{
    protected TestClass()
    { }

    public static T Add(T x, T y)
    {
        return (dynamic)x + (dynamic)y;
    }
}

public class TestClass : TestClass<double>
{
    // Inherited classes will also need to have protected constructors to prevent people from creating instances of them.
    protected TestClass()
    { }
}

TestClass.Add(3.0, 4.0)
TestClass<int>.Add(3, 4)

// Creating a class instance is not allowed because the constructors are inaccessible.
// new TestClass();
// new TestClass<int>();

Unfortunately because of the "by-design" language limitation we can't do:

public static class TestClass<T>
{
    public static T Add(T x, T y)
    {
        return (dynamic)x + (dynamic)y;
    }
}

public static class TestClass : TestClass<double>
{
}

How do I raise the same Exception with a custom message in Python?

if you want to custom the error type, a simple thing you can do is to define an error class based on ValueError.

Environment.GetFolderPath(...CommonApplicationData) is still returning "C:\Documents and Settings\" on Vista

Output on Ubuntu 9.10 -> Ubuntu 12.04 with mono 2.10.8.1:

SpecialFolder.ApplicationData: /home/$USER/.config
SpecialFolder.CommonApplicationData: /usr/share
SpecialFolder.ProgramFiles: 
SpecialFolder.DesktopDirectory: /home/$USER/Desktop
SpecialFolder.LocalApplicationData: /home/$USER/.local/share
SpecialFolder.MyDocuments: /home/$USER
SpecialFolder.System: 

SpecialFolder.Personal: /home/$USER

Output on Ubuntu 16.04 with mono 4.2.1

SpecialFolder.ApplicationData: /home/$USER/.config
SpecialFolder.CommonApplicationData: /usr/share
SpecialFolder.ProgramFiles:
SpecialFolder.DesktopDirectory: /home/$USER/Desktop
SpecialFolder.LocalApplicationData: /home/$USER/.local/share
SpecialFolder.MyDocuments: /home/$USER
SpecialFolder.Desktop: /home/$USER/Desktop
SpecialFolder.Personal: /home/$USER

SpecialFolder.System: 
SpecialFolder.Programs: 
SpecialFolder.Favorites: 
SpecialFolder.Startup: 
SpecialFolder.Recent: 
SpecialFolder.SendTo: 
SpecialFolder.StartMenu: 
SpecialFolder.MyMusic: /home/$USER/Music
SpecialFolder.MyVideos: /home/$USER/Videos
SpecialFolder.MyComputer: 
SpecialFolder.NetworkShortcuts: 
SpecialFolder.Fonts: /home/$USER/.fonts
SpecialFolder.Templates: /home/$USER/Templates
SpecialFolder.CommonStartMenu: 
SpecialFolder.CommonPrograms: 
SpecialFolder.CommonStartup: 
SpecialFolder.CommonDesktopDirectory: 
SpecialFolder.PrinterShortcuts: 
SpecialFolder.InternetCache: 
SpecialFolder.Cookies: 
SpecialFolder.History: 
SpecialFolder.Windows: 
SpecialFolder.MyPictures: /home/$USER/Pictures
SpecialFolder.UserProfile: /home/$USER
SpecialFolder.SystemX86: 
SpecialFolder.ProgramFilesX86: 
SpecialFolder.CommonProgramFiles: 
SpecialFolder.CommonProgramFilesX86: 
SpecialFolder.CommonTemplates: /usr/share/templates
SpecialFolder.CommonDocuments: 
SpecialFolder.CommonAdminTools: 
SpecialFolder.AdminTools: 
SpecialFolder.CommonMusic: 
SpecialFolder.CommonPictures: 
SpecialFolder.CommonVideos: 
SpecialFolder.Resources: 
SpecialFolder.LocalizedResources: 
SpecialFolder.CommonOemLinks: 
SpecialFolder.CDBurning: 

where $USER is the current user

Output on Ubuntu 16.04 using dotnet core (3.0.100)

ApplicationData: /home/$USER/.config
CommonApplicationData: /usr/share
ProgramFiles: 
DesktopDirectory: /home/$USER/Desktop
LocalApplicationData: /home/$USER/.local/share
MyDocuments: /home/$USER
System: 
Personal: /home/$USER

Output on Android 6 using Xamarin 7.2

Environment.SpecialFolder.ApplicationData: /data/user/0/$APPNAME/files/.config
Environment.SpecialFolder.CommonApplicationData: /usr/share
Environment.SpecialFolder.ProgramFiles: 
Environment.SpecialFolder.DesktopDirectory: /data/user/0/$APPNAME/files/Desktop
Environment.SpecialFolder.LocalApplicationData: /data/user/0/$APPNAME/files/.local/share
Environment.SpecialFolder.MyDocuments: /data/user/0/$APPNAME/files
Environment.SpecialFolder.Desktop: /data/user/0/$APPNAME/files/Desktop
Environment.SpecialFolder.Personal: /data/user/0/$APPNAME/files

Environment.SpecialFolder.Startup: 
Environment.SpecialFolder.Recent: 
Environment.SpecialFolder.SendTo: 
Environment.SpecialFolder.StartMenu: 
Environment.SpecialFolder.MyMusic: /data/user/0/$APPNAME/files/Music
Environment.SpecialFolder.MyVideos: /data/user/0/$APPNAME/files/Videos
Environment.SpecialFolder.MyComputer: 
Environment.SpecialFolder.NetworkShortcuts: 
Environment.SpecialFolder.Fonts: /data/user/0/$APPNAME/files/.fonts
Environment.SpecialFolder.Templates: /data/user/0/$APPNAME/files/Templates
Environment.SpecialFolder.CommonStartMenu: 
Environment.SpecialFolder.CommonPrograms: 
Environment.SpecialFolder.CommonStartup: 
Environment.SpecialFolder.CommonDesktopDirectory: 
Environment.SpecialFolder.PrinterShortcuts: 
Environment.SpecialFolder.InternetCache: 
Environment.SpecialFolder.Cookies: 
Environment.SpecialFolder.History: 
Environment.SpecialFolder.Windows: 
Environment.SpecialFolder.MyPictures: /data/user/0/$APPNAME/files/Pictures
Environment.SpecialFolder.UserProfile: /data/user/0/$APPNAME/files
Environment.SpecialFolder.SystemX86: 
Environment.SpecialFolder.ProgramFilesX86: 
Environment.SpecialFolder.CommonProgramFiles: 
Environment.SpecialFolder.CommonProgramFilesX86: 
Environment.SpecialFolder.CommonTemplates: /usr/share/templates
Environment.SpecialFolder.CommonDocuments: 
Environment.SpecialFolder.CommonAdminTools: 
Environment.SpecialFolder.AdminTools: 
Environment.SpecialFolder.CommonMusic: 
Environment.SpecialFolder.CommonPictures: 
Environment.SpecialFolder.CommonVideos: 
Environment.SpecialFolder.Resources: 
Environment.SpecialFolder.LocalizedResources: 
Environment.SpecialFolder.CommonOemLinks: 
Environment.SpecialFolder.CDBurning: 

Where $APPNAME is the name of your Xamarin application (eg. MyApp.Droid)

Output on iOS Simulator 10.3 using Xamarin 7.2

ApplicationData: /Users/$USER/Library/Developer/CoreSimulator/Devices/$DEVICEGUID/data/Containers/Data/Application/$APPLICATIONGUID/Documents/.config
CommonApplicationData: /usr/share
ProgramFiles: /Applications
DesktopDirectory: /Users/$USER/Library/Developer/CoreSimulator/Devices/$DEVICEGUID/data/Containers/Data/Application/$APPLICATIONGUID/Documents/Desktop
LocalApplicationData: /Users/$USER/Library/Developer/CoreSimulator/Devices/$DEVICEGUID/data/Containers/Data/Application/$APPLICATIONGUID/Documents
MyDocuments: /Users/$USER/Library/Developer/CoreSimulator/Devices/$DEVICEGUID/data/Containers/Data/Application/$APPLICATIONGUID/Documents
Desktop: /Users/$USER/Library/Developer/CoreSimulator/Devices/$DEVICEGUID/data/Containers/Data/Application/$APPLICATIONGUID/Documents/Desktop
MyDocuments: /Users/$USER/Library/Developer/CoreSimulator/Devices/$DEVICEGUID/data/Containers/Data/Application/$APPLICATIONGUID/Documents
Startup: 
Recent: 
SendTo: 
StartMenu: 
MyMusic: /Users/$USER/Library/Developer/CoreSimulator/Devices/$DEVICEGUID/data/Containers/Data/Application/$APPLICATIONGUID/Documents/Music
MyVideos: /Users/$USER/Library/Developer/CoreSimulator/Devices/$DEVICEGUID/data/Containers/Data/Application/$APPLICATIONGUID/Documents/Videos
MyComputer: 
NetworkShortcuts: 
Fonts: /Users/$USER/Library/Developer/CoreSimulator/Devices/$DEVICEGUID/data/Containers/Data/Application/$APPLICATIONGUID/Documents/.fonts
Templates: /Users/$USER/Library/Developer/CoreSimulator/Devices/$DEVICEGUID/data/Containers/Data/Application/$APPLICATIONGUID/Documents/Templates
CommonStartMenu: 
CommonPrograms: 
CommonStartup: 
CommonDesktopDirectory: 
PrinterShortcuts: 
InternetCache: /Users/$USER/Library/Developer/CoreSimulator/Devices/$DEVICEGUID/data/Containers/Data/Application/$APPLICATIONGUID/Library/Caches
Cookies: 
History: 
Windows: 
MyPictures: /Users/$USER/Library/Developer/CoreSimulator/Devices/$DEVICEGUID/data/Containers/Data/Application/$APPLICATIONGUID/Documents/Pictures
UserProfile: /Users/$USER/Library/Developer/CoreSimulator/Devices/$DEVICEGUID/data/Containers/Data/Application/$APPLICATIONGUID
SystemX86: 
ProgramFilesX86: 
CommonProgramFiles: 
CommonProgramFilesX86: 
CommonTemplates: /usr/share/templates
CommonDocuments: 
CommonAdminTools: 
AdminTools: 
CommonMusic: 
CommonPictures: 
CommonVideos: 
Resources: /Users/$USER/Library/Developer/CoreSimulator/Devices/$DEVICEGUID/data/Containers/Data/Application/$APPLICATIONGUID/Library
LocalizedResources: 
CommonOemLinks: 
CDBurning: 

Where $DEVICEGUID is the simulator GUID (depending on the selected simulator)

Output on ipad 10.3 using Xamarin 7.2

SpecialFolder.MyDocuments: /var/mobile/Containers/Data/Application/$APPLICATIONGUID/Documents

Output on ipad 13.3 using Xamarin 16.4

SpecialFolder.MyDocuments: /var/mobile/Containers/Data/Application/$APPLICATIONGUID/Documents
SpecialFolder.UserProfile: /private/var/mobile/Containers/Data/Application/$APPLICATIONGUID/Documents

Output on windows 10 using .net core 3.1

SpecialFolder.MyDocuments: C:\Users\$USER\Documents

Output on Ubuntu 18.04 using .net core 3.1

SpecialFolder.MyDocuments: /home/$USER

Output on MacOS Catalina using .net core 3.1

SpecialFolder.MyDocuments: /Users/$USER

Use of #pragma in C

My best advice is to look at your compiler's documentation, because pragmas are by definition implementation-specific. For instance, in embedded projects I've used them to locate code and data in different sections, or declare interrupt handlers. i.e.:

#pragma code BANK1
#pragma data BANK2

#pragma INT3 TimerHandler

How to fix syntax error, unexpected T_IF error in php?

PHP parser errors take some getting used to; if it complains about an unexpected 'something' at line X, look at line X-1 first. In this case it will not tell you that you forgot a semi-colon at the end of the previous line , instead it will complain about the if that comes next.

You'll get used to it :)

How can I export the schema of a database in PostgreSQL?

set up a new postgresql server and replace its data folder with the files from your external disk.

You will then be able to start that postgresql server up and retrieve the data using pg_dump (pg_dump -s for the schema-only as mentioned)

Proper use of mutexes in Python

I don't know why you're using the Window's Mutex instead of Python's. Using the Python methods, this is pretty simple:

from threading import Thread, Lock

mutex = Lock()

def processData(data):
    mutex.acquire()
    try:
        print('Do some stuff')
    finally:
        mutex.release()

while True:
    t = Thread(target = processData, args = (some_data,))
    t.start()

But note, because of the architecture of CPython (namely the Global Interpreter Lock) you'll effectively only have one thread running at a time anyway--this is fine if a number of them are I/O bound, although you'll want to release the lock as much as possible so the I/O bound thread doesn't block other threads from running.

An alternative, for Python 2.6 and later, is to use Python's multiprocessing package. It mirrors the threading package, but will create entirely new processes which can run simultaneously. It's trivial to update your example:

from multiprocessing import Process, Lock

mutex = Lock()

def processData(data):
    with mutex:
        print('Do some stuff')

if __name__ == '__main__':
    while True:
        p = Process(target = processData, args = (some_data,))
        p.start()

How to solve the “failed to lazily initialize a collection of role” Hibernate exception

To get rid of lazy initialization exception you should not call for lazy collection when you operate with detached object.

From my opinion, best approach is to use DTO, and not entity. In this case you can explicitly set fields which you want to use. As usual it's enough. No need to worry that something like jackson ObjectMapper, or hashCode generated by Lombok will call your methods implicitly.

For some specific cases you can use @EntityGrpaph annotation, which allow you to make eager load even if you have fetchType=lazy in your entity.

How to access the GET parameters after "?" in Express?

A nice technique i've started using with some of my apps on express is to create an object which merges the query, params, and body fields of express's request object.

//./express-data.js
const _ = require("lodash");

class ExpressData {

    /*
    * @param {Object} req - express request object
    */
    constructor (req) {

        //Merge all data passed by the client in the request
        this.props = _.merge(req.body, req.params, req.query);
     }

}

module.exports = ExpressData;

Then in your controller body, or anywhere else in scope of the express request chain, you can use something like below:

//./some-controller.js

const ExpressData = require("./express-data.js");
const router = require("express").Router();


router.get("/:some_id", (req, res) => {

    let props = new ExpressData(req).props;

    //Given the request "/592363122?foo=bar&hello=world"
    //the below would log out 
    // {
    //   some_id: 592363122,
    //   foo: 'bar',
    //   hello: 'world'
    // }
    console.log(props);

    return res.json(props);
});

This makes it nice and handy to just "delve" into all of the "custom data" a user may have sent up with their request.

Note

Why the 'props' field? Because that was a cut-down snippet, I use this technique in a number of my APIs, I also store authentication / authorisation data onto this object, example below.

/*
 * @param {Object} req - Request response object
*/
class ExpressData {

    /*
    * @param {Object} req - express request object
    */
    constructor (req) {

        //Merge all data passed by the client in the request
        this.props = _.merge(req.body, req.params, req.query);

        //Store reference to the user
        this.user = req.user || null;

        //API connected devices (Mobile app..) will send x-client header with requests, web context is implied.
        //This is used to determine how the user is connecting to the API 
        this.client = (req.headers) ? (req.headers["x-client"] || (req.client || "web")) : "web";
    }
} 

how to install Lex and Yacc in Ubuntu?

Use the synaptic packet manager in order to install yacc / lex. If you are feeling more comfortable doing this on the console just do:

sudo apt-get install bison flex

There are some very nice articles on the net on how to get started with those tools. I found the article from CodeProject to be quite good and helpful (see here). But you should just try and search for "introduction to lex", there are plenty of good articles showing up.

Why isn't sizeof for a struct equal to the sum of sizeof of each member?

Among the other well-explained answers about memory alignment and structure padding/packing, there is something which I have discovered in the question itself by reading it carefully.

"Why isn't sizeof for a struct equal to the sum of sizeof of each member?"

"Why does the sizeof operator return a size larger for a structure than the total sizes of the structure's members"?

Both questions suggest something what is plain wrong. At least in a generic, non-example focused view, which is the case here.

The result of the sizeof operand applied to a structure object can be equal to the sum of sizeof applied to each member separately. It doesn't have to be larger/different.

If there is no reason for padding, no memory will be padded.


One most implementations, if the structure contains only members of the same type:

struct foo {
   int a;   
   int b;
   int c;     
} bar;

Assuming sizeof(int) == 4, the size of the structure bar will be equal to the sum of the sizes of all members together, sizeof(bar) == 12. No padding done here.

Same goes for example here:

struct foo {
   short int a;   
   short int b;
   int c;     
} bar;

Assuming sizeof(short int) == 2 and sizeof(int) == 4. The sum of allocated bytes for a and b is equal to the allocated bytes for c, the largest member and with that everything is perfectly aligned. Thus, sizeof(bar) == 8.

This is also object of the second most popular question regarding structure padding, here:

How do I pass a command line argument while starting up GDB in Linux?

I'm using GDB7.1.1, as --help shows:

gdb [options] --args executable-file [inferior-arguments ...]

IMHO, the order is a bit unintuitive at first.

Query an XDocument for elements by name at any depth

You can do it this way:

xml.Descendants().Where(p => p.Name.LocalName == "Name of the node to find")

where xml is a XDocument.

Be aware that the property Name returns an object that has a LocalName and a Namespace. That's why you have to use Name.LocalName if you want to compare by name.

How to get commit history for just one branch?

The git merge-base command can be used to find a common ancestor. So if my_experiment has not been merged into master yet and my_experiment was created from master you could:

git log --oneline `git merge-base my_experiment master`..my_experiment

JQuery Redirect to URL after specified time

You can use

    $(document).ready(function(){
      setTimeout(function() {
       window.location.href = "http://test.example.com/;"
      }, 5000);
    });

Print a string as hex bytes?

With f-string:

"".join(f"{ord(c):x}" for c in "Hello")

Rename a table in MySQL

For Mysql 5.6.18 use the following command

ALTER TABLE `old_table` RENAME TO `new_table`

Also if there is an error saying ".... near RENAME TO ..." try removing the tick `

Error: stray '\240' in program

The /240 error is due to illegal spaces before every code of line.

eg.

Do

printf("Anything");

instead of

 printf("Anything");

This error is common when you copied and pasted the code in the IDE.

Error Running React Native App From Terminal (iOS)

In Mac: After all, you are getting this issue, there may be a chance of missing the following in System Preferences -> Network -> Ethernet -> Select Advanced -> Proxies

add the following line,

*.local,localhost

Efficiently finding the last line in a text file

with open('output.txt', 'r') as f:
    lines = f.read().splitlines()
    last_line = lines[-1]
    print last_line

Find first element by predicate

However this seems inefficient to me, as the filter will scan the whole list

No it won't - it will "break" as soon as the first element satisfying the predicate is found. You can read more about laziness in the stream package javadoc, in particular (emphasis mine):

Many stream operations, such as filtering, mapping, or duplicate removal, can be implemented lazily, exposing opportunities for optimization. For example, "find the first String with three consecutive vowels" need not examine all the input strings. Stream operations are divided into intermediate (Stream-producing) operations and terminal (value- or side-effect-producing) operations. Intermediate operations are always lazy.

Cannot find the object because it does not exist or you do not have permissions. Error in SQL Server

It can also happen due to a typo in referencing a table such as [dbo.Product] instead of [dbo].[Product].

Javascript form validation with password confirming

add this to your form:

<form  id="regform" action="insert.php" method="post">

add this to your function:

<script>
    function myFunction() {
        var pass1 = document.getElementById("pass1").value;
        var pass2 = document.getElementById("pass2").value;
        if (pass1 != pass2) {
            //alert("Passwords Do not match");
            document.getElementById("pass1").style.borderColor = "#E34234";
            document.getElementById("pass2").style.borderColor = "#E34234";
        }
        else {
            alert("Passwords Match!!!");
            document.getElementById("regForm").submit();
        }
    }
</script>

The service cannot be started, either because it is disabled or because it has no enabled devices associated with it

Try to open Services Window, by writing services.msc into Start->Run and hit Enter.

When window appears, then find SQL Browser service, right click and choose Properties, and then in dropdown list choose Automatic, or Manual, whatever you want, and click OK. Eventually, if not started immediately, you can again press right click on this service and click Start.

What is the difference between XAMPP or WAMP Server & IIS?

XAMPP is more powerful and resource taking than WAMP.
WAMP provides support for MySQL and PHP.
XAMPP provides support for MYSQL, PHP and PERL

XAMPP also has SSL feature while WAMP doesnt.
If your applications need to deal with native web apps only, Go for WAMP. If you need advanced features as stated above, go for XAMPP.

As of priority, you cant run both together with default installation as XAMPP gets a higher priority and it takes up ports. So WAMP cant be run in parallel with XAMPP.

How to handle calendar TimeZones using Java?

Method for converting from one timeZone to other(probably it works :) ).

/**
 * Adapt calendar to client time zone.
 * @param calendar - adapting calendar
 * @param timeZone - client time zone
 * @return adapt calendar to client time zone
 */
public static Calendar convertCalendar(final Calendar calendar, final TimeZone timeZone) {
    Calendar ret = new GregorianCalendar(timeZone);
    ret.setTimeInMillis(calendar.getTimeInMillis() +
            timeZone.getOffset(calendar.getTimeInMillis()) -
            TimeZone.getDefault().getOffset(calendar.getTimeInMillis()));
    ret.getTime();
    return ret;
}

How to stop mongo DB in one command

My special case is:

previously start mongod by:

sudo -u mongod mongod -f /etc/mongod.conf

now, want to stop mongod.

and refer official doc Stop mongod Processes, has tried:

(1) shutdownServer but failed:

> use admin
switched to db admin
> db.shutdownServer()
2019-03-06T14:13:15.334+0800 E QUERY    [thread1] Error: shutdownServer failed: {
        "ok" : 0,
        "errmsg" : "shutdown must run from localhost when running db without auth",
        "code" : 13
} :
_getErrorWithCode@src/mongo/shell/utils.js:25:13
DB.prototype.shutdownServer@src/mongo/shell/db.js:302:1
@(shell):1:1

(2) --shutdown still failed:

# mongod --shutdown
There doesn't seem to be a server running with dbpath: /data/db

(3) previous start command adding --shutdown:

sudo -u mongod mongod -f /etc/mongod.conf --shutdown
killing process with pid: 30213
failed to kill process: errno:1 Operation not permitted

(4) use service to stop:

service mongod stop

and

service mongod status

show expected Active: inactive (dead) but mongod actually still running, for can see process from ps:

# ps -edaf | grep mongo | grep -v grep
root     30213     1  0 Feb04 ?        03:33:22 mongod --port PORT --dbpath=/var/lib/mongo

and finally, really stop mongod by:

# sudo mongod -f /etc/mongod.conf --shutdown
killing process with pid: 30213

until now, root cause: still unknown ...

hope above solution is useful for your.

How do I import a .sql file in mysql database using PHP?

Warning: mysql_* extension is deprecated as of PHP 5.5.0, and has been removed as of PHP 7.0.0. Instead, either the mysqli or PDO_MySQL extension should be used. See also the MySQL API Overview for further help while choosing a MySQL API.
Whenever possible, importing a file to MySQL should be delegated to MySQL client.

the answer from Raj is useful, but (because of file($filename)) it will fail if your mysql-dump not fits in memory

If you are on shared hosting and there are limitations like 30 MB and 12s Script runtime and you have to restore a x00MB mysql dump, you can use this script:

it will walk the dumpfile query for query, if the script execution deadline is near, it saves the current fileposition in a tmp file and a automatic browser reload will continue this process again and again ... If an error occurs, the reload will stop and an the error is shown ...

if you comeback from lunch your db will be restored ;-)

the noLimitDumpRestore.php:

// your config
$filename = 'yourGigaByteDump.sql';
$dbHost = 'localhost';
$dbUser = 'user';
$dbPass = '__pass__';
$dbName = 'dbname';
$maxRuntime = 8; // less then your max script execution limit


$deadline = time()+$maxRuntime; 
$progressFilename = $filename.'_filepointer'; // tmp file for progress
$errorFilename = $filename.'_error'; // tmp file for erro

mysql_connect($dbHost, $dbUser, $dbPass) OR die('connecting to host: '.$dbHost.' failed: '.mysql_error());
mysql_select_db($dbName) OR die('select db: '.$dbName.' failed: '.mysql_error());

($fp = fopen($filename, 'r')) OR die('failed to open file:'.$filename);

// check for previous error
if( file_exists($errorFilename) ){
    die('<pre> previous error: '.file_get_contents($errorFilename));
}

// activate automatic reload in browser
echo '<html><head> <meta http-equiv="refresh" content="'.($maxRuntime+2).'"><pre>';

// go to previous file position
$filePosition = 0;
if( file_exists($progressFilename) ){
    $filePosition = file_get_contents($progressFilename);
    fseek($fp, $filePosition);
}

$queryCount = 0;
$query = '';
while( $deadline>time() AND ($line=fgets($fp, 1024000)) ){
    if(substr($line,0,2)=='--' OR trim($line)=='' ){
        continue;
    }

    $query .= $line;
    if( substr(trim($query),-1)==';' ){
        if( !mysql_query($query) ){
            $error = 'Error performing query \'<strong>' . $query . '\': ' . mysql_error();
            file_put_contents($errorFilename, $error."\n");
            exit;
        }
        $query = '';
        file_put_contents($progressFilename, ftell($fp)); // save the current file position for 
        $queryCount++;
    }
}

if( feof($fp) ){
    echo 'dump successfully restored!';
}else{
    echo ftell($fp).'/'.filesize($filename).' '.(round(ftell($fp)/filesize($filename), 2)*100).'%'."\n";
    echo $queryCount.' queries processed! please reload or wait for automatic browser refresh!';
}

python exception message capturing

If you want the error class, error message, and stack trace, use sys.exc_info().

Minimal working code with some formatting:

import sys
import traceback

try:
    ans = 1/0
except BaseException as ex:
    # Get current system exception
    ex_type, ex_value, ex_traceback = sys.exc_info()

    # Extract unformatter stack traces as tuples
    trace_back = traceback.extract_tb(ex_traceback)

    # Format stacktrace
    stack_trace = list()

    for trace in trace_back:
        stack_trace.append("File : %s , Line : %d, Func.Name : %s, Message : %s" % (trace[0], trace[1], trace[2], trace[3]))

    print("Exception type : %s " % ex_type.__name__)
    print("Exception message : %s" %ex_value)
    print("Stack trace : %s" %stack_trace)

Which gives the following output:

Exception type : ZeroDivisionError
Exception message : division by zero
Stack trace : ['File : .\\test.py , Line : 5, Func.Name : <module>, Message : ans = 1/0']

The function sys.exc_info() gives you details about the most recent exception. It returns a tuple of (type, value, traceback).

traceback is an instance of traceback object. You can format the trace with the methods provided. More can be found in the traceback documentation .

find filenames NOT ending in specific extensions on Unix?

$ find . -name \*.exe -o -name \*.dll -o -print

The first two -name options have no -print option, so they skipped. Everything else is printed.

Implements vs extends: When to use? What's the difference?

As shown in the figure given below, a class extends another class, an interface extends another interface but a class implements an interface. enter image description here

For more details

How to do select from where x is equal to multiple values?

Put parentheses around the "OR"s:

SELECT ads.*, location.county 
FROM ads
LEFT JOIN location ON location.county = ads.county_id
WHERE ads.published = 1 
AND ads.type = 13
AND
(
    ads.county_id = 2
    OR ads.county_id = 5
    OR ads.county_id = 7
    OR ads.county_id = 9
)

Or even better, use IN:

SELECT ads.*, location.county 
FROM ads
LEFT JOIN location ON location.county = ads.county_id
WHERE ads.published = 1 
AND ads.type = 13
AND ads.county_id IN (2, 5, 7, 9)

Programmatically find the number of cores on a machine

Windows (x64 and Win32) and C++11

The number of groups of logical processors sharing a single processor core. (Using GetLogicalProcessorInformationEx, see GetLogicalProcessorInformation as well)

size_t NumberOfPhysicalCores() noexcept {

    DWORD length = 0;
    const BOOL result_first = GetLogicalProcessorInformationEx(RelationProcessorCore, nullptr, &length);
    assert(GetLastError() == ERROR_INSUFFICIENT_BUFFER);

    std::unique_ptr< uint8_t[] > buffer(new uint8_t[length]);
    const PSYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX info = 
            reinterpret_cast< PSYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX >(buffer.get());

    const BOOL result_second = GetLogicalProcessorInformationEx(RelationProcessorCore, info, &length);
    assert(result_second != FALSE);

    size_t nb_physical_cores = 0;
    size_t offset = 0;
    do {
        const PSYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX current_info =
            reinterpret_cast< PSYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX >(buffer.get() + offset);
        offset += current_info->Size;
        ++nb_physical_cores;
    } while (offset < length);
        
    return nb_physical_cores;
}

Note that the implementation of NumberOfPhysicalCores is IMHO far from trivial (i.e. "use GetLogicalProcessorInformation or GetLogicalProcessorInformationEx"). Instead it is rather subtle if one reads the documentation (explicitly present for GetLogicalProcessorInformation and implicitly present for GetLogicalProcessorInformationEx) at MSDN.

The number of logical processors. (Using GetSystemInfo)

size_t NumberOfSystemCores() noexcept {
    SYSTEM_INFO system_info;
    ZeroMemory(&system_info, sizeof(system_info));
    
    GetSystemInfo(&system_info);
    
    return static_cast< size_t >(system_info.dwNumberOfProcessors);
}

Note that both methods can easily be converted to C/C++98/C++03.

Align the form to the center in Bootstrap 4

You need to use the various Bootstrap 4 centering methods...

  • Use text-center for inline elements.
  • Use justify-content-center for flexbox elements (ie; form-inline)

https://codeply.com/go/Am5LvvjTxC

Also, to offset the column, the col-sm-* must be contained within a .row, and the .row must be in a container...

<section id="cover">
    <div id="cover-caption">
        <div id="container" class="container">
            <div class="row">
                <div class="col-sm-10 offset-sm-1 text-center">
                    <h1 class="display-3">Welcome to Bootstrap 4</h1>
                    <div class="info-form">
                        <form action="" class="form-inline justify-content-center">
                            <div class="form-group">
                                <label class="sr-only">Name</label>
                                <input type="text" class="form-control" placeholder="Jane Doe">
                            </div>
                            <div class="form-group">
                                <label class="sr-only">Email</label>
                                <input type="text" class="form-control" placeholder="[email protected]">
                            </div>
                            <button type="submit" class="btn btn-success ">okay, go!</button>
                        </form>
                    </div>
                    <br>

                    <a href="#nav-main" class="btn btn-secondary-outline btn-sm" role="button">?</a>
                </div>
            </div>
        </div>
    </div>
</section>

Sort a list of lists with a custom compare function

Since the OP was asking for using a custom compare function (and this is what led me to this question as well), I want to give a solid answer here:

Generally, you want to use the built-in sorted() function which takes a custom comparator as its parameter. We need to pay attention to the fact that in Python 3 the parameter name and semantics have changed.

How the custom comparator works

When providing a custom comparator, it should generally return an integer/float value that follows the following pattern (as with most other programming languages and frameworks):

  • return a negative value (< 0) when the left item should be sorted before the right item
  • return a positive value (> 0) when the left item should be sorted after the right item
  • return 0 when both the left and the right item have the same weight and should be ordered "equally" without precedence

In the particular case of the OP's question, the following custom compare function can be used:

def compare(item1, item2):
    return fitness(item1) - fitness(item2)

Using the minus operation is a nifty trick because it yields to positive values when the weight of left item1 is bigger than the weight of the right item2. Hence item1 will be sorted after item2.

If you want to reverse the sort order, simply reverse the subtraction: return fitness(item2) - fitness(item1)

Calling sorted() in Python 2

sorted(mylist, cmp=compare)

or:

sorted(mylist, cmp=lambda item1, item2: fitness(item1) - fitness(item2))

Calling sorted() in Python 3

from functools import cmp_to_key
sorted(mylist, key=cmp_to_key(compare))

or:

from functools import cmp_to_key
sorted(mylist, key=cmp_to_key(lambda item1, item2: fitness(item1) - fitness(item2)))

How can I manually generate a .pyc file from a .py file

You can compile individual files(s) from the command line with:

python -m compileall <file_1>.py <file_n>.py

Why does npm install say I have unmet dependencies?

--dev installing devDependencies recursively (and its run forever..) how it can help to resolve the version differences?

You can try remove the node_moduls folder, then clean the npm cache and then run 'npm i' again

Margin-Top not working for span element?

Looks like you missed some options, try to add:

position: relative;
top: 25px;

Using SQL LOADER in Oracle to import CSV file

Try this

load data infile 'datafile location' into table schema.tablename fields terminated by ',' optionally enclosed by '|' (field1,field2,field3....)

In command prompt:

sqlldr system@databasename/password control='control file location'

When to use Task.Delay, when to use Thread.Sleep?

I want to add something. Actually, Task.Delay is a timer based wait mechanism. If you look at the source you would find a reference to a Timer class which is responsible for the delay. On the other hand Thread.Sleep actually makes current thread to sleep, that way you are just blocking and wasting one thread. In async programming model you should always use Task.Delay() if you want something(continuation) happen after some delay.

Python conditional assignment operator

No, not knowing which variables are defined is a bug, not a feature in Python.

Use dicts instead:

d = {}
d.setdefault('key', 1)
d['key'] == 1

d['key'] = 2
d.setdefault('key', 1)
d['key'] == 2

Right way to convert data.frame to a numeric matrix, when df also contains strings?

Here is an alternative way if the data frame just contains numbers.

_x000D_
_x000D_
apply(as.matrix.noquote(SFI),2,as.numeric)
_x000D_
_x000D_
_x000D_

but the most reliable way of converting a data frame to a matrix is using data.matrix() function.

C# - Simplest way to remove first occurrence of a substring from another string

You could use an extension method for fun. Typically I don't recommend attaching extension methods to such a general purpose class like string, but like I said this is fun. I borrowed @Luke's answer since there is no point in re-inventing the wheel.

[Test]
public void Should_remove_first_occurrance_of_string() {

    var source = "ProjectName\\Iteration\\Release1\\Iteration1";

    Assert.That(
        source.RemoveFirst("\\Iteration"),
        Is.EqualTo("ProjectName\\Release1\\Iteration1"));
}

public static class StringExtensions {
    public static string RemoveFirst(this string source, string remove) {
        int index = source.IndexOf(remove);
        return (index < 0)
            ? source
            : source.Remove(index, remove.Length);
    }
}

C# nullable string error

String is a reference type, so you don't need to (and cannot) use Nullable<T> here. Just declare typeOfContract as string and simply check for null after getting it from the query string. Or use String.IsNullOrEmpty if you want to handle empty string values the same as null.

SQLSTATE[28000] [1045] Access denied for user 'root'@'localhost' (using password: YES) Symfony2

I dont know what is the exact reason but I solved the problem running:

   app/console cache:clear --env=prod

Html helper for <input type="file" />

I had this same question a while back and came across one of Scott Hanselman's posts:

Implementing HTTP File Upload with ASP.NET MVC including Tests and Mocks

Hope this helps.

How to create a temporary table in SSIS control flow task and then use it in data flow task?

I'm late to this party but I'd like to add one bit to user756519's thorough, excellent answer. I don't believe the "RetainSameConnection on the Connection Manager" property is relevant in this instance based on my recent experience. In my case, the relevant point was their advice to set "ValidateExternalMetadata" to False.

I'm using a temp table to facilitate copying data from one database (and server) to another, hence the reason "RetainSameConnection" was not relevant in my particular case. And I don't believe it is important to accomplish what is happening in this example either, as thorough as it is.

Keyword not supported: "data source" initializing Entity Framework Context

Just use \" instead ", it should resolve the issue.

How to make a HTML Page in A4 paper size page(s)?

A4 size is 210x297mm

So you can set the HTML page to fit those sizes with CSS:

html,body{
    height:297mm;
    width:210mm;
}

Objective-C : BOOL vs bool

As mentioned above BOOL could be an unsigned char type depending on your architecture, while bool is of type int. A simple experiment will show the difference why BOOL and bool can behave differently:

bool ansicBool = 64;
if(ansicBool != true) printf("This will not print\n");

printf("Any given vlaue other than 0 to ansicBool is evaluated to %i\n", ansicBool);

BOOL objcBOOL = 64;
if(objcBOOL != YES) printf("This might print depnding on your architecture\n");

printf("BOOL will keep whatever value you assign it: %i\n", objcBOOL);

if(!objcBOOL) printf("This will not print\n");

printf("! operator will zero objcBOOL %i\n", !objcBOOL);

if(!!objcBOOL) printf("!! will evaluate objcBOOL value to %i\n", !!objcBOOL);

To your surprise if(objcBOOL != YES) will evaluates to 1 by the compiler, since YES is actually the character code 1, and in the eyes of compiler, character code 64 is of course not equal to character code 1 thus the if statement will evaluate to YES/true/1 and the following line will run. However since a none zero bool type always evaluates to the integer value of 1, the above issue will not effect your code. Below are some good tips if you want to use the Objective-C BOOL type vs the ANSI C bool type:

  • Always assign the YES or NO value and nothing else.
  • Convert BOOL types by using double not !! operator to avoid unexpected results.
  • When checking for YES use if(!myBool) instead of if(myBool != YES) it is much cleaner to use the not ! operator and gives the expected result.

Can a Windows batch file determine its own file name?

Bear in mind that 0 is a special case of parameter numbers inside a batch file, where 0 means this file as given on the command line.

So if the file is myfile.bat, you could call it in several ways as follows, each of which would give you a different output from the %0 or %~0 usage:

myfile

myfile.bat

mydir\myfile.bat

c:\mydir\myfile.bat

"c:\mydir\myfile.bat"

All of the above are legal calls if you call it from the correct relative place to the directory in which it exists. %~0 strips the quotes from the last example, whereas %0 does not.

Because these all give different results, %0 and %~0 are very unlikely to be what you actually want to use.

Here's a batch file to illustrate:

@echo Full path and filename: %~f0
@echo Drive: %~d0
@echo Path: %~p0
@echo Drive and path: %~dp0
@echo Filename without extension: %~n0
@echo Filename with    extension: %~nx0
@echo Extension: %~x0
@echo Filename as given on command line: %0
@echo Filename as given on command line minus quotes: %~0
@REM Build from parts
@SETLOCAL
@SET drv=%~d0
@SET pth=%~p0
@SET fpath=%~dp0
@SET fname=%~n0
@SET ext=%~x0
@echo Simply Constructed name: %fpath%%fname%%ext%
@echo Fully  Constructed name: %drv%%pth%%fname%%ext%
@ENDLOCAL
pause

jQuery position DIV fixed at top on scroll

instead of doing it like that, why not just make the flyout position:fixed, top:0; left:0; once your window has scrolled pass a certain height:

jQuery

  $(window).scroll(function(){
      if ($(this).scrollTop() > 135) {
          $('#task_flyout').addClass('fixed');
      } else {
          $('#task_flyout').removeClass('fixed');
      }
  });

css

.fixed {position:fixed; top:0; left:0;}

Example

How to count rows with SELECT COUNT(*) with SQLAlchemy?

I needed to do a count of a very complex query with many joins. I was using the joins as filters, so I only wanted to know the count of the actual objects. count() was insufficient, but I found the answer in the docs here:

http://docs.sqlalchemy.org/en/latest/orm/tutorial.html

The code would look something like this (to count user objects):

from sqlalchemy import func

session.query(func.count(User.id)).scalar() 

How to find the kafka version in linux

There are several methods to find kafka version

Method 1 simple:-

ps -ef|grep kafka

it will displays all running kafka clients in the console... Ex:- /usr/hdp/current/kafka-broker/bin/../libs/kafka-clients-0.10.0.2.5.3.0-37.jar we are using 0.10.0.2.5.3.0-37 version of kafka

Method 2:- go to

cd /usr/hdp/current/kafka-broker/libs
ll |grep kafka

Ex:- kafka_2.10-0.10.0.2.5.3.0-37.jar kafka-clients-0.10.0.2.5.3.0-37.jar

same result as method 1 we can find the version of kafka using in kafka libs.

How to uninstall a windows service and delete its files without rebooting

(so Windows releases it's hold on the file)

Instead, do Ctrl+Alt+Del right after the Stop of the service and kill the .exe of the service. Than, you can uninstall the service without rebooting. This happened to me in the past and it solves the part that you need to reboot.

How can I modify a saved Microsoft Access 2007 or 2010 Import Specification?

I have just discovered an apparent bug in the whole Saved Import/XML setup in Access. Also frustrated by the rigidity of the Saved Import system, I created forms and wrote code to pick apart the XML in which the Saved Import specs are stored, to the point that I could use this tool to actually create a Saved Import from scratch via coded examination of a source Excel workbook.

What I've found out is that, while Access correctly imports a worksheet per modifications of default settings by the user (for example, it likes to take any column with a header name ending with "ID" and make it an indexed field in the resulting table, but you can cancel this during the import process), and while it also correctly creates XML in accordance to the user changes, if you then drop the table and use the Saved Import to re-import the worksheet, it ignores the XML import spec and reverts back to using its own invented defaults, at least in the case of the "ID" columns.

You can try this on your own: import an worksheet Excel with at least one column header name ending with "ID" ("OrderID", "User ID", or just plain "ID"). During the process, be sure to set "Indexed" to No for those columns. Execute the import and check "Save import steps" in the final dialog window. If you inspect the resulting table design, you will see there is no index on the field(s) in question. Then delete the table, find the saved import and execute it again. This time, those fields will be set as Indexed in the table design, even though the XML still says no index.

I was pulling my hair out until I discovered what was going on, comparing the XML I built from scratch with examples created through the Access tool.

CSS Printing: Avoiding cut-in-half DIVs between pages?

page-break-inside: avoid; gave me trouble using wkhtmltopdf.

To avoid breaks in the text add display: table; to the CSS of the text-containing div.

I hope this works for you too. Thanks JohnS.

How can I easily view the contents of a datatable or dataview in the immediate window

Give Xml Visualizer a try. Haven't tried the latest version yet, but I can't work without the previous one in Visual Studio 2003.

on top of displaying DataSet hierarchically, there are also a lot of other handy features such as filtering and selecting the RowState which you want to view.

How can I list ALL DNS records?

What you want is called a zone transfer. You can request a zone transfer using dig -t axfr.

A zone is a domain and all of the domains below it that are not delegated to another server.

Note that zone transfers are not always supported. They're not used in normal lookup, only in replicating DNS data between servers; but there are other protocols that can be used for that (such as rsync over ssh), there may be a security risk from exposing names, and zone transfer responses cost more to generate and send than usual DNS lookups.