Programs & Examples On #State monad

A monad allowing state information to be attached to calculations

Spring configure @ResponseBody JSON format

For Spring version 4.1.3+

I tried Jama's solution, but then all responses were returned with Content-type 'application/json', including the main, generated HTML page.

Overriding configureMessageConverters(...) prevents spring from setting up the default converters. Spring 4.1.3 allows modification of already configured converters by overriding extendMessageConverters(...):

@Configuration
public class ConverterConfig extends WebMvcConfigurerAdapter {
    @Override
    public void extendMessageConverters(List<HttpMessageConverter<?>> converters) {
        for (HttpMessageConverter<?> converter : converters) {
            if (converter instanceof AbstractJackson2HttpMessageConverter) {
                AbstractJackson2HttpMessageConverter c = (AbstractJackson2HttpMessageConverter) converter;
                ObjectMapper objectMapper = c.getObjectMapper();
                objectMapper.setSerializationInclusion(Include.NON_NULL);
            }
        }

        super.extendMessageConverters(converters);
    }
}

see org.springframework..WebMvcConfigurationSupport#getMessageConverters()

see org.springframework..WebMvcConfigurationSupport#addDefaultHttpMessageConverters(...)

HTML code for INR

No! You should avoid using HTML entities.

Instead of using HTML entities for symbols you should just put those symbols directly into your text and correctly encode your document.

  • Instead of using &pound; you should use the character £.
  • For rupee there is no Unicode character. You can use a PNG file instead rupee. Alternatively you can use the unicode character ?? which is currently the most commonly used single character for rupee. Other alternatives are using INR, Rs. or rupees.

When the new Unicode symbol for the Indian Rupee is introduced then could use that instead (but note that it will be a while before all browsers support it).

In C#, why is String a reference type that behaves like a value type?

Isn't just as simple as Strings are made up of characters arrays. I look at strings as character arrays[]. Therefore they are on the heap because the reference memory location is stored on the stack and points to the beginning of the array's memory location on the heap. The string size is not known before it is allocated ...perfect for the heap.

That is why a string is really immutable because when you change it even if it is of the same size the compiler doesn't know that and has to allocate a new array and assign characters to the positions in the array. It makes sense if you think of strings as a way that languages protect you from having to allocate memory on the fly (read C like programming)

Bootstrap 3 breakpoints and media queries

Bootstrap does not document the media queries very well. Those variables of @screen-sm, @screen-md, @screen-lg are actually referring to LESS variables and not simple CSS.

When you customize Bootstrap you can change the media query breakpoints and when it compiles the @screen-xx variables are changed to whatever pixel width you defined as screen-xx. This is how a framework like this can be coded once and then customized by the end user to fit their needs.

A similar question on here that might provide more clarity: Bootstrap 3.0 Media queries

In your CSS, you will still have to use traditional media queries to override or add to what Bootstrap is doing.

In regards to your second question, that is not a typo. Once the screen goes below 768px the framework becomes completely fluid and resizes at any device width, removing the need for breakpoints. The breakpoint at 480px exists because there are specific changes that occur to the layout for mobile optimization.

To see this in action, go to this example on their site (http://getbootstrap.com/examples/navbar-fixed-top/), and resize your window to see how it treats the design after 768px.

Setting the focus to a text field

In a JFrame or JDialog you can always overwrite the setVisible() method, it works well. I haven't tried in a JPanel, but can be an alternative.

@Override
public void setVisible(boolean value) {
    super.setVisible(value);
    control.requestFocusInWindow();
}

Excel VBA App stops spontaneously with message "Code execution has been halted"

I have found a 2nd solution.

  1. Press "Debug" button in the popup.
  2. Press Ctrl+Pause|Break twice.
  3. Hit the play button to continue.
  4. Save the file after completion.

Hope this helps someone.

How do disable paging by swiping with finger in ViewPager but still be able to swipe programmatically?

I needed to disable swiping on one specific page, and give it a nice rubber-band animation, here's how:

    mViewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {

        @Override
        public void onPageScrolled(int position, float positionOffset,
                                   int positionOffsetPixels) {
            if (position == MANDATORY_PAGE_LOCATION && positionOffset > 0.5) {
                mViewPager.setCurrentItem(MANDATORY_PAGE_LOCATION, true);
            }
        }

Convert string to date in Swift

Sometimes, converting string to Date in swift can result to return nil so that you should add "!" mark to format.date function!

let dateFormatterUK = DateFormatter()
dateFormatterUK.dateFormat = "dd-MM-yyyy"

let stringDate = "11-03-2018"
let date = dateFormatterUK.date(from: stringDate)!

How to read a .xlsx file using the pandas Library in iPython?

Assign spreadsheet filename to file

Load spreadsheet

Print the sheet names

Load a sheet into a DataFrame by name: df1

file = 'example.xlsx'
xl = pd.ExcelFile(file)
print(xl.sheet_names)
df1 = xl.parse('Sheet1')

How to apply an XSLT Stylesheet in C#

This might help you

public static string TransformDocument(string doc, string stylesheetPath)
{
    Func<string,XmlDocument> GetXmlDocument = (xmlContent) =>
     {
         XmlDocument xmlDocument = new XmlDocument();
         xmlDocument.LoadXml(xmlContent);
         return xmlDocument;
     };

    try
    {
        var document = GetXmlDocument(doc);
        var style = GetXmlDocument(File.ReadAllText(stylesheetPath));

        System.Xml.Xsl.XslCompiledTransform transform = new System.Xml.Xsl.XslCompiledTransform();
        transform.Load(style); // compiled stylesheet
        System.IO.StringWriter writer = new System.IO.StringWriter();
        XmlReader xmlReadB = new XmlTextReader(new StringReader(document.DocumentElement.OuterXml));
        transform.Transform(xmlReadB, null, writer);
        return writer.ToString();
    }
    catch (Exception ex)
    {
        throw ex;
    }

}   

How to make sure docker's time syncs with that of the host?

I have the following in the compose file

volumes:
  - "/etc/timezone:/etc/timezone:ro"
  - "/etc/localtime:/etc/localtime:ro"

Then all good in Gerrit docker with its replication_log set with correct timestamp.

How to create an array from a CSV file using PHP and the fgetcsv function

Try this..

function getdata($csvFile){
    $file_handle = fopen($csvFile, 'r');
    while (!feof($file_handle) ) {
        $line_of_text[] = fgetcsv($file_handle, 1024);
    }
    fclose($file_handle);
    return $line_of_text;
}


// Set path to CSV file
$csvFile = 'test.csv';

$csv = getdata($csvFile);
echo '<pre>';
print_r($csv);
echo '</pre>';

Array
(
    [0] => Array
        (
            [0] => Project
            [1] => Date
            [2] => User
            [3] => Activity
            [4] => Issue
            [5] => Comment
            [6] => Hours
        )

    [1] => Array
        (
            [0] => test
            [1] => 04/30/2015
            [2] => test
            [3] => test
            [4] => test
            [5] => 
            [6] => 6.00
        ));

android.content.Context.getPackageName()' on a null object reference

The answers to this question helped me find my problem, but my source was different, so hopefully this can shed light on someone finding this page searching for answers to the 'random' context crash:

I had specified a SharedPreferences object, and tried to instantiate it at it's class-level declaration, like so:

public class MyFragment extends FragmentActivity {
    private SharedPreferences sharedPref =
        PreferenceManager.getDefaultSharedPreferences(this);

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    //...

Referencing this before the onCreate caused the "java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String android.content.Context.getPackageName()' on a null object reference" error for me.

Instantiating the object inside the onCreate() solved my problem, like so:

public class MyFragment extends FragmentActivity {
    private SharedPreferences sharedPref;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //...
        sharedPref = PreferenceManager.getDefaultSharedPreferences(this);

Hope that helps.

How does += (plus equal) work?

+= operator is used to concatenate strings or add numbers.

It will increment your sum variable with the amount next to it.

var sum = 0;
var valueAdded = 5; 

sum += valueAdded;

sum = 5

How can I put strings in an array, split by new line?

David: Great direction, but you missed \r. this worked for me:

$array = preg_split("/(\r\n|\n|\r)/", $string);

How to properly ignore exceptions

try:
      doSomething()
except Exception: 
    pass
else:
      stuffDoneIf()
      TryClauseSucceeds()

FYI the else clause can go after all exceptions and will only be run if the code in the try doesn't cause an exception.

How to print Two-Dimensional Array like table

public class FormattedTablePrint {

    public static void printRow(int[] row) {
        for (int i : row) {
            System.out.print(i);
            System.out.print("\t");
        }
        System.out.println();
    }

    public static void main(String[] args) {
        int twoDm[][]= new int[7][5];
        int i,j,k=1;

        for(i=0;i<7;i++) {
            for(j=0;j<5;j++) {
                twoDm[i][j]=k;
                k++;
            }
        }

        for(int[] row : twoDm) {
            printRow(row);
        }
    }
}

Output

1   2   3   4   5   
6   7   8   9   10  
11  12  13  14  15  
16  17  18  19  20  
21  22  23  24  25  
26  27  28  29  30  
31  32  33  34  35  

Of course, you might swap the 7 & 5 as mentioned in other answers, to get 7 per row.

How do I check two or more conditions in one <c:if>?

This look like a duplicate of JSTL conditional check.

The error is having the && outside the expression. Instead use

<c:if test="${ISAJAX == 0 && ISDATE == 0}">

Failed binder transaction when putting an bitmap dynamically in a widget

You can compress the bitmap as an byte's array and then uncompress it in another activity, like this.

Compress!!

        ByteArrayOutputStream stream = new ByteArrayOutputStream();
        bmp.compress(Bitmap.CompressFormat.PNG, 100, stream);
        byte[] bytes = stream.toByteArray(); 
        setresult.putExtra("BMP",bytes);

Uncompress!!

        byte[] bytes = data.getByteArrayExtra("BMP");
        Bitmap bmp = BitmapFactory.decodeByteArray(bytes, 0, bytes.length);

How can I convert a hex string to a byte array?

I think this may work.

public static byte[] StrToByteArray(string str)
    {
        Dictionary<string, byte> hexindex = new Dictionary<string, byte>();
        for (int i = 0; i <= 255; i++)
            hexindex.Add(i.ToString("X2"), (byte)i);

        List<byte> hexres = new List<byte>();
        for (int i = 0; i < str.Length; i += 2)            
            hexres.Add(hexindex[str.Substring(i, 2)]);

        return hexres.ToArray();
    }

ASP.NET Core Dependency Injection error: Unable to resolve service for type while attempting to activate

I had the same issue and found out that my code was using the injection before it was initialized.

services.AddControllers(); // Will cause a problem if you use your IBloggerRepository in there since it's defined after this line.
services.AddScoped<IBloggerRepository, BloggerRepository>();

I know it has nothing to do with the question, but since I was sent to this page, I figure out it my be useful to someone else.

How can I get the SQL of a PreparedStatement?

If you're using MySQL you can log the queries using MySQL's query log. I don't know if other vendors provide this feature, but chances are they do.

Multiplication on command line terminal

If you like python and have an option to install a package, you can use this utility that I made.

# install pythonp
python -m pip install pythonp

pythonp "5*5"
25

pythonp "1 / (1+math.exp(0.5))"
0.3775406687981454

# define a custom function and pass it to another higher-order function
pythonp "n=10;functools.reduce(lambda x,y:x*y, range(1,n+1))"     
3628800

How to prevent going back to the previous activity?

I'm not sure exactly what you want, but it sounds like it should be possible, and it also sounds like you're already on the right track.

Here are a few links that might help:

Disable back button in android

  MyActivity.java =>
    @Override
    public void onBackPressed() {

       return;
    }

How can I disable 'go back' to some activity?

  AndroidManifest.xml =>
<activity android:name=".SplashActivity" android:noHistory="true"/>

JS. How to replace html element with another element/text, represented in string?

idTABLE.parentElement.innerHTML =  '<span>123 element</span> 456';

while this works, it's still recommended to use getElementById: Do DOM tree elements with ids become global variables?

replaceChild would work fine if you want to go to the trouble of building up your replacement, element by element, using document.createElement and appendChild, but I don't see the point.

What happens to C# Dictionary<int, int> lookup if the key does not exist?

You should probably use:

if(myDictionary.ContainsKey(someInt))
{
  // do something
}

The reason why you can't check for null is that the key here is a value type.

Maven compile: package does not exist

the issue happened with me, I resolved by removing the scope tag only and built successfully.

Is it possible to start activity through adb shell?

You can also find the name of the current on screen activity using

adb shell dumpsys window windows | grep 'mCurrentFocus'

How to get object size in memory?

OK, this question has been answered and answer accepted but someone asked me to put my answer so there you go.

First of all, it is not possible to say for sure. It is an internal implementation detail and not documented. However, based on the objects included in the other object. Now, how do we calculate the memory requirement for our cached objects?

I had previously touched this subject in this article:

Now, how do we calculate the memory requirement for our cached objects? Well, as most of you would know, Int32 and float are four bytes, double and DateTime 8 bytes, char is actually two bytes (not one byte), and so on. String is a bit more complex, 2*(n+1), where n is the length of the string. For objects, it will depend on their members: just sum up the memory requirement of all its members, remembering all object references are simply 4 byte pointers on a 32 bit box. Now, this is actually not quite true, we have not taken care of the overhead of each object in the heap. I am not sure if you need to be concerned about this, but I suppose, if you will be using lots of small objects, you would have to take the overhead into consideration. Each heap object costs as much as its primitive types, plus four bytes for object references (on a 32 bit machine, although BizTalk runs 32 bit on 64 bit machines as well), plus 4 bytes for the type object pointer, and I think 4 bytes for the sync block index. Why is this additional overhead important? Well, let’s imagine we have a class with two Int32 members; in this case, the memory requirement is 16 bytes and not 8.

How can I reload .emacs after changing it?

The following should do it...

M-x load-file

How to find out which JavaScript events fired?

Just thought I'd add that you can do this in Chrome as well:

Ctrl + Shift + I (Developer Tools) > Sources> Event Listener Breakpoints (on the right).

You can also view all events that have already been attached by simply right clicking on the element and then browsing its properties (the panel on the right).

For example:

  • Right click on the upvote button to the left
  • Select inspect element
  • Collapse the styles section (section on the far right - double chevron)
  • Expand the event listeners option
  • Now you can see the events bound to the upvote
  • Not sure if it's quite as powerful as the firebug option, but has been enough for most of my stuff.

    Another option that is a bit different but surprisingly awesome is Visual Event: http://www.sprymedia.co.uk/article/Visual+Event+2

    It highlights all of the elements on a page that have been bound and has popovers showing the functions that are called. Pretty nifty for a bookmark! There's a Chrome plugin as well if that's more your thing - not sure about other browsers.

    AnonymousAndrew has also pointed out monitorEvents(window); here

    Difference between Activity and FragmentActivity

    A FragmentActivity is a subclass of Activity that was built for the Android Support Package.

    The FragmentActivity class adds a couple new methods to ensure compatibility with older versions of Android, but other than that, there really isn't much of a difference between the two. Just make sure you change all calls to getLoaderManager() and getFragmentManager() to getSupportLoaderManager() and getSupportFragmentManager() respectively.

    How to retrieve SQL result column value using column name in Python?

    python 2.7

    import pymysql
    
    conn = pymysql.connect(host='localhost', port=3306, user='root', passwd='password', db='sakila')
    
    cur = conn.cursor()
    
    n = cur.execute('select * from actor')
    c = cur.fetchall()
    
    for i in c:
        print i[1]
    

    How can I specify a local gem in my Gemfile?

    I believe you can do this:

    gem "foo", path: "/path/to/foo"
    

    How to trim white space from all elements in array?

    You can just iterate over the elements in the array and call array[i].trim() on each element

    Python: most idiomatic way to convert None to empty string?

    If you actually want your function to behave like the str() built-in, but return an empty string when the argument is None, do this:

    def xstr(s):
        if s is None:
            return ''
        return str(s)
    

    Difference between Apache CXF and Axis

    One more thing is the activity of the community. Compare the mailing list traffic for axis and cxf (2013).

    So if this is any indicator of usage then axis is by far less used than cxf.

    Compare CXF and Axis statistics at ohloh. CXF has very high activity while Axis has low activity overall.

    This is the chart for the number of commits over time for CXF (red) and Axis1 (green) Axis2 (blue). enter image description here

    How to fix Error: laravel.log could not be opened?

    It might be late but may help someone, changing directory permissions worked for me.

    Assuming that your Laravel project is in /var/www/html/ directory. Goto this directory.

    cd /var/www/html/
    

    Then change permissions of storage/ and bootstrap/cache/ directories.

    sudo chmod -R 777 storage/
    sudo chmod -R 777 bootstrap/cache/
    

    Illegal mix of collations MySQL Error

    Change the character set of the table to utf8

    ALTER TABLE your_table_name CONVERT TO CHARACTER SET utf8

    How to set shadows in React Native for android?

    The elevation style property on Android does not work unless backgroundColor has been specified for the element.

    Android - elevation style property does not work without backgroundColor

    Example:

    {
      shadowColor: 'black',
      shadowOpacity: 0.26,
      shadowOffset: { width: 0, height: 2},
      shadowRadius: 10,
      elevation: 3,
      backgroundColor: 'white'
    }
    

    Remove specific characters from a string in Javascript

    Regexp solution:

    ref = ref.replace(/^F0/, "");
    

    plain solution:

    if (ref.substr(0, 2) == "F0")
         ref = ref.substr(2);
    

    Generating a PDF file from React Components

    This may or may not be a sub-optimal way of doing things, but the simplest solution to the multi-page problem I found was to ensure all rendering is done before calling the jsPDFObj.save method.

    As for rendering hidden articles, this is solved with a similar fix to css image text replacement, I position absolutely the element to be rendered -9999px off the page left, this doesn't affect layout and allows for the elem to be visible to html2pdf, especially when using tabs, accordions and other UI components that depend on {display: none}.

    This method wraps the prerequisites in a promise and calls pdf.save() in the finally() method. I cannot be sure that this is foolproof, or an anti-pattern, but it would seem that it works in most cases I have thrown at it.

    _x000D_
    _x000D_
    // Get List of paged elements._x000D_
    let elems = document.querySelectorAll('.elemClass');_x000D_
    let pdf = new jsPDF("portrait", "mm", "a4");_x000D_
    _x000D_
    // Fix Graphics Output by scaling PDF and html2canvas output to 2_x000D_
    pdf.scaleFactor = 2;_x000D_
    _x000D_
    // Create a new promise with the loop body_x000D_
    let addPages = new Promise((resolve,reject)=>{_x000D_
      elems.forEach((elem, idx) => {_x000D_
        // Scaling fix set scale to 2_x000D_
        html2canvas(elem, {scale: "2"})_x000D_
          .then(canvas =>{_x000D_
            if(idx < elems.length - 1){_x000D_
              pdf.addImage(canvas.toDataURL("image/png"), 0, 0, 210, 297);_x000D_
              pdf.addPage();_x000D_
            } else {_x000D_
              pdf.addImage(canvas.toDataURL("image/png"), 0, 0, 210, 297);_x000D_
              console.log("Reached last page, completing");_x000D_
            }_x000D_
      })_x000D_
      _x000D_
      setTimeout(resolve, 100, "Timeout adding page #" + idx);_x000D_
    })_x000D_
    _x000D_
    addPages.finally(()=>{_x000D_
       console.log("Saving PDF");_x000D_
       pdf.save();_x000D_
    });
    _x000D_
    _x000D_
    _x000D_

    How to get Last record from Sqlite?

    Another option is to use SQLites LAST_VALUE() function in the following way.

    Given this table:

    +--------+---------+-------+
    | OBJECT |  STATUS |  TIME |
    +--------+---------+-------+
    |        |         |       |
    | 1      |  ON     |  100  |
    |        |         |       |
    | 1      |  OFF    |  102  |
    |        |         |       |
    | 1      |  ON     |  103  |
    |        |         |       |
    | 2      |  ON     |  101  |
    |        |         |       |
    | 2      |  OFF    |  102  |
    |        |         |       |
    | 2      |  ON     |  103  |
    |        |         |       |
    | 3      |  OFF    |  102  |
    |        |         |       |
    | 3      |  ON     |  103  |
    +--------+---------+-------+
    

    You can get the last status of every object with the following query

    SELECT                           
        DISTINCT OBJECT,             -- Only unique rows
        LAST_VALUE(STATUS) OVER (    -- The last value of the status column
            PARTITION BY OBJECT      -- Taking into account rows with the same value in the object column
            ORDER by time asc        -- "Last" when sorting the rows of every object by the time column in ascending order
            RANGE BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING    -- Take all rows in the patition
        ) as lastStatus
    FROM
        TABLE
    

    The result would look like:

    +--------+--------------+
    | OBJECT |  LAST_STATUS |
    +--------+--------------+
    |        |              |
    | 1      |  ON          |
    |        |              |
    | 2      |  ON          |
    |        |              |
    | 3      |  ON          |
    +--------+--------------+
    

    File inside jar is not visible for spring

    In the spring jar package, I use new ClassPathResource(filename).getFile(), which throws the exception:

    cannot be resolved to absolute file path because it does not reside in the file system: jar

    But using new ClassPathResource(filename).getInputStream() will solve this problem. The reason is that the configuration file in the jar does not exist in the operating system's file tree,so must use getInputStream().

    How to document a method with parameter(s)?

    python doc strings are free-form, you can document it in any way you like.

    Examples:

    def mymethod(self, foo, bars):
        """
        Does neat stuff!
        Parameters:
          foo - a foo of type FooType to bar with.
          bars - The list of bars
        """
    

    Now, there are some conventions, but python doesn't enforce any of them. Some projects have their own conventions. Some tools to work with docstrings also follow specific conventions.

    HTTP Ajax Request via HTTPS Page

    Make a bypass API in server.js. This works for me.

    app.post('/by-pass-api',function(req, response){
      const url = req.body.url;
      console.log("calling url", url);
      request.get(
        url,
        (error, res, body) => {
          if (error) {
            console.error(error)
            return response.status(200).json({'content': "error"}) 
    }
            return response.status(200).json(JSON.parse(body))
            },
          )
        })
    

    And call it using axios or fetch like this:

    const options = {
         method: 'POST',
         headers: {'content-type': 'application/json'},
         url:`http://localhost:3000/by-pass-api`, // your environment 
         data: { url },  // your https request here
        };
    

    How to add and remove classes in Javascript without jQuery

    To add class without JQuery just append yourClassName to your element className

    document.documentElement.className += " yourClassName";

    To remove class you can use replace() function

    document.documentElement.className.replace(/(?:^|\s)yourClassName(?!\S)/,'');

    Also as @DavidThomas mentioned you'd need to use the new RegExp() constructor if you want to pass class names dynamically to the replace function.

    How to clear basic authentication details in chrome

    This isn't exactly what the question is asking for but in case you accidentally saved basic auth credentials and want to clear them or update them:

    https://support.google.com/accounts/answer/6197437

    1. Open Chrome.
    2. At the top right, click More > and then Settings.
    3. At the bottom, click Advanced.
    4. Under "Passwords and forms," click Manage passwords.
    5. Under "Saved Passwords", click Remove on the site you want to clear saved basic auth credentials.

    Steps 1-4 can be quickly navigated with this link: chrome://settings/passwords

    This worked in Chrome Version 59.0.3071.115

    How to use Global Variables in C#?

    There's no such thing as a global variable in C#. Period.

    You can have static members if you want:

    public static class MyStaticValues
    {
       public static bool MyStaticBool {get;set;}
    }
    

    Git submodule head 'reference is not a tree' error

    Just to be sure, try updating your git binaries.

    GitHub for Windows has the version git version 1.8.4.msysgit.0 which in my case was the problem. Updating solved it.

    Using OpenGl with C#?

    What would you like these support libraries to do? Just using OpenGL from C# is simple enough and does not require any additional libraries afaik.

    Get the current first responder without using a private API

    Using Swift and with a specific UIView object this might help:

    func findFirstResponder(inView view: UIView) -> UIView? {
        for subView in view.subviews as! [UIView] {
            if subView.isFirstResponder() {
                return subView
            }
            
            if let recursiveSubView = self.findFirstResponder(inView: subView) {
                return recursiveSubView
            }
        }
        
        return nil
    }
    

    Just place it in your UIViewController and use it like this:

    let firstResponder = self.findFirstResponder(inView: self.view)
    

    Take note that the result is an Optional value so it will be nil in case no firstResponder was found in the given views subview hierarchy.

    Counting lines, words, and characters within a text file using Python

    Functions that might be helpful:

    • open("file").read() which reads the contents of the whole file at once
    • 'string'.splitlines() which separates lines from each other (and discards empty lines)

    By using len() and those functions you could accomplish what you're doing.

    round() for float in C++

    Since C++ 11 simply:

    #include <cmath>
    std::round(1.1)
    

    or to get int

    static_cast<int>(std::round(1.1))
    

    How to specify test directory for mocha?

    Now a days(year 2020) you can handle this using mocha configuration file:

    Step 1: Create .mocharc.js file at the root location of your application

    Step 2: Add below code in mocha config file:

    'use strict';
    
    module.exports = {
      spec: 'src/app/**/*.test.js'
    };
    

    For More option in config file refer this link: https://github.com/mochajs/mocha/blob/master/example/config/.mocharc.js

    Getting fb.me URL

    I'm not aware of any way to programmatically create these URLs, but the existing username space (www.facebook.com/something) works on fb.me also (e.g. http://fb.me/facebook )

    Git and nasty "error: cannot lock existing info/refs fatal"

    Run git fetch --all before git pull. That should solve the problem.

    Select multiple columns by labels in pandas

    How do I select multiple columns by labels in pandas?

    Multiple label-based range slicing is not easily supported with pandas, but position-based slicing is, so let's try that instead:

    loc = df.columns.get_loc
    df.iloc[:, np.r_[loc('A'):loc('C')+1, loc('E'), loc('G'):loc('I')+1]]
    
              A         B         C         E         G         H         I
    0 -1.666330  0.321260 -1.768185 -0.034774  0.023294  0.533451 -0.241990
    1  0.911498  3.408758  0.419618 -0.462590  0.739092  1.103940  0.116119
    2  1.243001 -0.867370  1.058194  0.314196  0.887469  0.471137 -1.361059
    3 -0.525165  0.676371  0.325831 -1.152202  0.606079  1.002880  2.032663
    4  0.706609 -0.424726  0.308808  1.994626  0.626522 -0.033057  1.725315
    5  0.879802 -1.961398  0.131694 -0.931951 -0.242822 -1.056038  0.550346
    6  0.199072  0.969283  0.347008 -2.611489  0.282920 -0.334618  0.243583
    7  1.234059  1.000687  0.863572  0.412544  0.569687 -0.684413 -0.357968
    8 -0.299185  0.566009 -0.859453 -0.564557 -0.562524  0.233489 -0.039145
    9  0.937637 -2.171174 -1.940916 -1.553634  0.619965 -0.664284 -0.151388
    

    Note that the +1 is added because when using iloc the rightmost index is exclusive.


    Comments on Other Solutions

    • filter is a nice and simple method for OP's headers, but this might not generalise well to arbitrary column names.

    • The "location-based" solution with loc is a little closer to the ideal, but you cannot avoid creating intermediate DataFrames (that are eventually thrown out and garbage collected) to compute the final result range -- something that we would ideally like to avoid.

    • Lastly, "pick your columns directly" is good advice as long as you have a manageably small number of columns to pick. It will, however not be applicable in some cases where ranges span dozens (or possibly hundreds) of columns.

    iOS 8 UITableView separator inset 0 not working

    simply put this two lines in cellForRowAtIndexPath method

    • if you want to all separator lines are start from zero [cell setSeparatorInset:UIEdgeInsetsZero]; [cell setLayoutMargins:UIEdgeInsetsZero];

    if you want to Specific separator line are start from zero suppose here is last line is start from zero

    if (indexPath.row == array.count-1) 
    {
       [cell setSeparatorInset:UIEdgeInsetsZero];
       [cell setLayoutMargins:UIEdgeInsetsZero];
    }
    else
       tblView.separatorInset=UIEdgeInsetsMake(0, 10, 0, 0);
    

    How to write ternary operator condition in jQuery?

    I'd do (added caching):

    var bbx = $("#blackbox");
     bbx.css('background-color') === 'rgb(255, 192, 203)' ? bbx.css('background','black') : bbx.css('background','pink')
    

    wroking fiddle (new AGAIN): http://jsfiddle.net/6nar4/37/

    I had to change the first operator as css() returns the rgb value of the color

    How do I pass a URL with multiple parameters into a URL?

    Rather than html encoding your URL parameter, you need to URL encode it:

    http://www.facebook.com/sharer.php?&t=FOOBAR&u=http%3A%2F%2Fwww.foobar.com%2F%3Ffirst%3D12%26sec%3D25%26position%3D
    

    You can do this easily in most languages - in javascript:

    var encodedParam = encodeURIComponent('www.foobar.com/?first=1&second=12&third=5');
    // encodedParam = 'http%3A%2F%2Fwww.foobar.com%2F%3Ffirst%3D12%26sec%3D25%26position%3D'
    

    (there are equivalent methods in other languages too)

    H2 in-memory database. Table not found

    <bean id="benchmarkDataSource"
        class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName" value="org.h2.Driver" />
        <property name="url" value="jdbc:h2:mem:testdb;DB_CLOSE_DELAY=-1" />
        <property name="username" value="sa" />
        <property name="password" value="" />
    </bean>
    

    RGB to hex and hex to RGB

    Looks like you're looking for something like this:

    function hexstr(number) {
        var chars = new Array("0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "a", "b", "c", "d", "e", "f");
        var low = number & 0xf;
        var high = (number >> 4) & 0xf;
        return "" + chars[high] + chars[low];
    }
    
    function rgb2hex(r, g, b) {
        return "#" + hexstr(r) + hexstr(g) + hexstr(b);
    }
    

    Best way to run scheduled tasks

    I've found this to be easy for all involved:

    • Create a webservice method such as DoSuchAndSuchProcess
    • Create a console app that calls this webmethod.
    • Schedule the console app in the task scheduler.

    Using this methodology all of the business logic is contained in your web app, but you have the reliability of the windows task manager, or any other commercial task manager to kick it off and record any return information such as an execution report. Using a web service instead of posting to a page has a bit of an advantage because it's easier to get return data from a webservice.

    What is the equivalent of Java static methods in Kotlin?

    All static member and function should be inside companion block

      companion object {
        @JvmStatic
        fun main(args: Array<String>) {
        }
    
        fun staticMethod() {
        }
      }
    

    Persistent invalid graphics state error when using ggplot2

    I ran into this same error and solved it by running:

    dev.off()
    

    and then running the plot again. I think the graphics device was messed up earlier somehow by exporting some graphics and it didn't get reset. This worked for me and it's simpler than reinstalling ggplot2.

    sqlplus statement from command line

    My version

    $ sqlplus -s username/password@host:port/service <<< "select 1 from dual;"
    
    
             1
    ----------
             1
    

    EDIT:

    For multiline you can use this

    $ echo -e "select 1 from dual; \n select 2 from dual;" | sqlplus -s username/password@host:port/service
    
    
             1
    ----------
             1
    
    
             2
    ----------
             2
    

    Regex: Use start of line/end of line signs (^ or $) in different context

    You can't use ^ and $ in character classes in the way you wish - they will be interpreted literally, but you can use an alternation to achieve the same effect:

    (^|,)garp(,|$)
    

    change array size

    In case you cannot use Array.Reset (the variable is not local) then Concat & ToArray helps:

    anObject.anArray.Concat(new string[] { newArrayItem }).ToArray();
    

    Using the RUN instruction in a Dockerfile with 'source' does not work

    RUN /bin/bash -c "source /usr/local/bin/virtualenvwrapper.sh"

    How to detect running app using ADB command

    Alternatively, you could go with pgrep or Process Grep. (Busybox is needed)

    You could do a adb shell pgrep com.example.app and it would display just the process Id.

    As a suggestion, since Android is Linux, you can use most basic Linux commands with adb shell to navigate/control around. :D

    CSS div 100% height

    CSS Flexbox was designed to simplify creating these types of layouts.

    _x000D_
    _x000D_
    html {
      height: 100%;
    }
    
    body {
      height: 100%;
      display: flex;
    }
    
    .Content {
      flex-grow: 1;
    }
    
    .Sidebar {
      width: 290px;
      flex-shrink: 0;
    }
    _x000D_
    <div class="Content" style="background:#bed">Content</div>
    <div class="Sidebar" style="background:#8cc">Sidebar</div>
    _x000D_
    _x000D_
    _x000D_

    C++ terminate called without an active exception

    How to reproduce that error:

    #include <iostream>
    #include <stdlib.h>
    #include <string>
    #include <thread>
    using namespace std;
    void task1(std::string msg){
      cout << "task1 says: " << msg;
    }
    int main() { 
      std::thread t1(task1, "hello"); 
      return 0;
    }
    

    Compile and run:

    el@defiant ~/foo4/39_threading $ g++ -o s s.cpp -pthread -std=c++11
    el@defiant ~/foo4/39_threading $ ./s
    terminate called without an active exception
    Aborted (core dumped)
    

    You get that error because you didn't join or detach your thread.

    One way to fix it, join the thread like this:

    #include <iostream>
    #include <stdlib.h>
    #include <string>
    #include <thread>
    using namespace std;
    void task1(std::string msg){
      cout << "task1 says: " << msg;
    }
    int main() { 
      std::thread t1(task1, "hello"); 
      t1.join();
      return 0;
    }
    

    Then compile and run:

    el@defiant ~/foo4/39_threading $ g++ -o s s.cpp -pthread -std=c++11
    el@defiant ~/foo4/39_threading $ ./s
    task1 says: hello
    

    The other way to fix it, detach it like this:

    #include <iostream>
    #include <stdlib.h>
    #include <string>
    #include <unistd.h>
    #include <thread>
    using namespace std;
    void task1(std::string msg){
      cout << "task1 says: " << msg;
    }
    int main() 
    { 
         {
    
            std::thread t1(task1, "hello"); 
            t1.detach();
    
         } //thread handle is destroyed here, as goes out of scope!
    
         usleep(1000000); //wait so that hello can be printed.
    }
    

    Compile and run:

    el@defiant ~/foo4/39_threading $ g++ -o s s.cpp -pthread -std=c++11
    el@defiant ~/foo4/39_threading $ ./s
    task1 says: hello
    

    Read up on detaching C++ threads and joining C++ threads.

    check if jquery has been loaded, then load it if false

    <script>
    if (typeof(jQuery) == 'undefined'){
            document.write('<scr' + 'ipt type="text/javascript" src=" https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></scr' + 'ipt>');
    }
    </script>
    

    How to center a button within a div?

    Responsive CSS option to center a button vertically and horizontally without being concerned with parent element size (using data attribute hooks for clarity and separation concerns):

    HTML

    <div data-element="card">
      <div data-container="button"><button>CTA...</button></div>
    </div>
    

    CSS

    [data-container="button"] {
      position: absolute;
      top: 50%;
      text-align: center;
      width: 100%;
    }
    

    Fiddle: https://jsfiddle.net/crrollyson/zebo1z8f/

    What does the SQL Server Error "String Data, Right Truncation" mean and how do I fix it?

    I got around the issue by using a convert on the "?", so my code looks like convert(char(50),?) and that got rid of the truncation error.

    AngularJS : The correct way of binding to a service properties

    I think this question has a contextual component.

    If you're simply pulling data from a service & radiating that information to it's view, I think binding directly to the service property is just fine. I don't want to write a lot of boilerplate code to simply map service properties to model properties to consume in my view.

    Further, performance in angular is based on two things. The first is how many bindings are on a page. The second is how expensive getter functions are. Misko talks about this here

    If you need to perform instance specific logic on the service data (as opposed to data massaging applied within the service itself), and the outcome of this impacts the data model exposed to the view, then I would say a $watcher is appropriate, as long as the function isn't terribly expensive. In the case of an expensive function, I would suggest caching the results in a local (to controller) variable, performing your complex operations outside of the $watcher function, and then binding your scope to the result of that.

    As a caveat, you shouldn't be hanging any properties directly off your $scope. The $scope variable is NOT your model. It has references to your model.

    In my mind, "best practice" for simply radiating information from service down to view:

    function TimerCtrl1($scope, Timer) {
      $scope.model = {timerData: Timer.data};
    };
    

    And then your view would contain {{model.timerData.lastupdated}}.

    How to automatically import data from uploaded CSV or XLS file into Google Sheets

    You can get Google Drive to automatically convert csv files to Google Sheets by appending

    ?convert=true
    

    to the end of the api url you are calling.

    EDIT: Here is the documentation on available parameters: https://developers.google.com/drive/v2/reference/files/insert

    Also, while searching for the above link, I found this question has already been answered here:

    Upload CSV to Google Drive Spreadsheet using Drive v2 API

    performing HTTP requests with cURL (using PROXY)

    From man curl:

    -x, --proxy <[protocol://][user:password@]proxyhost[:port]>
    
         Use the specified HTTP proxy. 
         If the port number is not specified, it is assumed at port 1080.
    

    General way:

    export http_proxy=http://your.proxy.server:port/
    

    Then you can connect through proxy from (many) application.

    And, as per comment below, for https:

    export https_proxy=https://your.proxy.server:port/
    

    Change working directory in my current shell context when running Node script

    The correct way to change directories is actually with process.chdir(directory). Here's an example from the documentation:

    console.log('Starting directory: ' + process.cwd());
    try {
      process.chdir('/tmp');
      console.log('New directory: ' + process.cwd());
    }
    catch (err) {
      console.log('chdir: ' + err);
    }
    

    This is also testable in the Node.js REPL:

    [monitor@s2 ~]$ node
    > process.cwd()
    '/home/monitor'
    > process.chdir('../');
    undefined
    > process.cwd();
    '/home'
    

    How to use ImageBackground to set background image for screen in react-native

    To add background Image, React Native is based on component, the ImageBackground Component requires two props style={{}} and source={require('')}

     <ImageBackground source={require('./wallpaper.jpg')} style={{width: '100%', height: '100%'}}> 
    <....yourContent Goes here...>
        </ImageBackground>
    

    Stuck at ".android/repositories.cfg could not be loaded."

    This happened on Windows 10 as well. I resolved it by creating an empty repositories.cfg file.

    Failed to build gem native extension (installing Compass)

    On Mac OS X 10.9, if you try xcode-select --install, you will get the following error :

    Can't install the software because it is not currently available from the Software Update server.

    The solution is to download Command Line Tools (OS X 10.9) directly from Apple website : https://developer.apple.com/downloads/index.action?name=for%20Xcode%20-

    You will then be able to install the last version of Command Line Tools.

    jquery json to string?

    The best way I have found is to use jQuery JSON

    Path to MSBuild

    To retrieve path of msbuild 15 (Visual Studio 2017) with batch from registry w/o additional tools:

    set regKey=HKLM\SOFTWARE\WOW6432Node\Microsoft\VisualStudio\SxS\VS7
    set regValue=15.0
    for /f "skip=2 tokens=3,*" %%A in ('reg.exe query %regKey% /v %regValue% 2^>nul') do (
        set vs17path=%%A %%B
    )
    set msbuild15path = %vs17path%\MSBuild\15.0\Bin\MSBuild.exe
    

    Better available tools:

    What do >> and << mean in Python?

    I think it is important question and it is not answered yet (the OP seems to already know about shift operators). Let me try to answer, the >> operator in your example is used for two different purposes. In c++ terms this operator is overloaded. In the first example it is used as bitwise operator (left shift), while in the second scenario it is merely used as output redirection. i.e.

    2 << 5 # shift to left by 5 bits
    2 >> 5 # shift to right by 5 bits
    print >> obj, "Hello world" # redirect the output to obj, 
    

    example

    with open('foo.txt', 'w') as obj:
        print >> obj, "Hello world" # hello world now saved in foo.txt
    

    update:

    In python 3 it is possible to give the file argument directly as follows:

    print("Hello world", file=open("foo.txt", "a")) # hello world now saved in foo.txt
    

    maven... Failed to clean project: Failed to delete ..\org.ow2.util.asm-asm-tree-3.1.jar

    Close the target folder and its file you have opened before mvn clean

    Install python 2.6 in CentOS

    Chris Lea provides a YUM repository for python26 RPMs that can co-exist with the 'native' 2.4 that is needed for quite a few admin tools on CentOS.

    Quick instructions that worked at least for me:

    $ sudo rpm -Uvh http://yum.chrislea.com/centos/5/i386/chl-release-5-3.noarch.rpm
    $ sudo rpm --import /etc/pki/rpm-gpg/RPM-GPG-KEY-CHL
    $ sudo yum install python26
    $ python26
    

    How to search a string in String array

    bool exists = arr.Contains("One");
    

    How to run python script on terminal (ubuntu)?

    Sorry, Im a newbie myself and I had this issue:

    ./hello.py: line 1: syntax error near unexpected token "Hello World"' ./hello.py: line 1:print("Hello World")'

    I added the file header for the python 'deal' as #!/usr/bin/python

    Then simple executed the program with './hello.py'

    Draw radius around a point in Google map

    I have just written a blog article that addresses exactly this, which you may find useful: http://seewah.blogspot.com/2009/10/circle-overlay-on-google-map.html

    Basically, you need to create a GGroundOverlay with the correct GLatLngBounds. The tricky bit is in working out the southwest corner coordinate and the northeast corner coordinate of this imaginery square (the GLatLngBounds) bounding this circle, based on the desired radius. The math is quite complicated, but you can just refer to getDestLatLng function in the blog. The rest should be pretty straightforward.

    Exact difference between CharSequence and String in java

    General differences

    There are several classes which implement the CharSequence interface besides String. Among these are

    • StringBuilder for variable-length character sequences which can be modified
    • CharBuffer for fixed-length low-level character sequences which can be modified

    Any method which accepts a CharSequence can operate on all of these equally well. Any method which only accepts a String will require conversion. So using CharSequence as an argument type in all the places where you don't care about the internals is prudent. However you should use String as a return type if you actually return a String, because that avoids possible conversions of returned values if the calling method actually does require a String.

    Also note that maps should use String as key type, not CharSequence, as map keys must not change. In other words, sometimes the immutable nature of String is essential.

    Specific code snippet

    As for the code you pasted: simply compile that, and have a look at the JVM bytecode using javap -v. There you will notice that both obj and str are references to the same constant object. As a String is immutable, this kind of sharing is all right.

    The + operator of String is compiled as invocations of various StringBuilder.append calls. So it is equivalent to

    System.out.println(
      (new StringBuilder())
      .append("output is : ")
      .append((Object)obj)
      .append(" ")
      .append(str)
      .toString()
    )
    

    I must confess I'm a bit surprised that my compiler javac 1.6.0_33 compiles the + obj using StringBuilder.append(Object) instead of StringBuilder.append(CharSequence). The former probably involves a call to the toString() method of the object, whereas the latter should be possible in a more efficient way. On the other hand, String.toString() simply returns the String itself, so there is little penalty there. So StringBuilder.append(String) might be more efficient by about one method invocation.

    How to prevent a click on a '#' link from jumping to top of page?

    you can even write it just like this:

    <a href="javascript:void(0);"></a>
    

    im not sure its a better way but it is a way :)

    How to Convert Int to Unsigned Byte and Back

    Java 8 provides Byte.toUnsignedInt to convert byte to int by unsigned conversion. In Oracle's JDK this is simply implemented as return ((int) x) & 0xff; because HotSpot already understands how to optimize this pattern, but it could be intrinsified on other VMs. More importantly, no prior knowledge is needed to understand what a call to toUnsignedInt(foo) does.

    In total, Java 8 provides methods to convert byte and short to unsigned int and long, and int to unsigned long. A method to convert byte to unsigned short was deliberately omitted because the JVM only provides arithmetic on int and long anyway.

    To convert an int back to a byte, just use a cast: (byte)someInt. The resulting narrowing primitive conversion will discard all but the last 8 bits.

    expected assignment or function call: no-unused-expressions ReactJS

    In my case it is happened due to curly braces of function if you use jsx then you need to change curly braces to Parentheses, see below code

    const [countries] = useState(["USA", "UK", "BD"])

    I tried this but not work, don't know why

     {countries.map((country) => {
            <MenuItem value={country}>{country}</MenuItem>
      })}
    

    But when I change Curly Braces to parentheses and Its working fine for me

      {countries.map((country) => ( //Changes is here instead of {
            <MenuItem value={country}>{country}</MenuItem>
      ))} //and here instead of }
                 
    

    Hopefully it will help you too...

    How do I execute a stored procedure in a SQL Agent job?

    As Marc says, you run it exactly like you would from the command line. See Creating SQL Server Agent Jobs on MSDN.

    Close a div by clicking outside

    You need

    $('body').click(function(e) {
        if (!$(e.target).closest('.popup').length){
            $(".popup").hide();
        }
    });
    

    Calling a javascript function in another js file

    This is actually coming very late, but I thought I should share,

    in index.html

    <script type="text/javascript" src="1.js"></script>
    <script type="text/javascript" src="2.js"></script>
    

    in 1.js

    fn1 = function() {
        alert("external fn clicked");
    }
    

    in 2.js

    fn1()
    

    How to compare files from two different branches?

    Agreeing with the answer suggested by @dahlbyk. If you want the diff to be written to a diff file for code reviews use the following command.

    git diff branch master -- filepath/filename.extension > filename.diff --cached
    

    I don't have "Dynamic Web Project" option in Eclipse new Project wizard

    Go to Eclipse --> Help

    and click--->Install new software

    then you can see a window ...There a click add

    Then put below url in url box: http://download.eclipse.org/webtools/repository/juno/

    i am having juno

    if u have any other means put that name . then click ok.

    No Hibernate Session bound to thread, and configuration does not allow creation of non-transactional one here

    Have you got org.springframework.orm.hibernate3.support.OpenSessionInViewFilter configured in webapp's web.xml (assuming your application is a webapp), or wrapping calls accordingly?

    ValidateRequest="false" doesn't work in Asp.Net 4

    Found solution on the error page itself. Just needed to add requestValidationMode="2.0" in web.config

    <system.web>
        <compilation debug="true" targetFramework="4.0" />
        <httpRuntime requestValidationMode="2.0" />
    </system.web>
    

    MSDN information: HttpRuntimeSection.RequestValidationMode Property

    php Replacing multiple spaces with a single space

    $output = preg_replace('/\s+/', ' ',$input);
    

    \s is shorthand for [ \t\n\r]. Multiple spaces will be replaced with single space.

    file_put_contents: Failed to open stream, no such file or directory

    I was also stuck on the same kind of problem and I followed the simple steps below.

    Just get the exact url of the file to which you want to copy, for example:

    http://www.test.com/test.txt (file to copy)
    

    Then pass the exact absolute folder path with filename where you do want to write that file.

    1. If you are on a Windows machine then d:/xampp/htdocs/upload/test.txt

    2. If you are on a Linux machine then /var/www/html/upload/test.txt

    You can get the document root with the PHP function $_SERVER['DOCUMENT_ROOT'].

    Sorting std::map using value

    Another solution would be the usage of std::make_move_iterator to build a new vector (C++11 )

        int main(){
    
          std::map<std::string, int> map;
           //Populate map
    
          std::vector<std::pair<std::string, int>> v {std::make_move_iterator(begin(map)),
                                          std::make_move_iterator(end(map))};
           // Create a vector with the map parameters
    
           sort(begin(v), end(v),
                 [](auto p1, auto p2){return p1.second > p2.second;});
           // Using sort + lambda function to return an ordered vector 
           // in respect to the int value that is now the 2nd parameter 
           // of our newly created vector v
      }
    

    How to return HTTP 500 from ASP.NET Core RC2 Web Api?

    For aspnetcore-3.1, you can also use Problem() like below;

    https://docs.microsoft.com/en-us/aspnet/core/web-api/handle-errors?view=aspnetcore-3.1

     [Route("/error-local-development")]
    public IActionResult ErrorLocalDevelopment(
        [FromServices] IWebHostEnvironment webHostEnvironment)
    {
        if (webHostEnvironment.EnvironmentName != "Development")
        {
            throw new InvalidOperationException(
                "This shouldn't be invoked in non-development environments.");
        }
    
        var context = HttpContext.Features.Get<IExceptionHandlerFeature>();
    
        return Problem(
            detail: context.Error.StackTrace,
            title: context.Error.Message);
    }
    

    How to check the function's return value if true or false

    you're comparing the result against a string ('false') not the built-in negative constant (false)

    just use

    if(ValidateForm() == false) {
    

    or better yet

    if(!ValidateForm()) {
    

    also why are you calling validateForm twice?

    Error:Execution failed for task ':app:processDebugResources'. > java.io.IOException: Could not delete folder "" in android studio

    I have same issue. When I clean my project and rebuild it then everything works fine.

    Build -> Clean Project

    useState set method not reflecting change immediately

    Much like setState in Class components created by extending React.Component or React.PureComponent, the state update using the updater provided by useState hook is also asynchronous, and will not be reflected immediately.

    Also, the main issue here is not just the asynchronous nature but the fact that state values are used by functions based on their current closures, and state updates will reflect in the next re-render by which the existing closures are not affected, but new ones are created. Now in the current state, the values within hooks are obtained by existing closures, and when a re-render happens, the closures are updated based on whether the function is recreated again or not.

    Even if you add a setTimeout the function, though the timeout will run after some time by which the re-render would have happened, the setTimeout will still use the value from its previous closure and not the updated one.

    setMovies(result);
    console.log(movies) // movies here will not be updated
    

    If you want to perform an action on state update, you need to use the useEffect hook, much like using componentDidUpdate in class components since the setter returned by useState doesn't have a callback pattern

    useEffect(() => {
        // action on update of movies
    }, [movies]);
    

    As far as the syntax to update state is concerned, setMovies(result) will replace the previous movies value in the state with those available from the async request.

    However, if you want to merge the response with the previously existing values, you must use the callback syntax of state updation along with the correct use of spread syntax like

    setMovies(prevMovies => ([...prevMovies, ...result]));
    

    How to configure welcome file list in web.xml

    I guess what you want is your index servlet to act as the welcome page, so change to:

    <welcome-file-list>
       <welcome-file>index</welcome-file>
    </welcome-file-list>
    

    So that the index servlet will be used. Note, you'll need a servlet spec 2.4 container to be able to do this.

    Note also, @BalusC gets my vote, for your index servlet on its own is superfluous.

    Gradle store on local file system

    Gradle's local repository folder is:

    • $USER_HOME/.gradle/caches/modules-2/files-2.1

    Defined dependencies will be loaded from remote repositories into gradle's local repository folder. For each loaded file, gradle will be create a new folder named with md5 value of the original file (pom,jar,..). Full path for the dependency file is made up from :

    • groupid + artifactid + version + FILE_MD5_VALUE + FILE_NAME

    If our defined dependency is:

    • compile 'org.springframework:spring-jdbc:4.3.4.RELEASE'

    Then the library will be loaded into :

    • /$USER_HOME/.gradle/caches/modules-2/files-2.1/org.springframework/spring-jdbc/4.3.4.RELEASE/42175d194cf6aa7c716c0887f30255e5c0a5262c/spring-jdbc-4.3.4.RELEASE.jar

    Upload artifacts to Nexus, without Maven

    The calls that you need to make against Nexus are REST api calls.

    The maven-nexus-plugin is a Maven plugin that you can use to make these calls. You could create a dummy pom with the necessary properties and make those calls through the Maven plugin.

    Something like:

    mvn -DserverAuthId=sonatype-nexus-staging -Dauto=true nexus:staging-close
    

    Assumed things:

    1. You have defined a server in your ~/.m2/settings.xml named sonatype-nexus-staging with your sonatype user and password set up - you will probably already have done this if you are deploying snapshots. But you can find more info here.
    2. Your local settings.xml includes the nexus plugins as specified here.
    3. The pom.xml sitting in your current directory has the correct Maven coordinates in its definition. If not, you can specify the groupId, artifactId, and version on the command line.
    4. The -Dauto=true will turn off the interactive prompts so you can script this.

    Ultimately, all this is doing is creating REST calls into Nexus. There is a full Nexus REST api but I have had little luck finding documentation for it that's not behind a paywall. You can turn on the debug mode for the plugin above and figure it out however by using -Dnexus.verboseDebug=true -X.

    You could also theoretically go into the UI, turn on the Firebug Net panel, and watch for /service POSTs and deduce a path there as well.

    How do I get the serial key for Visual Studio Express?

    I have an improvement on the answer @DewiMorgan gave for VS 2008 express. I have since confirmed it also works on VS 2005 express.
    It lets you run the software without it EVER requiring registration, and also makes it so you don't have to manually delete the key every 30 days. It does this by preventing the key from ever being written.

    (Deleting the correct key can also let you avoid registering VS 2015 "Community Edition," but using permissions to prevent the key being written will make the IDE crash, so I haven't found a great solution for it yet.)

    The directions assume Visual C# Express 2008, but this works on all the other visual studio express apps I can find.

    1. Open regedit, head to HKEY_CURRENT_USER\Software\Microsoft\VCSExpress\9.0\Registration.
    2. Delete the value Params. picture of me deleting the value 'Params' in the registry.
    3. Right click on the key 'Registration' in the tree, and click permissions.
    4. Click Advanced...
    5. Go to the permissions tab, and uncheck the box labeled Inherit from parent the permission entries that apply to child objects. Include these with entries explicitly defined here. me unchecking the box
    6. In the dialog that opens, click copy.
      the security dialog that pops up
      Note that in Windows 7 (and 8/8.1, I think), it appears the copy button was renamed to add, as in add inherited permissions as explicit permissions.

      In Windows 10, it appears things changed again. @ravuya says that you might have to manually re-create some of the permissions, as the registry editor no longer offers this exact functionality directly. I don't use Windows very much anymore, so I'll defer to them:

      On Win10, there is a button called "Disable Inheritance" that does the same thing as the checkbox mentioned in step 5. It is necessary to create new permissions just for Registration, instead of inheriting those permissions from an upstream registry key.

    7. Hit OK in the 'Advanced' window.
    8. Back in the first permissions window, click your user, and uncheck Full Control. Me unchecking 'full control'

    9. Do the same thing for the Administrators group. Me unchecking 'full control' for the Administrators group

    10. Hit OK or Apply. Congratulations, you will never again be plagued by the registration nag, and just like WinRAR, your trial will never expire.

    You may have to do the same thing for other (non-Visual C#) programs, like Visual Basic express or Visual C++ express.

    It has been reported by @IronManMark20 in the comments that simply deleting the registry key works and that Visual Studio does not attempt to re-create the key. I am not sure if I believe this because when I installed VS on a clean windows installation, the key was not created until I ran VS at least once. But for what it's worth, that may be an option as well.

    TortoiseSVN icons not showing up under Windows 7

    I had same problem here with TortoiseSVN 1.6.16. Icons were fine, but then I installed and uninstalled TortoiseGit and suddenly the TortoiseSVN icons stopped working. Looking at the registry I discovered that uninstalling TortoiseGit also removed all overlay icons. I simply reinstalled TortoiseSVN and it fixed the issue.

    How to "log in" to a website using Python's Requests module?

    Find out the name of the inputs used on the websites form for usernames <...name=username.../> and passwords <...name=password../> and replace them in the script below. Also replace the URL to point at the desired site to log into.

    login.py

    #!/usr/bin/env python
    
    import requests
    from requests.packages.urllib3.exceptions import InsecureRequestWarning
    requests.packages.urllib3.disable_warnings(InsecureRequestWarning)
    payload = { 'username': '[email protected]', 'password': 'blahblahsecretpassw0rd' }
    url = 'https://website.com/login.html'
    requests.post(url, data=payload, verify=False)
    

    The use of disable_warnings(InsecureRequestWarning) will silence any output from the script when trying to log into sites with unverified SSL certificates.

    Extra:

    To run this script from the command line on a UNIX based system place it in a directory, i.e. home/scripts and add this directory to your path in ~/.bash_profile or a similar file used by the terminal.

    # Custom scripts
    export CUSTOM_SCRIPTS=home/scripts
    export PATH=$CUSTOM_SCRIPTS:$PATH
    

    Then create a link to this python script inside home/scripts/login.py

    ln -s ~/home/scripts/login.py ~/home/scripts/login
    

    Close your terminal, start a new one, run login

    How to use default Android drawables

    To use the default android drawable resource, no need copy anything.. you can just import it first with..

    import android.R;
    

    but i will make your own resources will have an error if you want to use it. The error will be something like:

    R. cannot be resolved

    So, I prefer not to import android.R but import *my.own.package*.R;

    then when I can normally use my own resource with R.drawable.*something* without error, and put android.R.*something_default* to use the default android resources.

    How to deny access to a file in .htaccess

    Strong pattern matching — This is the method that I use here at Perishable Press. Using strong pattern matching, this technique prevents external access to any file containing “.hta”, “.HTA”, or any case-insensitive combination thereof. To illustrate, this code will prevent access through any of the following requests:

    • .htaccess
    • .HTACCESS
    • .hTaCcEsS
    • testFILE.htaccess
    • filename.HTACCESS
    • FILEROOT.hTaCcEsS

    ..etc., etc. Clearly, this method is highly effective at securing your site’s HTAccess files. Further, this technique also includes the fortifying “Satisfy All” directive. Note that this code should be placed in your domain’s root HTAccess file:

    # STRONG HTACCESS PROTECTION
    <Files ~ "^.*\.([Hh][Tt][Aa])">
    order allow,deny
    deny from all
    satisfy all
    </Files>
    

    Library not loaded: libmysqlclient.16.dylib error when trying to run 'rails server' on OS X 10.6 with mysql2 gem

    bundle install mysql --force helped me. It reinstalled dependencies which ware gone as a result of brew uninstall mysql.

    How to prepare a Unity project for git?

    Since Unity 4.3 you also have to enable External option from preferences, so full setup process looks like:

    1. Enable External option in Unity ? Preferences ? Packages ? Repository
    2. Switch to Hidden Meta Files in Editor ? Project Settings ? Editor ? Version Control Mode
    3. Switch to Force Text in Editor ? Project Settings ? Editor ? Asset Serialization Mode
    4. Save scene and project from File menu

    Note that the only folders you need to keep under source control are Assets and ProjectSettigns.

    More information about keeping Unity Project under source control you can find in this post.

    How to remove unused dependencies from composer?

    The right way to do this is:

    composer remove jenssegers/mongodb --update-with-dependencies
    

    I must admit the flag here is not quite obvious as to what it will do.

    Update

    composer remove jenssegers/mongodb
    

    As of v1.0.0-beta2 --update-with-dependencies is the default and is no longer required.

    Local variable referenced before assignment?

    In order for you to modify test1 while inside a function you will need to do define test1 as a global variable, for example:

    test1 = 0
    def testFunc():
        global test1 
        test1 += 1
    testFunc()
    

    However, if you only need to read the global variable you can print it without using the keyword global, like so:

    test1 = 0
    def testFunc():
         print test1 
    testFunc()
    

    But whenever you need to modify a global variable you must use the keyword global.

    "Fade" borders in CSS

    How to fade borders with CSS:

    <div style="border-style:solid;border-image:linear-gradient(red, transparent) 1;border-bottom:0;">Text</div>

    Please excuse the inline styles for the sake of demonstration. The 1 property for the border-image is border-image-slice, and in this case defines the border as a single continuous region.

    Source: Gradient Borders

    Centering Bootstrap input fields

    Try applying this style to your div class="input-group":

    text-align:center;
    

    View it: Fiddle.

    delete all from table

    This is deletes the table table_name.

    Replace it with the name of the table, which shall be deleted.

    DELETE FROM table_name;
    

    vertical align middle in <div>

    Old question but nowadays CSS3 makes vertical alignment really simple!

    Just add to #abc the following css:

    display:flex;
    align-items:center;
    

    Simple Demo

    Original question demo updated

    Simple Example:

    _x000D_
    _x000D_
    .vertical-align-content {_x000D_
      background-color:#f18c16;_x000D_
      height:150px;_x000D_
      display:flex;_x000D_
      align-items:center;_x000D_
      /* Uncomment next line to get horizontal align also */_x000D_
      /* justify-content:center; */_x000D_
    }
    _x000D_
    <div class="vertical-align-content">_x000D_
      Hodor!_x000D_
    </div>
    _x000D_
    _x000D_
    _x000D_

    Repeat a task with a time delay?

    There are 3 ways to do it:

    Use ScheduledThreadPoolExecutor

    A bit of overkill since you don't need a pool of Thread

       //----------------------SCHEDULER-------------------------
        private final ScheduledThreadPoolExecutor executor_ =
                new ScheduledThreadPoolExecutor(1);
         ScheduledFuture<?> schedulerFuture;
       public void  startScheduler() {
           schedulerFuture=  executor_.scheduleWithFixedDelay(new Runnable() {
                @Override
                public void run() {
                    //DO YOUR THINGS
                    pageIndexSwitcher.setVisibility(View.GONE);
                }
            }, 0L, 5*MILLI_SEC,  TimeUnit.MILLISECONDS);
        }
    
    
        public void  stopScheduler() {
            pageIndexSwitcher.setVisibility(View.VISIBLE);
            schedulerFuture.cancel(false);
            startScheduler();
        }
    

    Use Timer Task

    Old Android Style

        //----------------------TIMER  TASK-------------------------
    
        private Timer carousalTimer;
        private void startTimer() {
            carousalTimer = new Timer(); // At this line a new Thread will be created
            carousalTimer.scheduleAtFixedRate(new TimerTask() {
                @Override
                public void run() {
                    //DO YOUR THINGS
                    pageIndexSwitcher.setVisibility(INVISIBLE);
                }
            }, 0, 5 * MILLI_SEC); // delay
        }
    
        void stopTimer() {
            carousalTimer.cancel();
        }
    

    Use Handler and Runnable

    Modern Android Style

        //----------------------HANDLER-------------------------
    
        private Handler taskHandler = new android.os.Handler();
    
        private Runnable repeatativeTaskRunnable = new Runnable() {
            public void run() {
                //DO YOUR THINGS
            }
        };
    
       void startHandler() {
            taskHandler.postDelayed(repeatativeTaskRunnable, 5 * MILLI_SEC);
        }
    
        void stopHandler() {
            taskHandler.removeCallbacks(repeatativeTaskRunnable);
        }
    

    Non-Leaky Handler with Activity / Context

    Declare an inner Handler class which does not leak Memory in your Activity/Fragment class

    /**
         * Instances of static inner classes do not hold an implicit
         * reference to their outer class.
         */
        private static class NonLeakyHandler extends Handler {
            private final WeakReference<FlashActivity> mActivity;
    
            public NonLeakyHandler(FlashActivity activity) {
                mActivity = new WeakReference<FlashActivity>(activity);
            }
    
            @Override
            public void handleMessage(Message msg) {
                FlashActivity activity = mActivity.get();
                if (activity != null) {
                    // ...
                }
            }
        }
    

    Declare a runnable which will perform your repetitive task in your Activity/Fragment class

       private Runnable repeatativeTaskRunnable = new Runnable() {
            public void run() {
                new Handler(getMainLooper()).post(new Runnable() {
                    @Override
                    public void run() {
    
             //DO YOUR THINGS
            }
        };
    

    Initialize Handler object in your Activity/Fragment (here FlashActivity is my activity class)

    //Task Handler
    private Handler taskHandler = new NonLeakyHandler(FlashActivity.this);
    

    To repeat a task after fix time interval

    taskHandler.postDelayed(repeatativeTaskRunnable , DELAY_MILLIS);

    To stop the repetition of task

    taskHandler .removeCallbacks(repeatativeTaskRunnable );

    UPDATE: In Kotlin:

        //update interval for widget
        override val UPDATE_INTERVAL = 1000L
    
        //Handler to repeat update
        private val updateWidgetHandler = Handler()
    
        //runnable to update widget
        private var updateWidgetRunnable: Runnable = Runnable {
            run {
                //Update UI
                updateWidget()
                // Re-run it after the update interval
                updateWidgetHandler.postDelayed(updateWidgetRunnable, UPDATE_INTERVAL)
            }
    
        }
    
     // SATART updating in foreground
     override fun onResume() {
            super.onResume()
            updateWidgetHandler.postDelayed(updateWidgetRunnable, UPDATE_INTERVAL)
        }
    
    
        // REMOVE callback if app in background
        override fun onPause() {
            super.onPause()
            updateWidgetHandler.removeCallbacks(updateWidgetRunnable);
        }
    

    c# open a new form then close the current form?

    private void buttonNextForm(object sender, EventArgs e)
    {
        NextForm nf = new NextForm();//Object of the form that you want to open
        this.hide();//Hide cirrent form.
        nf.ShowModel();//Display the next form window
        this.Close();//While closing the NextForm, control will come again and will close this form as well
    }
    

    Unable to obtain LocalDateTime from TemporalAccessor when parsing LocalDateTime (Java 8)

    For what is worth if anyone should read again this topic(like me) the correct answer would be in DateTimeFormatter definition, e.g.:

    private static DateTimeFormatter DATE_FORMAT =  
                new DateTimeFormatterBuilder().appendPattern("dd/MM/yyyy[ [HH][:mm][:ss][.SSS]]")
                .parseDefaulting(ChronoField.HOUR_OF_DAY, 0)
                .parseDefaulting(ChronoField.MINUTE_OF_HOUR, 0)
                .parseDefaulting(ChronoField.SECOND_OF_MINUTE, 0)
                .toFormatter(); 
    

    One should set the optional fields if they will appear. And the rest of code should be exactly the same.

    What's the difference between session.persist() and session.save() in Hibernate?

    From this forum post

    persist() is well defined. It makes a transient instance persistent. However, it doesn't guarantee that the identifier value will be assigned to the persistent instance immediately, the assignment might happen at flush time. The spec doesn't say that, which is the problem I have with persist().

    persist() also guarantees that it will not execute an INSERT statement if it is called outside of transaction boundaries. This is useful in long-running conversations with an extended Session/persistence context.

    A method like persist() is required.

    save() does not guarantee the same, it returns an identifier, and if an INSERT has to be executed to get the identifier (e.g. "identity" generator, not "sequence"), this INSERT happens immediately, no matter if you are inside or outside of a transaction. This is not good in a long-running conversation with an extended Session/persistence context.

    Sending JSON to PHP using ajax

    just remove:

    ...
    //dataType: "json",
    url: "index.php",
    data: {myData:postData},
    //contentType: "application/json; charset=utf-8",
    ...
    

    Identifying Exception Type in a handler Catch Block

    you can add some extra information to your exception in your class and then when you catch the exception you can control your custom information to identify your exception

    this.Data["mykey"]="keyvalue"; //you can add any type of data if you want 
    

    and then you can get your value

    string mystr = (string) err.Data["mykey"];
    

    like that for more information: http://msdn.microsoft.com/en-us/library/system.exception.data.aspx

    How do I add a simple jQuery script to WordPress?

    Answer from here: https://premium.wpmudev.org/blog/adding-jquery-scripts-wordpress/

    Despite the fact WordPress has been around for a while, and the method of adding scripts to themes and plugins has been the same for years, there is still some confusion around how exactly you’re supposed to add scripts. So let’s clear it up.

    Since jQuery is still the most commonly used Javascript framework, let’s take a look at how you can add a simple script to your theme or plugin.

    jQuery’s Compatibility Mode

    Before we start attaching scripts to WordPress, let’s look at jQuery’s compatibility mode. WordPress comes pre-packaged with a copy of jQuery, which you should use with your code. When WordPress’ jQuery is loaded, it uses compatibility mode, which is a mechanism for avoiding conflicts with other language libraries.

    What this boils down to is that you can’t use the dollar sign directly as you would in other projects. When writing jQuery for WordPress you need to use jQuery instead. Take a look at the code below to see what I mean:

    Are multiple `.gitignore`s frowned on?

    I can think of at least two situations where you would want to have multiple .gitignore files in different (sub)directories.

    • Different directories have different types of file to ignore. For example the .gitignore in the top directory of your project ignores generated programs, while Documentation/.gitignore ignores generated documentation.

    • Ignore given files only in given (sub)directory (you can use /sub/foo in .gitignore, though).

    Please remember that patterns in .gitignore file apply recursively to the (sub)directory the file is in and all its subdirectories, unless pattern contains '/' (so e.g. pattern name applies to any file named name in given directory and all its subdirectories, while /name applies to file with this name only in given directory).

    How to get the connection String from a database

    put below tag in web.config file in configuration node

     <connectionStrings>
    <add name="NameOFConnectionString" connectionString="Data Source=Server;Initial Catalog=DatabaseName;User ID=User;Password=Pwd"
      providerName="System.Data.SqlClient" />
    

    then you can use above connectionstring, e.g.

    SqlConnection con = new SqlConnection();
                con.ConnectionString = ConfigurationManager.ConnectionStrings["NameOFConnectionString"].ToString();
    

    Modifying a file inside a jar

    Check out TrueZip.

    It does exactly what you want (to edit files inline inside a jar file), through a virtual file system API. It also supports nested archives (jar inside a jar) as well.

    Remote branch is not showing up in "git branch -r"

    I had the same issue. It seems the easiest solution is to just remove the remote, readd it, and fetch.

    Manually map column names with class properties

    The simple solution to the problem Kaleb is trying to solve is just to accept the property name if the column attribute doesn't exist:

    Dapper.SqlMapper.SetTypeMap(
        typeof(T),
        new Dapper.CustomPropertyTypeMap(
            typeof(T),
            (type, columnName) =>
                type.GetProperties().FirstOrDefault(prop =>
                    prop.GetCustomAttributes(false)
                        .OfType<ColumnAttribute>()
                        .Any(attr => attr.Name == columnName) || prop.Name == columnName)));
    
    

    Better way to sort array in descending order

    Depending on the sort order, you can do this :

        int[] array = new int[] { 3, 1, 4, 5, 2 };
        Array.Sort<int>(array,
                        new Comparison<int>(
                                (i1, i2) => i2.CompareTo(i1)
                        ));
    

    ... or this :

        int[] array = new int[] { 3, 1, 4, 5, 2 };
        Array.Sort<int>(array,
                        new Comparison<int>(
                                (i1, i2) => i1.CompareTo(i2)
                        ));
    

    i1 and i2 are just reversed.

    Measuring execution time of a function in C++

    • It is a very easy to use method in C++11.
    • We can use std::chrono::high_resolution_clock from header
    • We can write a method to print the method execution time in a much readable form.

    For example, to find the all the prime numbers between 1 and 100 million, it takes approximately 1 minute and 40 seconds. So the execution time get printed as:

    Execution Time: 1 Minutes, 40 Seconds, 715 MicroSeconds, 715000 NanoSeconds
    

    The code is here:

    #include <iostream>
    #include <chrono>
    
    using namespace std;
    using namespace std::chrono;
    
    typedef high_resolution_clock Clock;
    typedef Clock::time_point ClockTime;
    
    void findPrime(long n, string file);
    void printExecutionTime(ClockTime start_time, ClockTime end_time);
    
    int main()
    {
        long n = long(1E+8);  // N = 100 million
    
        ClockTime start_time = Clock::now();
    
        // Write all the prime numbers from 1 to N to the file "prime.txt"
        findPrime(n, "C:\\prime.txt"); 
    
        ClockTime end_time = Clock::now();
    
        printExecutionTime(start_time, end_time);
    }
    
    void printExecutionTime(ClockTime start_time, ClockTime end_time)
    {
        auto execution_time_ns = duration_cast<nanoseconds>(end_time - start_time).count();
        auto execution_time_ms = duration_cast<microseconds>(end_time - start_time).count();
        auto execution_time_sec = duration_cast<seconds>(end_time - start_time).count();
        auto execution_time_min = duration_cast<minutes>(end_time - start_time).count();
        auto execution_time_hour = duration_cast<hours>(end_time - start_time).count();
    
        cout << "\nExecution Time: ";
        if(execution_time_hour > 0)
        cout << "" << execution_time_hour << " Hours, ";
        if(execution_time_min > 0)
        cout << "" << execution_time_min % 60 << " Minutes, ";
        if(execution_time_sec > 0)
        cout << "" << execution_time_sec % 60 << " Seconds, ";
        if(execution_time_ms > 0)
        cout << "" << execution_time_ms % long(1E+3) << " MicroSeconds, ";
        if(execution_time_ns > 0)
        cout << "" << execution_time_ns % long(1E+6) << " NanoSeconds, ";
    }
    

    Cocoa: What's the difference between the frame and the bounds?

    All answers above are correct and this is my take on this:

    To differentiate between frame and bounds CONCEPTS developer should read:

    1. relative to the superview (one parent view) it is contained within = FRAME
    2. relative to its own coordinate system, determines its subview location = BOUNDS

    "bounds" is confusing because it gives the impression that the coordinates are the position of the view for which it is set. But these are in relations and adjusted according to the frame constants.

    iPhone screen

    bool to int conversion

    int x = 4<5;
    

    Completely portable. Standard conformant. bool to int conversion is implicit!

    §4.7/4 from the C++ Standard says (Integral Conversion)

    If the source type is bool, the value false is converted to zero and the value true is converted to one.


    As for C, as far as I know there is no bool in C. (before 1999) So bool to int conversion is relevant in C++ only. In C, 4<5 evaluates to int value, in this case the value is 1, 4>5 would evaluate to 0.

    EDIT: Jens in the comment said, C99 has _Bool type. bool is a macro defined in stdbool.h header file. true and false are also macro defined in stdbool.h.

    §7.16 from C99 says,

    The macro bool expands to _Bool.

    [..] true which expands to the integer constant 1, false which expands to the integer constant 0,[..]

    How to compile a 64-bit application using Visual C++ 2010 Express?

    64-bit tools are not available on Visual C++ Express by default. To enable 64-bit tools on Visual C++ Express, install the Windows Software Development Kit (SDK) in addition to Visual C++ Express. Otherwise, an error occurs when you attempt to configure a project to target a 64-bit platform using Visual C++ Express.

    How to: Configure Visual C++ Projects to Target 64-Bit Platforms

    Ref: http://msdn.microsoft.com/en-us/library/9yb4317s.aspx

    Warning: Attempt to present * on * whose view is not in the window hierarchy - swift

    Use of main thread to present and dismiss view controller worked for me.

    DispatchQueue.main.async { self.present(viewController, animated: true, completion: nil) }
    

    Convert Xml to Table SQL Server

    This is the answer, hope it helps someone :)

    First there are two variations on how the xml can be written:

    1

    <row>
        <IdInvernadero>8</IdInvernadero>
        <IdProducto>3</IdProducto>
        <IdCaracteristica1>8</IdCaracteristica1>
        <IdCaracteristica2>8</IdCaracteristica2>
        <Cantidad>25</Cantidad>
        <Folio>4568457</Folio>
    </row>
    <row>
        <IdInvernadero>3</IdInvernadero>
        <IdProducto>3</IdProducto>
        <IdCaracteristica1>1</IdCaracteristica1>
        <IdCaracteristica2>2</IdCaracteristica2>
        <Cantidad>72</Cantidad>
        <Folio>4568457</Folio>
    </row>
    

    Answer:

    SELECT  
           Tbl.Col.value('IdInvernadero[1]', 'smallint'),  
           Tbl.Col.value('IdProducto[1]', 'smallint'),  
           Tbl.Col.value('IdCaracteristica1[1]', 'smallint'),
           Tbl.Col.value('IdCaracteristica2[1]', 'smallint'),
           Tbl.Col.value('Cantidad[1]', 'int'),
           Tbl.Col.value('Folio[1]', 'varchar(7)')
    FROM   @xml.nodes('//row') Tbl(Col)  
    

    2.

    <row IdInvernadero="8" IdProducto="3" IdCaracteristica1="8" IdCaracteristica2="8" Cantidad ="25" Folio="4568457" />                         
    <row IdInvernadero="3" IdProducto="3" IdCaracteristica1="1" IdCaracteristica2="2" Cantidad ="72" Folio="4568457" />
    

    Answer:

    SELECT  
           Tbl.Col.value('@IdInvernadero', 'smallint'),  
           Tbl.Col.value('@IdProducto', 'smallint'),  
           Tbl.Col.value('@IdCaracteristica1', 'smallint'),
           Tbl.Col.value('@IdCaracteristica2', 'smallint'),
           Tbl.Col.value('@Cantidad', 'int'),
           Tbl.Col.value('@Folio', 'varchar(7)')
    
    FROM   @xml.nodes('//row') Tbl(Col)
    

    Taken from:

    1. http://kennyshu.blogspot.com/2007/12/convert-xml-file-to-table-in-sql-2005.html

    2. http://msdn.microsoft.com/en-us/library/ms345117(SQL.90).aspx

    How to use jQuery in chrome extension?

    In my case got a working solution through Cross-document Messaging (XDM) and Executing Chrome extension onclick instead of page load.

    manifest.json

    {
      "name": "JQuery Light",
      "version": "1",
      "manifest_version": 2,
    
      "browser_action": {
        "default_icon": "icon.png"
      },
    
      "content_scripts": [
        {
          "matches": [
            "https://*.google.com/*"
          ],
          "js": [
            "jquery-3.3.1.min.js",
            "myscript.js"
          ]
        }
      ],
    
      "background": {
        "scripts": [
          "background.js"
        ]
      }
    
    }
    

    background.js

    chrome.browserAction.onClicked.addListener(function (tab) {
      chrome.tabs.query({active: true, currentWindow: true}, function (tabs) {
        var activeTab = tabs[0];
        chrome.tabs.sendMessage(activeTab.id, {"message": "clicked_browser_action"});
      });
    });
    

    myscript.js

    chrome.runtime.onMessage.addListener(
        function (request, sender, sendResponse) {
            if (request.message === "clicked_browser_action") {
            console.log('Hello world!')
            }
        }
    );
    

    Python: Find in list

    As for your first question: that code is perfectly fine and should work if item equals one of the elements inside myList. Maybe you try to find a string that does not exactly match one of the items or maybe you are using a float value which suffers from inaccuracy.

    As for your second question: There's actually several possible ways if "finding" things in lists.

    Checking if something is inside

    This is the use case you describe: Checking whether something is inside a list or not. As you know, you can use the in operator for that:

    3 in [1, 2, 3] # => True
    

    Filtering a collection

    That is, finding all elements in a sequence that meet a certain condition. You can use list comprehension or generator expressions for that:

    matches = [x for x in lst if fulfills_some_condition(x)]
    matches = (x for x in lst if x > 6)
    

    The latter will return a generator which you can imagine as a sort of lazy list that will only be built as soon as you iterate through it. By the way, the first one is exactly equivalent to

    matches = filter(fulfills_some_condition, lst)
    

    in Python 2. Here you can see higher-order functions at work. In Python 3, filter doesn't return a list, but a generator-like object.

    Finding the first occurrence

    If you only want the first thing that matches a condition (but you don't know what it is yet), it's fine to use a for loop (possibly using the else clause as well, which is not really well-known). You can also use

    next(x for x in lst if ...)
    

    which will return the first match or raise a StopIteration if none is found. Alternatively, you can use

    next((x for x in lst if ...), [default value])
    

    Finding the location of an item

    For lists, there's also the index method that can sometimes be useful if you want to know where a certain element is in the list:

    [1,2,3].index(2) # => 1
    [1,2,3].index(4) # => ValueError
    

    However, note that if you have duplicates, .index always returns the lowest index:......

    [1,2,3,2].index(2) # => 1
    

    If there are duplicates and you want all the indexes then you can use enumerate() instead:

    [i for i,x in enumerate([1,2,3,2]) if x==2] # => [1, 3]
    

    PHP Get Highest Value from Array

    Try it.

    $data = array("a"=>1,"b"=>2,"c"=>4,"d"=>5); $maxKey = current(array_keys($data, max($data))); var_dump($maxKey);

    MongoDB Show all contents from all collections

    I prefer another approach if you are using mongo shell:

    First as the another answers: use my_database_name then:

    db.getCollectionNames().map( (name) => ({[name]: db[name].find().toArray().length}) )
    

    This query will show you something like this:

    [
            {
                    "agreements" : 60
            },
            {
                    "libraries" : 45
            },
            {
                    "templates" : 9
            },
            {
                    "users" : 19
            }
    ]
    
    

    You can use similar approach with db.getCollectionInfos() it is pretty useful if you have so much data & helpful as well.

    What does Python's socket.recv() return for non-blocking sockets if no data is received until a timeout occurs?

    When you use recv in connection with select if the socket is ready to be read from but there is no data to read that means the client has closed the connection.

    Here is some code that handles this, also note the exception that is thrown when recv is called a second time in the while loop. If there is nothing left to read this exception will be thrown it doesn't mean the client has closed the connection :

    def listenToSockets(self):
    
        while True:
    
            changed_sockets = self.currentSockets
    
            ready_to_read, ready_to_write, in_error = select.select(changed_sockets, [], [], 0.1)
    
            for s in ready_to_read:
    
                if s == self.serverSocket:
                    self.acceptNewConnection(s)
                else:
                    self.readDataFromSocket(s)
    

    And the function that receives the data :

    def readDataFromSocket(self, socket):
    
        data = ''
        buffer = ''
        try:
    
            while True:
                data = socket.recv(4096)
    
                if not data: 
                    break
    
                buffer += data
    
        except error, (errorCode,message): 
            # error 10035 is no data available, it is non-fatal
            if errorCode != 10035:
                print 'socket.error - ('+str(errorCode)+') ' + message
    
    
        if data:
            print 'received '+ buffer
        else:
            print 'disconnected'
    

    CardView background color always white

    You can do it either in XML or programmatically:

    In XML:

    card_view:cardBackgroundColor="@android:color/red"
    

    Programmatically:

    cardView.setCardBackgroundColor(Color.RED);
    

    "Strict Standards: Only variables should be passed by reference" error

    Instead of parsing it manually it's better to use pathinfo function:

    $path_parts = pathinfo($value);
    $extension = strtolower($path_parts['extension']);
    $fileName = $path_parts['filename'];
    

    JQuery - Storing ajax response into global variable

            function getJson(url) {
                return JSON.parse($.ajax({
                    type: 'GET',
                    url: url,
                    dataType: 'json',
                    global: false,
                    async: false,
                    success: function (data) {
                        return data;
                    }
                }).responseText);
            }
    
            var myJsonObj = getJson('/api/current');
    

    This works!!!

    How do I sort a table in Excel if it has cell references in it?

    Put a dollar sign in front of the row and/or column of the cell you want to remain constant.

    Fixed it for me!

    Can I install the "app store" in an IOS simulator?

    This is NOT possible

    The Simulator does not run ARM code, ONLY x86 code. Unless you have the raw source code from Apple, you won't see the App Store on the Simulator.

    The app you write you will be able to test in the Simulator by running it directly from Xcode even if you don't have a developer account. To test your app on an actual device, you will need to be apart of the Apple Developer program.

    How to use clock() in C++

    #include <iostream>
    #include <cstdio>
    #include <ctime>
    
    int main() {
        std::clock_t start;
        double duration;
    
        start = std::clock();
    
        /* Your algorithm here */
    
        duration = ( std::clock() - start ) / (double) CLOCKS_PER_SEC;
    
        std::cout<<"printf: "<< duration <<'\n';
    }
    

    Terminating a script in PowerShell

    Write-Error is for non-terminating errors and throw is for terminating errors

    The Write-Error cmdlet declares a non-terminating error. By default, errors are sent in the error stream to the host program to be displayed, along with output.

    Non-terminating errors write an error to the error stream, but they do not stop command processing. If a non-terminating error is declared on one item in a collection of input items, the command continues to process the other items in the collection.

    To declare a terminating error, use the Throw keyword. For more information, see about_Throw (http://go.microsoft.com/fwlink/?LinkID=145153).

    Using DISTINCT along with GROUP BY in SQL Server

    Use DISTINCT to remove duplicate GROUPING SETS from the GROUP BY clause

    In a completely silly example using GROUPING SETS() in general (or the special grouping sets ROLLUP() or CUBE() in particular), you could use DISTINCT in order to remove the duplicate values produced by the grouping sets again:

    SELECT DISTINCT actors
    FROM (VALUES('a'), ('a'), ('b'), ('b')) t(actors)
    GROUP BY CUBE(actors, actors)
    

    With DISTINCT:

    actors
    ------
    NULL
    a
    b
    

    Without DISTINCT:

    actors
    ------
    a
    b
    NULL
    a
    b
    a
    b
    

    But why, apart from making an academic point, would you do that?

    Use DISTINCT to find unique aggregate function values

    In a less far-fetched example, you might be interested in the DISTINCT aggregated values, such as, how many different duplicate numbers of actors are there?

    SELECT DISTINCT COUNT(*)
    FROM (VALUES('a'), ('a'), ('b'), ('b')) t(actors)
    GROUP BY actors
    

    Answer:

    count
    -----
    2
    

    Use DISTINCT to remove duplicates with more than one GROUP BY column

    Another case, of course, is this one:

    SELECT DISTINCT actors, COUNT(*)
    FROM (VALUES('a', 1), ('a', 1), ('b', 1), ('b', 2)) t(actors, id)
    GROUP BY actors, id
    

    With DISTINCT:

    actors  count
    -------------
    a       2
    b       1
    

    Without DISTINCT:

    actors  count
    -------------
    a       2
    b       1
    b       1
    

    For more details, I've written some blog posts, e.g. about GROUPING SETS and how they influence the GROUP BY operation, or about the logical order of SQL operations (as opposed to the lexical order of operations).

    Network usage top/htop on Linux

    Also iftop:

    display bandwidth usage on an interface

    iftop does for network usage what top(1) does for CPU usage. It listens to network traffic on a named interface and displays a table of current bandwidth usage by pairs of hosts. Handy for answering the question "why is our ADSL link so slow?"...

    Could not reliably determine the server's fully qualified domain name

    Under Debian Squeeze;

    1. Edit Apache2 conf file : vim /etc/apache2/apache2.conf
    2. Insert the following line at the apache2.conf: ServerName localhost
    3. Restart Apache2: apache2ctl restart or /etc/init.d/apache2 restart

    Should work fine (it did solve the problem in my case)

    tks noodl for the link on the different layouts. :)

    Force encode from US-ASCII to UTF-8 (iconv)

    You can use file -i file_name to check what exactly your original file format is.

    Once you get that, you can do the following:

    iconv -f old_format -t utf-8 input_file -o output_file
    

    CMD what does /im (taskkill)?

    It tells taskkill that the next parameter something.exe is an image name, a.k.a executable name

    C:\>taskkill /?
    
    TASKKILL [/S system [/U username [/P [password]]]]
             { [/FI filter] [/PID processid | /IM imagename] } [/T] [/F]
    
    Description:
        This tool is used to terminate tasks by process id (PID) or image name.
    
    Parameter List:
        /S    system           Specifies the remote system to connect to.
    
        /U    [domain\]user    Specifies the user context under which the
                               command should execute.
    
        /P    [password]       Specifies the password for the given user
                               context. Prompts for input if omitted.
    
        /FI   filter           Applies a filter to select a set of tasks.
                               Allows "*" to be used. ex. imagename eq acme*
    
        /PID  processid        Specifies the PID of the process to be terminated.
                               Use TaskList to get the PID.
    
        /IM   imagename        Specifies the image name of the process
                               to be terminated. Wildcard '*' can be used
                               to specify all tasks or image names.
    
        /T                     Terminates the specified process and any
                               child processes which were started by it.
    
        /F                     Specifies to forcefully terminate the process(es).
    
        /?                     Displays this help message.
    

    What is the yield keyword used for in C#?

    One major point about Yield keyword is Lazy Execution. Now what I mean by Lazy Execution is to execute when needed. A better way to put it is by giving an example

    Example: Not using Yield i.e. No Lazy Execution.

    public static IEnumerable<int> CreateCollectionWithList()
    {
        var list =  new List<int>();
        list.Add(10);
        list.Add(0);
        list.Add(1);
        list.Add(2);
        list.Add(20);
    
        return list;
    }
    

    Example: using Yield i.e. Lazy Execution.

    public static IEnumerable<int> CreateCollectionWithYield()
    {
        yield return 10;
        for (int i = 0; i < 3; i++) 
        {
            yield return i;
        }
    
        yield return 20;
    }
    

    Now when I call both methods.

    var listItems = CreateCollectionWithList();
    var yieldedItems = CreateCollectionWithYield();
    

    you will notice listItems will have a 5 items inside it (hover your mouse on listItems while debugging). Whereas yieldItems will just have a reference to the method and not the items. That means it has not executed the process of getting items inside the method. A very efficient a way of getting data only when needed. Actual implementation of yield can seen in ORM like Entity Framework and NHibernate etc.

    MySQL: Insert record if not exists in table

    I had a problem, and the method Mike advised worked partly, I had an error Dublicate Column name = '0', and changed the syntax of your query as this`

         $tQ = "INSERT  INTO names (name_id, surname_id, sum, sum2, sum3,sum4,sum5) 
                    SELECT '$name', '$surname', '$sum', '$sum2', '$sum3','$sum4','$sum5' 
    FROM DUAL
                    WHERE NOT EXISTS (
                    SELECT sum FROM names WHERE name_id = '$name' 
    AND surname_id = '$surname') LIMIT 1;";
    

    The problem was with column names. sum3 was equal to sum4 and mysql throwed dublicate column names, and I wrote the code in this syntax and it worked perfectly,

    iOS: Compare two dates

    I don't know exactly if you have asked this but if you only want to compare the date component of a NSDate you have to use NSCalendar and NSDateComponents to remove the time component.

    Something like this should work as a category for NSDate:

    - (NSComparisonResult)compareDateOnly:(NSDate *)otherDate {
        NSUInteger dateFlags = NSYearCalendarUnit|NSMonthCalendarUnit|NSDayCalendarUnit;
        NSCalendar *gregorianCalendar = [[[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar] autorelease];
        NSDateComponents *selfComponents = [gregorianCalendar components:dateFlags fromDate:self];
        NSDate *selfDateOnly = [gregorianCalendar dateFromComponents:selfComponents];
    
        NSDateComponents *otherCompents = [gregorianCalendar components:dateFlags fromDate:otherDate];
        NSDate *otherDateOnly = [gregorianCalendar dateFromComponents:otherCompents];
        return [selfDateOnly compare:otherDateOnly];
    }
    

    AJAX cross domain call

    I use this code for cross domain ajax call, I hope it will help more than one here. I'm using Prototype library and you can do the same with JQuery or Dojo or anything else:

    Step 1: create a new js file and put this class inside, I called it xss_ajax.js

    var WSAjax = Class.create ({
        initialize: function (_url, _callback){
            this.url = _url ;
            this.callback = _callback ;
            this.connect () ;
        },
        connect: function (){
            var script_id = null;
            var script = document.createElement('script');
            script.setAttribute('type', 'text/javascript');
            script.setAttribute('src', this.url);
            script.setAttribute('id', 'xss_ajax_script');
    
            script_id = document.getElementById('xss_ajax_script');
            if(script_id){
                document.getElementsByTagName('head')[0].removeChild(script_id);
            }
    
            // Insert <script> into DOM
            document.getElementsByTagName('head')[0].appendChild(script);
        },
        process: function (data){
            this.callback(data) ;
        }
    
    }) ;
    

    This class creates a dynamic script element which src attributes targets your JSON data provider (JSON-P in fact as your distant server must provide the data in this format :: call_back_function(//json_data_here) :: so when the script tag is created your JSON will be directly evaled as a function (we'll talk about passing the callback method name to server on step 2), the main concept behind this is that script like img elements are not concerned by the SOP constraints.

    Step2: in any html page where you wanna pull the JSON asynchronously (we call this AJAJ ~ Asynchronous JAvascript + JSON :-) instead of AJAX which use the XHTTPRequest object) do like below

    //load Prototype first
    //load the file you've created in step1
    
    
    var xss_crawler = new WSAjax (
         "http://your_json_data_provider_url?callback=xss_crawler.process"
     ,   function (_data){
                // your json data is _data and do whatever you like with it 
            }) ;
    

    D'you remenber the callback on step 1? so we pass it to the server and it will returns the JSON embeded in that method so in our case the server will return an evalable javascript code xss_crawler.process(//the_json_data), remember that xss_crawler is an instance of WSAjax class. The server code depends on you (if it's yours), but most of Ajax data providers let you specify the callback method in parameters like we did. In Ruby on rails I just did

    render :json=>MyModel.all(:limit=>10), :callback => params[:callback],:content_type => "application/json"
    

    and that's all, you can now pull data from another domain from your apps (widgets, maps etc), in JSON format only, don't forget.

    I hope it was helpfull, thanks for your patience :-), peace and sorry for code formatting, it doesn't work well

    How do I adb pull ALL files of a folder present in SD Card

    Single File/Folder using pull:

    adb pull "/sdcard/Folder1"
    

    Output:

    adb pull "/sdcard/Folder1"
    pull: building file list...
    pull: /sdcard/Folder1/image1.jpg -> ./image1.jpg
    pull: /sdcard/Folder1/image2.jpg -> ./image2.jpg
    pull: /sdcard/Folder1/image3.jpg -> ./image3.jpg
    3 files pulled. 0 files skipped.
    

    Specific Files/Folders using find from BusyBox:

    adb shell find "/sdcard/Folder1" -iname "*.jpg" | tr -d '\015' | while read line; do adb pull "$line"; done;
    

    Here is an explanation:

    adb shell find "/sdcard/Folder1" - use the find command, use the top folder
    -iname "*.jpg"                   - filter the output to only *.jpg files
    |                                - passes data(output) from one command to another
    tr -d '\015'                     - explained here: http://stackoverflow.com/questions/9664086/bash-is-removing-commands-in-while
    while read line;                 - while loop to read input of previous commands
    do adb pull "$line"; done;         - pull the files into the current running directory, finish. The quotation marks around $line are required to work with filenames containing spaces.
    

    The scripts will start in the top folder and recursively go down and find all the "*.jpg" files and pull them from your phone to the current directory.

    How to create a fixed sidebar layout with Bootstrap 4?

    I'm using the J.S. to fix a sidebar menu. I've tried a lot of solutions with CSS but it's the simplest way to solve it, just add J.S. adding and removing a native BootStrap class: "position-fixed".

    The J.S.:

    var lateral = false;
    function fixar() {
    
                var element, name, arr;
                element = document.getElementById("minhasidebar");
    
                if (lateral) {
                    element.className = element.className.replace(
                            /\bposition-fixed\b/g, "");
                    lateral = false;
                } else {
    
                    name = "position-fixed";
                    arr = element.className.split(" ");
                    if (arr.indexOf(name) == -1) {
                        element.className += " " + name;
                    }
                    lateral = true;
                }
    
            }
    

    The HTML:

    Sidebar:

    <aside>
            <nav class="sidebar ">
                 <div id="minhasidebar">
                     <ul class="nav nav-pills">
                         <li class="nav-item"><a class="nav-link active" 
                         th:href="@{/hoje/inicial}"> <i class="oi oi-clipboard"></i> 
                         <span>Hoje</span>
                         </a></li>
                     </ul>
                 </div>
            </nav>            
    </aside>
    

    Oracle SQL : timestamps in where clause

    For everyone coming to this thread with fractional seconds in your timestamp use:

    to_timestamp('2018-11-03 12:35:20.419000', 'YYYY-MM-DD HH24:MI:SS.FF')

    How to change the text on the action bar

    if u r using navigation bar to change fragment then u can add change it where u r changing Fragment like below example :

     public boolean onNavigationItemSelected(@NonNull MenuItem item) {
                switch (item.getItemId()) {
                    case R.id.clientsidedrawer:
                        //    Toast.makeText(getApplicationContext(),"Client selected",Toast.LENGTH_SHORT).show();
                        getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container, new clients_fragment()).commit();
                        break;
        
                    case R.id.adddatasidedrawer:
                        getSupportActionBar().setTitle("Add Client");
                        getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container, new addclient_fragment()).commit();
                        break;
        
                    case R.id.editid:
                        getSupportActionBar().setTitle("Edit Clients");
                        getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container, new Editclient()).commit();
                        break;
        
                    case R.id.taskid:
                        getSupportActionBar().setTitle("Task manager");
                        getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,new Taskmanager()).commit();
                        break;
    

    if u r using simple activity then just call :

    getSupportActionBar().setTitle("Contact Us");
    

    to change actionbar/toolbar color in activity use :

    getSupportActionBar().setBackgroundDrawable(new ColorDrawable(Color.parseColor("#06023b")));
    

    to set gradient to actionbar first create gradient : Example directry created > R.drawable.gradient_contactus

    <?xml version="1.0" encoding="utf-8"?>
    <shape
        xmlns:android="http://schemas.android.com/apk/res/android"
        android:shape="rectangle"
        >
    
        <gradient
            android:angle="90"
            android:startColor="#2980b9"
            android:centerColor="#6dd5fa"
            android:endColor="#2980b9">
        </gradient>
    
    
    </shape>
    

    and then set it like this :

    getSupportActionBar().setBackgroundDrawable(getResources().getDrawable(R.drawable.gradient_contactus));
    

    Disable HttpClient logging

    It took far too long to find this out, but JWebUnit comes bundled with the Logback logging component, so it won't even use log4j.properties or commons-logging.properties.

    Instead, create a file called logback.xml and place it in your source code folder (in my case, src):

    <configuration debug="false">
      <!-- definition of appender STDOUT -->
      <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
        <encoder>
          <pattern>%-4relative [%thread] %-5level %logger{35} - %msg %n</pattern>
        </encoder>
      </appender>
    
      <root level="ERROR">
        <!-- appender referenced after it is defined -->
        <appender-ref ref="STDOUT"/>
      </root> 
    </configuration>
    

    Logback looks to still be under development and the API seems to still be changing, so this code sample may fail in the future. See also this StackOverflow question.

    Is there an exponent operator in C#?

    Since no-one has yet wrote a function to do this with two integers, here's one way:

    private long CalculatePower(int number, int powerOf)
    {
        for (int i = powerOf; i > 1; i--)
            number *= number;
        return number;
    }
    CalculatePower(5, 3); // 125
    CalculatePower(8, 4); // 4096
    CalculatePower(6, 2); // 36
    

    Alternatively in VB.NET:

    Private Function CalculatePower(number As Integer, powerOf As Integer) As Long
        For i As Integer = powerOf To 2 Step -1
            number *= number
        Next
        Return number
    End Function
    CalculatePower(5, 3) ' 125
    CalculatePower(8, 4) ' 4096
    CalculatePower(6, 2) ' 36
    

    Make Div overlay ENTIRE page (not just viewport)?

    body:before {
        content: " ";
        width: 100%;
        height: 100%;
        position: fixed;
        z-index: -1;
        top: 0;
        left: 0;
        background: rgba(0, 0, 0, 0.5);
    }
    

    What does {0} mean when found in a string in C#?

    In addition to the value you wish to print, the {0} {1}, etc., you can specify a format. For example, {0,4} will be a value that is padded to four spaces.

    There are a number of built-in format specifiers, and in addition, you can make your own. For a decent tutorial/list see String Formatting in C#. Also, there is a FAQ here.

    Run Stored Procedure in SQL Developer?

    For those using SqlDeveloper 3+, in case you missed that:

    SqlDeveloper has feature to execute stored proc/function directly, and output are displayed in a easy-to-read manner.

    Just right click on the package/stored proc/ stored function, Click on Run and choose target to be the proc/func you want to execute, SqlDeveloper will generate the code snippet to execute (so that you can put your input parameters). Once executed, output parameters are displayed in lower half of the dialog box, and it even have built-in support for ref cursor: result of cursor will be displayed as a separate output tab.

    Handling click events on a drawable within an EditText

    That last contribution's use of contains(x,y) won't work directly on the result of getBounds() (except, by coincidence, when using "left" drawables). The getBounds method only provides the Rect defining points of the drawable item normalized with origin at 0,0 - so, you actually need to do the math of the original post to find out if the click is in the area of the drawable in the context of the containing EditText's dimensions, but change it for top, right, left etc. Alternatively you could describe a Rect that has coordinates actually relative to its position in the EditText container and use contains(), although in the end you're doing the same math.

    Combining them both gives you a pretty complete solution, I only added an instance attribute consumesEvent that lets the API user decide if the click event should be passed on or not by using its result to set ACTION_CANCEL or not.

    Also, I can't see why the bounds and actionX, actionY values are instance attributes rather than just local on the stack.

    Here's a cutout from an implementation based on the above that I put together. It fixes an issue that to properly consume the event you need to return false. It adds a "fuzz" factor to. In my use case of a Voice control icon in an EditText field, I found it hard to click, so the fuzz increases the effective bounds that are considered clicking the drawable. For me 15 worked well. I only needed drawableRight so I didn't plug the math in the others, to save some space, but you see the idea.

    package com.example.android;
    
    import android.content.Context;
    import android.graphics.drawable.Drawable;
    import android.util.AttributeSet;
    import android.util.Log;
    import android.view.MotionEvent;
    import android.widget.EditText;
    import android.graphics.Rect;
    
    import com.example.android.DrawableClickListener;
    
    public class ClickableButtonEditText extends EditText {
      public static final String LOG_TAG = "ClickableButtonEditText";
    
      private Drawable drawableRight;
      private Drawable drawableLeft;
      private Drawable drawableTop;
      private Drawable drawableBottom;
      private boolean consumeEvent = false;
      private int fuzz = 0;
    
      private DrawableClickListener clickListener;
    
      public ClickableButtonEditText(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
      }
    
      public ClickableButtonEditText(Context context, AttributeSet attrs) {
        super(context, attrs);
      }
    
      public ClickableButtonEditText(Context context) {
        super(context);
      }
    
      public void consumeEvent() {
        this.setConsumeEvent(true);
      }
    
      public void setConsumeEvent(boolean b) {
        this.consumeEvent = b;
      }
    
      public void setFuzz(int z) {
        this.fuzz = z;
      }
    
      public int getFuzz() {
        return fuzz;
      }
    
      @Override
      public void setCompoundDrawables(Drawable left, Drawable top, Drawable right, Drawable bottom) {
        if (right != null) {
          drawableRight = right;
        }
    
        if (left != null) {
          drawableLeft = left;
        }
        super.setCompoundDrawables(left, top, right, bottom);
      }
    
      @Override
      public boolean onTouchEvent(MotionEvent event) {
        if (event.getAction() == MotionEvent.ACTION_DOWN) {
          int x, y;
          Rect bounds;
          x = (int) event.getX();
          y = (int) event.getY();
          // this works for left since container shares 0,0 origin with bounds
          if (drawableLeft != null) {
            bounds = drawableLeft.getBounds();
            if (bounds.contains(x - fuzz, y - fuzz)) {
              clickListener.onClick(DrawableClickListener.DrawablePosition.LEFT);
              if (consumeEvent) {
                event.setAction(MotionEvent.ACTION_CANCEL);
                return false;
              }
            }
          } else if (drawableRight != null) {
            bounds = drawableRight.getBounds();
            if (x >= (this.getRight() - bounds.width() - fuzz) && x <= (this.getRight() - this.getPaddingRight() + fuzz) 
                  && y >= (this.getPaddingTop() - fuzz) && y <= (this.getHeight() - this.getPaddingBottom()) + fuzz) {
    
              clickListener.onClick(DrawableClickListener.DrawablePosition.RIGHT);
              if (consumeEvent) {
                event.setAction(MotionEvent.ACTION_CANCEL);
                return false;
              }
            }
          } else if (drawableTop != null) {
            // not impl reader exercise :)
          } else if (drawableBottom != null) {
            // not impl reader exercise :)
          }
        }
    
        return super.onTouchEvent(event);
      }
    
      @Override
      protected void finalize() throws Throwable {
        drawableRight = null;
        drawableBottom = null;
        drawableLeft = null;
        drawableTop = null;
        super.finalize();
      }
    
      public void setDrawableClickListener(DrawableClickListener listener) {
        this.clickListener = listener;
      }
    }
    

    Casting a variable using a Type variable

    After not finding anything to get around "Object must implement IConvertible" exception when using Zyphrax's answer (except for implementing the interface).. I tried something a little bit unconventional and worked for my situation.

    Using the Newtonsoft.Json nuget package...

    var castedObject = JsonConvert.DeserializeObject(JsonConvert.SerializeObject(myObject), myType);
    

    Django template how to look up a dictionary value with a variable

    You can't by default. The dot is the separator / trigger for attribute lookup / key lookup / slice.

    Dots have a special meaning in template rendering. A dot in a variable name signifies a lookup. Specifically, when the template system encounters a dot in a variable name, it tries the following lookups, in this order:

    • Dictionary lookup. Example: foo["bar"]
    • Attribute lookup. Example: foo.bar
    • List-index lookup. Example: foo[bar]

    But you can make a filter which lets you pass in an argument:

    https://docs.djangoproject.com/en/dev/howto/custom-template-tags/#writing-custom-template-filters

    @register.filter(name='lookup')
    def lookup(value, arg):
        return value[arg]
    
    {{ mydict|lookup:item.name }}
    

    Better way to check variable for null or empty string?

    // Function for basic field validation (present and neither empty nor only white space
    function IsNullOrEmptyString($str){
        return (!isset($str) || trim($str) === '');
    }
    

    How to use a table type in a SELECT FROM statement?

    You can't do it in a single query inside the package - you can't mix the SQL and PL/SQL types, and would need to define the types in the SQL layer as Tony, Marcin and Thio have said.

    If you really want this done locally, and you can index the table type by VARCHAR instead of BINARY_INTEGER, you can do something like this:

    -- dummy ITEM table as we don't know what the real ones looks like
    create table item(
        item_num number,
        currency varchar2(9)
    )
    /   
    
    insert into item values(1,'GBP');
    insert into item values(2,'AUD');
    insert into item values(3,'GBP');
    insert into item values(4,'AUD');
    insert into item values(5,'CDN');
    
    create package so_5165580 as
        type exch_row is record(
            exch_rt_eur number,
            exch_rt_usd number);
        type exch_tbl is table of exch_row index by varchar2(9);
        exch_rt exch_tbl;
        procedure show_items;
    end so_5165580;
    /
    
    create package body so_5165580 as
        procedure populate_rates is
            rate exch_row;
        begin
            rate.exch_rt_eur := 0.614394;
            rate.exch_rt_usd := 0.8494;
            exch_rt('GBP') := rate;
            rate.exch_rt_eur := 0.9817;
            rate.exch_rt_usd := 1.3572;
            exch_rt('AUD') := rate;
        end;
    
        procedure show_items is
            cursor c0 is
                select i.*
                from item i;
        begin
            for r0 in c0 loop
                if exch_rt.exists(r0.currency) then
                    dbms_output.put_line('Item ' || r0.item_num
                        || ' Currency ' || r0.currency
                        || ' EUR ' || exch_rt(r0.currency).exch_rt_eur
                        || ' USD ' || exch_rt(r0.currency).exch_rt_usd);
                else
                    dbms_output.put_line('Item ' || r0.item_num
                        || ' Currency ' || r0.currency
                        || ' ** no rates defined **');
                end if;
            end loop;
        end;
    begin
        populate_rates;
    end so_5165580;
    /
    

    So inside your loop, wherever you would have expected to use r0.exch_rt_eur you instead use exch_rt(r0.currency).exch_rt_eur, and the same for USD. Testing from an anonymous block:

    begin
        so_5165580.show_items;
    end;
    /
    
    Item 1 Currency GBP EUR .614394 USD .8494
    Item 2 Currency AUD EUR .9817 USD 1.3572
    Item 3 Currency GBP EUR .614394 USD .8494
    Item 4 Currency AUD EUR .9817 USD 1.3572
    Item 5 Currency CDN ** no rates defined **
    

    Based on the answer Stef posted, this doesn't need to be in a package at all; the same results could be achieved with an insert statement. Assuming EXCH holds exchange rates of other currencies against the Euro, including USD with currency_key=1:

    insert into detail_items
    with rt as (select c.currency_cd as currency_cd,
            e.exch_rt as exch_rt_eur,
            (e.exch_rt / usd.exch_rt) as exch_rt_usd
        from exch e,
            currency c,
            (select exch_rt from exch where currency_key = 1) usd
        where c.currency_key = e.currency_key)
    select i.doc,
        i.doc_currency,
        i.net_value,
        i.net_value / rt.exch_rt_usd AS net_value_in_usd,
        i.net_value / rt.exch_rt_eur as net_value_in_euro
    from item i
    join rt on i.doc_currency = rt.currency_cd;
    

    With items valued at 19.99 GBP and 25.00 AUD, you get detail_items:

    DOC DOC_CURRENCY NET_VALUE         NET_VALUE_IN_USD  NET_VALUE_IN_EURO
    --- ------------ ----------------- ----------------- -----------------
    1   GBP          19.99             32.53611          23.53426
    2   AUD          25                25.46041          18.41621
    

    If you want the currency stuff to be more re-usable you could create a view:

    create view rt as
    select c.currency_cd as currency_cd,
        e.exch_rt as exch_rt_eur,
        (e.exch_rt / usd.exch_rt) as exch_rt_usd
    from exch e,
        currency c,
        (select exch_rt from exch where currency_key = 1) usd
    where c.currency_key = e.currency_key;
    

    And then insert using values from that:

    insert into detail_items
    select i.doc,
        i.doc_currency,
        i.net_value,
        i.net_value / rt.exch_rt_usd AS net_value_in_usd,
        i.net_value / rt.exch_rt_eur as net_value_in_euro
    from item i
    join rt on i.doc_currency = rt.currency_cd;
    

    ERROR 2002 (HY000): Can't connect to local MySQL server through socket '/var/run/mysqld/mysql.sock' (2)

    ERROR 2002 (HY000): Can't connect to local MySQL server through socket '/var/run/mysqld/mysql.sock' (2)

    I get the error above when I try to log into MYSQL after installing it using brew, I am running MacOs, Oh yea I also noticed mysql is running I have restarted numerous times with no luck resolving the issue along with removing mysql and numerous reinstalls!

    So simple I could slap myself, no but really, I solved this by CD into the temp folder that contains mysqlx.sock and mysql.sock.lock files, I deleted the single sock.lock file only and this solved my issue after doing so and I can log into mysql using the mysql -uroot command. Here are the commands I used. (this issue had me hung up for a while)

    ~ cd /tmp 
    
    /tmp ls 
    

    (this will list all the sock files in the temp folder, output shown below)

    com.apple.launchd.8AgGW2s9Bb mysql.sock.lock
    com.apple.launchd.batxrSISAJ mysqlx.sock
    com.apple.launchd.cRCaxtT41m mysqlx.sock.lock
    com.google.Keystone          powerlog
    

    then run

    rm -R mysql.sock.lock 
    

    (use command above to remove the sock.lock file from the /tmp directory this resolved my issue)

    hope this helped :)

    Chrome violation : [Violation] Handler took 83ms of runtime

    Perhaps a little off topic, just be informed that these kind of messages can also be seen when you are debugging your code with a breakpoint inside an async function like setTimeout like below:

    [Violation] 'setTimeout' handler took 43129ms
    

    That number (43129ms) depends on how long you stop in your async function

    In WPF, what are the differences between the x:Name and Name attributes?

    They're both the same thing, a lot of framework elements expose a name property themselves, but for those that don't you can use x:name - I usually just stick with x:name because it works for everything.

    Controls can expose name themselves as a Dependency Property if they want to (because they need to use that Dependency Property internally), or they can choose not to.

    More details in msdn here and here:

    Some WPF framework-level applications might be able to avoid any use of the x:Name attribute, because the Name dependency property as specified within the WPF namespace for several of the important base classes such as FrameworkElement/FrameworkContentElement satisfies this same purpose. There are still some common XAML and framework scenarios where code access to an element with no Name property is necessary, most notably in certain animation and storyboard support classes. For instance, you should specify x:Name on timelines and transforms created in XAML, if you intend to reference them from code.

    If Name is available as a property on the class, Name and x:Name can be used interchangeably as attributes, but an error will result if both are specified on the same element.

    How do I set a program to launch at startup

    Several options, in order of preference:

    1. Add it to the current user's Startup folder. This requires the least permissions for your app to run, and gives the user the most control and feedback of what's going on. The down-side is it's a little more difficult determining whether to show the checkbox already checked next time they view that screen in your program.
    2. Add it to the HKey_Current_User\Software\Microsoft\Windows\CurrentVersion\Run registry key. The only problem here is it requires write access to the registry, which isn't always available.
    3. Create a Scheduled Task that triggers on User Login
    4. Add it to the HKey_Local_Machine\Software\Microsoft\Windows\CurrentVersion\Run registry key. The only problem here is it requires write access to the registry, which isn't always available.
    5. Set it up as a windows service. Only do this if you really mean it, and you know for sure you want to run this program for all users on the computer.

    This answer is older now. Since I wrote this, Windows 10 was released, which changes how the Start Menu folders work... including the Startup folder. It's not yet clear to me how easy it is to just add or remove a file in that folder without also referencing the internal database Windows uses for these locations.

    How to set ssh timeout?

    You could also connect with flag

    -o ServerAliveInterval=<secs>
    so the SSH client will send a null packet to the server each <secs> seconds, just to keep the connection alive. In Linux this could be also set globally in /etc/ssh/ssh_config or per-user in ~/.ssh/config.

    Delete all files in directory (but not directory) - one liner solution

    package com;
    import java.io.File;
    public class Delete {
        public static void main(String[] args) {
    
            String files; 
            File file = new File("D:\\del\\yc\\gh");
            File[] listOfFiles = file.listFiles(); 
            for (int i = 0; i < listOfFiles.length; i++) 
            {
                if (listOfFiles[i].isFile()) 
                {
                    files = listOfFiles[i].getName();
                    System.out.println(files);
                    if(!files.equalsIgnoreCase("Scan.pdf"))
                    {
                        boolean issuccess=new File(listOfFiles[i].toString()).delete();
                        System.err.println("Deletion Success "+issuccess);
                    }
                }
            }
        }
    }
    

    If you want to delete all files remove

    if(!files.equalsIgnoreCase("Scan.pdf"))
    

    statement it will work.

    Signed versus Unsigned Integers

    (in answer to the second question) By only using a sign bit (and not 2's complement), you can end up with -0. Not very pretty.

    Setting up a JavaScript variable from Spring model by using Thymeleaf

    Another way to do it is to create a dynamic javascript returned by a java controller like it is written here in the thymeleaf forum: http://forum.thymeleaf.org/Can-I-use-th-inline-for-a-separate-javascript-file-td4025766.html

    One way to handle this is to create a dynamic javascript file with the URLs embedded in it. Here are the steps (if you are using Spring MVC)

    @RequestMapping(path = {"/dynamic.js"}, method = RequestMethod.GET, produces = "application/javascript")
    @ResponseStatus(value = HttpStatus.OK)
    @ResponseBody
    public String dynamicJS(HttpServletRequest request) {
    
            return "Your javascript code....";
    
    }
    
    
      
    

    Number prime test in JavaScript

    Cool version:

    const isPrime = n => ![...Array(n).keys()].slice(2).map(i => !(n%i)).includes(true) && ![0,1].includes(n)
    

    Importing larger sql files into MySQL

    I really like the BigDump to do it. It's a very simple PHP file that you edit and send with your huge file through SSH or FTP. Run and wait! It's very easy to configure character encoding, comes UTF-8 by default.

    Apache is not running from XAMPP Control Panel ( Error: Apache shutdown unexpectedly. This may be due to a blocked port)

    Accompanying Timmay's answer, You need to do two changes-

    Listen 80 --> Listen 81 (near line 58)

    ServerName localhost:80 --> ServerName localhost:81 (near line 218)

    use current date as default value for a column

    To use the current date as the default for a date column, you will need to:

    1- open table designer

    2- select the column

    3- go to column proprerties

    4- set the value of Default value or binding propriete To (getdate())

    enter image description here

    Regular expression to match exact number of characters?

    Your solution is correct, but there is some redundancy in your regex.
    The similar result can also be obtained from the following regex:

    ^([A-Z]{3})$
    

    The {3} indicates that the [A-Z] must appear exactly 3 times.

    Current date and time - Default in MVC razor

    Before you return your model from the controller, set your ReturnDate property to DateTime.Now()

    myModel.ReturnDate = DateTime.Now()
    
    return View(myModel)
    

    Your view is not the right place to set values on properties so the controller is the better place for this.

    You could even have it so that the getter on ReturnDate returns the current date/time.

    private DateTime _returnDate = DateTime.MinValue;
    public DateTime ReturnDate{
       get{
         return (_returnDate == DateTime.MinValue)? DateTime.Now() : _returnDate;
       }
       set{_returnDate = value;}
    }
    

    Get just the filename from a path in a Bash script

    Here is an easy way to get the file name from a path:

    echo "$PATH" | rev | cut -d"/" -f1 | rev
    

    To remove the extension you can use, assuming the file name has only ONE dot (the extension dot):

    cut -d"." -f1
    

    Merge two json/javascript arrays in to one array

    You can use the new js spread operator if using es6:

    _x000D_
    _x000D_
    var json1 = [{id:1, name: 'xxx'}]_x000D_
    var json2 = [{id:2, name: 'xyz'}]_x000D_
    var finalObj = [...json1, ...json2]_x000D_
    _x000D_
    console.log(finalObj)
    _x000D_
    _x000D_
    _x000D_