Programs & Examples On #Arabic

The Arabic tag is for issues relating to displaying user interfaces and managing data in Arabic written language.

HTML - Arabic Support

The W3C has a good introduction.

In short:

HTML is a text markup language. Text means any characters, not just ones in ASCII.

  1. Save your text using a character encoding that includes the characters you want (UTF-8 is a good bet). This will probably require configuring your editor in a way that is specific to the particular editor you are using. (Obviously it also requires that you have a way to input the characters you want)
  2. Make sure your server sends the correct character encoding in the headers (how you do this depends on the server software you us)
  3. If the document you serve over HTTP specifies its encoding internally, then make sure that is correct too
  4. If anything happens to the document between you saving it and it being served up (e.g. being put in a database, being munged by a server side script, etc) then make sure that the encoding isn't mucked about with on the way.

You can also represent any unicode character with ASCII

How do I set the selected item in a drop down box

If you have a big drop down. it's much easier to use jQuery with PHP.

This is how to do it:

<script>
$(document).ready(function () {
    $('select[name="country"]').val('<?=$data[0]['Country']?>');
});
</script>

CSS selector based on element text?

Not with CSS directly, you could set CSS properties via JavaScript based on the internal contents but in the end you would still need to be operating in the definitions of CSS.

net::ERR_INSECURE_RESPONSE in Chrome

I was having this issue when testing my Cordova app on android. It just so happens that this android device does not persist its date, and will reset back to its factory date somehow. The API that it calls has a cert that is valid starting this year, while the device date after bootup is in 2017. For now, I have to adb shell and change the date manually.

Install GD library and freetype on Linux

Installing GD :

For CentOS / RedHat / Fedora :

sudo yum install php-gd

For Debian/ubuntu :

sudo apt-get install php5-gd

Installing freetype :

For CentOS / RedHat / Fedora :

sudo yum install freetype*

For Debian/ubuntu :

sudo apt-get install freetype*

Don't forget to restart apache after that (if you are using apache):

CentOS / RedHat / Fedora :

sudo /etc/init.d/httpd restart

Or

sudo service httpd restart

Debian/ubuntu :

sudo /etc/init.d/apache2 restart

Or

sudo service apache2 restart

How to specify font attributes for all elements on an html web page?

If you specify CSS attributes for your body element it should apply to anything within <body></body> so long as you don't override them later in the stylesheet.

Split Spark Dataframe string column into multiple columns

pyspark.sql.functions.split() is the right approach here - you simply need to flatten the nested ArrayType column into multiple top-level columns. In this case, where each array only contains 2 items, it's very easy. You simply use Column.getItem() to retrieve each part of the array as a column itself:

split_col = pyspark.sql.functions.split(df['my_str_col'], '-')
df = df.withColumn('NAME1', split_col.getItem(0))
df = df.withColumn('NAME2', split_col.getItem(1))

The result will be:

col1 | my_str_col | NAME1 | NAME2
-----+------------+-------+------
  18 |  856-yygrm |   856 | yygrm
 201 |  777-psgdg |   777 | psgdg

I am not sure how I would solve this in a general case where the nested arrays were not the same size from Row to Row.

CMake complains "The CXX compiler identification is unknown"

I just had this problem setting up my new laptop. The issue for me was that my toolchain (CodeSourcery) is 32bit and I had not installed the 32bit libs.

sudo apt-get install ia32-libs

Razor/CSHTML - Any Benefit over what we have?

  1. Everything is encoded by default!!! This is pretty huge.

  2. Declarative helpers can be compiled so you don't need to do anything special to share them. I think they will replace .ascx controls to some extent. You have to jump through some hoops to use an .ascx control in another project.

  3. You can make a section required which is nice.

When to use dynamic vs. static libraries

I'd give a general rule of thumb that if you have a large codebase, all built on top of lower level libraries (eg a Utils or Gui framework), which you want to partition into more manageable libraries then make them static libraries. Dynamic libraries don't really buy you anything and there are fewer surprises -- there will only be one instance of singletons for instance.

If you have a library that is entirely separate to the rest of the codebase (eg a third party library) then consider making it a dll. If the library is LGPL you may need to use a dll anyway due to the licensing conditions.

Using DISTINCT and COUNT together in a MySQL Query

FYI, this is probably faster,

SELECT count(1) FROM (SELECT distinct productId WHERE keyword = '$keyword') temp

than this,

SELECT COUNT(DISTINCT productId) WHERE keyword='$keyword'

How to set character limit on the_content() and the_excerpt() in wordpress

This also balances HTML tags so that they won't be left open and doesn't break words.

add_filter("the_content", "break_text");
function break_text($text){
    $length = 500;
    if(strlen($text)<$length+10) return $text;//don't cut if too short

    $break_pos = strpos($text, ' ', $length);//find next space after desired length
    $visible = substr($text, 0, $break_pos);
    return balanceTags($visible) . " […]";
} 

How do I install PyCrypto on Windows?

  1. Go to "Microsoft Visual C++ Compiler for Python 2.7" and continue based on "System Requirements" (this is what I did to put below steps together).

  2. Install setuptools (setuptools 6.0 or later is required for Python to automatically detect this compiler package) either by: pip install setuptools or download "Setuptools bootstrapping installer" source from, save this file somwhere on your filestystem as "ez_python.py" and install with: python ez_python.py

  3. Install wheel (wheel is recommended for producing pre-built binary packages). You can install it with: pip install wheel

  4. Open Windows elevated Command Prompt cmd.exe (with "Run as administrator") to install "Microsoft Visual C++ Compiler for Python 2.7" for all users. You can use following command to do so: msiexec /i C:\users\jozko\download\VCForPython27.msi ALLUSERS=1 just use your own path to file: msiexec /i <path to MSI> ALLUSERS=1

  5. Now you should be able to install pycrypto with: pip install pycrypto

How to set the color of "placeholder" text?

For Firefox use:

 input:-moz-placeholder { color: #aaa; }
 textarea:-moz-placeholder { color: #aaa;}

For all other browsers (Chrome, IE, Safari), just use:

 .placeholder { color: #aaa; }

Find and replace - Add carriage return OR Newline

If you want to avoid the hassle of escaping the special characters in your search and replacement string when using regular expressions, do the following steps:

  1. Search for your original string, and replace it with "UniqueString42", with regular expressions off.
  2. Search for "UniqueString42" and replace it with "UniqueString42\nUniqueString1337", with regular expressions on
  3. Search for "UniqueString42" and replace it with the first line of your replacement (often your original string), with regular expressions off.
  4. Search for "UniqueString42" and replace it with the second line of your replacement, with regular expressions off.

Note that even if you want to manually pich matches for the first search and replace, you can safely use "replace all" for the three last steps.

Example

For example, if you want to replace this:

public IFoo SomeField { get { return this.SomeField; } }

with that:

public IFoo Foo { get { return this.MyFoo; } }
public IBar Bar { get { return this.MyBar; } }

You would do the following substitutions:

  1. public IFoo SomeField { get { return this.SomeField; } } ? XOXOXOXO (regex off).
  2. XOXOXOXO ? XOXOXOXO\nHUHUHUHU (regex on).
  3. XOXOXOXO ? public IFoo Foo { get { return this.MyFoo; } } (regex off).
  4. HUHUHUHU ? public IFoo Bar { get { return this.MyBar; } } (regex off).

Why does one use dependency injection?

Quite frankly, I believe people use these Dependency Injection libraries/frameworks because they just know how to do things in runtime, as opposed to load time. All this crazy machinery can be substituted by setting your CLASSPATH environment variable (or other language equivalent, like PYTHONPATH, LD_LIBRARY_PATH) to point to your alternative implementations (all with the same name) of a particular class. So in the accepted answer you'd just leave your code like

var logger = new Logger() //sane, simple code

And the appropriate logger will be instantiated because the JVM (or whatever other runtime or .so loader you have) would fetch it from the class configured via the environment variable mentioned above.

No need to make everything an interface, no need to have the insanity of spawning broken objects to have stuff injected into them, no need to have insane constructors with every piece of internal machinery exposed to the world. Just use the native functionality of whatever language you're using instead of coming up with dialects that won't work in any other project.

P.S.: This is also true for testing/mocking. You can very well just set your environment to load the appropriate mock class, in load time, and skip the mocking framework madness.

How to check if a socket is connected/disconnected in C#?

The best way is simply to have your client send a PING every X seconds, and for the server to assume it is disconnected after not having received one for a while.

I encountered the same issue as you when using sockets, and this was the only way I could do it. The socket.connected property was never correct.

In the end though, I switched to using WCF because it was far more reliable than sockets.

How to execute UNION without sorting? (SQL)

I assume your tables are table1 and table2 respectively, and your solution is;

(select * from table1 MINUS select * from table2)
UNION ALL
(select * from table2 MINUS select * from table1)

How can I change the version of npm using nvm?

The easy way to change version is first to check your available version using nvm ls then select version from the list nvm use version

How to set seekbar min and max value

seekbar.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {

            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {

            }

            @Override
            public void onProgressChanged(SeekBar seekBar, int progress,
                    boolean fromUser) {

                int MIN = 5;
                if (progress < MIN) {

                    value.setText(" Time Interval (" + seektime + " sec)");
                } else {
                    seektime = progress;
                }
                value.setText(" Time Interval (" + seektime + " sec)");

            }
        });

Finding the Eclipse Version Number

Based on Neeme Praks' answer, the below code should give you the version of eclipse ide you're running within.

In my case, I was running in an eclipse-derived product, so Neeme's answer just gave me the version of that product. The OP asked how to find the Eclipse version, whih is what I was after. Therefore I needed to make a couple of changes, leading me to this:

    /**
     * Attempts to get the version of the eclipse ide we're running in.
     * @return the version, or null if it couldn't be detected.
     */
    static Version getEclipseVersion() {
        String product = "org.eclipse.platform.ide";
        IExtensionRegistry registry = Platform.getExtensionRegistry();
        IExtensionPoint point = registry.getExtensionPoint("org.eclipse.core.runtime.products");
        if (point != null) {
            IExtension[] extensions = point.getExtensions();
            for (IExtension ext : extensions) {
                if (product.equals(ext.getUniqueIdentifier())) {
                    IContributor contributor = ext.getContributor();
                    if (contributor != null) {
                        Bundle bundle = Platform.getBundle(contributor.getName());
                        if (bundle != null) {
                            return bundle.getVersion();
                        }
                    }
                }
            }
        }
        return null;
    }

This will return you a convenient Version, which can be compared thus:

    private static final Version DESIRED_MINIMUM_VERSION = new Version("4.9"); //other constructors are available
    boolean haveAtLeastMinimumDesiredVersion()
        Version thisVersion = getEclipseVersion();
        if (thisVersion == null) {
            //we might have a problem
        }
        //returns a positive number if thisVersion is greater than the given parameter (desiredVersion)
        return thisVersion.compareTo(DESIRED_MINIMUM_VERSION) >= 0;
    }

django: TypeError: 'tuple' object is not callable

There is comma missing in your tuple.

insert the comma between the tuples as shown:

pack_size = (('1', '1'),('3', '3'),(b, b),(h, h),(d, d), (e, e),(r, r))

Do the same for all

How to run an .ipynb Jupyter Notebook from terminal?

From the terminal run

jupyter nbconvert --execute --to notebook --inplace --allow-errors --ExecutePreprocessor.timeout=-1 my_nb.ipynb

The default timeout is 30 seconds. -1 removes the restriction.

If you wish to save the output notebook to a new notebook you can use the flag --output my_new_nb.ipynb

How to use radio on change event?

document.addEventListener('DOMContentLoaded', () => {
  const els = document.querySelectorAll('[name="bedStatus"]');

  const capitalize = (str) =>
    `${str.charAt(0).toUpperCase()}${str.slice(1)}`;

  const handler = (e) => alert(
    `${capitalize(e.target.value)} Thai Gayo${e.target.value === 'allot' ? ' Bhai' : ''}`
  );

  els.forEach((el) => {
    el.addEventListener('change', handler);
  });
});

Tokenizing Error: java.util.regex.PatternSyntaxException, dangling metacharacter '*'

I had similar problem with regex = "?". It happens for all special characters that have some meaning in a regex. So you need to have "\\" as a prefix to your regex.

String [] separado = line.split("\\*");

Webdriver Unable to connect to host 127.0.0.1 on port 7055 after 45000 ms

This issue has haunted me for long time and I have seen one working solution in case of Firefox was to use the upgraded firefox driver.

  • If your firefox upgrades are happening automatically than you may face this problem once in a while. Looks like Firefox guys are developing too fast, or they do not care about backward compatibility.

  • Every time I see this issue on my old scripts I check if the firefox version has changed since - most of the times it is.

  • Then I go to maven repo for selenium firefox driver repo - http://mvnrepository.com/artifact/org.seleniumhq.selenium/selenium-firefox-driver and download the latest version.

  • or update my pom.xml (if maven is used) with new version of firefox driver right now its - 2.40.0

  • There is no easy way to avoid this issue unless you really explicitly block the automatied update from firefox (You can do this (On Mac) in preferences - Advanced - Update - Select "Check for updates, but let me choose whether to install them")

  • If your scripts are running on a automated mode then you may want to disable updates. However this may create other issues. Since most people/user may have firefox updates enabled by default. So your application is not really being tested on any later versions.

move_uploaded_file gives "failed to open stream: Permission denied" error

Try this

find /var/www/html/mysite/images/ -type f -print0 | xargs -0 chmod -v 664

How to check if an alert exists using WebDriver?

I would suggest to use ExpectedConditions and alertIsPresent(). ExpectedConditions is a wrapper class that implements useful conditions defined in ExpectedCondition interface.

WebDriverWait wait = new WebDriverWait(driver, 300 /*timeout in seconds*/);
if(wait.until(ExpectedConditions.alertIsPresent())==null)
    System.out.println("alert was not present");
else
    System.out.println("alert was present");

How do I find which process is leaking memory?

If you can't do it deductively, consider the Signal Flare debugging pattern: Increase the amount of memory allocated by one process by a factor of ten. Then run your program.

If the amount of the memory leaked is the same, that process was not the source of the leak; restore the process and make the same modification to the next process.

When you hit the process that is responsible, you'll see the size of your memory leak jump (the "signal flare"). You can narrow it down still further by selectively increasing the allocation size of separate statements within this process.

Creating default object from empty value in PHP?

This is a warning which I faced in PHP 7, the easy fix to this is by initializing the variable before using it

$myObj=new \stdClass();

Once you have intialized it then you can use it for objects

 $myObj->mesg ="Welcome back - ".$c_user;

jQuery - What are differences between $(document).ready and $(window).load?

The ready event is always execute at the only html page is loaded to the browser and the functions are executed.... But the load event is executed at the time of all the page contents are loaded to the browser for the page..... we can use $ or jQuery when we use the noconflict() method in jquery scripts...

Display Yes and No buttons instead of OK and Cancel in Confirm box?

As far as I know, it's not possible to change the content of the buttons, at least not easily. It's fairly easy to have your own custom alert box using JQuery UI though

AngularJS - How to use $routeParams in generating the templateUrl?

I was having a similar issue and used $stateParams instead of routeParam

'No JUnit tests found' in Eclipse

I had the same problem and solved like this: I deleted @Test annotation and retyped it. It just worked, I have no idea why.

Python Save to file

You can use this function:

def saveListToFile(listname, pathtosave):
    file1 = open(pathtosave,"w") 
    for i in listname:
        file1.writelines("{}\n".format(i))    
    file1.close() 

# to save:
saveListToFile(list, path)

What is a callback?

callback work steps:

1) we have to implement ICallbackEventHandler Interface

2) Register the client script :

 String cbReference = Page.ClientScript.GetCallbackEventReference(this, "arg", "ReceiveServerData", "context");
    String callbackScript = "function UseCallBack(arg, context)" + "{ " + cbReference + ";}";
    Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "UseCallBack", callbackScript, true);

1) from UI call Onclient click call javascript function for EX:- builpopup(p1,p2,p3...)

var finalfield= p1,p2,p3; UseCallBack(finalfield, ""); data from the client passed to server side by using UseCallBack

2) public void RaiseCallbackEvent(string eventArgument) In eventArgument we get the passed data //do some server side operation and passed to "callbackResult"

3) GetCallbackResult() // using this method data will be passed to client(ReceiveServerData() function) side

callbackResult

4) Get the data at client side: ReceiveServerData(text) , in text server response , we wil get.

How do I view the Explain Plan in Oracle Sql developer?

EXPLAIN PLAN FOR

In SQL Developer, you don't have to use EXPLAIN PLAN FOR statement. Press F10 or click the Explain Plan icon.

enter image description here

It will be then displayed in the Explain Plan window.

If you are using SQL*Plus then use DBMS_XPLAN.

For example,

SQL> EXPLAIN PLAN FOR
  2  SELECT * FROM DUAL;

Explained.

SQL> SELECT * FROM TABLE(DBMS_XPLAN.DISPLAY);

PLAN_TABLE_OUTPUT
--------------------------------------------------------------------------
Plan hash value: 272002086

--------------------------------------------------------------------------
| Id  | Operation         | Name | Rows  | Bytes | Cost (%CPU)| Time     |
--------------------------------------------------------------------------
|   0 | SELECT STATEMENT  |      |     1 |     2 |     2   (0)| 00:00:01 |
|   1 |  TABLE ACCESS FULL| DUAL |     1 |     2 |     2   (0)| 00:00:01 |
--------------------------------------------------------------------------

8 rows selected.

SQL>

See How to create and display Explain Plan

How to measure time taken by a function to execute

Since console.time and performance.now aren't supported in some major browsers (i.e. IE10), I created a slim utility that utilizes the best available methods. However, it lacks error handling for false usages (calling End() on a not initialized timer).

Use it and improve it as you want.

Performance: {
    Timer: {},
    Start: function (name) {
        if (console && console.time) {
            console.time(name);
        } else if (window.performance.now) {
            this.Timer[name] = window.performance.now();
        } else {
            this.Timer[name] = new Date().getTime();
        }
    },
    End: function (name) {
        if (console && console.time) {
            console.timeEnd(name);
        } else {
            var result;
            if (window.performance.now) {
                result = window.performance.now() - this.Timer[name];
            } else {
                result = new Date().getTime() - this.Timer[name];
            }
            console.log(name + ": " + result);
        }
    }
}

How to initialize a list with constructor?

Using a collection initializer

From C# 3, you can use collection initializers to construct a List and populate it using a single expression. The following example constructs a Human and its ContactNumbers:

var human = new Human(1, "Address", "Name") {
    ContactNumbers = new List<ContactNumber>() {
        new ContactNumber(1),
        new ContactNumber(2),
        new ContactNumber(3)
    }
}

Specializing the Human constructor

You can change the constructor of the Human class to provide a way to populate the ContactNumbers property:

public class Human
{
    public Human(int id, string address, string name, IEnumerable<ContactNumber> contactNumbers) : this(id, address, name)
    {
        ContactNumbers = new List<ContactNumber>(contactNumbers);
    }

    public Human(int id, string address, string name, params ContactNumber[] contactNumbers) : this(id, address, name)
    {
        ContactNumbers = new List<ContactNumber>(contactNumbers);
    }
}

// Using the first constructor:
List<ContactNumber> numbers = List<ContactNumber>() {
    new ContactNumber(1),
    new ContactNumber(2),
    new ContactNumber(3)
};

var human = new Human(1, "Address", "Name", numbers);

// Using the second constructor:
var human = new Human(1, "Address", "Name",
    new ContactNumber(1),
    new ContactNumber(2),
    new ContactNumber(3)
);

Bottom line

Which alternative is a best practice? Or at least a good practice? You judge it! IMO, the best practice is to write the program as clearly as possible to anyone who has to read it. Using the collection initializer is a winner for me, in this case. With much less code, it can do almost the same things as the alternatives -- at least, the alternatives I gave...

How can apply multiple background color to one div

it is compatible with all the browsers, change values to fit your application

background: #fdfdfd;
background: -moz-linear-gradient(top, #fdfdfd 0%, #f6f6f6 60%, #f2f2f2 100%);
background: -webkit-gradient(linear, left top, left bottom, color-stop(0%,#fdfdfd), color-stop(60%,#f6f6f6), color-stop(100%,#f2f2f2));
background: -webkit-linear-gradient(top, #fdfdfd 0%,#f6f6f6 60%,#f2f2f2 100%);
background: -o-linear-gradient(top, #fdfdfd 0%,#f6f6f6 60%,#f2f2f2 100%);
background: -ms-linear-gradient(top, #fdfdfd 0%,#f6f6f6 60%,#f2f2f2 100%);
background: linear-gradient(to bottom, #fdfdfd 0%,#f6f6f6 60%,#f2f2f2 100%);
filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#fdfdfd', endColorstr='#f2f2f2',GradientType=0 

SQL Server: Query fast, but slow from procedure

I found the problem, here's the script of the slow and fast versions of the stored procedure:

dbo.ViewOpener__RenamedForCruachan__Slow.PRC

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

CREATE PROCEDURE dbo.ViewOpener_RenamedForCruachan_Slow
    @SessionGUID uniqueidentifier
AS

SELECT *
FROM Report_Opener_RenamedForCruachan
WHERE SessionGUID = @SessionGUID
ORDER BY CurrencyTypeOrder, Rank
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

dbo.ViewOpener__RenamedForCruachan__Fast.PRC

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

CREATE PROCEDURE dbo.ViewOpener_RenamedForCruachan_Fast
    @SessionGUID uniqueidentifier 
AS

SELECT *
FROM Report_Opener_RenamedForCruachan
WHERE SessionGUID = @SessionGUID
ORDER BY CurrencyTypeOrder, Rank
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

If you didn't spot the difference, I don't blame you. The difference is not in the stored procedure at all. The difference that turns a fast 0.5 cost query into one that does an eager spool of 6 million rows:

Slow: SET ANSI_NULLS OFF

Fast: SET ANSI_NULLS ON


This answer also could be made to make sense, since the view does have a join clause that says:

(table.column IS NOT NULL)

So there is some NULLs involved.


The explanation is further proved by returning to Query Analizer, and running

SET ANSI_NULLS OFF

.

DECLARE @SessionGUID uniqueidentifier
SET @SessionGUID = 'BCBA333C-B6A1-4155-9833-C495F22EA908'

.

SELECT *
FROM Report_Opener_RenamedForCruachan
WHERE SessionGUID = @SessionGUID
ORDER BY CurrencyTypeOrder, Rank

And the query is slow.


So the problem isn't because the query is being run from a stored procedure. The problem is that Enterprise Manager's connection default option is ANSI_NULLS off, rather than ANSI_NULLS on, which is QA's default.

Microsoft acknowledges this fact in KB296769 (BUG: Cannot use SQL Enterprise Manager to create stored procedures containing linked server objects). The workaround is include the ANSI_NULLS option in the stored procedure dialog:

Set ANSI_NULLS ON
Go
Create Proc spXXXX as
....

How can I get an int from stdio in C?

I'm not fully sure that this is what you're looking for, but if your question is how to read an integer using <stdio.h>, then the proper syntax is

int myInt;
scanf("%d", &myInt);

You'll need to do a lot of error-handling to ensure that this works correctly, of course, but this should be a good start. In particular, you'll need to handle the cases where

  1. The stdin file is closed or broken, so you get nothing at all.
  2. The user enters something invalid.

To check for this, you can capture the return code from scanf like this:

int result = scanf("%d", &myInt);

If stdin encounters an error while reading, result will be EOF, and you can check for errors like this:

int myInt;
int result = scanf("%d", &myInt);

if (result == EOF) {
    /* ... you're not going to get any input ... */
}

If, on the other hand, the user enters something invalid, like a garbage text string, then you need to read characters out of stdin until you consume all the offending input. You can do this as follows, using the fact that scanf returns 0 if nothing was read:

int myInt;
int result = scanf("%d", &myInt);

if (result == EOF) {
    /* ... you're not going to get any input ... */
}
if (result == 0) {
    while (fgetc(stdin) != '\n') // Read until a newline is found
        ;
}

Hope this helps!

EDIT: In response to the more detailed question, here's a more appropriate answer. :-)

The problem with this code is that when you write

printf("got the number: %d", scanf("%d", &x));

This is printing the return code from scanf, which is EOF on a stream error, 0 if nothing was read, and 1 otherwise. This means that, in particular, if you enter an integer, this will always print 1 because you're printing the status code from scanf, not the number you read.

To fix this, change this to

int x;
scanf("%d", &x);
/* ... error checking as above ... */
printf("got the number: %d", x);

Hope this helps!

What is @RenderSection in asp.net MVC

If

(1) you have a _Layout.cshtml view like this

<html>
    <body>
        @RenderBody()

    </body>
    <script type="text/javascript" src="~/lib/layout.js"></script>
    @RenderSection("scripts", required: false)
</html>

(2) you have Contacts.cshtml

@section Scripts{
    <script type="text/javascript" src="~/lib/contacts.js"></script>

}
<div class="row">
    <div class="col-md-6 col-md-offset-3">
        <h2>    Contacts</h2>
    </div>
</div>

(3) you have About.cshtml

<div class="row">
    <div class="col-md-6 col-md-offset-3">
        <h2>    Contacts</h2>
    </div>
</div>

On you layout page, if required is set to false "@RenderSection("scripts", required: false)", When page renders and user is on about page, the contacts.js doesn't render.

    <html>
        <body><div>About<div>             
        </body>
        <script type="text/javascript" src="~/lib/layout.js"></script>
    </html>

if required is set to true "@RenderSection("scripts", required: true)", When page renders and user is on ABOUT page, the contacts.js STILL gets rendered.

<html>
    <body><div>About<div>             
    </body>
    <script type="text/javascript" src="~/lib/layout.js"></script>
    <script type="text/javascript" src="~/lib/contacts.js"></script>
</html>

IN SHORT, when set to true, whether you need it or not on other pages, it will get rendered anyhow. If set to false, it will render only when the child page is rendered.

Stop absolutely positioned div from overlapping text

If you are working with elements of unknown size, and you want to use position: absolute on them or their siblings, you're inevitably going to have to deal with overlap. By setting absolute position you're removing the element from the document flow, but the behaviour you want is that your element should be be pushed around by its siblings so as not to overlap...ie it should flow! You're seeking two totally contradictory things.

You should rethink your layout.

Perhaps what you want is that the .btn element should be absolutely positioned with respect to one of its preceding siblings, rather than against their common parent? In that case, you should set position: relative on the element you'd like to position the button against, and then make the button a child of that element. Now you can use absolute positioning and control overlap.

Android Emulator sdcard push error: Read-only file system

I think the problem here is that you forgot to set SD card size

Follow these steps to make it work:

  1. step1: close running emulator
  2. step2: open Android Virtual Device Manager(eclipse menu bar)
  3. step3: choose your emulator -> Edit -> then set SD card size

This works well in my emulator!

seek() function?

When you open a file, the system points to the beginning of the file. Any read or write you do will happen from the beginning. A seek() operation moves that pointer to some other part of the file so you can read or write at that place.

So, if you want to read the whole file but skip the first 20 bytes, open the file, seek(20) to move to where you want to start reading, then continue with reading the file.

Or say you want to read every 10th byte, you could write a loop that does seek(9, 1) (moves 9 bytes forward relative to the current positions), read(1) (reads one byte), repeat.

Find Active Tab using jQuery and Twitter Bootstrap

Here is the answer for those of you who need a Boostrap 3 solution.

In bootstrap 3 use 'shown.bs.tab' instead of 'shown' in the next line

// tab
$('#rowTab a:first').tab('show');

$('a[data-toggle="tab"]').on('shown.bs.tab', function (e) {
//show selected tab / active
 console.log ( $(e.target).attr('id') );
});

How do I drop a MongoDB database from the command line?

In you command prompt, First connect to mongodb using following command:

mongo -h [host-name]:[port:number] -d [dbname] -u [username] -p [password]

you will be accessing db with <dbname>.

Run the following command to drop the whole database:

db.dropDatabase()

Custom HTTP Authorization Header

Put it in a separate, custom header.

Overloading the standard HTTP headers is probably going to cause more confusion than it's worth, and will violate the principle of least surprise. It might also lead to interoperability problems for your API client programmers who want to use off-the-shelf tool kits that can only deal with the standard form of typical HTTP headers (such as Authorization).

Utility of HTTP header "Content-Type: application/force-download" for mobile?

application/force-download is not a standard MIME type. It's a hack supported by some browsers, added fairly recently.

Your question doesn't really make any sense. It's like asking why Internet Explorer 4 doesn't support the latest CSS 3 functionality.

Node.js: Gzip compression?

How about this?

node-compress
A streaming compression / gzip module for node.js
To install, ensure that you have libz installed, and run:
node-waf configure
node-waf build
This will put the compress.node binary module in build/default.
...

Eclipse Java error: This selection cannot be launched and there are no recent launches

Make sure the "m" in main() is lowercase this would also cause java not to see your main method, I've done that several times unfortunately.

Finding duplicate integers in an array and display how many times they occurred

You can check the following codes. The codes are working.

 class Program {
    static void Main(string[] args) {
      int[] array = { 10, 5, 10, 2, 2, 3, 4, 5, 5, 6, 7, 8, 9, 11, 12, 12 };
      int count = 1;
      for (int i = 0; i < array.Length; i++) {
        for (int j = i + 1; j < array.Length; j++) {

          if (array[j] == array[j])
            count = count + 1;
        }
        Console.WriteLine("\t\n " + array[i] + " out of " + count);
        Console.ReadKey();
      }
    }
  }

How to implement an STL-style iterator and avoid common pitfalls?

http://www.cplusplus.com/reference/std/iterator/ has a handy chart that details the specs of § 24.2.2 of the C++11 standard. Basically, the iterators have tags that describe the valid operations, and the tags have a hierarchy. Below is purely symbolic, these classes don't actually exist as such.

iterator {
    iterator(const iterator&);
    ~iterator();
    iterator& operator=(const iterator&);
    iterator& operator++(); //prefix increment
    reference operator*() const;
    friend void swap(iterator& lhs, iterator& rhs); //C++11 I think
};

input_iterator : public virtual iterator {
    iterator operator++(int); //postfix increment
    value_type operator*() const;
    pointer operator->() const;
    friend bool operator==(const iterator&, const iterator&);
    friend bool operator!=(const iterator&, const iterator&); 
};
//once an input iterator has been dereferenced, it is 
//undefined to dereference one before that.

output_iterator : public virtual iterator {
    reference operator*() const;
    iterator operator++(int); //postfix increment
};
//dereferences may only be on the left side of an assignment
//once an output iterator has been dereferenced, it is 
//undefined to dereference one before that.

forward_iterator : input_iterator, output_iterator {
    forward_iterator();
};
//multiple passes allowed

bidirectional_iterator : forward_iterator {
    iterator& operator--(); //prefix decrement
    iterator operator--(int); //postfix decrement
};

random_access_iterator : bidirectional_iterator {
    friend bool operator<(const iterator&, const iterator&);
    friend bool operator>(const iterator&, const iterator&);
    friend bool operator<=(const iterator&, const iterator&);
    friend bool operator>=(const iterator&, const iterator&);

    iterator& operator+=(size_type);
    friend iterator operator+(const iterator&, size_type);
    friend iterator operator+(size_type, const iterator&);
    iterator& operator-=(size_type);  
    friend iterator operator-(const iterator&, size_type);
    friend difference_type operator-(iterator, iterator);

    reference operator[](size_type) const;
};

contiguous_iterator : random_access_iterator { //C++17
}; //elements are stored contiguously in memory.

You can either specialize std::iterator_traits<youriterator>, or put the same typedefs in the iterator itself, or inherit from std::iterator (which has these typedefs). I prefer the second option, to avoid changing things in the std namespace, and for readability, but most people inherit from std::iterator.

struct std::iterator_traits<youriterator> {        
    typedef ???? difference_type; //almost always ptrdiff_t
    typedef ???? value_type; //almost always T
    typedef ???? reference; //almost always T& or const T&
    typedef ???? pointer; //almost always T* or const T*
    typedef ???? iterator_category;  //usually std::forward_iterator_tag or similar
};

Note the iterator_category should be one of std::input_iterator_tag, std::output_iterator_tag, std::forward_iterator_tag, std::bidirectional_iterator_tag, or std::random_access_iterator_tag, depending on which requirements your iterator satisfies. Depending on your iterator, you may choose to specialize std::next, std::prev, std::advance, and std::distance as well, but this is rarely needed. In extremely rare cases you may wish to specialize std::begin and std::end.

Your container should probably also have a const_iterator, which is a (possibly mutable) iterator to constant data that is similar to your iterator except it should be implicitly constructable from a iterator and users should be unable to modify the data. It is common for its internal pointer to be a pointer to non-constant data, and have iterator inherit from const_iterator so as to minimize code duplication.

My post at Writing your own STL Container has a more complete container/iterator prototype.

Easy way to print Perl array? (with a little formatting)

I've not tried to run below, though. I think this's a tricky way.

map{print $_;} @array;

Null & empty string comparison in Bash

fedorqui has a working solution but there is another way to do the same thing.

Chock if a variable is set

#!/bin/bash
amIEmpty='Hello'
# This will be true if the variable has a value
if [ $amIEmpty ]; then
    echo 'No, I am not!';
fi

Or to verify that a variable is empty

#!/bin/bash      
amIEmpty=''
# This will be true if the variable is empty
if [ ! $amIEmpty ]; then
    echo 'Yes I am!';
fi

tldp.org has good documentation about if in bash:
http://tldp.org/LDP/Bash-Beginners-Guide/html/sect_07_01.html

Convert string to variable name in python

This is the best way, I know of to create dynamic variables in python.

my_dict = {}
x = "Buffalo"
my_dict[x] = 4

I found a similar, but not the same question here Creating dynamically named variables from user input

Bootstrap 3 collapse accordion: collapse all works but then cannot expand all while maintaining data-parent

The best and tested solution is to put the following small snippet which will collapse the accordion tab which is already open when you load. In my case the last sixth tab was open so I made it collapsed on page load.

 $(document).ready(){
      $('#collapseSix').collapse("hide");
 }

Setting Remote Webdriver to run tests in a remote computer using Java

You have to install a Selenium Server (a Hub) and register your remote WebDriver to it. Then, your client will talk to the Hub which will find a matching WebDriver to execute your test.

You can have a look at here for more information.

putting datepicker() on dynamically created elements - JQuery/JQueryUI

This was what worked for me (using jquery datepicker):

$('body').on('focus', '.datepicker', function() {
 $(this).removeClass('hasDatepicker').datepicker();
});

Adding an arbitrary line to a matplotlib plot in ipython notebook

Matplolib now allows for 'annotation lines' as the OP was seeking. The annotate() function allows several forms of connecting paths and a headless and tailess arrow, i.e., a simple line, is one of them.

ax.annotate("",
            xy=(0.2, 0.2), xycoords='data',
            xytext=(0.8, 0.8), textcoords='data',
            arrowprops=dict(arrowstyle="-",
                      connectionstyle="arc3, rad=0"),
            )

In the documentation it says you can draw only an arrow with an empty string as the first argument.

From the OP's example:

%matplotlib notebook
import numpy as np
import matplotlib.pyplot as plt

np.random.seed(5)
x = np.arange(1, 101)
y = 20 + 3 * x + np.random.normal(0, 60, 100)
plt.plot(x, y, "o")


# draw vertical line from (70,100) to (70, 250)
plt.annotate("",
              xy=(70, 100), xycoords='data',
              xytext=(70, 250), textcoords='data',
              arrowprops=dict(arrowstyle="-",
                              connectionstyle="arc3,rad=0."), 
              )

# draw diagonal line from (70, 90) to (90, 200)
plt.annotate("",
              xy=(70, 90), xycoords='data',
              xytext=(90, 200), textcoords='data',
              arrowprops=dict(arrowstyle="-",
                              connectionstyle="arc3,rad=0."), 
              )

plt.show()

Example inline image

Just as in the approach in gcalmettes's answer, you can choose the color, line width, line style, etc..

Here is an alteration to a portion of the code that would make one of the two example lines red, wider, and not 100% opaque.

# draw vertical line from (70,100) to (70, 250)
plt.annotate("",
              xy=(70, 100), xycoords='data',
              xytext=(70, 250), textcoords='data',
              arrowprops=dict(arrowstyle="-",
                              edgecolor = "red",
                              linewidth=5,
                              alpha=0.65,
                              connectionstyle="arc3,rad=0."), 
              )

You can also add curve to the connecting line by adjusting the connectionstyle.

Detecting arrow key presses in JavaScript

If you use jquery then you can also do like this,

 $(document).on("keydown", '.class_name', function (event) {
    if (event.keyCode == 37) {
        console.log('left arrow pressed');
    }
    if (event.keyCode == 38) {
        console.log('up arrow pressed');
    }
    if (event.keyCode == 39) {
        console.log('right arrow pressed');
    }
    if (event.keyCode == 40) {
        console.log('down arrow pressed');
    }
 });

How to get the body's content of an iframe in Javascript?

Chalkey is correct, you need to use the src attribute to specify the page to be contained in the iframe. Providing you do this, and the document in the iframe is in the same domain as the parent document, you can use this:

var e = document.getElementById("id_description_iframe");
if(e != null) {
   alert(e.contentWindow.document.body.innerHTML);
}

Obviously you can then do something useful with the contents instead of just putting them in an alert.

6 digits regular expression

You could try

^[0-9]{1,6}$

it should work.

Difference between core and processor

I have read all answers, but this link was more clear explanation for me about difference between CPU(Processor) and Core. So I'm leaving here some notes from there.

The main difference between CPU and Core is that the CPU is an electronic circuit inside the computer that carries out instruction to perform arithmetic, logical, control and input/output operations while the core is an execution unit inside the CPU that receives and executes instructions.

enter image description here

How to make an HTTP POST web request

Simple GET request

using System.Net;

...

using (var wb = new WebClient())
{
    var response = wb.DownloadString(url);
}

Simple POST request

using System.Net;
using System.Collections.Specialized;

...

using (var wb = new WebClient())
{
    var data = new NameValueCollection();
    data["username"] = "myUser";
    data["password"] = "myPassword";

    var response = wb.UploadValues(url, "POST", data);
    string responseInString = Encoding.UTF8.GetString(response);
}

Extract only right most n letters from a string

Write an extension method to express the Right(n); function. The function should deal with null or empty strings returning an empty string, strings shorter than the max length returning the original string and strings longer than the max length returning the max length of rightmost characters.

public static string Right(this string sValue, int iMaxLength)
{
  //Check if the value is valid
  if (string.IsNullOrEmpty(sValue))
  {
    //Set valid empty string as string could be null
    sValue = string.Empty;
  }
  else if (sValue.Length > iMaxLength)
  {
    //Make the string no longer than the max length
    sValue = sValue.Substring(sValue.Length - iMaxLength, iMaxLength);
  }

  //Return the string
  return sValue;
}

What's the difference between commit() and apply() in SharedPreferences

I'm experiencing some problems using apply() instead commit(). As stated before in other responses, the apply() is asynchronous. I'm getting the problem that the changes formed to a "string set" preference are never written to the persistent memory.

It happens if you "force detention" of the program or, in the ROM that I have installed on my device with Android 4.1, when the process is killed by the system due to memory necessities.

I recommend to use "commit()" instead "apply()" if you want your preferences alive.

Adding a SVN repository in Eclipse

It worked for me, In eclipse: Window > Preference > Team > SVN: select SVNKit (Pure Java) instead JavaHL(JNI)

How to set height property for SPAN

Use

.title{
  display: inline-block;
  height: 25px;
}

The only trick is browser support. Check if your list of supported browsers handles inline-block here.

Run class in Jar file

Assuming you are in the directory where myJar.jar file is and that myClass has a public static void main() method on it:

You use the following command line:

java -cp ./myJar.jar myClass

Where:

  1. myJar.jar is in the current path, note that . isn't in the current path on most systems. A fully qualified path is preferred here as well.

  2. myClass is a fully qualified package path to the class, the example assumes that myClass is in the default package which is bad practice, if it is in a nested package it would be com.mycompany.mycode.myClass.

How to run html file using node js

http access and get the html files served on 8080:

>npm install -g http-server

>http-server

if you have public (./public/index.html) folder it will be the root of your server if not will be the one that you run the server. you could send the folder as paramenter ex:

http-server [path] [options]

expected Result:

*> Starting up http-server, serving ./public Available on:

http://LOCALIP:8080

http://127.0.0.1:8080

Hit CTRL-C to stop the server

http-server stopped.*

Now, you can run: http://localhost:8080

will open the index.html on the ./public folder

references: https://www.npmjs.com/package/http-server

How do I convert a list into a string with spaces in Python?

" ".join(my_list)

you need to join with a space not an empty string ...

Android webview launches browser when calling loadurl

If you're using webChromeClient I'll suggest you to use webChromeClient and webViewClient together. because webChromeClient does not provides shouldOverrideUrlLoading. It is okay to use both.

        webview.webViewClient = WebViewClient()
        webview.webChromeClient = Callback()

private inner class Callback : WebChromeClient() {
        override fun onProgressChanged(view: WebView?, newProgress: Int) {
            super.onProgressChanged(view, newProgress)
           
            if (newProgress == 0) {
                progressBar.visibility = View.VISIBLE
            } else if (newProgress == 100) {
                progressBar.visibility = View.GONE
            }
        }

    }

You have not concluded your merge (MERGE_HEAD exists)

This worked for me:

git log
`git reset --hard <089810b5be5e907ad9e3b01f>`
git pull
git status

Android ListView Text Color

  1. Create a styles file, for example: my_styles.xml and save it in res/values.
  2. Add the following code:

    <?xml version="1.0" encoding="utf-8"?>
    <resources>
    
    <style name="ListFont" parent="@android:style/Widget.ListView">
        <item name="android:textColor">#FF0000</item>
        <item name="android:typeface">sans</item>
    </style>
    
    </resources>
    
  3. Add your style to your Activity definition in your AndroidManifest.xml as an android:theme attribute, and assign as value the name of the style you created. For example:

    <activity android:name="your.activityClass" android:theme="@style/ListFont">
    

NOTE: the Widget.ListView comes from here. Also check this.

Convert timestamp long to normal date format

I tried this and worked for me.

Date = (long)(DateTime.Now.Subtract(new DateTime(1970, 1, 1, 0, 0, 0))).TotalSeconds

How can I pretty-print JSON using Go?

//You can do it with json.MarshalIndent(data, "", "  ")

package main

import(
  "fmt"
  "encoding/json" //Import package
)

//Create struct
type Users struct {
    ID   int
    NAME string
}

//Asign struct
var user []Users
func main() {
 //Append data to variable user
 user = append(user, Users{1, "Saturn Rings"})
 //Use json package the blank spaces are for the indent
 data, _ := json.MarshalIndent(user, "", "  ")
 //Print json formatted
 fmt.Println(string(data))
}

S3 Static Website Hosting Route All Paths to Index.html

There are few problems with the S3/Redirect based approach mentioned by others.

  1. Mutliple redirects happen as your app's paths are resolved. For example: www.myapp.com/path/for/test gets redirected as www.myapp.com/#/path/for/test
  2. There is a flicker in the url bar as the '#' comes and goes due the action of your SPA framework.
  3. The seo is impacted because - 'Hey! Its google forcing his hand on redirects'
  4. Safari support for your app goes for a toss.

The solution is:

  1. Make sure you have the index route configured for your website. Mostly it is index.html
  2. Remove routing rules from S3 configurations
  3. Put a Cloudfront in front of your S3 bucket.
  4. Configure error page rules for your Cloudfront instance. In the error rules specify:

    • Http error code: 404 (and 403 or other errors as per need)
    • Error Caching Minimum TTL (seconds) : 0
    • Customize response: Yes
    • Response Page Path : /index.html
    • HTTP Response Code: 200

      1. For SEO needs + making sure your index.html does not cache, do the following:
    • Configure an EC2 instance and setup an nginx server.

    • Assign a public ip to your EC2 instance.
    • Create an ELB that has the EC2 instance you created as an instance
    • You should be able to assign the ELB to your DNS.
    • Now, configure your nginx server to do the following things: Proxy_pass all requests to your CDN (for index.html only, serve other assets directly from your cloudfront) and for search bots, redirect traffic as stipulated by services like Prerender.io

I can help in more details with respect to nginx setup, just leave a note. Have learnt it the hard way.

Once the cloud front distribution update. Invalidate your cloudfront cache once to be in the pristine mode. Hit the url in the browser and all should be good.

SQL Server: UPDATE a table by using ORDER BY

IF OBJECT_ID('tempdb..#TAB') IS NOT NULL
BEGIN
    DROP TABLE #TAB
END

CREATE TABLE #TAB(CH1 INT,CH2 INT,CH3 INT)

DECLARE @CH2 INT = NULL , @CH3 INT=NULL,@SPID INT=NULL,@SQL NVARCHAR(4000)='', @ParmDefinition NVARCHAR(50)= '',
@RET_MESSAGE AS VARCHAR(8000)='',@RET_ERROR INT=0


SET @ParmDefinition='@SPID INT,@CH2 INT OUTPUT,@CH3 INT OUTPUT'

SET @SQL='UPDATE T
            SET CH1=@SPID,@CH2= T.CH2,@CH3= T.CH3
            FROM #TAB T WITH(ROWLOCK)
            INNER JOIN (
                        SELECT TOP(1)  CH1,CH2,CH3
                        FROM
                        #TAB WITH(NOLOCK)
                        WHERE CH1 IS NULL
                        ORDER BY CH2 DESC) V ON T.CH2= V.CH2 AND T.CH3= V.CH3' 

INSERT INTO #TAB
(CH2 ,CH3 )
SELECT 1,2 UNION ALL
SELECT 2,3 UNION ALL
SELECT 3,4

BEGIN TRY
    WHILE EXISTS(SELECT TOP 1 1 FROM #TAB WHERE CH1 IS NULL)
    BEGIN

        EXECUTE @RET_ERROR = sp_executesql @SQL, @ParmDefinition,@SPID =@@SPID,  @CH2=@CH2 OUTPUT,@CH3=@CH3 OUTPUT;  

        SELECT * FROM #TAB
        SELECT @CH2,@CH3

    END

END TRY
BEGIN CATCH

    SET @RET_ERROR=ERROR_NUMBER()
    SET @RET_MESSAGE =  '@ERROR_NUMBER : ' + CAST(ERROR_NUMBER()  AS VARCHAR(255)) + '@ERROR_SEVERITY  :' + CAST( ERROR_SEVERITY()  AS VARCHAR(255)) 
    + '@ERROR_STATE :' + CAST(ERROR_STATE() AS VARCHAR(255)) + '@ERROR_LINE :' + CAST( ERROR_LINE() AS VARCHAR(255)) 
    +  '@ERROR_MESSAGE :' + ERROR_MESSAGE()  ;

    SELECT @RET_ERROR,@RET_MESSAGE;

END CATCH

What is the difference between Bower and npm?

For many people working with node.js, a major benefit of bower is for managing dependencies that are not javascript at all. If they are working with languages that compile to javascript, npm can be used to manage some of their dependencies. however, not all their dependencies are going to be node.js modules. Some of those that compile to javascript may have weird source language specific mangling that makes passing them around compiled to javascript an inelegant option when users are expecting source code.

Not everything in an npm package needs to be user-facing javascript, but for npm library packages, at least some of it should be.

Redeploy alternatives to JRebel

I have written an article about DCEVM: Spring-mvc + Velocity + DCEVM

I think it's worth it, since my environment is running without any problems.

How to change to an older version of Node.js

nvm install 0.5.0 #install previous version of choice

nvm alias default 0.5.0 #set it to default

nvm use default #use the new default as active version globally.

Without the last, the active version doesn't change to the new default. So, when you open a new terminal or restart server, the old default version remains active.

What is an efficient way to implement a singleton pattern in Java?

Another argument often used against singletons is their testability problems. Singletons are not easily mockable for testing purposes. If this turns out to be a problem, I like to make the following slight modification:

public class SingletonImpl {

    private static SingletonImpl instance;

    public static SingletonImpl getInstance() {
        if (instance == null) {
            instance = new SingletonImpl();
        }
        return instance;
    }

    public static void setInstance(SingletonImpl impl) {
        instance = impl;
    }

    public void a() {
        System.out.println("Default Method");
    }
}

The added setInstance method allows setting a mockup implementation of the singleton class during testing:

public class SingletonMock extends SingletonImpl {

    @Override
    public void a() {
        System.out.println("Mock Method");
    }

}

This also works with early initialization approaches:

public class SingletonImpl {

    private static final SingletonImpl instance = new SingletonImpl();

    private static SingletonImpl alt;

    public static void setInstance(SingletonImpl inst) {
        alt = inst;
    }

    public static SingletonImpl getInstance() {
        if (alt != null) {
            return alt;
        }
        return instance;
    }

    public void a() {
        System.out.println("Default Method");
    }
}

public class SingletonMock extends SingletonImpl {

    @Override
    public void a() {
        System.out.println("Mock Method");
    }

}

This has the drawback of exposing this functionality to the normal application too. Other developers working on that code could be tempted to use the ´setInstance´ method to alter a specific function and thus changing the whole application behaviour, and therefore this method should contain at least a good warning in its javadoc.

Still, for the possibility of mockup-testing (when needed), this code exposure may be an acceptable price to pay.

How to concatenate characters in java?

You can use the String constructor.

System.out.println(new String(new char[]{a,b,c}));

jQuery getTime function

this is my way :

    <script type="text/javascript">
$(document).ready(function() {
    setInterval(function(){currentTime("#idTimeField")}, 500);
});
function currentTime(field) {
    var now = new Date();
    now = now.getHours() + ':' + now.getMinutes() + ':' + now.getSeconds();
    $(field).val(now);
}

it's not maybe the best but do the work :)

Ruby replace string with captured regex pattern

Try '\1' for the replacement (single quotes are important, otherwise you need to escape the \):

"foo".gsub(/(o+)/, '\1\1\1')
#=> "foooooo"

But since you only seem to be interested in the capture group, note that you can index a string with a regex:

"foo"[/oo/]
#=> "oo"
"Z_123: foobar"[/^Z_.*(?=:)/]
#=> "Z_123"

How do I add more members to my ENUM-type column in MySQL?

In MYSQL server version: 5.0.27 i tried this and it worked fine for me check in your version

ALTER TABLE carmake
     MODIFY `country` ENUM('Japan', 'USA', 'England', 'Australia', 'Germany', 'France', 'Italy', 'Spain', 'Czech Republic', 'China', 'South Korea', 'India', 'Sweden', 'Malaysia');

How to dynamically add rows to a table in ASP.NET?

You can use the asp:Table in your web form and build it via code:

http://msdn.microsoft.com/en-us/library/7bewx260.aspx

Also, check out asp.net for tutorials and such.

How do you fix the "element not interactable" exception?

Found a workaround years later after encountering the same problem again - unable to click element even though it SHOULD be clickable. The solution is to catch ElementNotInteractable exception and attempt to execute a script to click the element.

Example in Typescript

async clickElement(element: WebElement) {
    try {
        return await element.click();
    } catch (error) {
        if (error.name == 'ElementNotInteractableError') {
            return await this.driver.executeScript((element: WebElement) => {
                element.click();
            }, element);
        }
    }
}

Maximum size of a varchar(max) variable

As far as I can tell there is no upper limit in 2008.

In SQL Server 2005 the code in your question fails on the assignment to the @GGMMsg variable with

Attempting to grow LOB beyond maximum allowed size of 2,147,483,647 bytes.

the code below fails with

REPLICATE: The length of the result exceeds the length limit (2GB) of the target large type.

However it appears these limitations have quietly been lifted. On 2008

DECLARE @y VARCHAR(MAX) = REPLICATE(CAST('X' AS VARCHAR(MAX)),92681); 

SET @y = REPLICATE(@y,92681);

SELECT LEN(@y) 

Returns

8589767761

I ran this on my 32 bit desktop machine so this 8GB string is way in excess of addressable memory

Running

select internal_objects_alloc_page_count
from sys.dm_db_task_space_usage
WHERE session_id = @@spid

Returned

internal_objects_alloc_page_co 
------------------------------ 
2144456    

so I presume this all just gets stored in LOB pages in tempdb with no validation on length. The page count growth was all associated with the SET @y = REPLICATE(@y,92681); statement. The initial variable assignment to @y and the LEN calculation did not increase this.

The reason for mentioning this is because the page count is hugely more than I was expecting. Assuming an 8KB page then this works out at 16.36 GB which is obviously more or less double what would seem to be necessary. I speculate that this is likely due to the inefficiency of the string concatenation operation needing to copy the entire huge string and append a chunk on to the end rather than being able to add to the end of the existing string. Unfortunately at the moment the .WRITE method isn't supported for varchar(max) variables.

Addition

I've also tested the behaviour with concatenating nvarchar(max) + nvarchar(max) and nvarchar(max) + varchar(max). Both of these allow the 2GB limit to be exceeded. Trying to then store the results of this in a table then fails however with the error message Attempting to grow LOB beyond maximum allowed size of 2147483647 bytes. again. The script for that is below (may take a long time to run).

DECLARE @y1 VARCHAR(MAX) = REPLICATE(CAST('X' AS VARCHAR(MAX)),2147483647); 
SET @y1 = @y1 + @y1;
SELECT LEN(@y1), DATALENGTH(@y1)  /*4294967294, 4294967292*/


DECLARE @y2 NVARCHAR(MAX) = REPLICATE(CAST('X' AS NVARCHAR(MAX)),1073741823); 
SET @y2 = @y2 + @y2;
SELECT LEN(@y2), DATALENGTH(@y2)  /*2147483646, 4294967292*/


DECLARE @y3 NVARCHAR(MAX) = @y2 + @y1
SELECT LEN(@y3), DATALENGTH(@y3)   /*6442450940, 12884901880*/

/*This attempt fails*/
SELECT @y1 y1, @y2 y2, @y3 y3
INTO Test

Read response body in JAX-RS client from a post request

Realizing the revision of the code I found the cause of why the reading method did not work for me. The problem was that one of the dependencies that my project used jersey 1.x. Update the version, adjust the client and it works.

I use the following maven dependency:

<dependency>
<groupId>org.glassfish.jersey.core</groupId>
<artifactId>jersey-client</artifactId>
<version>2.28</version>

Regards

Carlos Cepeda

Secure FTP using Windows batch script

The built in FTP command doesn't have a facility for security. Use cUrl instead. It's scriptable, far more robust and has FTP security.

Why call super() in a constructor?

A call to your parent class's empty constructor super() is done automatically when you don't do it yourself. That's the reason you've never had to do it in your code. It was done for you.

When your superclass doesn't have a no-arg constructor, the compiler will require you to call super with the appropriate arguments. The compiler will make sure that you instantiate the class correctly. So this is not something you have to worry about too much.

Whether you call super() in your constructor or not, it doesn't affect your ability to call the methods of your parent class.

As a side note, some say that it's generally best to make that call manually for reasons of clarity.

Nginx not picking up site in sites-enabled?

Changing from:

include /etc/nginx/sites-enabled/*; 

to

include /etc/nginx/sites-enabled/*.*; 

fixed my issue

How do I make background-size work in IE?

Even later, but this could be usefull too. There is the jQuery-backstretch-plugin you can use as a polyfill for background-size: cover. I guess it must be possible (and fairly simple) to grab the css-background-url property with jQuery and feed it to the jQuery-backstretch plugin. Good practice would be to test for background-size-support with modernizr and use this plugin as a fallback.

The backstretch-plugin was mentioned on SO here.The jQuery-backstretch-plugin-site is here.

In similar fashion you could make a jQuery-plugin or script that makes background-size work in your situation (background-size: 100%) and in IE8-. So to answer your question: Yes there is a way but atm there is no plug-and-play solution (ie you have to do some coding yourself).

(disclaimer: I didn't examine the backstretch-plugin thoroughly but it seems to do the same as background-size: cover)

No 'Access-Control-Allow-Origin' header in Angular 2 app

I also encountered the same problem and passed the following way to solve this problem.

step 1:

$ npm install --save-dev http-proxy-middleware

step 2:

add a proxy when i fetch web api, if you use lite-server you can add a file bs-config.js .

//file: bs-config.js
var proxyMiddleware = require('http-proxy-middleware');

module.exports = {
    server: {
        middleware: {
            1: proxyMiddleware('/example-api', {
                target: 'http://api.example.com',
                changeOrigin: true,
                pathRewrite: {
                '^/news-at-api': '/api'
                }
            })
        }
    }
};

hope this helps.

Print "hello world" every X seconds

Try doing this:

Timer t = new Timer();
t.schedule(new TimerTask() {
    @Override
    public void run() {
       System.out.println("Hello World");
    }
}, 0, 5000);

This code will run print to console Hello World every 5000 milliseconds (5 seconds). For more info, read https://docs.oracle.com/javase/1.5.0/docs/api/java/util/Timer.html

Is there a command line utility for rendering GitHub flavored Markdown?

I've not found a quick and easy method for GitHub-flavoured Markdown, but I have found a slightly more generic version - Pandoc. It converts from/to a number of formats, including Markdown, Rest, HTML and others.

I've also developed a Makefile to convert all .md files to .html (in large part to the example at Writing, Markdown and Pandoc):

# 'Makefile'
MARKDOWN = pandoc --from gfm --to html --standalone
all: $(patsubst %.md,%.html,$(wildcard *.md)) Makefile

clean:
    rm -f $(patsubst %.md,%.html,$(wildcard *.md))
    rm -f *.bak *~

%.html: %.md
    $(MARKDOWN) $< --output $@

How to get memory available or used in C#

For the complete system you can add the Microsoft.VisualBasic Framework as a reference;

 Console.WriteLine("You have {0} bytes of RAM",
        new Microsoft.VisualBasic.Devices.ComputerInfo().TotalPhysicalMemory);
        Console.ReadLine();

How can I preview a merge in git?

If you're like me, you're looking for equivalent to svn update -n. The following appears to do the trick. Note that make sure to do a git fetch first so that your local repo has the appropriate updates to compare against.

$ git fetch origin
$ git diff --name-status origin/master
D       TableAudit/Step0_DeleteOldFiles.sh
D       TableAudit/Step1_PopulateRawTableList.sh
A       manbuild/staff_companies.sql
M       update-all-slave-dbs.sh

or if you want a diff from your head to the remote:

$ git fetch origin
$ git diff origin/master

IMO this solution is much easier and less error prone (and therefore much less risky) than the top solution which proposes "merge then abort".

Plot size and resolution with R markdown, knitr, pandoc, beamer

I think that is a frequently asked question about the behavior of figures in beamer slides produced from Pandoc and markdown. The real problem is, R Markdown produces PNG images by default (from knitr), and it is hard to get the size of PNG images correct in LaTeX by default (I do not know why). It is fairly easy, however, to get the size of PDF images correct. One solution is to reset the default graphical device to PDF in your first chunk:

```{r setup, include=FALSE}
knitr::opts_chunk$set(dev = 'pdf')
```

Then all the images will be written as PDF files, and LaTeX will be happy.

Your second problem is you are mixing up the HTML units with LaTeX units in out.width / out.height. LaTeX and HTML are very different technologies. You should not expect \maxwidth to work in HTML, or 200px in LaTeX. Especially when you want to convert Markdown to LaTeX, you'd better not set out.width / out.height (use fig.width / fig.height and let LaTeX use the original size).

LEFT INNER JOIN vs. LEFT OUTER JOIN - Why does the OUTER take longer?

This is because the LEFT OUTER Join is doing more work than an INNER Join BEFORE sending the results back.

The Inner Join looks for all records where the ON statement is true (So when it creates a new table, it only puts in records that match the m.SubID = a.SubID). Then it compares those results to your WHERE statement (Your last modified time).

The Left Outer Join...Takes all of the records in your first table. If the ON statement is not true (m.SubID does not equal a.SubID), it simply NULLS the values in the second table's column for that recordset.

The reason you get the same number of results at the end is probably coincidence due to the WHERE clause that happens AFTER all of the copying of records.

Join (SQL) Wikipedia

Print an integer in binary format in Java

public static void main(String[] args) 
{
    int i = 13;
    short s = 13;
    byte b = 13;

    System.out.println("i: " + String.format("%32s", 
            Integer.toBinaryString(i)).replaceAll(" ", "0"));

    System.out.println("s: " + String.format("%16s", 
            Integer.toBinaryString(0xFFFF & s)).replaceAll(" ", "0"));

    System.out.println("b: " + String.format("%8s", 
            Integer.toBinaryString(0xFF & b)).replaceAll(" ", "0"));

}

Output:

i: 00000000000000000000000000001101
s: 0000000000001101
b: 00001101

define a List like List<int,string>?

Use C# Dictionary datastructure it good for you...

Dictionary<string, int> dict = new Dictionary<string, int>();
dict.Add("one", 1);
dict.Add("two", 2);

You can retrieve data from Ditionary in a simple way..

foreach (KeyValuePair<string, int> pair in dict)
{
    MessageBox.Show(pair.Key.ToString ()+ "  -  "  + pair.Value.ToString () );
}

For more example using C# Dictionary... C# Dictionary

Navi.

MongoDB SELECT COUNT GROUP BY

This would be the easier way to do it using aggregate:

db.contest.aggregate([
    {"$group" : {_id:"$province", count:{$sum:1}}}
])

TypeLoadException says 'no implementation', but it is implemented

I also ran into this problem while running my unittests. The application ran fine and with no errors. The cause of the problem in my case was that I had turned off the building of the test projects. Reenabling the building of my testprojects solved the issues.

How do I use a third-party DLL file in Visual Studio C++?

These are two ways of using a DLL file in Windows:

  1. There is a stub library (.lib) with associated header files. When you link your executable with the lib-file it will automatically load the DLL file when starting the program.

  2. Loading the DLL manually. This is typically what you want to do if you are developing a plugin system where there are many DLL files implementing a common interface. Check out the documentation for LoadLibrary and GetProcAddress for more information on this.

For Qt I would suspect there are headers and a static library available that you can include and link in your project.

Event system in Python

You may have a look at pymitter (pypi). Its a small single-file (~250 loc) approach "providing namespaces, wildcards and TTL".

Here's a basic example:

from pymitter import EventEmitter

ee = EventEmitter()

# decorator usage
@ee.on("myevent")
def handler1(arg):
   print "handler1 called with", arg

# callback usage
def handler2(arg):
    print "handler2 called with", arg
ee.on("myotherevent", handler2)

# emit
ee.emit("myevent", "foo")
# -> "handler1 called with foo"

ee.emit("myotherevent", "bar")
# -> "handler2 called with bar"

Format number as percent in MS SQL Server

took the challenge to solve this issue. comment number 5 (M.Ali) asked for --"The required answer is 97.36 % (not 0.97 %) .." so for that i'm attaching a photo who compare between post number 3 (sqluser) to my solution. (i'm using the postgre_sql on a mac)

enter image description here

To enable extensions, verify that they are enabled in those .ini files - Vagrant/Ubuntu/Magento 2.0.2

When I went to create a laravel project, I got this problem.

After googling, I got this solution.

I followed these steps:

Step 1: sudo apt-get install -y php7.2-gd

Step 2: sudo apt-get install php7.2-intl

Step 3: sudo apt-get install php7.2-xsl

Step 4: sudo apt-get install php7.2-mbstring

Deleting an object in java?

You should remove the references to it by assigning null or leaving the block where it was declared. After that, it will be automatically deleted by the garbage collector (not immediately, but eventually).

Example 1:

Object a = new Object();
a = null; // after this, if there is no reference to the object,
          // it will be deleted by the garbage collector

Example 2:

if (something) {
    Object o = new Object(); 
} // as you leave the block, the reference is deleted.
  // Later on, the garbage collector will delete the object itself.

Not something that you are currently looking for, but FYI: you can invoke the garbage collector with the call System.gc()

Reading and writing environment variables in Python?

Use os.environ[str(DEBUSSY)] for both reading and writing (http://docs.python.org/library/os.html#os.environ).

As for reading, you have to parse the number from the string yourself of course.

Create File If File Does Not Exist

For Example

    string rootPath = Path.GetPathRoot(Environment.GetFolderPath(Environment.SpecialFolder.System));
        rootPath += "MTN";
        if (!(File.Exists(rootPath)))
        {
            File.CreateText(rootPath);
        }

Does "git fetch --tags" include "git fetch"?

I'm going to answer this myself.

I've determined that there is a difference. "git fetch --tags" might bring in all the tags, but it doesn't bring in any new commits!

Turns out one has to do this to be totally "up to date", i.e. replicated a "git pull" without the merge:

$ git fetch --tags
$ git fetch

This is a shame, because it's twice as slow. If only "git fetch" had an option to do what it normally does and bring in all the tags.

How to throw RuntimeException ("cannot find symbol")

throw new RuntimeException(msg);

You need the new in there. It's creating an instance and throwing it, not calling a method.

How to check if a line has one of the strings in a list?

One approach is to combine the search strings into a regex pattern as in this answer.

Filtering a list based on a list of booleans

Like so:

filtered_list = [i for (i, v) in zip(list_a, filter) if v]

Using zip is the pythonic way to iterate over multiple sequences in parallel, without needing any indexing. This assumes both sequences have the same length (zip stops after the shortest runs out). Using itertools for such a simple case is a bit overkill ...

One thing you do in your example you should really stop doing is comparing things to True, this is usually not necessary. Instead of if filter[idx]==True: ..., you can simply write if filter[idx]: ....

Nested classes' scope?

All explanations can be found in Python Documentation The Python Tutorial

For your first error <type 'exceptions.NameError'>: name 'outer_var' is not defined. The explanation is:

There is no shorthand for referencing data attributes (or other methods!) from within methods. I find that this actually increases the readability of methods: there is no chance of confusing local variables and instance variables when glancing through a method.

quoted from The Python Tutorial 9.4

For your second error <type 'exceptions.NameError'>: name 'OuterClass' is not defined

When a class definition is left normally (via the end), a class object is created.

quoted from The Python Tutorial 9.3.1

So when you try inner_var = Outerclass.outer_var, the Quterclass hasn't been created yet, that's why name 'OuterClass' is not defined

A more detailed but tedious explanation for your first error:

Although classes have access to enclosing functions’ scopes, though, they do not act as enclosing scopes to code nested within the class: Python searches enclosing functions for referenced names, but never any enclosing classes. That is, a class is a local scope and has access to enclosing local scopes, but it does not serve as an enclosing local scope to further nested code.

quoted from Learning.Python(5th).Mark.Lutz

Tomcat 7.0.43 "INFO: Error parsing HTTP request header"

In our case it turned out that the error happened because we have a custom filter in our application which does HttpServletResponse sendRedirect() to other url.

For some reason, the redirection is not closing the keep-alive status of the connection, hence the timeout exception.

We checked with Tomcat Docs and when we disabled the maxKeepAliveRequests by setting it's value to 1 and the error stopped showing up.

For now we do not have the actual solution to the error.

'cannot open git-upload-pack' error in Eclipse when cloning or pushing git repository

I'm using Eclipse Kepler SR2 on Ubuntu 12.04LTS and was trying to access an internal GitHub using HTTPS. Unfortunately, my underlying JVM with which Eclipse was started experienced problems with the self-signed certificate of the server. Switching to a different JVM for Eclipse got the HTTPS connection to our GitHub working.

Create a simple Eclipse starter that uses a different JDK, e.g. with OpenJDK: /Eclipse_Kepler_4.4.2/eclipse -vm /usr/lib/jvm/java-6-openjdk-i386/jre/bin

All combinations of a list of lists

Numpy can do it:

 >>> import numpy
 >>> a = [[1,2,3],[4,5,6],[7,8,9,10]]
 >>> [list(x) for x in numpy.array(numpy.meshgrid(*a)).T.reshape(-1,len(a))]
[[ 1, 4, 7], [1, 5, 7], [1, 6, 7], ....]

Android canvas draw rectangle

Create a new class MyView, Which extends View. Override the onDraw(Canvas canvas) method to draw rectangle on Canvas.

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;
import android.util.AttributeSet;
import android.view.View;

public class MyView extends View {

 Paint paint;
 Path path;

 public MyView(Context context) {
  super(context);
  init();
 }

 public MyView(Context context, AttributeSet attrs) {
  super(context, attrs);
  init();
 }

 public MyView(Context context, AttributeSet attrs, int defStyle) {
  super(context, attrs, defStyle);
  init();
 }

 private void init(){
  paint = new Paint();
  paint.setColor(Color.BLUE);
  paint.setStrokeWidth(10);
  paint.setStyle(Paint.Style.STROKE);

 }

 @Override
 protected void onDraw(Canvas canvas) {
  // TODO Auto-generated method stub
  super.onDraw(canvas);

  canvas.drawRect(30, 50, 200, 350, paint);
  canvas.drawRect(100, 100, 300, 400, paint);
  //drawRect(left, top, right, bottom, paint)

 }

}

Then Move your Java activity to setContentView() using our custom View, MyView.Call this way.

    public void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(new MyView(this));
  }

For more details you can visit here

http://developer.android.com/reference/android/graphics/Canvas.html

Jackson - best way writes a java list to a json array

In objectMapper we have writeValueAsString() which accepts object as parameter. We can pass object list as parameter get the string back.

List<Apartment> aptList =  new ArrayList<Apartment>();
    Apartment aptmt = null;
    for(int i=0;i<5;i++){
         aptmt= new Apartment();
         aptmt.setAptName("Apartment Name : ArrowHead Ranch");
         aptmt.setAptNum("3153"+i);
         aptmt.setPhase((i+1));
         aptmt.setFloorLevel(i+2);
         aptList.add(aptmt);
    }
mapper.writeValueAsString(aptList)

Go back button in a page

onclick="history.go(-1)" Simply

jQuery `.is(":visible")` not working in Chrome

I assume it has something to do with a quirk in our HTML because other places on the same page work just fine.

The only way I was able to solve this problem was to do:

if($('#element_id').css('display') == 'none')
{
   // Take element is hidden action
}
else
{
   // Take element is visible action
}

Handling multiple IDs in jQuery

Solution:

To your secondary question

var elem1 = $('#elem1'),
    elem2 = $('#elem2'),
    elem3 = $('#elem3');

You can use the variable as the replacement of selector.

elem1.css({'display':'none'}); //will work

In the below case selector is already stored in a variable.

$(elem1,elem2,elem3).css({'display':'none'}); // will not work

What's the opposite of 'make install', i.e. how do you uninstall a library in Linux?

make clean removes any intermediate or output files from your source / build tree. However, it only affects the source / build tree; it does not touch the rest of the filesystem and so will not remove previously installed software.

If you're lucky, running make uninstall will work. It's up to the library's authors to provide that, however; some authors provide an uninstall target, others don't.

If you're not lucky, you'll have to manually uninstall it. Running make -n install can be helpful, since it will show the steps that the software would take to install itself but won't actually do anything. You can then manually reverse those steps.

strdup() - what does it do in C?

From strdup man:

The strdup() function shall return a pointer to a new string, which is a duplicate of the string pointed to by s1. The returned pointer can be passed to free(). A null pointer is returned if the new string cannot be created.

Exercises to improve my Java programming skills

Once you are quite good in Java SE (lets say you are able to pass SCJP), I'd suggest you get junior Java programmer job and improve yourself on real world problems

How do you add an action to a button programmatically in xcode

 CGRect buttonFrame = CGRectMake( x-pos, y-pos, width, height );   //
 CGRectMake(10,5,10,10) 

 UIButton *button = [[UIButton alloc] initWithFrame: buttonFrame];

 button setTitle: @"My Button" forState: UIControlStateNormal];

 [button addTarget:self action:@selector(btnClicked:) 
 forControlEvents:UIControlEventTouchUpInside];

 [button setTitleColor: [UIColor BlueVolor] forState:
 UIControlStateNormal];

 [view addSubview:button];




 -(void)btnClicked {
    // your code }

Utils to read resource text file to String (Java)

If you want to get your String from a project resource like the file testcase/foo.json in src/main/resources in your project, do this:

String myString= 
 new String(Files.readAllBytes(Paths.get(getClass().getClassLoader().getResource("testcase/foo.json").toURI())));

Note that the getClassLoader() method is missing on some of the other examples.

Replace duplicate spaces with a single space in T-SQL

update mytable
set myfield = replace(myfield, '  ',  ' ')
where myfield like '%  %'

Try this..

HttpClient 4.0.1 - how to release connection?

This seems to work great :

      if( response.getEntity() != null ) {
         response.getEntity().consumeContent();
      }//if

And don't forget to consume the entity even if you didn't open its content. For instance, you expect a HTTP_OK status from the response and don't get it, you still have to consume the entity !

HTML5 <video> element on Android

Roman's answer worked fine for me - or at least, it gave me what I was expecting. Opening the video in the phone's native application is exactly the same as what the iPhone does.

It's probably worth adjusting your viewpoint and expect video to be played fullscreen in its own application, and coding for that. It's frustrating that clicking the video isn't sufficient to get it playing in the same way as the iPhone does, but seeing as it only takes an onclick attribute to launch it, it's not the end of the world.

My advice, FWIW, is to use a poster image, and make it obvious that it will play the video. I'm working on a project at the moment that does precisely that, and the clients are happy with it - and also that they're getting the Android version of a web app for free, of course, because the contract was only for an iPhone web app.

Just for illustration, a working Android video tag is below. Nice and simple.

<video src="video/placeholder.m4v" poster="video/placeholder.jpg" onclick="this.play();"/>

Python: PIP install path, what is the correct location for this and other addons?

Modules go in site-packages and executables go in your system's executable path. For your environment, this path is /usr/local/bin/.

To avoid having to deal with this, simply use easy_install, distribute or pip. These tools know which files need to go where.

How can I set a custom baud rate on Linux?

There is an serial I/O chip on your motherboard's CPU (16650 UART). This chip uses 8-bit port as control and data bus, and thus you can issue a command to it through writing to this chip through the control and data bus.

Usually, an application did the following steps on the serial port

  1. Set baud rate, parity, encoding, flow control, and starting / ending sequence length during program start. This setup can be done via ioctl to the serial device or 'stty' command. In fact, the stty command uses ioctl to that serial device.
  2. Write characters of data to the serial device and the driver will be writing data charaters to the UART chip through its 8-bit data bus.

In short, you can specify the baud rate only in the STTY command, and then all other options would be kept as default, and it should enough to connect to ohter devices.

How can I get phone serial number (IMEI)

try this

 final TelephonyManager tm =(TelephonyManager)getBaseContext().getSystemService(Context.TELEPHONY_SERVICE);

  String deviceid = tm.getDeviceId();

In Node.js, how do I turn a string to a json?

You need to use this function.

JSON.parse(yourJsonString);

And it will return the object / array that was contained within the string.

Javascript Date - set just the date, ignoring time?

_x000D_
_x000D_
var today = new Date();
var year = today.getFullYear();
var mes = today.getMonth()+1;
var dia = today.getDate();
var fecha =dia+"-"+mes+"-"+year;
console.log(fecha);
_x000D_
_x000D_
_x000D_

pandas: merge (join) two data frames on multiple columns

the problem here is that by using the apostrophes you are setting the value being passed to be a string, when in fact, as @Shijo stated from the documentation, the function is expecting a label or list, but not a string! If the list contains each of the name of the columns beings passed for both the left and right dataframe, then each column-name must individually be within apostrophes. With what has been stated, we can understand why this is inccorect:

new_df = pd.merge(A_df, B_df,  how='left', left_on='[A_c1,c2]', right_on = '[B_c1,c2]')

And this is the correct way of using the function:

new_df = pd.merge(A_df, B_df,  how='left', left_on=['A_c1','c2'], right_on = ['B_c1','c2'])

How to make/get a multi size .ico file?

The excellent (free trial) IcoFX allows you to create and edit icons, including multiple sizes up to 256x256, PNG compression, and transparency. I highly recommend it over most of the alternates.

Get your copy here: http://icofx.ro/ . It supports Windows XP onwards.


Windows automatically chooses the proper icon from the file, depending on where it is to be displayed. For more information on icon design and the sizes/bit depths you should include, see these references:

How do I link a JavaScript file to a HTML file?

this is demo code but it will help 

<!DOCTYPE html>
<html>
<head>
<title>APITABLE 3</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script>


$(document).ready(function(){

$.ajax({
    type: "GET",
    url: "https://reqres.in/api/users/",

    data: '$format=json',

    dataType: 'json',
    success: function (data) {
 $.each(data.data,function(d,results){
     console.log(data);

 $("#apiData").append(
                        "<tr>"
                          +"<td>"+results.first_name+"</td>"
                          +"<td>"+results.last_name+"</td>"
                          +"<td>"+results.id+"</td>"
                          +"<td>"+results.email+"</td>"
  +"<td>"+results.bentrust+"</td>"
                        +"</tr>" )
                    })
 } 

});

});


</script>
</head>
<body>


    <table id="apiTable">

        <thead>
            <tr>
            <th>Id</th>
            <br>
            <th>Email</th>
            <br>
            <th>Firstname</th>
            <br>
            <th>Lastname</th>
        </tr>
        </thead>
        <tbody id="apiData"></tbody>    





</body>
</html> 

Use of #pragma in C

Putting #pragma once at the top of your header file will ensure that it is only included once. Note that #pragma once is not standard C99, but supported by most modern compilers.

An alternative is to use include guards (e.g. #ifndef MY_FILE #define MY_FILE ... #endif /* MY_FILE */)

Android Layout Weight

Think it that way, will be simpler

If you have 3 buttons and their weights are 1,3,1 accordingly, it will work like table in HTML

Provide 5 portions for that line: 1 portion for button 1, 3 portion for button 2 and 1 portion for button 1

Excel Macro - Select all cells with data and format as table

Try this one for current selection:

Sub A_SelectAllMakeTable2()
    Dim tbl As ListObject
    Set tbl = ActiveSheet.ListObjects.Add(xlSrcRange, Selection, , xlYes)
    tbl.TableStyle = "TableStyleMedium15"
End Sub

or equivalent of your macro (for Ctrl+Shift+End range selection):

Sub A_SelectAllMakeTable()
    Dim tbl As ListObject
    Dim rng As Range

    Set rng = Range(Range("A1"), Range("A1").SpecialCells(xlLastCell))
    Set tbl = ActiveSheet.ListObjects.Add(xlSrcRange, rng, , xlYes)
    tbl.TableStyle = "TableStyleMedium15"
End Sub

How to convert a string to utf-8 in Python

  • First, str in Python is represented in Unicode.
  • Second, UTF-8 is an encoding standard to encode Unicode string to bytes. There are many encoding standards out there (e.g. UTF-16, ASCII, SHIFT-JIS, etc.).

When the client sends data to your server and they are using UTF-8, they are sending a bunch of bytes not str.

You received a str because the "library" or "framework" that you are using, has implicitly converted some random bytes to str.

Under the hood, there is just a bunch of bytes. You just need ask the "library" to give you the request content in bytes and you will handle the decoding yourself (if library can't give you then it is trying to do black magic then you shouldn't use it).

  • Decode UTF-8 encoded bytes to str: bs.decode('utf-8')
  • Encode str to UTF-8 bytes: s.encode('utf-8')

Change header background color of modal of twitter bootstrap

You can use the css below, put this in your custom css to override the bootstrap css.

.modal-header {
    padding:9px 15px;
    border-bottom:1px solid #eee;
    background-color: #0480be;
    -webkit-border-top-left-radius: 5px;
    -webkit-border-top-right-radius: 5px;
    -moz-border-radius-topleft: 5px;
    -moz-border-radius-topright: 5px;
     border-top-left-radius: 5px;
     border-top-right-radius: 5px;
 }

How do I add a project as a dependency of another project?

Assuming the MyEjbProject is not another Maven Project you own or want to build with maven, you could use system dependencies to link to the existing jar file of the project like so

<project>
   ...
   <dependencies>
      <dependency>
         <groupId>yourgroup</groupId>
         <artifactId>myejbproject</artifactId>
         <version>2.0</version>
         <scope>system</scope>
         <systemPath>path/to/myejbproject.jar</systemPath>
      </dependency>
   </dependencies>
   ...
</project>

That said it is usually the better (and preferred way) to install the package to the repository either by making it a maven project and building it or installing it the way you already seem to do.


If they are, however, dependent on each other, you can always create a separate parent project (has to be a "pom" project) declaring the two other projects as its "modules". (The child projects would not have to declare the third project as their parent). As a consequence you'd get a new directory for the new parent project, where you'd also quite probably put the two independent projects like this:

parent
|- pom.xml
|- MyEJBProject
|   `- pom.xml
`- MyWarProject
    `- pom.xml

The parent project would get a "modules" section to name all the child modules. The aggregator would then use the dependencies in the child modules to actually find out the order in which the projects are to be built)

<project>
   ...
   <artifactId>myparentproject</artifactId>
   <groupId>...</groupId>
   <version>...</version>

   <packaging>pom</packaging>
   ...
   <modules>
     <module>MyEJBModule</module>
     <module>MyWarModule</module>
   </modules>
   ...
</project>

That way the projects can relate to each other but (once they are installed in the local repository) still be used independently as artifacts in other projects


Finally, if your projects are not in related directories, you might try to give them as relative modules:

filesystem
 |- mywarproject
 |   `pom.xml
 |- myejbproject
 |   `pom.xml
 `- parent
     `pom.xml

now you could just do this (worked in maven 2, just tried it):

<!--parent-->
<project>
  <modules>
    <module>../mywarproject</module>
    <module>../myejbproject</module>
  </modules>
</project>

Java 8 List<V> into Map<K, V>

Most of the answers listed, miss a case when the list has duplicate items. In that case there answer will throw IllegalStateException. Refer the below code to handle list duplicates as well:

public Map<String, Choice> convertListToMap(List<Choice> choices) {
    return choices.stream()
        .collect(Collectors.toMap(Choice::getName, choice -> choice,
            (oldValue, newValue) -> newValue));
  }

How to create custom view programmatically in swift having controls text field, button etc

The CGRectZero constant is equal to a rectangle at position (0,0) with zero width and height. This is fine to use, and actually preferred, if you use AutoLayout, since AutoLayout will then properly place the view.

But, I expect you do not use AutoLayout. So the most simple solution is to specify the size of the custom view by providing a frame explicitly:

customView = MyCustomView(frame: CGRect(x: 0, y: 0, width: 200, height: 50))
self.view.addSubview(customView)

Note that you also need to use addSubview otherwise your view is not added to the view hierarchy.

How can I push a specific commit to a remote, and not previous commits?

You could also, in another directory:

  • git clone [your repository]
  • Overwrite the .git directory in your original repository with the .git directory of the repository you just cloned right now.
  • git add and git commit your original

How to send a JSON object using html form data

The accepted answer is out of date; nowadays you can simply add enctype="application/json" to your form tag and the browser will jsonify the data automatically.

The spec for this behavior is here: https://www.w3.org/TR/html-json-forms/

git error: failed to push some refs to remote

This happens to me as I had a tag with the same as the branch and I tried to push the branch to remote.

How to order results with findBy() in Doctrine

The second parameter of findBy is for ORDER.

$ens = $em->getRepository('AcmeBinBundle:Marks')
          ->findBy(
             array('type'=> 'C12'), 
             array('id' => 'ASC')
           );

How to define two angular apps / modules in one page?

I made a POC for an Angular application using multiple modules and router-outlets to nest sub apps in a single page app. You can get the source code at: https://github.com/AhmedBahet/ng-sub-apps

Hope this will help

retrieve data from db and display it in table in php .. see this code whats wrong with it?

In your while statement just replace mysql_fetch_row with mysql_fetch_array or mysql_fetch_assoc... whichever works...

Function for Factorial in Python

def factorial(n):
    if n < 2:
        return 1
    return n * factorial(n - 1)

Why shouldn't `&apos;` be used to escape single quotes?

&apos; is not part of the HTML 4 standard.

&quot; is, though, so is fine to use.

How to fix "Your Ruby version is 2.3.0, but your Gemfile specified 2.2.5" while server starting

Your Gemfile has a line reading

ruby '2.2.5'

Change it to

ruby '2.3.0'

Then run

bundle install

How to open the Google Play Store directly from my Android application?

use market://

Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse("market://details?id=" + my_packagename));

stringstream, string, and char* conversion confusion

In this line:

const char* cstr2 = ss.str().c_str();

ss.str() will make a copy of the contents of the stringstream. When you call c_str() on the same line, you'll be referencing legitimate data, but after that line the string will be destroyed, leaving your char* to point to unowned memory.

How to change Rails 3 server default port in develoment?

You could install $ gem install foreman, and use foreman to start your server as defined in your Procfile like:

web: bundle exec rails -p 10524

You can check foreman gem docs here: https://github.com/ddollar/foreman for more info

The benefit of this approach is not only can you set/change the port in the config easily and that it doesn't require much code to be added but also you can add different steps in the Procfile that foreman will run for you so you don't have to go though them each time you want to start you application something like:

bundle: bundle install
web: bundle exec rails -p 10524
...
...

Cheers

postgresql sequence nextval in schema

SELECT last_value, increment_by from "other_schema".id_seq;

for adding a seq to a column where the schema is not public try this.

nextval('"other_schema".id_seq'::regclass)

What does "opt" mean (as in the "opt" directory)? Is it an abbreviation?

Add-on software packages.

See http://www.pathname.com/fhs/2.2/fhs-3.12.html for details.

Also described at Wikipedia.

Its use dates back at least to the late 1980s, when it was a standard part of System V UNIX. These days, it's also seen in Linux, Solaris (which is SysV), OSX Cygwin, etc. Other BSD unixes (FreeBSD, NetBSD, etc) tend to follow other rules, so you don't usually see BSD systems with an /opt unless they're administered by someone who is more comfortable in other environments.

Opening Android Settings programmatically

You can make another class for doing this kind of activities.

public class Go {

   public void Setting(Context context)
    {
        Intent intent = new Intent(android.provider.Settings.ACTION_SETTINGS);
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        context.startActivity(intent);
    }
}

How to check if an appSettings key exists?

Using the new c# syntax with TryParse worked well for me:

  // TimeOut
  if (int.TryParse(ConfigurationManager.AppSettings["timeOut"], out int timeOut))
  {
     this.timeOut = timeOut;
  }

ReactJs: What should the PropTypes be for this.props.children?

The PropTypes documentation has the following

// Anything that can be rendered: numbers, strings, elements or an array
// (or fragment) containing these types.
optionalNode: PropTypes.node,

So, you can use PropTypes.node to check for objects or arrays of objects

static propTypes = {
   children: PropTypes.node.isRequired,
}

How to hash some string with sha256 in Java?

String hashWith256(String textToHash) {
    MessageDigest digest = MessageDigest.getInstance("SHA-256");
    byte[] byteOfTextToHash = textToHash.getBytes(StandardCharsets.UTF_8);
    byte[] hashedByetArray = digest.digest(byteOfTextToHash);
    String encoded = Base64.getEncoder().encodeToString(hashedByetArray);
    return encoded;
}

Replace line break characters with <br /> in ASP.NET MVC Razor view

Try the following:

@MvcHtmlString.Create(Model.CommentText.Replace(Environment.NewLine, "<br />"))

Update:

According to marcind's comment on this related question, the ASP.NET MVC team is looking to implement something similar to the <%: and <%= for the Razor view engine.

Update 2:

We can turn any question about HTML encoding into a discussion on harmful user inputs, but enough of that already exists.

Anyway, take care of potential harmful user input.

@MvcHtmlString.Create(Html.Encode(Model.CommentText).Replace(Environment.NewLine, "<br />"))

Update 3 (Asp.Net MVC 3):

@Html.Raw(Html.Encode(Model.CommentText).Replace("\n", "<br />"))

How to fix git error: RPC failed; curl 56 GnuTLS

All I did was disconnect and reconnect my pc from the wifi and it worked. Sometimes the answer might be very simple. Mine works now

How to change Maven local repository in eclipse

In general, these answer the question: How to change your user settings file? But the question I wanted answered was how to change my local maven repository location. The answer is that you have to edit settings.xml. If the file does not exist, you have to create it. You set or change the location of the file at Window > Preferences > Maven > User Settings. It's the User Settings entry at

Maven User Settings dialog

It's the second file input; the first with information in it.

If it's not clear, [redacted] should be replaced with the local file path to your .m2 folder.

If you click the "open file" link, it opens the settings.xml file for editing in Eclipse.

If you have no settings.xml file yet, the following will set the local repository to the Windows 10 default value for a user named mdfst13:

<settings xmlns="http://maven.apache.org/SETTINGS/1.0.0"
          xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
          xsi:schemaLocation="http://maven.apache.org/SETTINGS/1.0.0
                              https://maven.apache.org/xsd/settings-1.0.0.xsd">

  <localRepository>C:\Users\mdfst13\.m2\repository</localRepository>
</settings>

You should set this to a value appropriate to your system. I haven't tested it, but I suspect that in Linux, the default value would be /home/mdfst13/.m2/repository. And of course, you probably don't want to set it to the default value. If you are reading this, you probably want to set it to some other value. You could just delete it if you wanted the default.

Credit to this comment by @ejaenv for the name of the element in the settings file: <localRepository>. See Maven — Settings Reference for more information.

Credit to @Ajinkya's answer for specifying the location of the User Settings value in Eclipse Photon.

If you already have a settings.xml file, you should merge this into your existing file. I.e. <settings and <localRepository> should only appear once in the file, and you probably want to retain any settings already there. Or to say that another way, edit any existing local repository entry if it exists or just add that line to the file if it doesn't.

I had to restart Eclipse for it to load data into the new repository. Neither "Update Settings" nor "Reindex" was sufficient.

How to check if that data already exist in the database during update (Mongoose And Express)

For anybody falling on this old solution. There is a better way from the mongoose docs.

var s = new Schema({ name: { type: String, unique: true }});
s.path('name').index({ unique: true });

How to export plots from matplotlib with transparent background?

Png files can handle transparency. So you could use this question Save plot to image file instead of displaying it using Matplotlib so as to save you graph as a png file.

And if you want to turn all white pixel transparent, there's this other question : Using PIL to make all white pixels transparent?

If you want to turn an entire area to transparent, then there's this question: And then use the PIL library like in this question Python PIL: how to make area transparent in PNG? so as to make your graph transparent.

git undo all uncommitted or unsaved changes

there is also git stash - which "stashes" your local changes and can be reapplied at a later time or dropped if is no longer required

more info on stashing

Best Practice: Access form elements by HTML id or name attribute?

Just to add to everything already said, you may access the inputs either with the name or id using preferably the elements property of the Object form, because without it you may get a property of the form named "foo" rather than an HTML element. And according to @Paul D. Waite it's perfectly ok to have both name and id.

_x000D_
_x000D_
var myForm = document.getElementById("myform")_x000D_
console.log(myForm.foo.value) // hey_x000D_
console.log(myForm.foo2.value) // hey_x000D_
//preferable_x000D_
console.log(myForm.elements.foo.value) // hey_x000D_
console.log(myForm.elements.foo2.value) // hey
_x000D_
<form id="myform">_x000D_
  <input type="text" name="foo" id="foo2" value="hey">_x000D_
</form>
_x000D_
_x000D_
_x000D_

According to MDN on the HTMLFormElement.elements page

The HTMLFormElement property elements returns an HTMLFormControlsCollection listing all the form controls contained in the element. Independently, you can obtain just the number of form controls using the length property.

You can access a particular form control in the returned collection by using either an index or the element's name or id.

How to call a vue.js function on page load

You can call this function in beforeMount section of a Vue component: like following:

 ....
 methods:{
     getUnits: function() {...}
 },
 beforeMount(){
    this.getUnits()
 },
 ......

Working fiddle: https://jsfiddle.net/q83bnLrx/1/

There are different lifecycle hooks Vue provide:

I have listed few are :

  1. beforeCreate: Called synchronously after the instance has just been initialized, before data observation and event/watcher setup.
  2. created: Called synchronously after the instance is created. At this stage, the instance has finished processing the options which means the following have been set up: data observation, computed properties, methods, watch/event callbacks. However, the mounting phase has not been started, and the $el property will not be available yet.
  3. beforeMount: Called right before the mounting begins: the render function is about to be called for the first time.
  4. mounted: Called after the instance has just been mounted where el is replaced by the newly created vm.$el.
  5. beforeUpdate: Called when the data changes, before the virtual DOM is re-rendered and patched.
  6. updated: Called after a data change causes the virtual DOM to be re-rendered and patched.

You can have a look at complete list here.

You can choose which hook is most suitable to you and hook it to call you function like the sample code provided above.

Generate random int value from 3 to 6

Here is the simple and single line of code

For this use the SQL Inbuild RAND() function.

Here is the formula to generate random number between two number (RETURN INT Range)

Here a is your First Number (Min) and b is the Second Number (Max) in Range

SELECT FLOOR(RAND()*(b-a)+a)

Note: You can use CAST or CONVERT function as well to get INT range number.

( CAST(RAND()*(25-10)+10 AS INT) )

Example:

SELECT FLOOR(RAND()*(25-10)+10);

Here is the formula to generate random number between two number (RETURN DECIMAL Range)

SELECT RAND()*(b-a)+a;

Example:

SELECT RAND()*(25-10)+10;

More details check this: https://www.techonthenet.com/sql_server/functions/rand.php

css transform, jagged edges in chrome

Just thought that we'd throw in our solution too as we had the exact same problem on Chrome/Windows.

We tried the solution by @stevenWatkins above, but still had the "stepping".

Instead of

-webkit-backface-visibility: hidden;

We used:

-webkit-backface-visibility: initial;

For us this did the trick

How to replace substrings in windows batch file

I have made a function for that, you only call it in a batch program within needing to code more.

The working is basically the same as the others, as it's the best way to do it.
Here's the link where I have that function

Passing arrays as parameters in bash

Commenting on Ken Bertelson solution and answering Jan Hettich:

How it works

the takes_ary_as_arg descTable[@] optsTable[@] line in try_with_local_arys() function sends:

  1. This is actually creates a copy of the descTable and optsTable arrays which are accessible to the takes_ary_as_arg function.
  2. takes_ary_as_arg() function receives descTable[@] and optsTable[@] as strings, that means $1 == descTable[@] and $2 == optsTable[@].
  3. in the beginning of takes_ary_as_arg() function it uses ${!parameter} syntax, which is called indirect reference or sometimes double referenced, this means that instead of using $1's value, we use the value of the expanded value of $1, example:

    baba=booba
    variable=baba
    echo ${variable} # baba
    echo ${!variable} # booba
    

    likewise for $2.

  4. putting this in argAry1=("${!1}") creates argAry1 as an array (the brackets following =) with the expanded descTable[@], just like writing there argAry1=("${descTable[@]}") directly. the declare there is not required.

N.B.: It is worth mentioning that array initialization using this bracket form initializes the new array according to the IFS or Internal Field Separator which is by default tab, newline and space. in that case, since it used [@] notation each element is seen by itself as if he was quoted (contrary to [*]).

My reservation with it

In BASH, local variable scope is the current function and every child function called from it, this translates to the fact that takes_ary_as_arg() function "sees" those descTable[@] and optsTable[@] arrays, thus it is working (see above explanation).

Being that case, why not directly look at those variables themselves? It is just like writing there:

argAry1=("${descTable[@]}")

See above explanation, which just copies descTable[@] array's values according to the current IFS.

In summary

This is passing, in essence, nothing by value - as usual.

I also want to emphasize Dennis Williamson comment above: sparse arrays (arrays without all the keys defines - with "holes" in them) will not work as expected - we would loose the keys and "condense" the array.

That being said, I do see the value for generalization, functions thus can get the arrays (or copies) without knowing the names:

  • for ~"copies": this technique is good enough, just need to keep aware, that the indices (keys) are gone.
  • for real copies: we can use an eval for the keys, for example:

    eval local keys=(\${!$1})
    

and then a loop using them to create a copy. Note: here ! is not used it's previous indirect/double evaluation, but rather in array context it returns the array indices (keys).

  • and, of course, if we were to pass descTable and optsTable strings (without [@]), we could use the array itself (as in by reference) with eval. for a generic function that accepts arrays.

Spring MVC UTF-8 Encoding

Make sure you register Spring's CharacterEncodingFilter in your web.xml (must be the first filter in that file).

<filter>  
    <filter-name>encodingFilter</filter-name>  
    <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>  
    <init-param>  
       <param-name>encoding</param-name>  
       <param-value>UTF-8</param-value>  
    </init-param>  
    <init-param>  
       <param-name>forceEncoding</param-name>  
       <param-value>true</param-value>  
    </init-param>  
</filter>  
<filter-mapping>  
    <filter-name>encodingFilter</filter-name>  
    <url-pattern>/*</url-pattern>  
</filter-mapping> 

If you are on Tomcat you might not have set the URIEncoding in your server.xml. If you don't set it to UTF-8 it won't work. Definitely keep the CharacterEncodingFilter. Nevertheless, here's a concise checklist to follow. It will definitely guide you to make this work.

How to horizontally center an element

Well, I managed to find a solution that maybe will fit all situations, but uses JavaScript:

Here's the structure:

<div class="container">
  <div class="content">Your content goes here!</div>
  <div class="content">Your content goes here!</div>
  <div class="content">Your content goes here!</div>
</div>

And here's the JavaScript snippet:

$(document).ready(function() {
  $('.container .content').each( function() {
    container = $(this).closest('.container');
    content = $(this);

    containerHeight = container.height();
    contentHeight = content.height();

    margin = (containerHeight - contentHeight) / 2;
    content.css('margin-top', margin);
  })
});

If you want to use it in a responsive approach, you can add the following:

$(window).resize(function() {
  $('.container .content').each( function() {
    container = $(this).closest('.container');
    content = $(this);

    containerHeight = container.height();
    contentHeight = content.height();

    margin = (containerHeight - contentHeight) / 2;
    content.css('margin-top', margin);
  })
});

Android WebView not loading URL

Just as an alternative solution:

For me webView.getSettings().setUserAgentString("Android WebView") did the trick.

I already had implemented INTERNET permission and WebViewClient as well as WebChromeClient

How to install PyQt4 on Windows using pip?

I am using PyCharm, and was able to install PyQt5.

PyQt4, as well as PyQt4Enhanced and windows_whl both failed to install, I'm guessing that's because Qt4 is no longer supported.

How to upload a file in Django?

Demo

See the github repo, works with Django 3

A minimal Django file upload example

1. Create a django project

Run startproject::

$ django-admin.py startproject sample

now a folder(sample) is created.

2. create an app

Create an app::

$ cd sample
$ python manage.py startapp uploader

Now a folder(uploader) with these files are created::

uploader/
  __init__.py
  admin.py
  app.py
  models.py
  tests.py
  views.py
  migrations/
    __init__.py

3. Update settings.py

On sample/settings.py add 'uploader' to INSTALLED_APPS and add MEDIA_ROOT and MEDIA_URL, ie::

INSTALLED_APPS = [
    'uploader',
    ...<other apps>...      
]

MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
MEDIA_URL = '/media/'

4. Update urls.py

in sample/urls.py add::

...<other imports>...
from django.conf import settings
from django.conf.urls.static import static
from uploader import views as uploader_views

urlpatterns = [
    ...<other url patterns>...
    path('', uploader_views.UploadView.as_view(), name='fileupload'),
]+ static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

5. Update models.py

update uploader/models.py::

from django.db import models
class Upload(models.Model):
    upload_file = models.FileField()    
    upload_date = models.DateTimeField(auto_now_add =True)

6. Update views.py

update uploader/views.py::

from django.views.generic.edit import CreateView
from django.urls import reverse_lazy
from .models import Upload
class UploadView(CreateView):
    model = Upload
    fields = ['upload_file', ]
    success_url = reverse_lazy('fileupload')
    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context['documents'] = Upload.objects.all()
        return context

7. create templates

Create a folder sample/uploader/templates/uploader

Create a file upload_form.html ie sample/uploader/templates/uploader/upload_form.html::

<div style="padding:40px;margin:40px;border:1px solid #ccc">
    <h1>Django File Upload</h1>
    <form method="post" enctype="multipart/form-data">
      {% csrf_token %}
      {{ form.as_p }}
      <button type="submit">Submit</button>
    </form><hr>
    <ul>
    {% for document in documents %}
        <li>
            <a href="{{ document.upload_file.url }}">{{ document.upload_file.name }}</a>
            <small>({{ document.upload_file.size|filesizeformat }}) - {{document.upload_date}}</small>
        </li>
    {% endfor %}
    </ul>
</div>

8. Syncronize database

Syncronize database and runserver::

$ python manage.py makemigrations
$ python manage.py migrate
$ python manage.py runserver

visit http://localhost:8000/

Multiple FROMs - what it means

The first answer is too complex, historic, and uninformative for my tastes.


It's actually rather simple. Docker provides for a functionality called multi-stage builds the basic idea here is to,

  • Free you from having to manually remove what you don't want, by forcing you to whitelist what you do want,
  • Free resources that would otherwise be taken up because of Docker's implementation.

Let's start with the first. Very often with something like Debian you'll see.

RUN apt-get update \ 
  && apt-get dist-upgrade \
  && apt-get install <whatever> \
  && apt-get clean

We can explain all of this in terms of the above. The above command is chained together so it represents a single change with no intermediate Images required. If it was written like this,

RUN apt-get update ;
RUN apt-get dist-upgrade;
RUN apt-get install <whatever>;
RUN apt-get clean;

It would result in 3 more temporary intermediate Images. Having it reduced to one image, there is one remaining problem: apt-get clean doesn't clean up artifacts used in the install. If a Debian maintainer includes in his install a script that modifies the system that modification will also be present in the final solution (see something like pepperflashplugin-nonfree for an example of that).

By using a multi-stage build you get all the benefits of a single changed action, but it will require you to manually whitelist and copy over files that were introduced in the temporary image using the COPY --from syntax documented here. Moreover, it's a great solution where there is no alternative (like an apt-get clean), and you would otherwise have lots of un-needed files in your final image.

See also

Apply style to parent if it has child with css

It's not possible with CSS3. There is a proposed CSS4 selector, $, to do just that, which could look like this (Selecting the li element):

ul $li ul.sub { ... }

See the list of CSS4 Selectors here.

As an alternative, with jQuery, a one-liner you could make use of would be this:

$('ul li:has(ul.sub)').addClass('has_sub');

You could then go ahead and style the li.has_sub in your CSS.

Setting mime type for excel document

For anyone who is still stumbling with this after using all of the possible MIME types listed in the question:

I have found that iMacs tend to also throw a MIME type of "text/xls" for XLS Excel files, hope this helps.

How to access a DOM element in React? What is the equilvalent of document.getElementById() in React

Since React uses JSX code to create an HTML we cannot refer dom using regulation methods like documment.querySelector or getElementById.

Instead we can use React ref system to access and manipulate Dom as shown in below example:

constructor(props){

    super(props);
    this.imageRef = React.createRef(); // create react ref
}

componentDidMount(){

    **console.log(this.imageRef)** // acessing the attributes of img tag when dom loads
}


render = (props) => {

const {urls,description} = this.props.image;
    return (

            <img
             **ref = {this.imageRef} // assign the ref of img tag here**
             src = {urls.regular} 
             alt = {description}
             />

        );

}

}

Open the terminal in visual studio?

New in the most recent version of Visual Studio, there is View --> Terminal, which will open a PowerShell instance as a VS dockable window, rather than a floating PowerShell or cmd instance from the Developer Command Prompt.

View then Terminal

Could not load file or assembly 'EntityFramework' after downgrading EF 5.0.0.0 --> 4.3.1.0

I received the exact same error message. Except that my error message said "Could not load file or assembly 'EntityFramework, Version=6.0.0.0...", because I installed EF 6.1.1. Here's what I did to resolve the problem.

1) I started NuGet Manager Console by clicking on Tools > NuGet Package Manager > Package Manager Console 2) I uninstalled the installed EntityFramework 6.1.1 by typing the following command:

Uninstall-package EntityFramework

3) Once I received confirmation that the package has been uninstalled successfully, I installed the 5.0.0 version by typing the following command:

Install-Package EntityFramework -version 5.0.0

The problem is resolved.

Differences between arm64 and aarch64

It seems that ARM64 was created by Apple and AARCH64 by the others, most notably GNU/GCC guys.

After some googling I found this link:

The LLVM 64-bit ARM64/AArch64 Back-Ends Have Merged

So it makes sense, iPad calls itself ARM64, as Apple is using LLVM, and Edge uses AARCH64, as Android is using GNU GCC toolchain.

Viewing all defined variables

A few things you could use:

  • dir() will give you the list of in scope variables:
  • globals() will give you a dictionary of global variables
  • locals() will give you a dictionary of local variables

.NET Console Application Exit Event

You can use the ProcessExit event of the AppDomain:

class Program
{
    static void Main(string[] args)
    {
        AppDomain.CurrentDomain.ProcessExit += new EventHandler(CurrentDomain_ProcessExit);           
        // do some work

    }

    static void CurrentDomain_ProcessExit(object sender, EventArgs e)
    {
        Console.WriteLine("exit");
    }
}

Update

Here is a full example program with an empty "message pump" running on a separate thread, that allows the user to input a quit command in the console to close down the application gracefully. After the loop in MessagePump you will probably want to clean up resources used by the thread in a nice manner. It's better to do that there than in ProcessExit for several reasons:

  • Avoid cross-threading problems; if external COM objects were created on the MessagePump thread, it's easier to deal with them there.
  • There is a time limit on ProcessExit (3 seconds by default), so if cleaning up is time consuming, it may fail if pefromed within that event handler.

Here is the code:

class Program
{
    private static bool _quitRequested = false;
    private static object _syncLock = new object();
    private static AutoResetEvent _waitHandle = new AutoResetEvent(false);

    static void Main(string[] args)
    {
        AppDomain.CurrentDomain.ProcessExit += new EventHandler(CurrentDomain_ProcessExit);
        // start the message pumping thread
        Thread msgThread = new Thread(MessagePump);
        msgThread.Start();
        // read input to detect "quit" command
        string command = string.Empty;
        do
        {
            command = Console.ReadLine();
        } while (!command.Equals("quit", StringComparison.InvariantCultureIgnoreCase));
        // signal that we want to quit
        SetQuitRequested();
        // wait until the message pump says it's done
        _waitHandle.WaitOne();
        // perform any additional cleanup, logging or whatever
    }

    private static void SetQuitRequested()
    {
        lock (_syncLock)
        {
            _quitRequested = true;
        }
    }

    private static void MessagePump()
    {
        do
        {
            // act on messages
        } while (!_quitRequested);
        _waitHandle.Set();
    }

    static void CurrentDomain_ProcessExit(object sender, EventArgs e)
    {
        Console.WriteLine("exit");
    }
}

How to get the current time in milliseconds in C Programming

There is no portable way to get resolution of less than a second in standard C So best you can do is, use the POSIX function gettimeofday().

How to open a Bootstrap modal window using jQuery?

<form id="myform" class="form-wizard">
    <h2 class="form-wizard-heading">BootStap Wizard Form</h2>
    <input type="text" value=""/>
    <input type="submit" id="submitButton"/>
</form>

<!-- Modal -->
<div id="myModal" class="modal hide fade" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
    <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
        <h3 id="myModalLabel">Modal header</h3>
    </div>
    <div class="modal-body">
        <p>One fine body…</p>
    </div>
    <div class="modal-footer">
        <button class="btn" data-dismiss="modal" aria-hidden="true">Close</button>
        <button class="btn btn-primary">Save changes</button>
    </div>
</div>

You can launch the modal with the code below this.

$(document).ready(function(){
    $("#submitButton").click(function(){
        $("#myModal").modal();
    });
});

How can I load the contents of a text file into a batch file variable?

You can use:

set content=
for /f "delims=" %%i in ('type text.txt') do set content=!content! %%i