Programs & Examples On #Xcopy

xcopy is a Windows command to copy all files, directories, and subdirectories from a specified path to a target directory

XCOPY switch to create specified directory if it doesn't exist?

Simple short answer is this:

xcopy /Y /I "$(SolutionDir)<my-src-path>" "$(SolutionDir)<my-dst-path>\"

XCOPY: Overwrite all without prompt in BATCH

The solution is the /Y switch:

xcopy "C:\Users\ADMIN\Desktop\*.*" "D:\Backup\" /K /D /H /Y

BATCH file asks for file or folder

I had exactly the same problem, where is wanted to copy a file into an external hard drive for backup purposes. If I wanted to copy a complete folder, then COPY was quite happy to create the destination folder and populate it with all the files. However, I wanted to copy a file once a day and add today's date to the file. COPY was happy to copy the file and rename it in the new format, but only as long as the destination folder already existed.

my copy command looked like this:

COPY C:\SRCFOLDER\MYFILE.doc D:\DESTFOLDER\MYFILE_YYYYMMDD.doc

Like you, I looked around for alternative switches or other copy type commands, but nothing really worked like I wanted it to. Then I thought about splitting out the two different requirements by simply adding a make directory ( MD or MKDIR ) command before the copy command.

So now i have

MKDIR D:\DESTFOLDER

COPY C:\SRCFOLDER\MYFILE.doc D:\DESTFOLDER\MYFILE_YYYYMMDD.doc

If the destination folder does NOT exist, then it creates it. If the destination folder DOES exist, then it generates an error message.. BUT, this does not stop the batch file from continuing on to the copy command.

The error message says: A subdirectory or file D:\DESTFOLDER already exists

As i said, the error message doesn't stop the batch file working and it is a really simple fix to the problem.

Hope that this helps.

What is going wrong when Visual Studio tells me "xcopy exited with code 4"

If any other solution is in the debug mode then first stop them all and after that restart the visual studio. It worked for me.

Xcopy Command excluding files and folders

Just give full path to exclusion file: eg..

-- no - - - - -xcopy c:\t1 c:\t2 /EXCLUDE:list-of-excluded-files.txt

correct - - - xcopy c:\t1 c:\t2 /EXCLUDE:C:\list-of-excluded-files.txt

In this example the file would be located " C:\list-of-excluded-files.txt "

or...

correct - - - xcopy c:\t1 c:\t2 /EXCLUDE:C:\mybatch\list-of-excluded-files.txt

In this example the file would be located " C:\mybatch\list-of-excluded-files.txt "

Full path fixes syntax error.

How do I find files with a path length greater than 260 characters in Windows?

From http://www.powershellmagazine.com/2012/07/24/jaap-brassers-favorite-powershell-tips-and-tricks/:

Get-ChildItem –Force –Recurse –ErrorAction SilentlyContinue –ErrorVariable AccessDenied

the first part just iterates through this and sub-folders; using -ErrorVariable AccessDenied means push the offending items into the powershell variable AccessDenied.

You can then scan through the variable like so

$AccessDenied |
Where-Object { $_.Exception -match "must be less than 260 characters" } |
ForEach-Object { $_.TargetObject }

If you don't care about these files (may be applicable in some cases), simply drop the -ErrorVariable AccessDenied part.

batch to copy files with xcopy

You must specify your file in the copy:

xcopy C:\source\myfile.txt C:\target

Or if you want to copy all txt files for example

xcopy C:\source\*.txt C:\target

batch file Copy files with certain extensions from multiple directories into one directory

Brandon, short and sweet. Also flexible.

set dSource=C:\Main directory\sub directory
set dTarget=D:\Documents
set fType=*.doc
for /f "delims=" %%f in ('dir /a-d /b /s "%dSource%\%fType%"') do (
    copy /V "%%f" "%dTarget%\" 2>nul
)

Hope this helps.

I would add some checks after the copy (using '||') but i'm not sure how "copy /v" reacts when it encounters an error.

you may want to try this:

copy /V "%%f" "%dTarget%\" 2>nul|| echo En error occured copying "%%F".&& exit /b 1

As the copy line. let me know if you get something out of it (in no position to test a copy failure atm..)

xcopy file, rename, suppress "Does xxx specify a file name..." message

I suggest robocopy instead of copy or xcopy. Used as command or in GUI on clients or servers. Tolerant of network pauses and you can choose to ignore file attributes when copying of copy by file attributes. Oh, and it supports multi-core machines so files are copied much faster in "parallel" with each other instead of sequentially. robocopy can be found on MS TechNet.

/exclude in xcopy just for a file type

The /EXCLUDE: argument expects a file containing a list of excluded files.

So create a file called excludedfileslist.txt containing:

.cs\

Then a command like this:

xcopy /r /d /i /s /y /exclude:excludedfileslist.txt C:\dev\apan C:\web\apan

Alternatively you could use Robocopy, but would require installing / copying a robocopy.exe to the machines.

Update

An anonymous comment edit which simply stated "This Solution exclude also css file!"

This is true creating a excludedfileslist.txt file contain just:

.cs

(note no backslash on the end)

Will also exclude all of the following:

  • file1.cs
  • file2.css
  • dir1.cs\file3.txt
  • dir2\anyfile.cs.something.txt

Sometimes people don't read or understand the XCOPY command's help, here is an item I would like to highlight:

Using /exclude

  • List each string in a separate line in each file. If any of the listed strings match any part of the absolute path of the file to be copied, that file is then excluded from the copying process. For example, if you specify the string "\Obj\", you exclude all files underneath the Obj directory. If you specify the string ".obj", you exclude all files with the .obj extension.

As the example states it excludes "all files with the .obj extension" but it doesn't state that it also excludes files or directories named file1.obj.tmp or dir.obj.output\example2.txt.

There is a way around .css files being excluded also, change the excludedfileslist.txt file to contain just:

.cs\

(note the backslash on the end).

Here is a complete test sequence for your reference:

C:\test1>ver

Microsoft Windows [Version 6.1.7601]

C:\test1>md src
C:\test1>md dst
C:\test1>md src\dir1
C:\test1>md src\dir2.cs
C:\test1>echo "file contents" > src\file1.cs
C:\test1>echo "file contents" > src\file2.css
C:\test1>echo "file contents" > src\dir1\file3.txt
C:\test1>echo "file contents" > src\dir1\file4.cs.txt
C:\test1>echo "file contents" > src\dir2.cs\file5.txt

C:\test1>xcopy /r /i /s /y .\src .\dst
.\src\file1.cs
.\src\file2.css
.\src\dir1\file3.txt
.\src\dir1\file4.cs.txt
.\src\dir2.cs\file5.txt
5 File(s) copied

C:\test1>echo .cs > excludedfileslist.txt
C:\test1>xcopy /r /i /s /y /exclude:excludedfileslist.txt .\src .\dst
.\src\dir1\file3.txt
1 File(s) copied

C:\test1>echo .cs\ > excludedfileslist.txt
C:\test1>xcopy /r /i /s /y /exclude:excludedfileslist.txt .\src .\dst
.\src\file2.css
.\src\dir1\file3.txt
.\src\dir1\file4.cs.txt
3 File(s) copied

This test was completed on a Windows 7 command line and retested on Windows 10 "10.0.14393".

Note that the last example does exclude .\src\dir2.cs\file5.txt which may or may not be unexpected for you.

Copy files without overwrite

It won't let me comment directly on the incorrect messages - but let me just warn everyone, that the definition of the /XN and /XO options are REVERSED compared to what has been posted in previous messages.

The Exclude Older/Newer files option is consistent with the information displayed in RoboCopy's logging: RoboCopy will iterate through the SOURCE and then report whether each file in the SOURCE is "OLDER" or "NEWER" than the file in the destination.

Consequently, /XO will exclude OLDER SOURCE files (which is intuitive), not "older than the source" as had been claimed here.

If you want to copy only new or changed source files, but avoid replacing more recent destination files, then /XO is the correct option to use.

What __init__ and self do in Python?

Just a demo for the question.

class MyClass:

    def __init__(self):
        print('__init__ is the constructor for a class')

    def __del__(self):
        print('__del__ is the destructor for a class')

    def __enter__(self):
        print('__enter__ is for context manager')
        return self

    def __exit__(self, exc_type, exc_value, traceback):
        print('__exit__ is for context manager')

    def greeting(self):
        print('hello python')


if __name__ == '__main__':
    with MyClass() as mycls:
        mycls.greeting()

$ python3 class.objects_instantiation.py
__init__ is the constructor for a class
__enter__ is for context manager
hello python
__exit__ is for context manager
__del__ is the destructor for a class

CRON job to run on the last day of the month

55 23 28-31 * * echo "[ $(date -d +1day +%d) -eq 1 ] && my.sh" | /bin/bash 

how to use #ifdef with an OR condition?

OR condition in #ifdef

#if defined LINUX || defined ANDROID
// your code here
#endif /* LINUX || ANDROID */

or-

#if defined(LINUX) || defined(ANDROID)
// your code here
#endif /* LINUX || ANDROID */

Both above are the same, which one you use simply depends on your taste.


P.S.: #ifdef is simply the short form of #if defined, however, does not support complex condition.


Further-

  • AND: #if defined LINUX && defined ANDROID
  • XOR: #if defined LINUX ^ defined ANDROID

Where is NuGet.Config file located in Visual Studio project?

I have created an answer for this post that might help: https://stackoverflow.com/a/63816822/2399164

Summary:

I am a little late to the game but I believe I found a simple solution to this problem...

  1. Create a "NuGet.Config" file in the same directory as your .sln
<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <packageSources>
    <add key="nuget.org" value="https://api.nuget.org/v3/index.json" protocolVersion="3" />
    <add key="{{CUSTOM NAME}}" value="{{CUSTOM SOURCE}}" />
  </packageSources>
  <packageRestore>
    <add key="enabled" value="True" />
    <add key="automatic" value="True" />
  </packageRestore>
  <bindingRedirects>
    <add key="skip" value="False" />
  </bindingRedirects>
  <packageManagement>
    <add key="format" value="0" />
    <add key="disabled" value="False" />
  </packageManagement>
</configuration>
  1. That is it! Create your "Dockerfile" here as well

  2. Run docker build with your Dockerfile and all will get resolved

How to send a PUT/DELETE request in jQuery?

Here's an updated ajax call for when you are using JSON with jQuery > 1.9:

$.ajax({
    url: '/v1/object/3.json',
    method: 'DELETE',
    contentType: 'application/json',
    success: function(result) {
        // handle success
    },
    error: function(request,msg,error) {
        // handle failure
    }
});

How to increase the distance between table columns in HTML?

Set the width of the <td>s to 50px and then add your <td> + another fake <td>

Fiddle.

_x000D_
_x000D_
table tr td:empty {_x000D_
  width: 50px;_x000D_
}_x000D_
  _x000D_
table tr td {_x000D_
  padding-top: 10px;_x000D_
  padding-bottom: 10px;_x000D_
}
_x000D_
<table>_x000D_
  <tr>_x000D_
    <td>First Column</td>_x000D_
    <td></td>_x000D_
    <td>Second Column</td>_x000D_
    <td></td>_x000D_
    <td>Third Column</td>_x000D_
  </tr>_x000D_
</table>
_x000D_
_x000D_
_x000D_

Code Explained:

The first CSS rule checks for empty td's and give them a width of 50px then the second rule give the padding of top and bottom to all the td's.

How do I remove all non-ASCII characters with regex and Notepad++?

This expression will search for non-ASCII values:

[^\x00-\x7F]+

Tick off 'Search Mode = Regular expression', and click Find Next.

Source: Regex any ASCII character

What is __stdcall?

C or C++ itself do not define those identifiers. They are compiler extensions and stand for certain calling conventions. That determines where to put arguments, in what order, where the called function will find the return address, and so on. For example, __fastcall means that arguments of functions are passed over registers.

The Wikipedia Article provides an overview of the different calling conventions found out there.

How to Lock the data in a cell in excel using vba

Sub LockCells()

Range("A1:A1").Select

Selection.Locked = True

Selection.FormulaHidden = False

ActiveSheet.Protect DrawingObjects:=False, Contents:=True, Scenarios:= False, AllowFormattingCells:=True, AllowFormattingColumns:=True, AllowFormattingRows:=True, AllowInsertingColumns:=True, AllowInsertingRows:=True, AllowInsertingHyperlinks:=True, AllowDeletingColumns:=True, AllowDeletingRows:=True, AllowSorting:=True, AllowFiltering:=True, AllowUsingPivotTables:=True

End Sub

What is the meaning of "operator bool() const"

It's user-defined implicit conversion function to convert your class into either true or false.

//usage
bool value = yourclassinstance; //yourclassinstance is converted into bool!

Set up adb on Mac OS X

For Mac users : Step 1: Install the Android Studio

Step2 : Open the terminal and type

cd

Step 3: Type below mentioned command changing the userName:

export PATH=“/Users/{user_name}/Library/Android/sdk/platform-tools”:$PATH

Running Python in PowerShell?

As far as I have understood your question, you have listed two issues.

PROBLEM 1:

You are not able to execute the Python scripts by double clicking the Python file in Windows.

REASON:

The script runs too fast to be seen by the human eye.

SOLUTION:

Add input() in the bottom of your script and then try executing it with double click. Now the cmd will be open until you close it.

EXAMPLE:

print("Hello World")
input()

PROBLEM 2:

./ issue

SOLUTION:

Use Tab to autocomplete the filenames rather than manually typing the filename with ./ autocomplete automatically fills all this for you.

USAGE:

CD into the directory in which .py files are present and then assume the filename is test.py then type python te and then press Tab, it will be automatically converted to python ./test.py.

How to compare two tables column by column in oracle

Try to use 3rd party tool, such as SQL Data Examiner which compares Oracle databases and shows you differences.

How to create file execute mode permissions in Git on Windows?

Indeed, it would be nice if git-add had a --mode flag

git 2.9.x/2.10 (Q3 2016) actually will allow that (thanks to Edward Thomson):

git add --chmod=+x -- afile
git commit -m"Executable!"

That makes the all process quicker, and works even if core.filemode is set to false.

See commit 4e55ed3 (31 May 2016) by Edward Thomson (ethomson).
Helped-by: Johannes Schindelin (dscho).
(Merged by Junio C Hamano -- gitster -- in commit c8b080a, 06 Jul 2016)

add: add --chmod=+x / --chmod=-x options

The executable bit will not be detected (and therefore will not be set) for paths in a repository with core.filemode set to false, though the users may still wish to add files as executable for compatibility with other users who do have core.filemode functionality.
For example, Windows users adding shell scripts may wish to add them as executable for compatibility with users on non-Windows.

Although this can be done with a plumbing command (git update-index --add --chmod=+x foo), teaching the git-add command allows users to set a file executable with a command that they're already familiar with.

How to use .htaccess in WAMP Server?

Open the httpd.conf file and search for

"rewrite"

, then remove

"#"

at the starting of the line,so the line looks like.

LoadModule rewrite_module modules/mod_rewrite.so

then restart the wamp.

Relative Paths in Javascript in an external file

get the location of your javascript file during run time using jQuery by parsing the DOM for the 'src' attribute that referred it:

var jsFileLocation = $('script[src*=example]').attr('src');  // the js file path
jsFileLocation = jsFileLocation.replace('example.js', '');   // the js folder path

(assuming your javascript file is named 'example.js')

jquery find closest previous sibling with class

Using prevUntil() will allow us to get a distant sibling without having to get all. I had a particularly long set that was too CPU intensive using prevAll().

var category = $('li.current_sub').prev('li.par_cat');
if (category.length == 0){
  category = $('li.current_sub').prevUntil('li.par_cat').last().prev();
}
category.show();

This gets the first preceding sibling if it matches, otherwise it gets the sibling preceding the one that matches, so we just back up one more with prev() to get the desired element.

Body set to overflow-y:hidden but page is still scrollable in Chrome

I finally found a way to fix the issue so I'm answering here.

I set the overflow-y on the #content instead, and wrapped my steps in another div. It works.

Here is the final code:

<body>
  <div id="content">
    <div id="steps">
       <div class="step">this is the 1st step</div>
       <div class="step">this is the 2nd step</div>
       <div class="step">this is the 3rd step</div>
     </div>
   </div>
</body>

#content {
  position:absolute;
  width:100%;
  overflow-y:hidden;
  top:0;
  bottom:0;
}
.step {
  position:relative;
  height:500px;
  margin-bottom:500px;
}

CSS to keep element at "fixed" position on screen

Try this one:

p.pos_fixed {
    position:fixed;
    top:30px;
    right:5px;
}

Wait till a Function with animations is finished until running another Function

You can use the javascript Promise and async/await to implement a synchronized call of the functions.

Suppose you want to execute n number of functions in a synchronized manner that are stored in an array, here is my solution for that.

_x000D_
_x000D_
async function executeActionQueue(funArray) {_x000D_
  var length = funArray.length;_x000D_
  for(var i = 0; i < length; i++) {_x000D_
    await executeFun(funArray[i]);_x000D_
  }_x000D_
};_x000D_
_x000D_
function executeFun(fun) {_x000D_
  return new Promise((resolve, reject) => {_x000D_
    _x000D_
    // Execute required function here_x000D_
    _x000D_
    fun()_x000D_
      .then((data) => {_x000D_
        // do required with data _x000D_
        resolve(true);_x000D_
      })_x000D_
      .catch((error) => {_x000D_
      // handle error_x000D_
        resolve(true);_x000D_
      });_x000D_
  })_x000D_
};_x000D_
_x000D_
executeActionQueue(funArray);
_x000D_
_x000D_
_x000D_

Visibility of global variables in imported modules

Since I haven't seen it in the answers above, I thought I would add my simple workaround, which is just to add a global_dict argument to the function requiring the calling module's globals, and then pass the dict into the function when calling; e.g:

# external_module
def imported_function(global_dict=None):
    print(global_dict["a"])


# calling_module
a = 12
from external_module import imported_function
imported_function(global_dict=globals())

>>> 12

Authentication issue when debugging in VS2013 - iis express

It appears that the right answer is provided by user3149240 above. However, As Neil Watson pointed out, the applicationhost.config file is at play here.

The changes can actually be made in the VS Property pane or in the file albeit in a different spot. Near the bottom of the applicationhost.config file is a set of location elements. Each app for IIS Express seems to have one of these. Changing the settings in the UI updates this section of the file. So, you can either change the settings through the UI or modify this file.

Here is an example with anonymous auth off and Windows auth on:

<location path="MyApp">
    <system.webServer>
        <security>
            <authentication>
                <windowsAuthentication enabled="true" />
                <anonymousAuthentication enabled="false" />
            </authentication>
        </security>
    </system.webServer>
</location>

This is equivalent in the VS UI to:

Anonymous Authentication: Disabled
Windows Authentication: Enabled

How do you find the current user in a Windows environment?

This is the main difference between username variable and whoami command:

C:\Users\user.name>echo %username%
user.name

C:\Users\user.name>whoami
domain\user.name

DOMAIN = bios name of the domain (not fqdn)

What is the role of the package-lock.json?

This file is automatically created and used by npm to keep track of your package installations and to better manage the state and history of your project’s dependencies. You shouldn’t alter the contents of this file.

ASP.NET Custom Validator Client side & Server Side validation not firing

Client-side validation was not being executed at all on my web form and I had no idea why. It turns out the problem was the name of the javascript function was the same as the server control ID.

So you can't do this...

<script>
  function vld(sender, args) { args.IsValid = true; }
</script>
<asp:CustomValidator runat="server" id="vld" ClientValidationFunction="vld" />

But this works:

<script>
  function validate_vld(sender, args) { args.IsValid = true; }
</script>
<asp:CustomValidator runat="server" id="vld" ClientValidationFunction="validate_vld" />

I'm guessing it conflicts with internal .NET Javascript?

Check for false

You can use something simpler:

if(!var){
    console.log('var is false'); 
}

What is the 'instanceof' operator used for in Java?

public class Animal{ float age; }

public class Lion extends Animal { int claws;}

public class Jungle {
    public static void main(String args[]) {

        Animal animal = new Animal(); 
        Animal animal2 = new Lion(); 
        Lion lion = new Lion(); 
        Animal animal3 = new Animal(); 
        Lion lion2 = new Animal();   //won't compile (can't reference super class object with sub class reference variable) 

        if(animal instanceof Lion)  //false

        if(animal2 instanceof Lion)  //true

        if(lion insanceof Lion) //true

        if(animal3 instanceof Animal) //true 

    }
}

Extracting specific columns in numpy array

I think the solution here is not working with an update of the python version anymore, one way to do it with a new python function for it is:

extracted_data = data[['Column Name1','Column Name2']].to_numpy()

which gives you the desired outcome.

The documentation you can find here: https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.to_numpy.html#pandas.DataFrame.to_numpy

sql server invalid object name - but tables are listed in SSMS tables list

I realize this question has already been answered, however, I had a different solution:

If you are writing a script where you drop the tables without recreating them, those tables will show as missing if you try to reference them later on.

Note: This isn't going to happen with a script that is constantly ran, but sometimes it's easier to have a script with queries to reerence than to type them everytime.

Get top most UIViewController

Where did you put the code in?

I try your code in my demo, I found out, if you put the code in

func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { 

will fail, because key window have been setting yet.

But I put your code in some view controller's

override func viewDidLoad() {

It just works.

Best way to unselect a <select> in jQuery?

$("option:selected").attr("selected", false);

Best way to encode Degree Celsius symbol into web page?

Using sup on the letter "o" and a capital "C"

_x000D_
_x000D_
<sup>o</sup>C
_x000D_
_x000D_
_x000D_

Should work in all browsers and IE6+

Formatting code in Notepad++

If all you need is alignment, try the plugin called Code Alignment.

You can get it from the built-in plugin manager in Notepad++.

How to comment/uncomment in HTML code

Depending on your editor, this should be a fairly easy macro to write.

  • Go to beginning of line or highlighted area
  • Insert <!--
  • Go to end of line or highlighted area
  • Insert -->

Another macro to reverse these steps, and you are done.

Edit: this simplistic approach does not handle nested comment tags, but should make the commenting/uncommenting easier in the general case.

How to use Python to login to a webpage and retrieve cookies for later usage?

Here's a version using the excellent requests library:

from requests import session

payload = {
    'action': 'login',
    'username': USERNAME,
    'password': PASSWORD
}

with session() as c:
    c.post('http://example.com/login.php', data=payload)
    response = c.get('http://example.com/protected_page.php')
    print(response.headers)
    print(response.text)

Permanently Set Postgresql Schema Path

You can set the default search_path at the database level:

ALTER DATABASE <database_name> SET search_path TO schema1,schema2;

Or at the user or role level:

ALTER ROLE <role_name> SET search_path TO schema1,schema2;

Or if you have a common default schema in all your databases you could set the system-wide default in the config file with the search_path option.

When a database is created it is created by default from a hidden "template" database named template1, you could alter that database to specify a new default search path for all databases created in the future. You could also create another template database and use CREATE DATABASE <database_name> TEMPLATE <template_name> to create your databases.

How can I generate an MD5 hash?

private String hashuj(String dane) throws ServletException{
    try {
        MessageDigest m = MessageDigest.getInstance("MD5");
        byte[] bufor = dane.getBytes();
        m.update(bufor,0,bufor.length);
        BigInteger hash = new BigInteger(1,m.dige`enter code here`st());
        return String.format("%1$032X", hash);

    } catch (NoSuchAlgorithmException nsae) {
        throw new ServletException("Algorytm szyfrowania nie jest obslugiwany!");
    }
}

how to change language for DataTable

for Arabic language

 var table = $('#my_table')
                .DataTable({
                 "columns":{//......}
                 "language": 
                        {
                            "sProcessing": "???? ???????...",
                            "sLengthMenu": "???? _MENU_ ??????",
                            "sZeroRecords": "?? ???? ??? ??? ?????",
                            "sInfo": "????? _START_ ??? _END_ ?? ??? _TOTAL_ ????",
                            "sInfoEmpty": "???? 0 ??? 0 ?? ??? 0 ???",
                            "sInfoFiltered": "(?????? ?? ????? _MAX_ ?????)",
                            "sInfoPostFix": "",
                            "sSearch": "????:",
                            "sUrl": "",
                            "oPaginate": {
                                "sFirst": "?????",
                                "sPrevious": "??????",
                                "sNext": "??????",
                                "sLast": "??????"
                            }
                        }
                });

Ref: https://datatables.net/plug-ins/i18n/Arabic

Author: Ossama Khayat

JavaScript: Alert.Show(message) From ASP.NET Code-behind

if you are using ScriptManager on the page then you can also try using this:

System.Web.UI.ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "AlertBox", "alert('Your Message');", true);

Finding what methods a Python object has

To check if it has a particular method:

hasattr(object,"method")

Why does ++[[]][+[]]+[+[]] return the string "10"?

++[[]][+[]] => 1 // [+[]] = [0], ++0 = 1
[+[]] => [0]

Then we have a string concatenation

1+[0].toString() = 10

How to avoid reverse engineering of an APK file?

Your client should hire someone that knows what they are doing, who can make the right decisions and can mentor you.

Talk above about you having some ability to change the transaction processing system on the backend is absurd - you shouldn't be allowed to make such architectural changes, so don't expect to be able to.

My rationale on this:

Since your domain is payment processing, its safe to assume that PCI DSS and/or PA DSS (and potential state/federal law) will be significant to your business - to be compliant you must show you are secure. To be insecure then find out (via testing) that you aren't secure, then fixing, retesting, etcetera until security can be verified at a suitable level = expensive, slow, high-risk way to success. To do the right thing, think hard up front, commit experienced talent to the job, develop in a secure manner, then test, fix (less), etcetera (less) until security can be verified at a suitable level = inexpensive, fast, low-risk way to success.

Rails create or update magic?

Rails 6

Rails 6 added an upsert and upsert_all methods that deliver this functionality.

Model.upsert(column_name: value)

[upsert] It does not instantiate any models nor does it trigger Active Record callbacks or validations.

Rails 5, 4, and 3

Not if you are looking for an "upsert" (where the database executes an update or an insert statement in the same operation) type of statement. Out of the box, Rails and ActiveRecord have no such feature. You can use the upsert gem, however.

Otherwise, you can use: find_or_initialize_by or find_or_create_by, which offer similar functionality, albeit at the cost of an additional database hit, which, in most cases, is hardly an issue at all. So unless you have serious performance concerns, I would not use the gem.

For example, if no user is found with the name "Roger", a new user instance is instantiated with its name set to "Roger".

user = User.where(name: "Roger").first_or_initialize
user.email = "[email protected]"
user.save

Alternatively, you can use find_or_initialize_by.

user = User.find_or_initialize_by(name: "Roger")

In Rails 3.

user = User.find_or_initialize_by_name("Roger")
user.email = "[email protected]"
user.save

You can use a block, but the block only runs if the record is new.

User.where(name: "Roger").first_or_initialize do |user|
  # this won't run if a user with name "Roger" is found
  user.save 
end

User.find_or_initialize_by(name: "Roger") do |user|
  # this also won't run if a user with name "Roger" is found
  user.save
end

If you want to use a block regardless of the record's persistence, use tap on the result:

User.where(name: "Roger").first_or_initialize.tap do |user|
  user.email = "[email protected]"
  user.save
end

Autoincrement VersionCode with gradle extra properties

Define versionName in AndroidManifest.xml

android:versionName="5.1.5"

Inside android{...} block in build.gradle of app level :

defaultConfig {
        applicationId "com.example.autoincrement"
        minSdkVersion 18
        targetSdkVersion 23
        multiDexEnabled true
        def version = getIncrementationVersionName()
        versionName version
}

Outside android{...} block in build.gradle of app level :

def getIncrementedVersionName() {
    List<String> runTasks = gradle.startParameter.getTaskNames();

    //find version name in manifest
    def manifestFile = file('src/main/AndroidManifest.xml')
    def matcher = Pattern.compile('versionName=\"(\\d+)\\.(\\d+)\\.(\\d+)\"').matcher(manifestFile.getText())
    matcher.find()

    //extract versionName parts
    def firstPart = Integer.parseInt(matcher.group(1))
    def secondPart = Integer.parseInt(matcher.group(2))
    def thirdPart = Integer.parseInt(matcher.group(3))

    //check is runTask release or not
    // if release - increment version
    for (String item : runTasks) {
        if (item.contains("assemble") && item.contains("Release")) {
            thirdPart++
            if (thirdPart == 10) {
                thirdPart = 0;
                secondPart++
                if (secondPart == 10) {
                    secondPart = 0;
                    firstPart++
                }
            }
        }
    }

    def versionName = firstPart + "." + secondPart + "." + thirdPart

    // update manifest
    def manifestContent = matcher.replaceAll('versionName=\"' + versionName + '\"')
    manifestFile.write(manifestContent)

    println "incrementVersionName = " + versionName

    return versionName
}

After create singed APK :

android:versionName="5.1.6"

Note : If your versionName different from my, you need change regex and extract parts logic.

How to get the parents of a Python class?

The FASTEST way, to see all parents, and IN ORDER, just use the built in __mro__

i.e. repr(YOUR_CLASS.__mro__)


>>>
>>>
>>> import getpass
>>> getpass.GetPassWarning.__mro__

outputs, IN ORDER


(<class 'getpass.GetPassWarning'>, <type 'exceptions.UserWarning'>,
<type 'exceptions.Warning'>, <type 'exceptions.Exception'>, 
<type 'exceptions.BaseException'>, <type 'object'>)
>>>

There you have it. The "best" answer right now, has 182 votes (as I am typing this) but this is SO much simpler than some convoluted for loop, looking into bases one class at a time, not to mention when a class extends TWO or more parent classes. Importing and using inspect just clouds the scope unnecessarily. It honestly is a shame people don't know to just use the built-ins

I Hope this Helps!

How to define a List bean in Spring?

Stacker posed a great answer, I would go one step farther to make it more dynamic and use Spring 3 EL Expression.

<bean id="listBean" class="java.util.ArrayList">
        <constructor-arg>
            <value>#{springDAOBean.getGenericListFoo()}</value>
        </constructor-arg>
</bean>

I was trying to figure out how I could do this with the util:list but couldn't get it work due to conversion errors.

Node.js - get raw request body using Express

This solution worked for me:

var rawBodySaver = function (req, res, buf, encoding) {
  if (buf && buf.length) {
    req.rawBody = buf.toString(encoding || 'utf8');
  }
}

app.use(bodyParser.json({ verify: rawBodySaver }));
app.use(bodyParser.urlencoded({ verify: rawBodySaver, extended: true }));
app.use(bodyParser.raw({ verify: rawBodySaver, type: '*/*' }));

When I use solution with req.on('data', function(chunk) { }); it not working on chunked request body.

JavaScript seconds to time string with format hh:mm:ss

I loved Powtac's answer, but I wanted to use it in angular.js, so I created a filter using his code.

.filter('HHMMSS', ['$filter', function ($filter) {
    return function (input, decimals) {
        var sec_num = parseInt(input, 10),
            decimal = parseFloat(input) - sec_num,
            hours   = Math.floor(sec_num / 3600),
            minutes = Math.floor((sec_num - (hours * 3600)) / 60),
            seconds = sec_num - (hours * 3600) - (minutes * 60);

        if (hours   < 10) {hours   = "0"+hours;}
        if (minutes < 10) {minutes = "0"+minutes;}
        if (seconds < 10) {seconds = "0"+seconds;}
        var time    = hours+':'+minutes+':'+seconds;
        if (decimals > 0) {
            time += '.' + $filter('number')(decimal, decimals).substr(2);
        }
        return time;
    };
}])

It's functionally identical, except that I added in an optional decimals field to display fractional seconds. Use it like you would any other filter:

{{ elapsedTime | HHMMSS }} displays: 01:23:45

{{ elapsedTime | HHMMSS : 3 }} displays: 01:23:45.678

Checking on a thread / remove from list

mythreads = threading.enumerate()

Enumerate returns a list of all Thread objects still alive. https://docs.python.org/3.6/library/threading.html

Text inset for UITextField?

If you want to change TOP and LEFT indent only then

// placeholder position

- (CGRect)textRectForBounds:(CGRect)bounds {

CGRect frame = bounds;
frame.origin.y = 3;
 frame.origin.x = 5;
bounds = frame;
return CGRectInset( bounds , 0 , 0 );
}

// text position

- (CGRect)editingRectForBounds:(CGRect)bounds {

CGRect frame = bounds;
frame.origin.y = 3;
 frame.origin.x = 5;
bounds = frame;
return CGRectInset( bounds , 0 , 0 );
}

docker: "build" requires 1 argument. See 'docker build --help'

My problem was the Dockerfile.txt needed to be converted to a Unix executable file. Once I did that that error went away.

You may need to remove the .txt portion before doing this, but on a mac go to terminal and cd into the directory where your Dockerfile is and the type

chmod +x "Dockerfile"

And then it will convert your file to a Unix executable file which can then be executed by the Docker build command.

Setting CSS pseudo-class rules from JavaScript

Just place the css in a template string.

const cssTemplateString = `.foo:[psuedoSelector]{prop: value}`;

Then create a style element and place the string in the style tag and attach it to the document.

const styleTag = document.createElement("style");
styleTag.innerHTML = cssTemplateString;
document.head.insertAdjacentElement('beforeend', styleTag);

Specificity will take care of the rest. Then you can remove and add style tags dynamically. This is a simple alternative to libraries and messing with the stylesheet array in the DOM. Happy Coding!

perform an action on checkbox checked or unchecked event on html form

The problem is how you've attached the listener:

<input type="checkbox" ...  onchange="doalert(this.id)">

Inline listeners are effectively wrapped in a function which is called with the element as this. That function then calls the doalert function, but doesn't set its this so it will default to the global object (window in a browser).

Since the window object doesn't have a checked property, this.checked always resolves to false.

If you want this within doalert to be the element, attach the listener using addEventListener:

window.onload = function() {
  var input = document.querySelector('#g01-01');
  if (input) {   
    input.addEventListener('change', doalert, false);
  }
}

Or if you wish to use an inline listener:

<input type="checkbox" ...  onchange="doalert.call(this, this.id)">

How do you enable mod_rewrite on any OS?

network solutions offers the advice to put a php.ini in the cgi-bin to enable mod_rewrite

Load resources from relative path using local html in uiwebview

I crammed everything into one line (bad I know) and had no troubles with it:

[webView loadRequest:[NSURLRequest requestWithURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"test" 
                                                                                                         ofType:@"html"]
                                                             isDirectory:NO]]];         

How does one convert a HashMap to a List in Java?

If you only want it to iterate over your HashMap, no need for a list:

HashMap<Integer, String> map = new HashMap<Integer, String>();
map.put (1, "Mark");
map.put (2, "Tarryn");
for (String s : map.values()) {
    System.out.println(s);
}

Of course, if you want to modify your map structurally (i.e. more than only changing the value for an existing key) while iterating, then you better use the "copy to ArrayList" method, since otherwise you'll get a ConcurrentModificationException. Or export as an array:

HashMap<Integer, String> map = new HashMap<Integer, String>();
map.put (1, "Mark");
map.put (2, "Tarryn");
for (String s : map.values().toArray(new String[]{})) {
    System.out.println(s);
}

How do I escape ampersands in XML so they are rendered as entities in HTML?

I have tried &amp, but it didn't work. Based on Wim ten Brink's answer I tried &amp;amp and it worked.

One of my fellow developers suggested me to use &#x26; and that worked regardless of how many times it may be rendered.

PHP Warning: mysqli_connect(): (HY000/2002): Connection refused

For me to make it work again I just deleted the files

ib_logfile0

and

ib_logfile1

.

from :

/Applications/MAMP/db/mysql56/ib_logfile0 

Mac 10.13.3
MAMP:Version 4.3 (853)

Find a row in dataGridView based on column and value

Those who use WPF

for (int i = 0; i < dataGridName.Items.Count; i++)
{
      string cellValue= ((DataRowView)dataGridName.Items[i]).Row["columnName"].ToString();                
      if (cellValue.Equals("Search_string")) // check the search_string is present in the row of ColumnName
      {
         object item = dataGridName.Items[i];
         dataGridName.SelectedItem = item; // selecting the row of dataGridName
         dataGridName.ScrollIntoView(item);                    
         break;
      }
}

if you want to get the selected row items after this, the follwing code snippet is helpful

DataRowView drv = dataGridName.SelectedItem as DataRowView;
DataRow dr = drv.Row;
string item1= Convert.ToString(dr.ItemArray[0]);// get the first column value from selected row 
string item2= Convert.ToString(dr.ItemArray[1]);// get the second column value from selected row 

Changing Fonts Size in Matlab Plots

If anyone was wondering how to change the font sizes without messing around with the Matlab default fonts, and change every font in a figure, I found this thread where suggests this:

set(findall(fig, '-property', 'FontSize'), 'FontSize', 10, 'fontWeight', 'bold')

findall is a pretty handy command and in the case above it really finds all the children who have a 'FontSize' property: axes lables, axes titles, pushbuttons, etc.

Hope it helps.

How to calculate the width of a text string of a specific font and font-size?

The way I am doing it my code is to make an extension of UIFont: (This is Swift 4.1)

extension UIFont {


    public func textWidth(s: String) -> CGFloat
    {
        return s.size(withAttributes: [NSAttributedString.Key.font: self]).width
    }

} // extension UIFont

java.lang.ClassNotFoundException: HttpServletRequest

Your web app has servlet container specific libraries like servlet-api.jar file in its /WEB-INF/lib. This is not right. Remove them all. The /WEB-INF/lib should contain only the libraries specific to the Web app, not to the servlet container. The servlet container (like Tomcat) is the one who should already provide the servlet container specific libraries. If you supply libraries from an arbitrary servlet container of a different make/version, you'll run into this kind of problems, as your web app wouldn't be able to run on a servlet container of a different make/version than those libraries originated from.

This is a pretty common starter's mistake when they encounter compile-time errors, as they haven't set up their IDE project right. See also How do I import the javax.servlet API in my Eclipse project?

Change grid interval and specify tick labels in Matplotlib

A subtle alternative to MaxNoe's answer where you aren't explicitly setting the ticks but instead setting the cadence.

import matplotlib.pyplot as plt
from matplotlib.ticker import (AutoMinorLocator, MultipleLocator)

fig, ax = plt.subplots(figsize=(10, 8))

# Set axis ranges; by default this will put major ticks every 25.
ax.set_xlim(0, 200)
ax.set_ylim(0, 200)

# Change major ticks to show every 20.
ax.xaxis.set_major_locator(MultipleLocator(20))
ax.yaxis.set_major_locator(MultipleLocator(20))

# Change minor ticks to show every 5. (20/4 = 5)
ax.xaxis.set_minor_locator(AutoMinorLocator(4))
ax.yaxis.set_minor_locator(AutoMinorLocator(4))

# Turn grid on for both major and minor ticks and style minor slightly
# differently.
ax.grid(which='major', color='#CCCCCC', linestyle='--')
ax.grid(which='minor', color='#CCCCCC', linestyle=':')

Matplotlib Custom Grid

How to append to the end of an empty list?

Like Mikola said, append() returns a void, so every iteration you're setting list1 to a nonetype because append is returning a nonetype. On the next iteration, list1 is null so you're trying to call the append method of a null. Nulls don't have methods, hence your error.

Remove all child nodes from a parent?

A other users suggested,

.empty()

is good enought, because it removes all descendant nodes (both tag-nodes and text-nodes) AND all kind of data stored inside those nodes. See the JQuery's API empty documentation.

If you wish to keep data, like event handlers for example, you should use

.detach()

as described on the JQuery's API detach documentation.

The method .remove() could be usefull for similar purposes.

Method to get all files within folder and subfolders that will return a list

I am not sure of why you're adding the strings to files, which is declared as a field rather than a temporary variable. You could change the signature of DirSearch to:

private List<string> DirSearch(string sDir)

And, after the catch block, add:

return files;

Alternatively, you could create a temporary variable inside of your method and return it, which seems to me the approach you might desire. Otherwise, each time you call that method, the newly found strings will be added to the same list as before and you'll have duplicates.

How to start and stop android service from a adb shell?

Responding to pzulw's feedback to sandroid about specifying the intent.

The format of the component name is described in the api docs for ComponentName.unflattenFromString

It splits the string at the first '/', taking the part before as the package name and the part after as the class name. As a special convenience (to use, for example, when parsing component names on the command line), if the '/' is immediately followed by a '.' then the final class name will be the concatenation of the package name with the string following the '/'. Thus "com.foo/.Blah" becomes package="com.foo" class="com.foo.Blah".

How exactly does binary code get converted into letters?

Assuming that by "binary code" you mean just plain old data (sequences of bits, or bytes), and that by "letters" you mean characters, the answer is in two steps. But first, some background.

  • A character is just a named symbol, like "LATIN CAPITAL LETTER A" or "GREEK SMALL LETTER PI" or "BLACK CHESS KNIGHT". Do not confuse a character (abstract symbol) with a glyph (a picture of a character).
  • A character set is a particular set of characters, each of which is associated with a special number, called its codepoint. To see the codepoint mappings in the Unicode character set, see http://www.unicode.org/Public/UNIDATA/UnicodeData.txt.

Okay now here are the two steps:

  1. The data, if it is textual, must be accompanied somehow by a character encoding, something like UTF-8, Latin-1, US-ASCII, etc. Each character encoding scheme specifies in great detail how byte sequences are interpreted as codepoints (and conversely how codepoints are encoded as byte sequences).

  2. Once the byte sequences are interpreted as codepoints, you have your characters, because each character has a specific codepoint.

A couple notes:

  • In some encodings, certain byte sequences correspond to no codepoints at all, so you can have character decoding errors.
  • In some character sets, there are codepoints that are unused, that is, they correspond to no character at all.

In other words, not every byte sequence means something as text.

Android: How to handle right to left swipe gestures

I've been doing similar things, but for horizontal swipes only

import android.content.Context
import android.view.GestureDetector
import android.view.MotionEvent
import android.view.View

abstract class OnHorizontalSwipeListener(val context: Context) : View.OnTouchListener {    

    companion object {
         const val SWIPE_MIN = 50
         const val SWIPE_VELOCITY_MIN = 100
    }

    private val detector = GestureDetector(context, GestureListener())

    override fun onTouch(view: View, event: MotionEvent) = detector.onTouchEvent(event)    

    abstract fun onRightSwipe()

    abstract fun onLeftSwipe()

    private inner class GestureListener : GestureDetector.SimpleOnGestureListener() {    

        override fun onDown(e: MotionEvent) = true

        override fun onFling(e1: MotionEvent, e2: MotionEvent, velocityX: Float, velocityY: Float)
            : Boolean {

            val deltaY = e2.y - e1.y
            val deltaX = e2.x - e1.x

            if (Math.abs(deltaX) < Math.abs(deltaY)) return false

            if (Math.abs(deltaX) < SWIPE_MIN
                    && Math.abs(velocityX) < SWIPE_VELOCITY_MIN) return false

            if (deltaX > 0) onRightSwipe() else onLeftSwipe()

            return true
        }
    }
}

And then it can be used for view components

private fun listenHorizontalSwipe(view: View) {
    view.setOnTouchListener(object : OnHorizontalSwipeListener(context!!) {
            override fun onRightSwipe() {
                Log.d(TAG, "Swipe right")
            }

            override fun onLeftSwipe() {
                Log.d(TAG, "Swipe left")
            }

        }
    )
}

How to prevent rm from reporting that a file was not found?

The main use of -f is to force the removal of files that would not be removed using rm by itself (as a special case, it "removes" non-existent files, thus suppressing the error message).

You can also just redirect the error message using

$ rm file.txt 2> /dev/null

(or your operating system's equivalent). You can check the value of $? immediately after calling rm to see if a file was actually removed or not.

How to launch a Google Chrome Tab with specific URL using C#

As a simplification to chrfin's response, since Chrome should be on the run path if installed, you could just call:

Process.Start("chrome.exe", "http://www.YourUrl.com");

This seem to work as expected for me, opening a new tab if Chrome is already open.

Read remote file with node.js (http.get)

You can do something like this, without using any external libraries.

const fs = require("fs");
const https = require("https");

const file = fs.createWriteStream("data.txt");

https.get("https://www.w3.org/TR/PNG/iso_8859-1.txt", response => {
  var stream = response.pipe(file);

  stream.on("finish", function() {
    console.log("done");
  });
});

Error You must specify a region when running command aws ecs list-container-instances

"You must specify a region" is a not an ECS specific error, it can happen with any AWS API/CLI/SDK command.

For the CLI, either set the AWS_DEFAULT_REGION environment variable. e.g.

export AWS_DEFAULT_REGION=us-east-1

or add it into the command (you will need this every time you use a region-specific command)

AWS_DEFAULT_REGION=us-east-1 aws ecs list-container-instances --cluster default

or set it in the CLI configuration file: ~/.aws/config

[default]
region=us-east-1

or pass/override it with the CLI call:

aws ecs list-container-instances --cluster default --region us-east-1

How to use Angular4 to set focus by element id

Here is an Angular4+ directive that you can re-use in any component. Based on code given in the answer by Niel T in this question.

import { NgZone, Renderer, Directive, Input } from '@angular/core';

@Directive({
    selector: '[focusDirective]'
})
export class FocusDirective {
    @Input() cssSelector: string

    constructor(
        private ngZone: NgZone,
        private renderer: Renderer
    ) { }

    ngOnInit() {
        console.log(this.cssSelector);
        this.ngZone.runOutsideAngular(() => {
            setTimeout(() => {
                this.renderer.selectRootElement(this.cssSelector).focus();
            }, 0);
        });
    }
}

You can use it in a component template like this:

<input id="new-email" focusDirective cssSelector="#new-email"
  formControlName="email" placeholder="Email" type="email" email>

Give the input an id and pass the id to the cssSelector property of the directive. Or you can pass any cssSelector you like.

Comments from Niel T:

Since the only thing I'm doing is setting the focus on an element, I don't need to concern myself with change detection, so I can actually run the call to renderer.selectRootElement outside of Angular. Because I need to give the new sections time to render, the element section is wrapped in a timeout to allow the rendering threads time to catch up before the element selection is attempted. Once all that is setup, I can simply call the element using basic CSS selectors.

How to set delay in android?

You can use CountDownTimer which is much more efficient than any other solution posted. You can also produce regular notifications on intervals along the way using its onTick(long) method

Have a look at this example showing a 30seconds countdown

   new CountDownTimer(30000, 1000) {
         public void onFinish() {
             // When timer is finished 
             // Execute your code here
     }

     public void onTick(long millisUntilFinished) {
              // millisUntilFinished    The amount of time until finished.
     }
   }.start();

How to get info on sent PHP curl request

You can also use a proxy tool like Charles to capture the outgoing request headers, data, etc. by passing the proxy details through CURLOPT_PROXY to your curl_setopt_array method.

For example:

$proxy = '127.0.0.1:8888';
$opt = array (
    CURLOPT_URL => "http://www.example.com",
    CURLOPT_PROXY => $proxy,
    CURLOPT_POST => true,
    CURLOPT_VERBOSE => true,
    );

$ch = curl_init();
curl_setopt_array($ch, $opt);
curl_exec($ch);
curl_close($ch);

Constantly print Subprocess output while process is running

In Python 3.6 I used this:

import subprocess

cmd = "command"
output = subprocess.call(cmd, shell=True)
print(process)

In javascript, how do you search an array for a substring match

I've created a simple to use library (ss-search) which is designed to handle objects, but could also work in your case:

search(windowArray.map(x => ({ key: x }), ["key"], "SEARCH_TEXT").map(x => x.key)

The advantage of using this search function is that it will normalize the text before executing the search to return more accurate results.

check if a string matches an IP address pattern in python?

update: The original answer bellow is good for 2011, but since 2012, one is likely better using Python's ipaddress stdlib module - besides checking IP validity for IPv4 and IPv6, it can do a lot of other things as well.</update>

It looks like you are trying to validate IP addresses. A regular expression is probably not the best tool for this.

If you want to accept all valid IP addresses (including some addresses that you probably didn't even know were valid) then you can use IPy (Source):

from IPy import IP
IP('127.0.0.1')

If the IP address is invalid it will throw an exception.

Or you could use socket (Source):

import socket
try:
    socket.inet_aton(addr)
    # legal
except socket.error:
    # Not legal

If you really want to only match IPv4 with 4 decimal parts then you can split on dot and test that each part is an integer between 0 and 255.

def validate_ip(s):
    a = s.split('.')
    if len(a) != 4:
        return False
    for x in a:
        if not x.isdigit():
            return False
        i = int(x)
        if i < 0 or i > 255:
            return False
    return True

Note that your regular expression doesn't do this extra check. It would accept 999.999.999.999 as a valid address.

set font size in jquery

$("#"+styleTarget).css('font-size', newFontSize);

CSS horizontal scroll

try using table structure, it's more back compatible. Check this outHorizontal Scrolling using Tables

Prime numbers between 1 to 100 in C Programming Language

The condition i==j+1 will not be true for i==2. This can be fixed by a couple of changes to the inner loop:

#include <stdio.h>
int main(void)
{
 for (int i=2; i<100; i++)
 {
  for (int j=2; j<=i; j++)   // Changed upper bound
  {
    if (i == j)  // Changed condition and reversed order of if:s
      printf("%d\n",i);
    else if (i%j == 0)
      break;
  }
 }
}

Access parent DataContext from DataTemplate

I was searching how to do something similar in WPF and I got this solution:

<ItemsControl ItemsSource="{Binding MyItems,Mode=OneWay}">
<ItemsControl.ItemsPanel>
    <ItemsPanelTemplate>
        <StackPanel Orientation="Vertical" />
    </ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
<ItemsControl.ItemTemplate>
    <DataTemplate>
        <RadioButton 
            Content="{Binding}" 
            Command="{Binding Path=DataContext.CustomCommand, 
                        RelativeSource={RelativeSource Mode=FindAncestor,      
                        AncestorType={x:Type ItemsControl}} }"
            CommandParameter="{Binding}" />
    </DataTemplate>
</ItemsControl.ItemTemplate>

I hope this works for somebody else. I have a data context which is set automatically to the ItemsControls, and this data context has two properties: MyItems -which is a collection-, and one command 'CustomCommand'. Because of the ItemTemplate is using a DataTemplate, the DataContext of upper levels is not directly accessible. Then the workaround to get the DC of the parent is use a relative path and filter by ItemsControl type.

How to add double quotes to a string that is inside a variable?

In C# you can use:

 string1 = @"Your ""Text"" Here";
 string2 = "Your \"Text\" Here";

Unexpected token ILLEGAL in webkit

It won't be exactly refering to the given problem, but I wanna share my mistake here, maybe some1 will make simmilar one and will also land with his/her problem here:

Ive got Unexpected token ILLEGAL error because I named a function with a number as 1st char.

It was 3x3check(). Changing it to check3x3() solved my problem.

textarea's rows, and cols attribute in CSS

I don't think you can. I always go with height and width.

textarea{
width:400px;
height:100px;
}

the nice thing about doing it the CSS way is that you can completely style it up. Now you can add things like:

textarea{
width:400px;
height:100px;
border:1px solid #000000;
background-color:#CCCCCC;
}

How to block users from closing a window in Javascript?

Well you can use the window.onclose event and return false in the event handler.

function closedWin() {
    confirm("close ?");
    return false; /* which will not allow to close the window */
}
if(window.addEventListener) {
     window.addEventListener("close", closedWin, false);
}

window.onclose = closedWin;

Code was taken from this site.

In the other hand, if they force the closing (by using task manager or something in those lines) you cannot do anything about it.

java.sql.SQLException: No suitable driver found for jdbc:mysql://localhost:3306/dbname

In your code you are missing Class.forName("com.mysql.jdbc.Driver");

This is what you are missing to have everything working.

How to create a printable Twitter-Bootstrap page

If you want to keep columns on A4 print (which is around 540px) this is a good idea

@media print {
    .make-grid(print-A4);
}

.make-print-A4-column(@columns) {
    @media print {
        float: left;
        width: percentage((@columns / @grid-columns));
    }
}

You can use it like this:

<div class="col-sm-4 col-print-A4-4">

Is having an 'OR' in an INNER JOIN condition a bad idea?

You can use UNION ALL instead.

SELECT mt.ID, mt.ParentID, ot.MasterID FROM dbo.MainTable AS mt Union ALL SELECT mt.ID, mt.ParentID, ot.MasterID FROM dbo.OtherTable AS ot

JQuery Ajax POST in Codeigniter

The question has already been answered but I thought I would also let you know that rather than using the native PHP $_POST I reccomend you use the CodeIgniter input class so your controller code would be

function post_action()
{   
    if($this->input->post('textbox') == "")
    {
        $message = "You can't send empty text";
    }
    else
    {
        $message = $this->input->post('textbox');
    }
    echo $message;
}

How to insert a column in a specific position in oracle without dropping and recreating the table?

Although this is somewhat old I would like to add a slightly improved version that really changes column order. Here are the steps (assuming we have a table TAB1 with columns COL1, COL2, COL3):

  1. Add new column to table TAB1:
alter table TAB1 add (NEW_COL number);
  1. "Copy" table to temp name while changing the column order AND rename the new column:
create table tempTAB1 as select NEW_COL as COL0, COL1, COL2, COL3 from TAB1;
  1. drop existing table:
drop table TAB1;
  1. rename temp tablename to just dropped tablename:
rename tempTAB1 to TAB1;

MySQL: How to add one day to datetime field in query

$date = strtotime(date("Y-m-d", strtotime($date)) . " +1 day");

Or, simplier:

date("Y-m-d H:i:s", time()+((60*60)*24));

Oracle SQL - select within a select (on the same table!)

SELECT eh."Gc_Staff_Number",
       eh."Start_Date",
       MAX(eh2."End_Date") AS "End_Date"
FROM   "Employment_History" eh
LEFT JOIN  "Employment_History" eh2
ON eh."Employee_Number" = eh2."Employee_Number" and eh2."Current_Flag" != 'Y'
WHERE  eh."Current_Flag" = 'Y' 
GROUP BY eh."Gc_Staff_Number",
       eh."Start_Date

Hiding a button in Javascript

If the space on that page is not disabled then put your button inside a div.

<div id="a1">
<button>Click here</button>
</div>

Using Jquery:

<script language="javascript">
$("#a1").hide();
</script>

Using JS:

<script language="javascript">
document.getElementById("a1").style.visibility = "hidden";
document.getElementById("a1").style.display = "none";
</script>

img tag displays wrong orientation

You can use Exif-JS , to check the "Orientation" property of the image. Then apply a css transform as needed.

EXIF.getData(imageElement, function() {
                var orientation = EXIF.getTag(this, "Orientation");

                if(orientation == 6)
                    $(imageElement).css('transform', 'rotate(90deg)')
});  

CSS: Auto resize div to fit container width

CSS auto-fit container between float:left & float:right divs solved my problem, thanks for your comments.

#left
{
    width:200px;
    float:left;
    background-color:antiquewhite;
    margin-left:10px;
}
#content
{
    overflow:hidden;
    margin-left:10px;
    background-color:AppWorkspace;
}

Create folder with batch but only if it doesn't already exist

I use this way, you should put a backslash at the end of the directory name to avoid that place exists in a file without extension with the same name as the directory you specified, never use "C:\VTS" because it can a file exists with the name "VTS" saved in "C:" partition, the correct way is to use "C:\VTS\", check out the backslash after the VTS, so is the right way.

@echo off
@break off
@title Create folder with batch but only if it doesn't already exist - D3F4ULT
@color 0a
@cls

setlocal EnableDelayedExpansion

if not exist "C:\VTS\" (
  mkdir "C:\VTS\"
  if "!errorlevel!" EQU "0" (
    echo Folder created successfully
  ) else (
    echo Error while creating folder
  )
) else (
  echo Folder already exists
)

pause
exit

The tilde operator in Python

One should note that in the case of array indexing, array[~i] amounts to reversed_array[i]. It can be seen as indexing starting from the end of the array:

[0, 1, 2, 3, 4, 5, 6, 7, 8]
    ^                 ^
    i                ~i

fatal: does not appear to be a git repository

You've got the syntax for the scp-style way of specifying a repository slightly wrong - it has to be:

[user@]host.xz:path/to/repo.git/

... as you can see in the git clone documentation. You should use instead the URL:

[email protected]:/gittest.git

i.e. in the URL you're using, you missed out the : (colon)

To update the URL for origin you could do:

git remote set-url origin [email protected]:/gittest.git

Is there a standard sign function (signum, sgn) in C/C++?

There is a C99 math library function called copysign(), which takes the sign from one argument and the absolute value from the other:

result = copysign(1.0, value) // double
result = copysignf(1.0, value) // float
result = copysignl(1.0, value) // long double

will give you a result of +/- 1.0, depending on the sign of value. Note that floating point zeroes are signed: (+0) will yield +1, and (-0) will yield -1.

Why is access to the path denied?

If this is an IIS website that is having the problem, check the Identity property of the advanced settings for the application pool that the site or application uses. You may find that it is set to ApplicationPoolIdentity, and in that case then this is the user that will have to have access to the path.

Or you can go old style and simply set the Identity to Network Service, and give the Network Service user access to the path.

String comparison - Android

try this.

        String g1 = "Male";
        String g2 = "Female";
        String gender = "Male";
        String salutation = "";
        if (gender.equalsIgnoreCase(g1))

            salutation = "Mr.";
        else if (gender.equalsIgnoreCase(g2))

            salutation = "Ms.";
        System.out.println("Welcome " + salutation);

Output:

Welcome Mr.

Xcode 10 Error: Multiple commands produce

For dependency projects managed by cocoapods, solved the problem by providing a local podspec to exclude info.plist from sources. Take godzippa as an example

Podfile pod 'Godzippa', :podspec => "venders/godzippa.podspec"

venders/godzippa.podspec s.source_files = 'Sources/*.{h,m}'

How to make the corners of a button round?

Create file myButton.xml

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
    <solid android:color="@color/colorButton"/>
    <corners android:radius="10dp"/>
</shape>

add to your button

 <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:background="@drawable/myButton"/>

How to add subject alernative name to ssl certs?

Both IP and DNS can be specified with the keytool additional argument -ext SAN=dns:abc.com,ip:1.1.1.1

Example:

keytool -genkeypair -keystore <keystore> -dname "CN=test, OU=Unknown, O=Unknown, L=Unknown, ST=Unknown, C=Unknown" -keypass <keypwd> -storepass <storepass> -keyalg RSA -alias unknown -ext SAN=dns:test.abc.com,ip:1.1.1.1

Return list of items in list greater than some value

You can use a list comprehension to filter it:

j2 = [i for i in j if i >= 5]

If you actually want it sorted like your example was, you can use sorted:

j2 = sorted(i for i in j if i >= 5)

or call sort on the final list:

j2 = [i for i in j if i >= 5]
j2.sort()

Android Studio: /dev/kvm device permission denied

Open Terminal and log as admin

sudo su

Go to the dev folder

cd /dev/

Change the kvm mode

chmod 777 -R kvm

Generate random colors (RGB)

You could also use Hex Color Code,

Name    Hex Color Code  RGB Color Code
Red     #FF0000         rgb(255, 0, 0)
Maroon  #800000         rgb(128, 0, 0)
Yellow  #FFFF00         rgb(255, 255, 0)
Olive   #808000         rgb(128, 128, 0)

For example

import matplotlib.pyplot as plt
import random

number_of_colors = 8

color = ["#"+''.join([random.choice('0123456789ABCDEF') for j in range(6)])
             for i in range(number_of_colors)]
print(color)

['#C7980A', '#F4651F', '#82D8A7', '#CC3A05', '#575E76', '#156943', '#0BD055', '#ACD338']

Lets try plotting them in a scatter plot

for i in range(number_of_colors):
    plt.scatter(random.randint(0, 10), random.randint(0,10), c=color[i], s=200)

plt.show()

enter image description here

Is it possible to use jQuery to read meta tags

Just use something like:

var author = $('meta[name=author]').attr('content');

C++ convert string to hexadecimal and vice versa

Here is an other solution, largely inspired by the one by @fredoverflow.

/**
 * Return hexadecimal representation of the input binary sequence
 */
std::string hexitize(const std::vector<char>& input, const char* const digits = "0123456789ABCDEF")
{
    std::ostringstream output;

    for (unsigned char gap = 0, beg = input[gap]; gap < input.length(); beg = input[++gap])
        output << digits[beg >> 4] << digits[beg & 15];

    return output.str();
}

Length was required parameter in the intended usage.

How can I get screen resolution in java?

Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
double width = screenSize.getWidth();
double height = screenSize.getHeight();
framemain.setSize((int)width,(int)height);
framemain.setResizable(true);
framemain.setExtendedState(JFrame.MAXIMIZED_BOTH);

DELETE_FAILED_INTERNAL_ERROR Error while Installing APK

I was getting the same Error in MI Note 4 I solved my problem :- Enable Install via USB in Developer Option. Developer Option>>Install Via USB To enable Install Via USB Turn off WiFi And Turn On Network Data and try to Enable

How to set background color of HTML element using css properties in JavaScript

You might find your code is more maintainable if you keep all your styles, etc. in CSS and just set / unset class names in JavaScript.

Your CSS would obviously be something like:

.highlight {
    background:#ff00aa;
}

Then in JavaScript:

element.className = element.className === 'highlight' ? '' : 'highlight';

Correct use for angular-translate in controllers

What is happening is that Angular-translate is watching the expression with an event-based system, and just as in any other case of binding or two-way binding, an event is fired when the data is retrieved, and the value changed, which obviously doesn't work for translation. Translation data, unlike other dynamic data on the page, must, of course, show up immediately to the user. It can't pop in after the page loads.

Even if you can successfully debug this issue, the bigger problem is that the development work involved is huge. A developer has to manually extract every string on the site, put it in a .json file, manually reference it by string code (ie 'pageTitle' in this case). Most commercial sites have thousands of strings for which this needs to happen. And that is just the beginning. You now need a system of keeping the translations in synch when the underlying text changes in some of them, a system for sending the translation files out to the various translators, of reintegrating them into the build, of redeploying the site so the translators can see their changes in context, and on and on.

Also, as this is a 'binding', event-based system, an event is being fired for every single string on the page, which not only is a slower way to transform the page but can slow down all the actions on the page, if you start adding large numbers of events to it.

Anyway, using a post-processing translation platform makes more sense to me. Using GlobalizeIt for example, a translator can just go to a page on the site and start editing the text directly on the page for their language, and that's it: https://www.globalizeit.com/HowItWorks. No programming needed (though it can be programmatically extensible), it integrates easily with Angular: https://www.globalizeit.com/Translate/Angular, the transformation of the page happens in one go, and it always displays the translated text with the initial render of the page.

Full disclosure: I'm a co-founder :)

When to use Interface and Model in TypeScript / Angular

As @ThierryTemplier said for receiving data from server and also transmitting model between components (to keep intellisense list and make design time error), it's fine to use interface but I think for sending data to server (DTOs) it's better to use class to take advantages of auto mapping DTO from model.

HTTP Status 404 - The requested resource (/) is not available

I had the same problem with my localhost project using Eclipse Luna, Maven and Tomcat - the Tomcat homepage would appear fine, however my project would get the 404 error.

After trying many suggested solutions (updating spring .jar file, changing properties of the Tomcat server, add/remove project, change JRE from 1.6 to 7 etc) which did not fix the issue, what worked for me was to just Refresh my project. It seems Eclipse does not automatically refresh the project after a (Maven) build. In Eclipse 3.3.1 there was a 'Refresh Automatically' option under Preferences > General > Workspace however that option doesn't look to be in Luna.

  1. Maven clean-install on the project.
  2. ** Right-click the project and select 'Refresh'. **
  3. Right-click the Eclipse Tomcat server and select 'Clean'.
  4. Right-click > Publish and then start the Tomcat server.

Change background position with jQuery

rebellion's answer above won't actually work, because to CSS, 'background-position' is actually shorthand for 'background-position-x' and 'background-position-y' so the correct version of his code would be:

$(document).ready(function(){
    $('#submenu li').hover(function(){
        $('#carousel').css('background-position-x', newValueX);
        $('#carousel').css('background-position-y', newValue);
    }, function(){
        $('#carousel').css('background-position-x', oldValueX);
        $('#carousel').css('background-position-y', oldValueY);
    });
});

It took about 4 hours of banging my head against it to come to that aggravating realization.

Android Webview - Webpage should fit the device screen

This seems like an XML problem. Open the XML document containing your Web-View. Delete the padding code at the top.

Then in the layout , add

android:layout_width="fill_parent"
android:layout_height="fill_parent"

In the Web-View, add

android:layout_width="fill_parent"
android:layout_height="fill_parent" 

This makes the Web-View fit the device screen.

Get full path without filename from path that includes filename

Path.GetDirectoryName() returns the directory name, so for what you want (with the trailing reverse solidus character) you could call Path.GetDirectoryName(filePath) + Path.DirectorySeparatorChar.

SQL update fields of one table from fields of another one

you can build and execute dynamic sql to do this, but its really not ideal

"The following SDK components were not installed: sys-img-x86-addon-google_apis-google-22 and addon-google_apis-google-22"

I am using Windows 7 Professional and I was having same problem @Bayu Mohammad Lufty not worked for me.

I simply delete .AndroidStudio1.2 from my C:\Users\UserName\ and restart my Android studio again. It open Android Studio perfectly! It configured everything again in next start :)

How do I pass command-line arguments to a WinForms application?

The best way to work with args for your winforms app is to use

string[] args = Environment.GetCommandLineArgs();

You can probably couple this with the use of an enum to solidify the use of the array througout your code base.

"And you can use this anywhere in your application, you aren’t just restricted to using it in the main() method like in a console application."

Found at:HERE

How to empty a Heroku database

Assuming you want to reset your PostgreSQL database and set it back up, use:

heroku apps

to list your applications on Heroku. Find the name of your current application (application_name). Then run

heroku config | grep POSTGRESQL

to get the name of your databases. An example could be

HEROKU_POSTGRESQL_WHITE_URL

Finally, given application_name and database_url, you should run

heroku pg:reset `database_url` --confirm `application_name`
heroku run rake db:migrate
heroku restart

Adding elements to a collection during iteration

I tired ListIterator but it didn't help my case, where you have to use the list while adding to it. Here's what works for me:

Use LinkedList.

LinkedList<String> l = new LinkedList<String>();
l.addLast("A");

while(!l.isEmpty()){
    String str = l.removeFirst();
    if(/* Condition for adding new element*/)
        l.addLast("<New Element>");
    else
        System.out.println(str);
}

This could give an exception or run into infinite loops. However, as you have mentioned

I'm pretty sure it won't in my case

checking corner cases in such code is your responsibility.

How do I update/upsert a document in Mongoose?

After reading the posts above, I decided to use this code:

    itemModel.findOne({'pid':obj.pid},function(e,r){
        if(r!=null)
        {
             itemModel.update({'pid':obj.pid},obj,{upsert:true},cb);
        }
        else
        {
            var item=new itemModel(obj);
            item.save(cb);
        }
    });

if r is null, we create new item. Otherwise, use upsert in update because update does not create new item.

javac: file not found: first.java Usage: javac <options> <source files>

First set your path to C:/Program Files/Java/jdk1.8.0/bin in the environment variables. Say, your file is saved in the C: drive Now open the command prompt and move to the directory using c: javac Filename.java java Filename

Make sure you save the file name as .java.

If it is saved as a text file name then file not found error results as it cannot the text file.

Python: find position of element in array

There is a built in method for doing this:

numpy.where()

You can find out more about it in the excellent detailed documentation.

ASP MVC in IIS 7 results in: HTTP Error 403.14 - Forbidden

Please note sometimes wrong Managed pipeline mode will cause this error. There are two choices to select integrated and classic.

Unable to start the mysql server in ubuntu

I think this is because you are using client software and not the server.

  • mysql is client
  • mysqld is the server

Try: sudo service mysqld start

To check that service is running use: ps -ef | grep mysql | grep -v grep.

Uninstalling:

sudo apt-get purge mysql-server
sudo apt-get autoremove
sudo apt-get autoclean

Re-Installing:

sudo apt-get update
sudo apt-get install mysql-server

Backup entire folder before doing this:

sudo rm /etc/apt/apt.conf.d/50unattended-upgrades*
sudo apt-get update
sudo apt-get upgrade

Warning: mysqli_query() expects at least 2 parameters, 1 given. What?

The issue is that you're not saving the mysqli connection. Change your connect to:

$aVar = mysqli_connect('localhost','tdoylex1_dork','dorkk','tdoylex1_dork');

And then include it in your query:

$query1 = mysqli_query($aVar, "SELECT name1 FROM users
    ORDER BY RAND()
    LIMIT 1");
$aName1 = mysqli_fetch_assoc($query1);
$name1 = $aName1['name1'];

Also don't forget to enclose your connections variables as strings as I have above. This is what's causing the error but you're using the function wrong, mysqli_query returns a query object but to get the data out of this you need to use something like mysqli_fetch_assoc http://php.net/manual/en/mysqli-result.fetch-assoc.php to actually get the data out into a variable as I have above.

Rounding a variable to two decimal places C#

Use System.Math.Round to rounds a decimal value to a specified number of fractional digits.

var pay = 200 + bonus;
pay = System.Math.Round(pay, 2);
Console.WriteLine(pay);

MSDN References:

How can I initialize base class member variables in derived class constructor?

# include<stdio.h>
# include<iostream>
# include<conio.h>

using namespace std;

class Base{
    public:
        Base(int i, float f, double d): i(i), f(f), d(d)
        {
        }
    virtual void Show()=0;
    protected:
        int i;
        float f;
        double d;
};


class Derived: public Base{
    public:
        Derived(int i, float f, double d): Base( i, f, d)
        {
        }
        void Show()
        {
            cout<< "int i = "<<i<<endl<<"float f = "<<f<<endl <<"double d = "<<d<<endl;
        }
};

int main(){
    Base * b = new Derived(10, 1.2, 3.89);
    b->Show();
    return 0;
}

It's a working example in case you want to initialize the Base class data members present in the Derived class object, whereas you want to push these values interfacing via Derived class constructor call.

Count(*) vs Count(1) - SQL Server

I would expect the optimiser to ensure there is no real difference outside weird edge cases.

As with anything, the only real way to tell is to measure your specific cases.

That said, I've always used COUNT(*).

Regex not operator

You could capture the (2001) part and replace the rest with nothing.

public static string extractYearString(string input) {
    return input.replaceAll(".*\(([0-9]{4})\).*", "$1");
}

var subject = "(2001) (asdf) (dasd1123_asd 21.01.2011 zqge)(dzqge) name (20019)";
var result = extractYearString(subject);
System.out.println(result); // <-- "2001"

.*\(([0-9]{4})\).* means

  • .* match anything
  • \( match a ( character
  • ( begin capture
  • [0-9]{4} any single digit four times
  • ) end capture
  • \) match a ) character
  • .* anything (rest of string)

Best Practice to Organize Javascript Library & CSS Folder Structure

 root/
   assets/
      lib/-------------------------libraries--------------------
          bootstrap/--------------Libraries can have js/css/images------------
              css/
              js/
              images/  
          jquery/
              js/
          font-awesome/
              css/
              images/
     common/--------------------common section will have application level resources             
          css/
          js/
          img/

 index.html

This is how I organized my application's static resources.

Could not instantiate mail function. Why this error occurring

Make sure that you also include smtp class which comes with phpmailer:

// for mailing
require("phpmailer/class.phpmailer.php");
require("phpmailer/class.smtp.php");

Passing $_POST values with cURL

Check out this page which has an example of how to do it.

Asynchronous shell exec in PHP

Use a named fifo.

#!/bin/sh
mkfifo trigger
while true; do
    read < trigger
    long_running_task
done

Then whenever you want to start the long running task, simply write a newline (nonblocking to the trigger file.

As long as your input is smaller than PIPE_BUF and it's a single write() operation, you can write arguments into the fifo and have them show up as $REPLY in the script.

Link to add to Google calendar

There is a comprehensive doc for google calendar and other calendar services: https://github.com/InteractionDesignFoundation/add-event-to-calendar-docs/blob/master/services/google.md

An example of working link: https://calendar.google.com/calendar/render?action=TEMPLATE&text=Bithday&dates=20201231T193000Z/20201231T223000Z&details=With%20clowns%20and%20stuff&location=North%20Pole

Splitting a string into chunks of a certain size

    public static List<string> SplitByMaxLength(this string str)
    {
        List<string> splitString = new List<string>();

        for (int index = 0; index < str.Length; index += MaxLength)
        {
            splitString.Add(str.Substring(index, Math.Min(MaxLength, str.Length - index)));
        }

        return splitString;
    }

Actionbar notification count icon (badge) like Google has

Just to add. If someone wants to implement a filled circle bubble, heres the code (name it bage_circle.xml):

<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="ring"
    android:useLevel="false"
    android:thickness="9dp"
    android:innerRadius="0dp"
    >

    <solid
        android:color="#F00"
        />
    <stroke
        android:width="1dip"
        android:color="#FFF" />

    <padding
        android:top="2dp"
        android:bottom="2dp"/>

</shape>

You may have to adjust the thickness according to your need.

enter image description here

EDIT: Here's the layout for button (name it badge_layout.xml):

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content">

    <com.joanzapata.iconify.widget.IconButton
        android:layout_width="44dp"
        android:layout_height="44dp"
        android:textSize="24sp"
        android:textColor="@color/white"
        android:background="@drawable/action_bar_icon_bg"
        android:id="@+id/badge_icon_button"/>

    <TextView
        android:id="@+id/badge_textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignTop="@id/badge_icon_button"
        android:layout_alignRight="@id/badge_icon_button"
        android:layout_alignEnd="@id/badge_icon_button"
        android:text="10"
        android:paddingEnd="8dp"
        android:paddingRight="8dp"
        android:paddingLeft="8dp"
        android:gravity="center"
        android:textColor="#FFF"
        android:textSize="11sp"
        android:background="@drawable/badge_circle"/>
</RelativeLayout>

In Menu create item:

<item
        android:id="@+id/menu_messages"
        android:showAsAction="always"
        android:actionLayout="@layout/badge_layout"/>

In onCreateOptionsMenu get reference to the Menu item:

    itemMessages = menu.findItem(R.id.menu_messages);

    badgeLayout = (RelativeLayout) itemMessages.getActionView();
    itemMessagesBadgeTextView = (TextView) badgeLayout.findViewById(R.id.badge_textView);
    itemMessagesBadgeTextView.setVisibility(View.GONE); // initially hidden

    iconButtonMessages = (IconButton) badgeLayout.findViewById(R.id.badge_icon_button);
    iconButtonMessages.setText("{fa-envelope}");
    iconButtonMessages.setTextColor(getResources().getColor(R.color.action_bar_icon_color_disabled));

    iconButtonMessages.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            if (HJSession.getSession().getSessionId() != null) {

                Intent intent = new Intent(getThis(), HJActivityMessagesContexts.class);
                startActivityForResult(intent, HJRequestCodes.kHJRequestCodeActivityMessages.ordinal());
            } else {
                showLoginActivity();
            }
        }
    });

After receiving notification for messages, set the count:

itemMessagesBadgeTextView.setText("" + count);
itemMessagesBadgeTextView.setVisibility(View.VISIBLE);
iconButtonMessages.setTextColor(getResources().getColor(R.color.white));

This code uses Iconify-fontawesome.

compile 'com.joanzapata.iconify:android-iconify-fontawesome:2.1.+'

How to deny access to a file in .htaccess

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

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

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

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

Is it bad to have my virtualenv directory inside my git repository?

I use what is basically David Sickmiller's answer with a little more automation. I create a (non-executable) file at the top level of my project named activate with the following contents:

[ -n "$BASH_SOURCE" ] \
    || { echo 1>&2 "source (.) this with Bash."; exit 2; }
(
    cd "$(dirname "$BASH_SOURCE")"
    [ -d .build/virtualenv ] || {
        virtualenv .build/virtualenv
        . .build/virtualenv/bin/activate
        pip install -r requirements.txt
    }
)
. "$(dirname "$BASH_SOURCE")/.build/virtualenv/bin/activate"

(As per David's answer, this assumes you're doing a pip freeze > requirements.txt to keep your list of requirements up to date.)

The above gives the general idea; the actual activate script (documentation) that I normally use is a bit more sophisticated, offering a -q (quiet) option, using python when python3 isn't available, etc.

This can then be sourced from any current working directory and will properly activate, first setting up the virtual environment if necessary. My top-level test script usually has code along these lines so that it can be run without the developer having to activate first:

cd "$(dirname "$0")"
[[ $VIRTUAL_ENV = $(pwd -P) ]] || . ./activate

Sourcing ./activate, not activate, is important here because the latter will find any other activate in your path before it will find the one in the current directory.

Is it possible to create a File object from InputStream

Easy Java 9 solution with try with resources block

public static void copyInputStreamToFile(InputStream input, File file) {  

    try (OutputStream output = new FileOutputStream(file)) {
        input.transferTo(output);
    } catch (IOException ioException) {
        ioException.printStackTrace();
    }

}

java.io.InputStream#transferTo is available since Java 9.

String.equals() with multiple conditions (and one action on result)

if (Arrays.asList("John", "Mary", "Peter").contains(name)) {
}
  • This is not as fast as using a prepared Set, but it performs no worse than using OR.
  • This doesn't crash when name is NULL (same with Set).
  • I like it because it looks clean

Post Build exited with code 1

For those, who use 'copy' command in Build Events (Pre-build event command line or/and Post-build event command line) from Project -> Properties: target folder should exist

Get week of year in JavaScript like in PHP

Not ISO-8601 week number but if the search engine pointed you here anyways.

As said above but without a class:

let now = new Date();
let onejan = new Date(now.getFullYear(), 0, 1);
let week = Math.ceil( (((now.getTime() - onejan.getTime()) / 86400000) + onejan.getDay() + 1) / 7 );

how to activate a textbox if I select an other option in drop down box

Coded an example at http://jsbin.com/orisuv

HTML

<select name="color" onchange='checkvalue(this.value)'> 
    <option>pick a color</option>  
    <option value="red">RED</option>
    <option value="blue">BLUE</option>
    <option value="others">others</option>
</select> 
<input type="text" name="color" id="color" style='display:none'/>

Javascript

function checkvalue(val)
{
    if(val==="others")
       document.getElementById('color').style.display='block';
    else
       document.getElementById('color').style.display='none'; 
}

fastest way to export blobs from table into individual files

For me what worked by combining all the posts I have read is:

1.Enable OLE automation - if not enabled

sp_configure 'show advanced options', 1;  
GO  
RECONFIGURE;  
GO  
sp_configure 'Ole Automation Procedures', 1;  
GO  
RECONFIGURE;  
GO

2.Create a folder where the generated files will be stored:

C:\GREGTESTING

3.Create DocTable that will be used for file generation and store there the blobs in Doc_Content
enter image description here

CREATE TABLE [dbo].[Document](
    [Doc_Num] [numeric](18, 0) IDENTITY(1,1) NOT NULL,
    [Extension] [varchar](50) NULL,
    [FileName] [varchar](200) NULL,
    [Doc_Content] [varbinary](max) NULL   
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY] 

INSERT [dbo].[Document] ([Extension] ,[FileName] , [Doc_Content] )
    SELECT 'pdf', 'SHTP Notional hire - January 2019.pdf', 0x....(varbinary blob)

Important note!

Don't forget to add in Doc_Content column the varbinary of file you want to generate!

4.Run the below script

DECLARE @outPutPath varchar(50) = 'C:\GREGTESTING'
, @i bigint
, @init int
, @data varbinary(max) 
, @fPath varchar(max)  
, @folderPath  varchar(max)

--Get Data into temp Table variable so that we can iterate over it 
DECLARE @Doctable TABLE (id int identity(1,1), [Doc_Num]  varchar(100) , [FileName]  varchar(100), [Doc_Content] varBinary(max) )



INSERT INTO @Doctable([Doc_Num] , [FileName],[Doc_Content])
Select [Doc_Num] , [FileName],[Doc_Content] FROM  [dbo].[Document]



SELECT @i = COUNT(1) FROM @Doctable   

WHILE @i >= 1   

BEGIN    

SELECT 
    @data = [Doc_Content],
    @fPath = @outPutPath + '\' + [Doc_Num] +'_' +[FileName],
    @folderPath = @outPutPath + '\'+ [Doc_Num]
FROM @Doctable WHERE id = @i

EXEC sp_OACreate 'ADODB.Stream', @init OUTPUT; -- An instace created
EXEC sp_OASetProperty @init, 'Type', 1;  
EXEC sp_OAMethod @init, 'Open'; -- Calling a method
EXEC sp_OAMethod @init, 'Write', NULL, @data; -- Calling a method
EXEC sp_OAMethod @init, 'SaveToFile', NULL, @fPath, 2; -- Calling a method
EXEC sp_OAMethod @init, 'Close'; -- Calling a method
EXEC sp_OADestroy @init; -- Closed the resources
print 'Document Generated at - '+  @fPath   

--Reset the variables for next use
SELECT @data = NULL  
, @init = NULL
, @fPath = NULL  
, @folderPath = NULL
SET @i -= 1
END   

5.The results is shown below: enter image description here

deleted object would be re-saved by cascade (remove deleted object from associations)

Had the same error. Removing the object from the model did the trick.

Code which shows the mistake:

void update() {
    VBox vBox = mHboxEventSelection.getVboxSelectionRows();

    Session session = HibernateUtilEventsCreate.getSessionFactory().openSession();
    session.beginTransaction();

    HashMap<String, EventLink> existingEventLinks = new HashMap<>();
    for (EventLink eventLink : mEventProperty.getEventLinks()) {
        existingEventLinks.put(eventLink.getEvent().getName(), eventLink);
    }

    mEventProperty.setName(getName());

    for (Node node : vBox.getChildren()) {

        if (node instanceof HBox) {
            JFXComboBox<EventEntity> comboBoxEvents = (JFXComboBox<EventEntity>) ((HBox) node).getChildren().get(0);
            if (comboBoxEvents.getSelectionModel().getSelectedIndex() == -1) {
                Log.w(TAG, "update: Invalid eventEntity collection");
            }

            EventEntity eventEntity = comboBoxEvents.getSelectionModel().getSelectedItem();
            Log.v(TAG, "update(" + mCostType + "): event-id=" + eventEntity.getId() + " - " + eventEntity.getName());

            String split = ((JFXTextField) (((HBox) node).getChildren().get(1))).getText();
            if (split.isEmpty()) {
                split = "0";
            }
            if (existingEventLinks.containsKey(eventEntity.getName())) {
                // event-link did exist
                EventLink eventLink = existingEventLinks.get(eventEntity.getName());
                eventLink.setSplit(Integer.parseInt(split));
                session.update(eventLink);
                existingEventLinks.remove(eventEntity.getName(), eventLink);
            } else {
                // event-link is a new one, so create!
                EventLink link1 = new EventLink();

                link1.setProperty(mEventProperty);
                link1.setEvent(eventEntity);
                link1.setCreationTime(new Date(System.currentTimeMillis()));
                link1.setSplit(Integer.parseInt(split));

                eventEntity.getEventLinks().add(link1);
                session.saveOrUpdate(eventEntity);
            }

        }
    }

    for (Map.Entry<String, EventLink> entry : existingEventLinks.entrySet()) {
        Log.i(TAG, "update: will delete link=" + entry.getKey());
        EventLink val = entry.getValue();
        mEventProperty.getEventLinks().remove(val); // <- remove from model
        session.delete(val);
    }

    session.saveOrUpdate(mEventProperty);

    session.getTransaction().commit();
    session.close();
}

Error "The connection to adb is down, and a severe error has occurred."

The previous solutions will probably work. I solved it downloading the latest ADT (Android Developer Tools) and overwriting all files in the SDK folder.

http://developer.android.com/sdk/index.html

Once you overwrite it, Eclipse may give a warning saying that the path for SDK hasn't been found, go to Preferences and change the path to another folder (C:), click Apply, and then change it again and set the SDK path and click Apply again.

Laravel 5.4 ‘cross-env’ Is Not Recognized as an Internal or External Command

I think this log entry Local package.json exists, but node_modules missing, did you mean to install? has gave me the solution.

npm install && npm run dev

how to count the total number of lines in a text file using python

You can use sum() with a generator expression here. The generator expression will be [1, 1, ...] up to the length of the file. Then we call sum() to add them all together, to get the total count.

with open('text.txt') as myfile:
    count = sum(1 for line in myfile)

It seems by what you have tried that you don't want to include empty lines. You can then do:

with open('text.txt') as myfile:
    count = sum(1 for line in myfile if line.rstrip('\n'))

JQuery Ajax - How to Detect Network Connection error when making Ajax call

If you are making cross domain call the Use Jsonp. else the error is not returned.

Read user input inside a loop

You can redirect the regular stdin through unit 3 to keep the get it inside the pipeline:

{ cat notify-finished | while read line; do
    read -u 3 input
    echo "$input"
done; } 3<&0

BTW, if you really are using cat this way, replace it with a redirect and things become even easier:

while read line; do
    read -u 3 input
    echo "$input"
done 3<&0 <notify-finished

Or, you can swap stdin and unit 3 in that version -- read the file with unit 3, and just leave stdin alone:

while read line <&3; do
    # read & use stdin normally inside the loop
    read input
    echo "$input"
done 3<notify-finished

Recursive file search using PowerShell

When searching folders where you might get an error based on security (e.g. C:\Users), use the following command:

Get-ChildItem -Path V:\Myfolder -Filter CopyForbuild.bat -Recurse -ErrorAction SilentlyContinue -Force

Check play state of AVPlayer

A more reliable alternative to NSNotification is to add yourself as observer to player's rate property.

[self.player addObserver:self
              forKeyPath:@"rate"
                 options:NSKeyValueObservingOptionNew
                 context:NULL];

Then check if the new value for observed rate is zero, which means that playback has stopped for some reason, like reaching the end or stalling because of empty buffer.

- (void)observeValueForKeyPath:(NSString *)keyPath
                      ofObject:(id)object
                        change:(NSDictionary<NSString *,id> *)change
                       context:(void *)context {
    if ([keyPath isEqualToString:@"rate"]) {
        float rate = [change[NSKeyValueChangeNewKey] floatValue];
        if (rate == 0.0) {
            // Playback stopped
        } else if (rate == 1.0) {
            // Normal playback
        } else if (rate == -1.0) {
            // Reverse playback
        }
    }
}

For rate == 0.0 case, to know what exactly caused the playback to stop, you can do the following checks:

if (self.player.error != nil) {
    // Playback failed
}
if (CMTimeGetSeconds(self.player.currentTime) >=
    CMTimeGetSeconds(self.player.currentItem.duration)) {
    // Playback reached end
} else if (!self.player.currentItem.playbackLikelyToKeepUp) {
    // Not ready to play, wait until enough data is loaded
}

And don't forget to make your player stop when it reaches the end:

self.player.actionAtItemEnd = AVPlayerActionAtItemEndPause;

How to add include and lib paths to configure/make cycle?

This took a while to get right. I had this issue when cross-compiling in Ubuntu for an ARM target. I solved it with:

PATH=$PATH:/ccpath/bin CC=ccname-gcc AR=ccname-ar LD=ccname-ld CPPFLAGS="-nostdinc -I/ccrootfs/usr/include ..." LDFLAGS=-L/ccrootfs/usr/lib ./autogen.sh --build=`config.guess` --host=armv5tejl-unknown-linux-gnueabihf

Notice CFLAGS is not used with autogen.sh/configure, using it gave me the error: "configure: error: C compiler cannot create executables". In the build environment I was using an autogen.sh script was provided, if you don't have an autogen.sh script substitute ./autogen.sh with ./configure in the command above. I ran config.guess on the target system to get the --host parameter.

After successfully running autogen.sh/configure, compile with:

PATH=$PATH:/ccpath/bin CC=ccname-gcc AR=ccname-ar LD=ccname-ld CPPFLAGS="-nostdinc -I/ccrootfs/usr/include ..." LDFLAGS=-L/ccrootfs/usr/lib CFLAGS="-march=... -mcpu=... etc." make

The CFLAGS I chose to use were: "-march=armv5te -fno-tree-vectorize -mthumb-interwork -mcpu=arm926ej-s". It will take a while to get all of the include directories set up correctly: you might want some includes pointing to your cross-compiler and some pointing to your root file system includes, and there will likely be some conflicts.

I'm sure this is not the perfect answer. And I am still seeing some include directories pointing to / and not /ccrootfs in the Makefiles. Would love to know how to correct this. Hope this helps someone.

SQL Server : Arithmetic overflow error converting expression to data type int

On my side, this error came from the data type "INT' in the Null values column. The error is resolved by just changing the data a type to varchar.

Get month name from date in Oracle

to_char(mydate, 'MONTH') will do the job.

embedding image in html email

The following is working code with two ways of achieving this:

using System;
using Outlook = Microsoft.Office.Interop.Outlook;

namespace ConsoleApp2
{
    class Program
    {
        static void Main(string[] args)
        {

            Method1();
            Method2();
        }

        public static void Method1()
        {
            Outlook.Application outlookApp = new Outlook.Application();
            Outlook.MailItem mailItem = outlookApp.CreateItem(Outlook.OlItemType.olMailItem);
            mailItem.Subject = "This is the subject";
            mailItem.To = "[email protected]";
            string imageSrc = "D:\\Temp\\test.jpg"; // Change path as needed

            var attachments = mailItem.Attachments;
            var attachment = attachments.Add(imageSrc);
            attachment.PropertyAccessor.SetProperty("http://schemas.microsoft.com/mapi/proptag/0x370E001F", "image/jpeg");
            attachment.PropertyAccessor.SetProperty("http://schemas.microsoft.com/mapi/proptag/0x3712001F", "myident"); // Image identifier found in the HTML code right after cid. Can be anything.
            mailItem.PropertyAccessor.SetProperty("http://schemas.microsoft.com/mapi/id/{00062008-0000-0000-C000-000000000046}/8514000B", true);

            // Set body format to HTML

            mailItem.BodyFormat = Outlook.OlBodyFormat.olFormatHTML;
            string msgHTMLBody = "<html><head></head><body>Hello,<br><br>This is a working example of embedding an image unsing C#:<br><br><img align=\"baseline\" border=\"1\" hspace=\"0\" src=\"cid:myident\" width=\"\" 600=\"\" hold=\" /> \"></img><br><br>Regards,<br>Tarik Hoshan</body></html>";
            mailItem.HTMLBody = msgHTMLBody;
            mailItem.Send();
        }

        public static void Method2()
        {

            // Create the Outlook application.
            Outlook.Application outlookApp = new Outlook.Application();

            Outlook.MailItem mailItem = (Outlook.MailItem)outlookApp.CreateItem(Outlook.OlItemType.olMailItem);

            //Add an attachment.
            String attachmentDisplayName = "MyAttachment";

            // Attach the file to be embedded
            string imageSrc = "D:\\Temp\\test.jpg"; // Change path as needed

            Outlook.Attachment oAttach = mailItem.Attachments.Add(imageSrc, Outlook.OlAttachmentType.olByValue, null, attachmentDisplayName);

            mailItem.Subject = "Sending an embedded image";

            string imageContentid = "someimage.jpg"; // Content ID can be anything. It is referenced in the HTML body

            oAttach.PropertyAccessor.SetProperty("http://schemas.microsoft.com/mapi/proptag/0x3712001E", imageContentid);

            mailItem.HTMLBody = String.Format(
                "<body>Hello,<br><br>This is an example of an embedded image:<br><br><img src=\"cid:{0}\"><br><br>Regards,<br>Tarik</body>",
                imageContentid);

            // Add recipient
            Outlook.Recipient recipient = mailItem.Recipients.Add("[email protected]");
            recipient.Resolve();

            // Send.
            mailItem.Send();
        }
    }
}

How do you properly use namespaces in C++?

I did not see any mention of it in the other answers, so here are my 2 Canadian cents:

On the "using namespace" topic, a useful statement is the namespace alias, allowing you to "rename" a namespace, normally to give it a shorter name. For example, instead of:

Some::Impossibly::Annoyingly::Long:Name::For::Namespace::Finally::TheClassName foo;
Some::Impossibly::Annoyingly::Long:Name::For::Namespace::Finally::AnotherClassName bar;

you can write:

namespace Shorter = Some::Impossibly::Annoyingly::Long:Name::For::Namespace::Finally;
Shorter::TheClassName foo;
Shorter::AnotherClassName bar;

How can I alias a default import in JavaScript?

defaultMember already is an alias - it doesn't need to be the name of the exported function/thing. Just do

import alias from 'my-module';

Alternatively you can do

import {default as alias} from 'my-module';

but that's rather esoteric.

Bubble Sort Homework

def bubbleSort(alist):
if len(alist) <= 1:
    return alist
for i in range(0,len(alist)):
   print "i is :%d",i
   for j in range(0,i):
      print "j is:%d",j
      print "alist[i] is :%d, alist[j] is :%d"%(alist[i],alist[j])
      if alist[i] > alist[j]:
         alist[i],alist[j] = alist[j],alist[i]
return alist

alist = [54,26,93,17,77,31,44,55,20,-23,-34,16,11,11,11]

print bubbleSort(alist)

How to Compare two strings using a if in a stored procedure in sql server 2008?

Two things:

  1. Only need one (1) equals sign to evaluate
  2. You need to specify a length on the VARCHAR - the default is a single character.

Use:

DECLARE @temp VARCHAR(10)
    SET @temp = 'm'

IF @temp = 'm'
  SELECT 'yes'
ELSE
  SELECT 'no'

VARCHAR(10) means the VARCHAR will accommodate up to 10 characters. More examples of the behavior -

DECLARE @temp VARCHAR
    SET @temp = 'm'

IF @temp = 'm'
  SELECT 'yes'
ELSE
  SELECT 'no'

...will return "yes"

DECLARE @temp VARCHAR
    SET @temp = 'mtest'

IF @temp = 'm'
  SELECT 'yes'
ELSE
  SELECT 'no'

...will return "no".

Move layouts up when soft keyboard is shown?

Make changes in the activity of your Manifest file like

android:windowSoftInputMode="adjustResize"

OR

Make changes in your onCreate() method in the activity class like

getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN);

What does Statement.setFetchSize(nSize) method really do in SQL Server JDBC driver?

Try this:

String SQL = "select col1, col2, coln from mytable where timecol = yesterday";

connection.setAutoCommit(false);
PreparedStatement stmt = connection.prepareStatement(SQL, SQLServerResultSet.TYPE_SS_SERVER_CURSOR_FORWARD_ONLY, SQLServerResultSet.CONCUR_READ_ONLY);
stmt.setFetchSize(2000);

stmt.set....

stmt.execute();
ResultSet rset = stmt.getResultSet();

while (rset.next()) {
    // ......

How to allow only integers in a textbox?

step by step

given you have a textbox as following,

<asp:TextBox ID="TextBox13" runat="server" 
  onkeypress="return functionx(event)" >
</asp:TextBox>

you create a JavaScript function like this:

     <script type = "text/javascript">
         function functionx(evt) 
         {
            if (evt.charCode > 31 && (evt.charCode < 48 || evt.charCode > 57))
                  {
                    alert("Allow Only Numbers");
                    return false;
                  }
          }
     </script>

the first part of the if-statement excludes the ASCII control chars, the or statements exclued anything, that is not a number

How can I convert integer into float in Java?

// The integer I want to convert

int myInt = 100;

// Casting of integer to float

float newFloat = (float) myInt

Creating a Menu in Python

It looks like you've just finished step 3. Instead of running a function, you just print out a statement. A function is defined in the following way:

def addstudent():
    print("Student Added.")

then called by writing addstudent().

I would recommend using a while loop for your input. You can define the menu option outside the loop, put the print statement inside the loop, and do while(#valid option is not picked), then put the if statements after the while. Or you can do a while loop and continue the loop if a valid option is not selected.

Additionally, a dictionary is defined in the following way:

my_dict = {key:definition,...}

Using PUT method in HTML form

If you are using nodejs, you can install the package method-override that lets you do this using a middleware. Link to documentation: http://expressjs.com/en/resources/middleware/method-override.html

After installing this, all I had to do was the following:

var methodOverride = require('method-override')
app.use(methodOverride('_method'))

How do I do a simple 'Find and Replace" in MsSQL?

If you are working with SQL Server 2005 or later there is also a CLR library available at http://www.sqlsharp.com/ that provides .NET implementations of string and RegEx functions which, depending on your volume and type of data may be easier to use and in some cases the .NET string manipulation functions can be more efficient than T-SQL ones.

How can I check if a jQuery plugin is loaded?

for the plugins that doesn't use fn namespace (for example pnotify), this works:

if($.pluginname) {
    alert("plugin loaded");
} else {
    alert("plugin not loaded");
}

This doesn't work:

if($.fn.pluginname)

How to store printStackTrace into a string

StackTraceElement[] stack = new Exception().getStackTrace();
String theTrace = "";
for(StackTraceElement line : stack)
{
   theTrace += line.toString();
}

unresolved external symbol __imp__fprintf and __imp____iob_func, SDL2

Paste this code in any of your source files and re-build. Worked for me !

#include stdio.h

FILE _iob[3];

FILE* __cdecl __iob_func(void) {

_iob[0] = *stdin;

_iob[0] = *stdout;

_iob[0] = *stderr;

return _iob;

}

Java better way to delete file if exists

I was working on this type of function, maybe this will interests some of you ...

public boolean deleteFile(File file) throws IOException {
    if (file != null) {
        if (file.isDirectory()) {
            File[] files = file.listFiles();

            for (File f: files) {
                deleteFile(f);
            }
        }
        return Files.deleteIfExists(file.toPath());
    }
    return false;
}

Html code as IFRAME source rather than a URL

use html5's new attribute srcdoc (srcdoc-polyfill) Docs

<iframe srcdoc="<html><body>Hello, <b>world</b>.</body></html>"></iframe>

Browser support - Tested in the following browsers:

Microsoft Internet Explorer
6, 7, 8, 9, 10, 11
Microsoft Edge
13, 14
Safari
4, 5.0, 5.1 ,6, 6.2, 7.1, 8, 9.1, 10
Google Chrome
14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24.0.1312.5 (beta), 25.0.1364.5 (dev), 55
Opera
11.1, 11.5, 11.6, 12.10, 12.11 (beta) , 42
Mozilla FireFox
3.0, 3.6, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18 (beta), 50

How to find pg_config path

I had exactly the same error, but I installed postgreSQL through brew and re-run the original command and it worked perfectly :

brew install postgresql

How do I negate a test with regular expressions in a bash script?

I like to simplify the code without using conditional operators in such cases:

TEMP=/mnt/silo/bin
[[ ${PATH} =~ ${TEMP} ]] || PATH=$PATH:$TEMP

What is the difference between an abstract function and a virtual function?

Abstract function cannot have a body and MUST be overridden by child classes

Virtual Function will have a body and may or may not be overridden by child classes

Invoke-Command error "Parameter set cannot be resolved using the specified named parameters"

The accepted answer is correct regarding the Invoke-Command cmdlet, but more broadly speaking, cmdlets can have parameter sets where groups of input parameters are defined, such that you can't use two parameters that aren't members of the same parameter set.

If you're running into this error with any other cmdlet, look up its Microsoft documentation, and see if the the top of the page has distinct sets of parameters listed. For example, the documentation for Set-AzureDeployment defines three sets at the top of the page.

What's the idiomatic syntax for prepending to a short python list?

If someone finds this question like me, here are my performance tests of proposed methods:

Python 2.7.8

In [1]: %timeit ([1]*1000000).insert(0, 0)
100 loops, best of 3: 4.62 ms per loop

In [2]: %timeit ([1]*1000000)[0:0] = [0]
100 loops, best of 3: 4.55 ms per loop

In [3]: %timeit [0] + [1]*1000000
100 loops, best of 3: 8.04 ms per loop

As you can see, insert and slice assignment are as almost twice as fast than explicit adding and are very close in results. As Raymond Hettinger noted insert is more common option and I, personally prefer this way to prepend to list.

How to fire an event when v-model changes?

Just to add to the correct answer above, in Vue.JS v1.0 you can write

<a v-on:click="doSomething">

So in this example it would be

 v-on:change="foo"

See: http://v1.vuejs.org/guide/syntax.html#Arguments

HTML span align center not working?

The align attribute is deprecated. Use CSS text-align instead. Also, the span will not center the text unless you use display:block or display:inline-block and set a value for the width, but then it will behave the same as a div (block element).

Can you post an example of your layout? Use www.jsfiddle.net

Hadoop: «ERROR : JAVA_HOME is not set»

The solution that worked for me was setting my JAVA_HOME in /etc/environment

Though JAVA_HOME can be set inside the /etc/profile files, the preferred location for JAVA_HOME or any system variable is /etc/environment.

Open /etc/environment in any text editor like nano or vim and add the following line:

JAVA_HOME="/usr/lib/jvm/your_java_directory"

Load the variables:

source /etc/environment

Check if the variable loaded correctly:

echo $JAVA_HOME

How do I navigate to another page when PHP script is done?

if ($done)
{
    header("Location: /url/to/the/other/page");
    exit;
}

How to convert a char to a String?

I've tried the suggestions but ended up implementing it as follows

editView.setFilters(new InputFilter[]{new InputFilter()
        {
            @Override
            public CharSequence filter(CharSequence source, int start, int end,
                                       Spanned dest, int dstart, int dend)
            {
                String prefix = "http://";

                //make sure our prefix is visible
                String destination = dest.toString();

                //Check If we already have our prefix - make sure it doesn't
                //get deleted
                if (destination.startsWith(prefix) && (dstart <= prefix.length() - 1))
                {
                    //Yep - our prefix gets modified - try preventing it.
                    int newEnd = (dend >= prefix.length()) ? dend : prefix.length();

                    SpannableStringBuilder builder = new SpannableStringBuilder(
                            destination.substring(dstart, newEnd));
                    builder.append(source);
                    if (source instanceof Spanned)
                    {
                        TextUtils.copySpansFrom(
                                (Spanned) source, 0, source.length(), null, builder, newEnd);
                    }

                    return builder;
                }
                else
                {
                    //Accept original replacement (by returning null)
                    return null;
                }
            }
        }});

How do I parse a string with a decimal point to a double?

string testString1 = "2,457";
string testString2 = "2.457";    
double testNum = 0.5;
char decimalSepparator;
decimalSepparator = testNum.ToString()[1];

Console.WriteLine(double.Parse(testString1.Replace('.', decimalSepparator).Replace(',', decimalSepparator)));
Console.WriteLine(double.Parse(testString2.Replace('.', decimalSepparator).Replace(',', decimalSepparator)));

Converting a SimpleXML Object to an Array

I found this in the PHP manual comments:

/**
 * function xml2array
 *
 * This function is part of the PHP manual.
 *
 * The PHP manual text and comments are covered by the Creative Commons 
 * Attribution 3.0 License, copyright (c) the PHP Documentation Group
 *
 * @author  k dot antczak at livedata dot pl
 * @date    2011-04-22 06:08 UTC
 * @link    http://www.php.net/manual/en/ref.simplexml.php#103617
 * @license http://www.php.net/license/index.php#doc-lic
 * @license http://creativecommons.org/licenses/by/3.0/
 * @license CC-BY-3.0 <http://spdx.org/licenses/CC-BY-3.0>
 */
function xml2array ( $xmlObject, $out = array () )
{
    foreach ( (array) $xmlObject as $index => $node )
        $out[$index] = ( is_object ( $node ) ) ? xml2array ( $node ) : $node;

    return $out;
}

It could help you. However, if you convert XML to an array you will loose all attributes that might be present, so you cannot go back to XML and get the same XML.

get jquery `$(this)` id

this is the DOM element on which the event was hooked. this.id is its ID. No need to wrap it in a jQuery instance to get it, the id property reflects the attribute reliably on all browsers.

$("select").change(function() {    
    alert("Changed: " + this.id);
}

Live example

You're not doing this in your code sample, but if you were watching a container with several form elements, that would give you the ID of the container. If you want the ID of the element that triggered the event, you could get that from the event object's target property:

$("#container").change(function(event) {
    alert("Field " + event.target.id + " changed");
});

Live example

(jQuery ensures that the change event bubbles, even on IE where it doesn't natively.)

How to use hex() without 0x in Python?

You can simply write

hex(x)[2:]

to get the first two characters removed.

Checking for duplicate strings in JavaScript array

var strArray = [ "q", "w", "w", "e", "i", "u", "r", "q"];
var alreadySeen = [];

strArray.forEach(function(str) {
  if (alreadySeen[str])
    alert(str);
  else
    alreadySeen[str] = true;
});

I added another duplicate in there from your original just to show it would find a non-consecutive duplicate.

Updated version with arrow function:

const strArray = [ "q", "w", "w", "e", "i", "u", "r", "q"];
const alreadySeen = [];

strArray.forEach(str => alreadySeen[str] ? alert(str) : alreadySeen[str] = true);

Test class with a new() call in it with Mockito

For the future I would recommend Eran Harel's answer (refactoring moving new to factory that can be mocked). But if you don't want to change the original source code, use very handy and unique feature: spies. From the documentation:

You can create spies of real objects. When you use the spy then the real methods are called (unless a method was stubbed).

Real spies should be used carefully and occasionally, for example when dealing with legacy code.

In your case you should write:

TestedClass tc = spy(new TestedClass());
LoginContext lcMock = mock(LoginContext.class);
when(tc.login(anyString(), anyString())).thenReturn(lcMock);

How to add images in select list?

My solution is to use FontAwesome and then add library images as text! You just need the Unicodes and they are found here: FontAwesome Reference File forUnicodes

Here is an example state filter:

<select name='state' style='height: 45px; font-family:Arial, FontAwesome;'>
<option value=''>&#xf039; &nbsp; All States</option>
<option value='enabled' style='color:green;'>&#xf00c; &nbsp; Enabled</option>
<option value='paused' style='color:orange;'>&#xf04c; &nbsp; Paused</option>
<option value='archived' style='color:red;'>&#xf023; &nbsp; Archived</option>
</select>

Note the font-family:Arial, FontAwesome; is required to be assigned in style for select like given in the example!

Execute command on all files in a directory

The following bash code will pass $file to command where $file will represent every file in /dir

for file in /dir/*
do
  cmd [option] "$file" >> results.out
done

Example

el@defiant ~/foo $ touch foo.txt bar.txt baz.txt
el@defiant ~/foo $ for i in *.txt; do echo "hello $i"; done
hello bar.txt
hello baz.txt
hello foo.txt

Git: Cannot see new remote branch

Doing a git remote update will also update the list of branches available from the remote repository.

If you are using TortoiseGit, as of version 1.8.3.0, you can do "Git -> Sync" and there will be a "Remote Update" button in the lower left of the window that appears. Click that. Then you should be able to do "Git -> Switch/Checkout" and have the new remote branch appear in the dropdown of branches you can select.