Programs & Examples On #Javascript engine

jQuery ajax post file field

File uploads can not be done this way, no matter how you break it down. If you want to do an ajax/async upload, I would suggest looking into something like Uploadify, or Valums

jQuery change URL of form submit

Try using this:

$(".move_to").on("click", function(e){
    e.preventDefault();
    $('#contactsForm').attr('action', "/test1").submit();
});

Moving the order in which you use .preventDefault() might fix your issue. You also didn't use function(e) so e.preventDefault(); wasn't working.

Here it is working: http://jsfiddle.net/TfTwe/1/ - first of all, click the 'Check action attribute.' link. You'll get an alert saying undefined. Then click 'Set action attribute.' and click 'Check action attribute.' again. You'll see that the form's action attribute has been correctly set to /test1.

How Can I Resolve:"can not open 'git-upload-pack' " error in eclipse?

This works for me: http://gitblit.com/setup_client.html

Eclipse/EGit/JGit

Window->Preferences->Team->Git->Configuration
Click the New Entry button

Key = http.sslVerify
Value = false

How can I get Apache gzip compression to work?

<ifModule mod_gzip.c>
mod_gzip_on Yes
mod_gzip_dechunk Yes
mod_gzip_item_include file .(html?|txt|css|js|php|pl)$
mod_gzip_item_include handler ^cgi-script$
mod_gzip_item_include mime ^text/.*
mod_gzip_item_include mime ^application/x-javascript.*
mod_gzip_item_exclude mime ^image/.*
mod_gzip_item_exclude rspheader ^Content-Encoding:.*gzip.*
</ifModule>

<IfModule mod_deflate.c>
# Insert filters
AddOutputFilterByType DEFLATE text/plain
AddOutputFilterByType DEFLATE text/html
AddOutputFilterByType DEFLATE text/xml
AddOutputFilterByType DEFLATE text/css
AddOutputFilterByType DEFLATE application/xml
AddOutputFilterByType DEFLATE application/xhtml+xml
AddOutputFilterByType DEFLATE application/rss+xml
AddOutputFilterByType DEFLATE application/javascript
AddOutputFilterByType DEFLATE application/x-javascript
AddOutputFilterByType DEFLATE application/x-httpd-php
AddOutputFilterByType DEFLATE application/x-httpd-fastphp
AddOutputFilterByType DEFLATE image/svg+xml

# Drop problematic browsers
BrowserMatch ^Mozilla/4 gzip-only-text/html
BrowserMatch ^Mozilla/4\.0[678] no-gzip
BrowserMatch \bMSI[E] !no-gzip !gzip-only-text/html

# Make sure proxies don't deliver the wrong content
Header append Vary User-Agent env=!dont-vary
</IfModule>

How to delete the first row of a dataframe in R?

No one probably really wants to remove row one. So if you are looking for something meaningful, that is conditional selection

#remove rows that have long length and "0" value for vector E

>> setNew<-set[!(set$length=="long" & set$E==0),]

How can I convert a char to int in Java?

I you have the char '9', it will store its ASCII code, so to get the int value, you have 2 ways

char x = '9';
int y = Character.getNumericValue(x);   //use a existing function
System.out.println(y + " " + (y + 1));  // 9  10

or

char x = '9';
int y = x - '0';                        // substract '0' code to get the difference
System.out.println(y + " " + (y + 1));  // 9  10

And it fact, this works also :

char x = 9;
System.out.println(">" + x + "<");     //>  < prints a horizontal tab
int y = (int) x;
System.out.println(y + " " + (y + 1)); //9 10

You store the 9 code, which corresponds to a horizontal tab (you can see when print as String, bu you can also use it as int as you see above

How to install a specific JDK on Mac OS X?

As a rule you cannot install other versions of Java on a Mac than those provided by Apple through Software Update. If you need Java 6 you must have a 64-bit Intel computer. You should always have Java 5 and 1.4 and perhaps 1.3 installed if you have at least OS X 10.4.

If you have VERY much elbow grease and is willing to work with beta software you can install the OpenJDK under OS X, but I don't think you want to go there.

Create array of regex matches

Here's a simple example:

Pattern pattern = Pattern.compile(regexPattern);
List<String> list = new ArrayList<String>();
Matcher m = pattern.matcher(input);
while (m.find()) {
    list.add(m.group());
}

(if you have more capturing groups, you can refer to them by their index as an argument of the group method. If you need an array, then use list.toArray())

Create an Android GPS tracking application

The source code for the Android mobile application open-gpstracker which you appreciated is available here.

You can checkout the code using SVN client application or via Git:

Debugging the source code will surely help you.

Drop-down menu that opens up/upward with pure css

If we are use chosen dropdown list, then we can use below css(No JS/JQuery require)

<select chosen="{width: '100%'}" ng- 
   model="modelName" class="form-control input- 
   sm"
   ng- 
   options="persons.persons as 
   persons.persons for persons in 
   jsonData"
   ng- 
   change="anyFunction(anyParam)" 
   required>
   <option value=""> </option>
</select>
<style>   
.chosen-container .chosen-drop {
    border-bottom: 0;
    border-top: 1px solid #aaa;
    top: auto;
    bottom: 40px;
}

.chosen-container.chosen-with-drop .chosen-single {
    border-top-left-radius: 0px;
    border-top-right-radius: 0px;

    border-bottom-left-radius: 5px;
    border-bottom-right-radius: 5px;

    background-image: none;
}

.chosen-container.chosen-with-drop .chosen-drop {
    border-bottom-left-radius: 0px;
    border-bottom-right-radius: 0px;

    border-top-left-radius: 5px;
    border-top-right-radius: 5px;

    box-shadow: none;

    margin-bottom: -16px;
}
</style>

Tab key == 4 spaces and auto-indent after curly braces in Vim

The auto-indent is based on the current syntax mode. I know that if you are editing Foo.java, then entering a { and hitting Enter indents the following line.

As for tabs, there are two settings. Within Vim, type a colon and then "set tabstop=4" which will set the tabs to display as four spaces. Hit colon again and type "set expandtab" which will insert spaces for tabs.

You can put these settings in a .vimrc (or _vimrc on Windows) in your home directory, so you only have to type them once.

Using only CSS, show div on hover over <a>

From my testing using this CSS:

.expandable{
display: none;
}
.expand:hover+.expandable{
display:inline !important;
}
.expandable:hover{
display:inline !important;
}

And this HTML:

<div class="expand">expand</div>
<div class="expand">expand</div>
<div class="expandable">expandable</div>

, it resulted that it does expand using the second , but does not expand using the first one. So if there is a div between the hover target and the hidden div, then it will not work.

How to change a nullable column to not nullable in a Rails migration?

If you do it in a migration then you could probably do it like this:

# Make sure no null value exist
MyModel.where(date_column: nil).update_all(date_column: Time.now)

# Change the column to not allow null
change_column :my_models, :date_column, :datetime, null: false

How can I update NodeJS and NPM to the next versions?

Upgrading for Windows Users

Windows users should read Troubleshooting > Upgrading on Windows in the npm wiki.

Upgrading on windows 10 using PowerShell (3rd party edit)

The link above Troubleshooting#upgrading-on-windows points to a github page npm-windows-upgrade the lines below are quotes from the readme. I successfully upgraded from npm 2.7.4 to npm 3.9.3 using node v5.7.0 and powershell (presumably powershell version 5.0.10586.122)

First, ensure that you can execute scripts on your system by running the following command from an elevated PowerShell. To run PowerShell as Administrator, click Start, search for PowerShell, right-click PowerShell and select Run as Administrator.

Set-ExecutionPolicy Unrestricted -Scope CurrentUser -Force    

Then, to install and use this upgrader tool, run (also from an elevated PowerShell or cmd.exe):

npm install --global --production npm-windows-upgrade
npm-windows-upgrade

In Javascript, how do I check if an array has duplicate values?

Another approach (also for object/array elements within the array1) could be2:

function chkDuplicates(arr,justCheck){
  var len = arr.length, tmp = {}, arrtmp = arr.slice(), dupes = [];
  arrtmp.sort();
  while(len--){
   var val = arrtmp[len];
   if (/nul|nan|infini/i.test(String(val))){
     val = String(val);
    }
    if (tmp[JSON.stringify(val)]){
       if (justCheck) {return true;}
       dupes.push(val);
    }
    tmp[JSON.stringify(val)] = true;
  }
  return justCheck ? false : dupes.length ? dupes : null;
}
//usages
chkDuplicates([1,2,3,4,5],true);                           //=> false
chkDuplicates([1,2,3,4,5,9,10,5,1,2],true);                //=> true
chkDuplicates([{a:1,b:2},1,2,3,4,{a:1,b:2},[1,2,3]],true); //=> true
chkDuplicates([null,1,2,3,4,{a:1,b:2},NaN],true);          //=> false
chkDuplicates([1,2,3,4,5,1,2]);                            //=> [1,2]
chkDuplicates([1,2,3,4,5]);                                //=> null

See also...

1 needs a browser that supports JSON, or a JSON library if not.
2 edit: function can now be used for simple check or to return an array of duplicate values

Python naming conventions for modules

nib is fine. If in doubt, refer to the Python style guide.

From PEP 8:

Package and Module Names Modules should have short, all-lowercase names. Underscores can be used in the module name if it improves readability. Python packages should also have short, all-lowercase names, although the use of underscores is discouraged.

Since module names are mapped to file names, and some file systems are case insensitive and truncate long names, it is important that module names be chosen to be fairly short -- this won't be a problem on Unix, but it may be a problem when the code is transported to older Mac or Windows versions, or DOS.

When an extension module written in C or C++ has an accompanying Python module that provides a higher level (e.g. more object oriented) interface, the C/C++ module has a leading underscore (e.g. _socket).

How to change column width in DataGridView?

In my Visual Studio 2019 it worked only after I set the AutoSizeColumnsMode property to None.

Illegal mix of collations MySQL Error

I found that using cast() was the best solution for me:

cast(Format(amount, "Standard") AS CHAR CHARACTER SET utf8) AS Amount

There is also a convert() function. More details on it here

Another resource here

Difference between CR LF, LF and CR line break types?

NL derived from EBCDIC NL = x'15' which would logically compare to CRLF x'odoa ascii... this becomes evident when physcally moving data from mainframes to midrange. Coloquially (as only arcane folks use ebcdic) NL has been equated with either CR or LF or CRLF

Use <Image> with a local file

I had this exact same issue until I realized I hadn't put the image in my Image.xcassets. I was able to drag and drop it into Xcode with Image.xcassets open and after rebuilding, it fixed the problem!

enter image description here

How permission can be checked at runtime without throwing SecurityException?

Step 1 - add permission request

    String[] permissionArrays = new String[]{Manifest.permission.CAMERA, 
    Manifest.permission.WRITE_EXTERNAL_STORAGE};
    int REQUEST_CODE = 101;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            requestPermissions(permissionArrays, REQUEST_CODE );
        } else {
             // if already permition granted
            // PUT YOUR ACTION (Like Open cemara etc..)
        }
    }

Step 2 - Handle Permission result

     @Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
    super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    boolean openActivityOnce = true;
    boolean openDialogOnce = true;
    if (requestCode == REQUEST_CODE ) {
        for (int i = 0; i < grantResults.length; i++) {
            String permission = permissions[i];

            isPermitted = grantResults[i] == PackageManager.PERMISSION_GRANTED;

            if (grantResults[i] == PackageManager.PERMISSION_DENIED) {
                // user rejected the permission

            }else {
                //  user grant the permission
                // you can perfome your action 
            }
        }
    }
}

DISTINCT clause with WHERE

SELECT DISTINCT dbo.Table.Email,dbo.Table.FirstName dbo.Table.LastName, dbo.Table.DateOfBirth (etc) FROM dbo.Table.Contacts WHERE Email = 'name@email';

How to replace text in a column of a Pandas dataframe?

Use the vectorised str method replace:

In [30]:

df['range'] = df['range'].str.replace(',','-')
df
Out[30]:
      range
0    (2-30)
1  (50-290)

EDIT

So if we look at what you tried and why it didn't work:

df['range'].replace(',','-',inplace=True)

from the docs we see this desc:

str or regex: str: string exactly matching to_replace will be replaced with value

So because the str values do not match, no replacement occurs, compare with the following:

In [43]:

df = pd.DataFrame({'range':['(2,30)',',']})
df['range'].replace(',','-', inplace=True)
df['range']
Out[43]:
0    (2,30)
1         -
Name: range, dtype: object

here we get an exact match on the second row and the replacement occurs.

How to change status bar color in Flutter?

Change status bar color when you are not using AppBar

First Import this

import 'package:flutter/services.dart';

Now use below code to change status bar color in your application when you are not using the AppBar

SystemChrome.setSystemUIOverlayStyle(SystemUiOverlayStyle.dark.copyWith(

    statusBarColor: AppColors.statusBarColor,/* set Status bar color in Android devices. */
    
    statusBarIconBrightness: Brightness.dark,/* set Status bar icons color in Android devices.*/
    
    statusBarBrightness: Brightness.dark)/* set Status bar icon color in iOS. */
); 

To change the status bar color in iOS when you are using SafeArea

Scaffold(
  body: Container(
    color: Colors.red, /* Set your status bar color here */
    child: SafeArea(child: Container(
      /* Add your Widget here */
    )),
  ),
); 

Trigger a keypress/keydown/keyup event in JS/jQuery?

You could dispatching events like

el.dispatchEvent(new Event('focus'));
el.dispatchEvent(new KeyboardEvent('keypress',{'key':'a'}));

How can I make a div not larger than its contents?

Try display: inline-block;. For it to be cross browser compatible please use the below css code.

_x000D_
_x000D_
div {_x000D_
  display: inline-block;_x000D_
  display:-moz-inline-stack;_x000D_
  zoom:1;_x000D_
  *display:inline;_x000D_
  border-style: solid;_x000D_
  border-color: #0000ff;_x000D_
}
_x000D_
<div>_x000D_
  <table>_x000D_
    <tr>_x000D_
      <td>Column1</td>_x000D_
      <td>Column2</td>_x000D_
      <td>Column3</td>_x000D_
    </tr>_x000D_
  </table>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Where is JAVA_HOME on macOS Mojave (10.14) to Lion (10.7)?

For Java 11 (JDK 11) it can be located with the following command:

/usr/libexec/java_home -v 11

What's the difference between using CGFloat and float?

As others have said, CGFloat is a float on 32-bit systems and a double on 64-bit systems. However, the decision to do that was inherited from OS X, where it was made based on the performance characteristics of early PowerPC CPUs. In other words, you should not think that float is for 32-bit CPUs and double is for 64-bit CPUs. (I believe, Apple's ARM processors were able to process doubles long before they went 64-bit.) The main performance hit of using doubles is that they use twice the memory and therefore might be slower if you are doing a lot of floating point operations.

Best way to check for "empty or null value"

To check for null and empty:

coalesce(string, '') = ''

To check for null, empty and spaces (trim the string)

coalesce(TRIM(string), '') = ''

Java command not found on Linux

You can add one of the Java path to PATH variable using the following command.

export PATH=$PATH:/usr/java/jre1.6.0_24/bin/

You can add this line to .bashrc file in your home directory. Adding this to .bashrc will ensure everytime you open bash it will be PATH variable is updated.

Angularjs - simple form submit

I have been doing quite a bit of research and in attempt to resolve a different issue I ended up coming to a good portion of the solution in my other post here:

Angularjs - Form Post Data Not Posted?

The solution does not include uploading images currently but I intend to expand upon and create a clear and well working example. If updating these posts is possible I will keep them up to date all the way until a stable and easy to learn from example is compiled.

MVC Razor Radio Button

I wanted to share one way to do the radio button (and entire HTML form) without using the @Html.RadioButtonFor helper, although I think @Html.RadioButtonFor is probably the better and newer way (for one thing, it's strongly typed, so is closely linked to theModelProperty). Nevertheless, here's an old-fashioned, different way you can do it:

    <form asp-action="myActionMethod" method="post">
        <h3>Do you like pizza?</h3>
        <div class="checkbox">
            <label>
                <input asp-for="likesPizza"/> Yes
            </label>
        </div>
    </form>

This code can go in a myView.cshtml file, and also uses classes to get the radio-button (checkbox) formatting.

How to get cookie expiration date / creation date from javascript?

The information is not available through document.cookie, but if you're really desperate for it, you could try performing a request through the XmlHttpRequest object to the current page and access the cookie header using getResponseHeader().

How to display loading message when an iFrame is loading?

I have followed the following approach

First, add sibling div

$('<div class="loading"></div>').insertBefore("#Iframe");

and then when the iframe completed loading

$("#Iframe").load(function(){
   $(this).siblings(".loading-fetching-content").remove(); 
  });

Why can't I push to this bare repository?

git push --all

is the canonical way to push everything to a new bare repository.

Another way to do the same thing is to create your new, non-bare repository and then make a bare clone with

git clone --bare

then use

git remote add origin <new-remote-repo>

in the original (non-bare) repository.

'typeid' versus 'typeof' in C++

C++ language has no such thing as typeof. You must be looking at some compiler-specific extension. If you are talking about GCC's typeof, then a similar feature is present in C++11 through the keyword decltype. Again, C++ has no such typeof keyword.

typeid is a C++ language operator which returns type identification information at run time. It basically returns a type_info object, which is equality-comparable with other type_info objects.

Note, that the only defined property of the returned type_info object has is its being equality- and non-equality-comparable, i.e. type_info objects describing different types shall compare non-equal, while type_info objects describing the same type have to compare equal. Everything else is implementation-defined. Methods that return various "names" are not guaranteed to return anything human-readable, and even not guaranteed to return anything at all.

Note also, that the above probably implies (although the standard doesn't seem to mention it explicitly) that consecutive applications of typeid to the same type might return different type_info objects (which, of course, still have to compare equal).

How to convert HTML to PDF using iTextSharp

Here's the link I used as a guide. Hope this helps!

Converting HTML to PDF using ITextSharp

protected void Page_Load(object sender, EventArgs e)
    {
        try
        {
            string strHtml = string.Empty;
            //HTML File path -http://aspnettutorialonline.blogspot.com/
            string htmlFileName = Server.MapPath("~") + "\\files\\" + "ConvertHTMLToPDF.htm";
            //pdf file path. -http://aspnettutorialonline.blogspot.com/
            string pdfFileName = Request.PhysicalApplicationPath + "\\files\\" + "ConvertHTMLToPDF.pdf";

            //reading html code from html file
            FileStream fsHTMLDocument = new FileStream(htmlFileName, FileMode.Open, FileAccess.Read);
            StreamReader srHTMLDocument = new StreamReader(fsHTMLDocument);
            strHtml = srHTMLDocument.ReadToEnd();
            srHTMLDocument.Close();

            strHtml = strHtml.Replace("\r\n", "");
            strHtml = strHtml.Replace("\0", "");

            CreatePDFFromHTMLFile(strHtml, pdfFileName);

            Response.Write("pdf creation successfully with password -http://aspnettutorialonline.blogspot.com/");
        }
        catch (Exception ex)
        {
            Response.Write(ex.Message);
        }
    }
    public void CreatePDFFromHTMLFile(string HtmlStream, string FileName)
    {
        try
        {
            object TargetFile = FileName;
            string ModifiedFileName = string.Empty;
            string FinalFileName = string.Empty;

            /* To add a Password to PDF -http://aspnettutorialonline.blogspot.com/ */
            TestPDF.HtmlToPdfBuilder builder = new TestPDF.HtmlToPdfBuilder(iTextSharp.text.PageSize.A4);
            TestPDF.HtmlPdfPage first = builder.AddPage();
            first.AppendHtml(HtmlStream);
            byte[] file = builder.RenderPdf();
            File.WriteAllBytes(TargetFile.ToString(), file);

            iTextSharp.text.pdf.PdfReader reader = new iTextSharp.text.pdf.PdfReader(TargetFile.ToString());
            ModifiedFileName = TargetFile.ToString();
            ModifiedFileName = ModifiedFileName.Insert(ModifiedFileName.Length - 4, "1");

            string password = "password";
            iTextSharp.text.pdf.PdfEncryptor.Encrypt(reader, new FileStream(ModifiedFileName, FileMode.Append), iTextSharp.text.pdf.PdfWriter.STRENGTH128BITS, password, "", iTextSharp.text.pdf.PdfWriter.AllowPrinting);
            //http://aspnettutorialonline.blogspot.com/
            reader.Close();
            if (File.Exists(TargetFile.ToString()))
                File.Delete(TargetFile.ToString());
            FinalFileName = ModifiedFileName.Remove(ModifiedFileName.Length - 5, 1);
            File.Copy(ModifiedFileName, FinalFileName);
            if (File.Exists(ModifiedFileName))
                File.Delete(ModifiedFileName);

        }
        catch (Exception ex)
        {
            throw ex;
        }
    }

You can download the sample file. Just place the html you want to convert in the files folder and run. It will automatically generate the pdf file and place it in the same folder. But in your case, you can specify your html path in the htmlFileName variable.

Can regular JavaScript be mixed with jQuery?

Yes, they're both JavaScript, you can use whichever functions are appropriate for the situation.

In this case you can just put the code in a document.ready handler, like this:

$(function() {
  var canvas = document.getElementById("canvas");
  if (canvas.getContext) {
    var ctx = canvas.getContext("2d");

    ctx.fillStyle = "rgb(200,0,0)";
    ctx.fillRect (10, 10, 55, 50);

    ctx.fillStyle = "rgba(0, 0, 200, 0.5)";
    ctx.fillRect (30, 30, 55, 50);
  }
});

Android Studio: Add jar as library?

Like many before pointed out you shall add

compile files('libs/gson-2.2.3.jar') 

to your build.gradle file.

However I have a project in Android Studio that was migrated from Eclipse and in this case the "libs" folder is named "lib" so for me removing the "s" solved the problem.

How to do a case sensitive search in WHERE clause (I'm using SQL Server)?

USE BINARY_CHECKSUM

SELECT 
FROM Users
WHERE   
    BINARY_CHECKSUM(Username) = BINARY_CHECKSUM(@Username)
    AND BINARY_CHECKSUM(Password) = BINARY_CHECKSUM(@Password)

Datatable select with multiple conditions

Try this,
I think ,this is one of the simple solutions.

int rowIndex = table.Rows.IndexOf(table.Select("A = 'foo' AND B = 'bar' AND C = 'baz'")[0]);
string strD= Convert.ToString(table.Rows[rowIndex]["D"]);

Make sure,combination of values for column A, B and C is unique in the datatable.

How to auto adjust the <div> height according to content in it?

height:59.55%;//First specify your height then make overflow auto overflow:auto;

Add ripple effect to my button with button background color?

Add the "?attr/selectableItemBackground" to your view's android:foreground attribute if it already has a background along with android:clickable="true".

Create a asmx web service in C# using visual studio 2013

on the web site box, you have selected .NETFramework 4.5 and it doesn show, so click there and choose the 3.5...i hope it helps.

Connect to SQL Server 2012 Database with C# (Visual Studio 2012)

I tested all the answers here, but for me, none worked. So I studied a bit the problem, and finally I found the connection string needed. To get this string, you do:
1. in you project name:
a. right click the project name,
b. click Add,
c. select SQL Server Database (obviously you can rename it as you wish).
Now the new desired database will be added to your project.
2. The database is visible in the Server Explorer window.
3. Left click the database name in the Server Explorer window; now check the Solution Explorer window, and you will find the "Connection String", along side with Provider, State, Type, Version.
4. Copy the connection string provided, and put it in the Page_Load method:

string source = @"Data Source=(LocalDB)\v11.0;AttachDbFilename=c:\x\x\documents\visual studio 2013\Projects\WebApplication3\WebApplication3\App_Data\Product.mdf;Integrated Security=True";
SqlConnection conn = new SqlConnection(source);
conn.Open();
//your code here;
conn.Close();

I renamed my database as Product. Also, in the "AttachDbFilename", you must replace "c:\x\x\documents\" with your path to the phisical address of the .mdf file.

It worked for me, but I must mention this method works for VS2012 and VS2013. Don't know about other versions.

Onclick event to remove default value in a text input field

As stated before I even saw this question placeholder is the answer. HTML5 for the win! But for those poor unfortunate souls that cannot rely on that functionality take a look at the jquery plugin as an augmentation as well. HTML5 Placeholder jQuery Plugin

<input name="Name" placeholder="Enter Your Name">

How to add/update an attribute to an HTML element using JavaScript?

What do you want to do with the attribute? Is it an html attribute or something of your own?

Most of the time you can simply address it as a property: want to set a title on an element? element.title = "foo" will do it.

For your own custom JS attributes the DOM is naturally extensible (aka expando=true), the simple upshot of which is that you can do element.myCustomFlag = foo and subsequently read it without issue.

FORCE INDEX in MySQL - where do I put it?

FORCE_INDEX is going to be deprecated after MySQL 8:

Thus, you should expect USE INDEX, FORCE INDEX, and IGNORE INDEX to be deprecated in 
a future release of MySQL, and at some time thereafter to be removed altogether.

https://dev.mysql.com/doc/refman/8.0/en/index-hints.html

You should be using JOIN_INDEX, GROUP_INDEX, ORDER_INDEX, and INDEX instead, for v8.

How to check if an array element exists?

According to the php manual you can do this in two ways. It depends what you need to check.

If you want to check if the given key or index exists in the array use array_key_exists

<?php
$search_array = array('first' => 1, 'second' => 4);
if (array_key_exists('first', $search_array)) {
echo "The 'first' element is in the array";
 }
?>

If you want to check if a value exists in an array use in_array

 <?php
 $os = array("Mac", "NT", "Irix", "Linux");
if (in_array("Irix", $os)) {
echo "Got Irix";
}
?>

How to add a delay for a 2 or 3 seconds

System.Threading.Thread.Sleep(
    (int)System.TimeSpan.FromSeconds(3).TotalMilliseconds);

Or with using statements:

Thread.Sleep((int)TimeSpan.FromSeconds(2).TotalMilliseconds);

I prefer this to 1000 * numSeconds (or simply 3000) because it makes it more obvious what is going on to someone who hasn't used Thread.Sleep before. It better documents your intent.

How to clear the JTextField by clicking JButton

Looking for EventHandling, ActionListener?

or code?

JButton b = new JButton("Clear");
b.addActionListener(new ActionListener(){
    public void actionPerformed(ActionEvent e){
        textfield.setText("");
        //textfield.setText(null); //or use this
    }
});

Also See
How to Use Buttons

C++ convert string to hexadecimal and vice versa

Using lookup tables and the like works, but is just overkill, here are some very simple ways of taking a string to hex and hex back to a string:

#include <stdexcept>
#include <sstream>
#include <iomanip>
#include <string>
#include <cstdint>

std::string string_to_hex(const std::string& in) {
    std::stringstream ss;

    ss << std::hex << std::setfill('0');
    for (size_t i = 0; in.length() > i; ++i) {
        ss << std::setw(2) << static_cast<unsigned int>(static_cast<unsigned char>(in[i]));
    }

    return ss.str(); 
}

std::string hex_to_string(const std::string& in) {
    std::string output;

    if ((in.length() % 2) != 0) {
        throw std::runtime_error("String is not valid length ...");
    }

    size_t cnt = in.length() / 2;

    for (size_t i = 0; cnt > i; ++i) {
        uint32_t s = 0;
        std::stringstream ss;
        ss << std::hex << in.substr(i * 2, 2);
        ss >> s;

        output.push_back(static_cast<unsigned char>(s));
    }

    return output;
}

How to Execute a Python File in Notepad ++?

First option: (Easiest, recommended)

Open Notepad++. On the menu go to: Run -> Run.. (F5). Type in:

C:\Python26\python.exe "$(FULL_CURRENT_PATH)"

Now, instead of pressing run, press save to create a shortcut for it.

Notes

  • If you have Python 3.1: type in Python31 instead of Python26
  • Add -i if you want the command line window to stay open after the script has finished

Second option

Use a batch script that runs the Python script and then create a shortcut to that from Notepad++.

As explained here: http://it-ride.blogspot.com/2009/08/notepad-and-python.html


Third option: (Not safe)

The code opens “HKEY_CURRENT_USER\Software\Python\PythonCore”, if the key exists it will get the path from the first child key of this key.

Check if this key exists, and if does not, you could try creating it.

MINGW64 "make build" error: "bash: make: command not found"

You can also use Chocolatey.

Having it installed, just run:

choco install make

When it finishes, it is installed and available in Git for Bash / MinGW.

convert datetime to date format dd/mm/yyyy

This works for me:

string dateTimeString = "21?-?10?-?2014? ?15?:?40?:?30";
dateTimeString = Regex.Replace(dateTimeString, @"[^\u0000-\u007F]", string.Empty);

string inputFormat = "dd-MM-yyyy HH:mm:ss";
string outputFormat = "yyyy-MM-dd HH:mm:ss";
var dateTime = DateTime.ParseExact(dateTimeString, inputFormat, CultureInfo.InvariantCulture);
string output = dateTime.ToString(outputFormat);

Console.WriteLine(output);

How do I fix maven error The JAVA_HOME environment variable is not defined correctly?

A very common mistake people make is that, when they set JAVA_HOME or JRE_HOME, they set the value to C:\Program Files\Java\jdk1.8.0_221\bin or similar.

Please note JAVA_HOME and JRE_HOME value should not contain \bin

Remove NA values from a vector

?max shows you that there is an extra parameter na.rm that you can set to TRUE.

Apart from that, if you really want to remove the NAs, just use something like:

myvec[!is.na(myvec)]

Assign command output to variable in batch file

A method has already been devised, however this way you don't need a temp file.

for /f "delims=" %%i in ('command') do set output=%%i

However, I'm sure this has its own exceptions and limitations.

How to change the Jupyter start-up folder

I just had the same problem and tested the methods mentioned above. After several trials, I realized that they are partially correct and are not the complete solution. I tested the below in Windows 10 and Anaconda 4.4.0 with python 3.6.

There are two ways to do even though they have only very small difference. Follow the way marneylc suggested above: i.e.

1) Open "Anaconda Prompt" and type jupyter notebook --generate-config

2) You find the file in C:\Users\username\.jupyter\jupyter_notebook_config.py

3) Change the line of #c.NotebookApp.notebook_dir = '' to c.NotebookApp.notebook_dir = 'c:\test\your_root\'

4) Then, go to the shortcut of Jupyter Notebook located in C:\Users\User_name\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Anaconda3 (64-bit)

5) Do the right click and go to the Properties

6) In the Target field, remove %USERPROFILE% as stenlytw suggested above.

7) Then, In the field of Start in, type the same directory of c:\test\your_root\ in jupyter_notebook_config.py

8) Done!

As the simpler way, after step 3, go to C:\Users\User_name\Anaconda3\Scripts

4-2) You can see the file of jupyter-notebook.exe and click it.

5-2) Then, the Jupyter start the folder you specified in jupyter_notebook_config.py. So make the shortcut of this file.

6-2) Done.

SQLSTATE[HY000] [2002] Connection refused within Laravel homestead

When Laravel connects to mysql on Homestad box and running commands on local environment:

DB_HOST=127.0.0.1
the app needs DB_PORT=3306
the migrations need DB_PORT=33060 otherwise gives Connection refused
phpunit needs DB_PORT=33060 otherwise gives Connection refused

DB_HOST=localhost
the app works with both DB_PORT=3306 or DB_PORT=33060
migrations cannot run
phpunit cannot run

Have in mind that phpunit takes its values from the .env.testing file, if exists, otherwise from the phpunit.xml file on the root folder of the app

SQL keys, MUL vs PRI vs UNI

For Mul, this was also helpful documentation to me - http://grokbase.com/t/mysql/mysql/9987k2ew41/key-field-mul-newbie-question

"MUL means that the key allows multiple rows to have the same value. That is, it's not a UNIque key."

For example, let's say you have two models, Post and Comment. Post has a has_many relationship with Comment. It would make sense then for the Comment table to have a MUL key(Post id) because many comments can be attributed to the same Post.

How to replace <span style="font-weight: bold;">foo</span> by <strong>foo</strong> using PHP and regex?

$text='<span style="font-weight: bold;">Foo</span>';
$text=preg_replace( '/<span style="font-weight: bold;">(.*?)<\/span>/', '<strong>$1</strong>',$text);

Note: only work for your example.

What is the difference between null and System.DBNull.Value?

DBNull.Value is what the .NET Database providers return to represent a null entry in the database. DBNull.Value is not null and comparissons to null for column values retrieved from a database row will not work, you should always compare to DBNull.Value.

http://msdn.microsoft.com/en-us/library/system.dbnull.value.aspx

Create Setup/MSI installer in Visual Studio 2017

You need to install this extension to Visual Studio 2017/2019 in order to get access to the Installer Projects.

According to the page:

This extension provides the same functionality that currently exists in Visual Studio 2015 for Visual Studio Installer projects. To use this extension, you can either open the Extensions and Updates dialog, select the online node, and search for "Visual Studio Installer Projects Extension," or you can download directly from this page.

Once you have finished installing the extension and restarted Visual Studio, you will be able to open existing Visual Studio Installer projects, or create new ones.

How to find all the subclasses of a class given its name?

Note: I see that someone (not @unutbu) changed the referenced answer so that it no longer uses vars()['Foo'] — so the primary point of my post no longer applies.

FWIW, here's what I meant about @unutbu's answer only working with locally defined classes — and that using eval() instead of vars() would make it work with any accessible class, not only those defined in the current scope.

For those who dislike using eval(), a way is also shown to avoid it.

First here's a concrete example demonstrating the potential problem with using vars():

class Foo(object): pass
class Bar(Foo): pass
class Baz(Foo): pass
class Bing(Bar): pass

# unutbu's approach
def all_subclasses(cls):
    return cls.__subclasses__() + [g for s in cls.__subclasses__()
                                       for g in all_subclasses(s)]

print(all_subclasses(vars()['Foo']))  # Fine because  Foo is in scope
# -> [<class '__main__.Bar'>, <class '__main__.Baz'>, <class '__main__.Bing'>]

def func():  # won't work because Foo class is not locally defined
    print(all_subclasses(vars()['Foo']))

try:
    func()  # not OK because Foo is not local to func()
except Exception as e:
    print('calling func() raised exception: {!r}'.format(e))
    # -> calling func() raised exception: KeyError('Foo',)

print(all_subclasses(eval('Foo')))  # OK
# -> [<class '__main__.Bar'>, <class '__main__.Baz'>, <class '__main__.Bing'>]

# using eval('xxx') instead of vars()['xxx']
def func2():
    print(all_subclasses(eval('Foo')))

func2()  # Works
# -> [<class '__main__.Bar'>, <class '__main__.Baz'>, <class '__main__.Bing'>]

This could be improved by moving the eval('ClassName') down into the function defined, which makes using it easier without loss of the additional generality gained by using eval() which unlike vars() is not context-sensitive:

# easier to use version
def all_subclasses2(classname):
    direct_subclasses = eval(classname).__subclasses__()
    return direct_subclasses + [g for s in direct_subclasses
                                    for g in all_subclasses2(s.__name__)]

# pass 'xxx' instead of eval('xxx')
def func_ez():
    print(all_subclasses2('Foo'))  # simpler

func_ez()
# -> [<class '__main__.Bar'>, <class '__main__.Baz'>, <class '__main__.Bing'>]

Lastly, it's possible, and perhaps even important in some cases, to avoid using eval() for security reasons, so here's a version without it:

def get_all_subclasses(cls):
    """ Generator of all a class's subclasses. """
    try:
        for subclass in cls.__subclasses__():
            yield subclass
            for subclass in get_all_subclasses(subclass):
                yield subclass
    except TypeError:
        return

def all_subclasses3(classname):
    for cls in get_all_subclasses(object):  # object is base of all new-style classes.
        if cls.__name__.split('.')[-1] == classname:
            break
    else:
        raise ValueError('class %s not found' % classname)
    direct_subclasses = cls.__subclasses__()
    return direct_subclasses + [g for s in direct_subclasses
                                    for g in all_subclasses3(s.__name__)]

# no eval('xxx')
def func3():
    print(all_subclasses3('Foo'))

func3()  # Also works
# -> [<class '__main__.Bar'>, <class '__main__.Baz'>, <class '__main__.Bing'>]

Sending mail attachment using Java

Using Spring Framework , you can add many attachments :

package com.mkyong.common;


import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;

import org.springframework.core.io.FileSystemResource;
import org.springframework.mail.MailParseException;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;

public class MailMail
{
    private JavaMailSender mailSender;
    private SimpleMailMessage simpleMailMessage;

    public void setSimpleMailMessage(SimpleMailMessage simpleMailMessage) {
        this.simpleMailMessage = simpleMailMessage;
    }

    public void setMailSender(JavaMailSender mailSender) {
        this.mailSender = mailSender;
    }

    public void sendMail(String dear, String content) {

       MimeMessage message = mailSender.createMimeMessage();

       try{
        MimeMessageHelper helper = new MimeMessageHelper(message, true);

        helper.setFrom(simpleMailMessage.getFrom());
        helper.setTo(simpleMailMessage.getTo());
        helper.setSubject(simpleMailMessage.getSubject());
        helper.setText(String.format(
            simpleMailMessage.getText(), dear, content));

        FileSystemResource file = new FileSystemResource("/home/abdennour/Documents/cv.pdf");
        helper.addAttachment(file.getFilename(), file);

         }catch (MessagingException e) {
        throw new MailParseException(e);
         }
         mailSender.send(message);
         }
}

To know how to configure your project to deal with this code , complete reading this tutorial .

Javascript: best Singleton pattern

Extending the above post by Tom, if you need a class type declaration and access the singleton instance using a variable, the code below might be of help. I like this notation as the code is little self guiding.

function SingletonClass(){
    if ( arguments.callee.instance )
        return arguments.callee.instance;
    arguments.callee.instance = this;
}


SingletonClass.getInstance = function() {
    var singletonClass = new SingletonClass();
    return singletonClass;
};

To access the singleton, you would

var singleTon = SingletonClass.getInstance();

How do I remove an array item in TypeScript?

Just wanted to add extension method for an array.

interface Array<T> {
      remove(element: T): Array<T>;
    }

    Array.prototype.remove = function (element) {
      const index = this.indexOf(element, 0);
      if (index > -1) {
        return this.splice(index, 1);
      }
      return this;
    };

How can I use external JARs in an Android project?

Goto Current Project

RightClick->Properties->Java Build Path->Add Jar Files into Libraries -> Click OK

Then it is added into the Referenced Libraries File in your Current Project .

How to extract the n-th elements from a list of tuples?

Timings for Python 3.6 for extracting the second element from a 2-tuple list.

Also, added numpy array method, which is simpler to read (but arguably simpler than the list comprehension).

from operator import itemgetter
elements = [(1,1) for _ in range(100000)]

%timeit second = [x[1] for x in elements]
%timeit second = list(map(itemgetter(1), elements))
%timeit second = dict(elements).values()
%timeit second = list(zip(*elements))[1]
%timeit second = np.array(elements)[:,1]

and the timings:

list comprehension:  4.73 ms ± 206 µs per loop
list(map):           5.3 ms ± 167 µs per loop
dict:                2.25 ms ± 103 µs per loop
list(zip)            5.2 ms ± 252 µs per loop
numpy array:        28.7 ms ± 1.88 ms per loop

Note that map() and zip() do not return a list anymore, hence the explicit conversion.

Java multiline string

In the IntelliJ IDE you just need to type:

""

Then position your cursor inside the quotation marks and paste your string. The IDE will expand it into multiple concatenated lines.

How can I access the MySQL command line with XAMPP for Windows?

  1. Open the XAMPP control panel.
  2. Click Shell.
  3. Type mysql --user=your_user_name --password=your_password.

Can I apply multiple background colors with CSS3?

Yes its possible! and you can use as many colors and images as you desire, here is the right way:

_x000D_
_x000D_
body{_x000D_
/* Its, very important to set the background repeat to: no-repeat */_x000D_
background-repeat:no-repeat; _x000D_
_x000D_
background-image:  _x000D_
/* 1) An image              */ url(http://lorempixel.com/640/100/nature/John3-16/), _x000D_
/* 2) Gradient              */ linear-gradient(to right, RGB(0, 0, 0), RGB(255, 255, 255)), _x000D_
/* 3) Color(using gradient) */ linear-gradient(to right, RGB(110, 175, 233), RGB(110, 175, 233));_x000D_
_x000D_
background-position:_x000D_
/* 1) Image position        */ 0 0, _x000D_
/* 2) Gradient position     */ 0 100px,_x000D_
/* 3) Color position        */ 0 130px;_x000D_
_x000D_
background-size:  _x000D_
/* 1) Image size            */ 640px 100px,_x000D_
/* 2) Gradient size         */ 100% 30px, _x000D_
/* 3) Color size            */ 100% 30px;_x000D_
}
_x000D_
_x000D_
_x000D_

Define global constants

One approach for Angular4 would be defining a constant at module level:

const api_endpoint = 'http://127.0.0.1:6666/api/';

@NgModule({
  declarations: [AppComponent],
  bootstrap: [AppComponent],
  providers: [
    MessageService,
    {provide: 'API_ENDPOINT', useValue: api_endpoint}
  ]
})
export class AppModule {
}

Then, in your service:

import {Injectable, Inject} from '@angular/core';

@Injectable()
export class MessageService {

    constructor(private http: Http, 
      @Inject('API_ENDPOINT') private api_endpoint: string) { }

    getMessages(): Observable<Message[]> {
        return this.http.get(this.api_endpoint+'/messages')
            .map(response => response.json())
            .map((messages: Object[]) => {
                return messages.map(message => this.parseData(message));
            });
    }

    private parseData(data): Message {
        return new Message(data);
    }
}

How to iterate over a JSONObject?

Can't believe that there is no more simple and secured solution than using an iterator in this answers...

JSONObject names () method returns a JSONArray of the JSONObject keys, so you can simply walk though it in loop:

JSONObject object = new JSONObject ();
JSONArray keys = object.names ();

for (int i = 0; i < keys.length (); i++) {
   
   String key = keys.getString (i); // Here's your key
   String value = object.getString (key); // Here's your value
   
}

How to check if a particular service is running on Ubuntu

the best way is using of nmap tool in terminal. nmap is an useful tool that analyse an up system, using it's IP Address, then show all actived network services.

open terminal and use of this example :

~$ nmap 192.168.1.3/24

Starting Nmap 5.21 ( http://nmap.org ) at 2016-05-16 22:49 IRDT
Nmap scan report for 192.168.1.3
Host is up (0.00020s latency).
Not shown: 994 closed ports
PORT     STATE SERVICE
22/tcp   open  ssh
23/tcp   open  telnet
139/tcp  open  netbios-ssn
445/tcp  open  microsoft-ds
3389/tcp open  ms-term-serv
3689/tcp open  rendezvous

Purpose of installing Twitter Bootstrap through npm?

  1. The point of using CDN is that it is faster, first of all, because it is a distributed network, but secondly, because the static files are being cached by the browsers and chances are high that, for example, the CDN's jquery library that your site uses had already been downloaded by the user's browser, and therefore the file had been cached, and therefore no unnecessary download is taking place. That being said, it is still a good idea to provide a fallback.

    Now, the point of bootstrap's npm package

    is that it provides bootstrap's javascript file as a module. As has been mentioned above, this makes it possible to require it using browserify, which is the most likely use case and, as I understand it, the main reason for bootstrap being published on npm.

  2. How to use it

    Imagine the following project structure:

    project
    |-- node_modules
    |-- public
    |   |-- css
    |   |-- img
    |   |-- js
    |   |-- index.html
    |-- package.json
    
    

In your index.html you can reference both css and js files like this:

<link rel="stylesheet" href="../node_modules/bootstrap/dist/css/bootstrap.min.css">
<script src="../node_modules/bootstrap/dist/js/bootstrap.min.js"></script>

Which is the simplest way, and correct for the .css files. But it is much better to include the bootstrap.js file like this somewhere in your public/js/*.js files:

var bootstrap = require('bootstrap');

And you include this code only in those javascript files where you actually need bootstrap.js. Browserify takes care of including this file for you.

Now, the drawback is that you now have your front-end files as node_modules dependencies, and the node_modules folder is usually not checked in with git. I think this is the most controversial part, with many opinions and solutions.


UPDATE March 2017

Almost two years have passed since I wrote this answer and an update is in place.

Now the generally accepted way is to use a bundler like webpack (or another bundler of choice) to bundle all your assets in a build step.

Firstly, it allows you to use commonjs syntax just like browserify, so to include bootstrap js code in your project you do the same:

const bootstrap = require('bootstrap');

As for the css files, webpack has so called "loaders". They allow you write this in your js code:

require('bootstrap/dist/css/bootstrap.css');

and the css files will be "magically" included in your build. They will be dynamically added as <style /> tags when your app runs, but you can configure webpack to export them as a separate css file. You can read more about that in webpack's documentation.

In conclusion.

  1. You should "bundle" your app code with a bundler
  2. You shouldn't commit neither node_modules nor the dynamically built files to git. You can add a build script to npm which should be used to deploy files on server. Anyway, this can be done in different ways depending on your preferred build process.

Convert InputStream to JSONObject

Here is a solution that doesn't use a loop and uses the Android API only:

InputStream inputStreamObject = PositionKeeperRequestTest.class.getResourceAsStream(jsonFileName);
byte[] data = new byte[inputStreamObject.available()];
if(inputStreamObject.read(data) == data.length) {
    JSONObject jsonObject = new JSONObject(new String(data));
}

mysql error 2005 - Unknown MySQL server host 'localhost'(11001)

The case is like :

 mysql connects will localhost when network is not up.
 mysql cannot connect when network is up.

You can try the following steps to diagnose and resolve the issue (my guess is that some other service is blocking port on which mysql is hosted):

  1. Disconnect the network.
  2. Stop mysql service (if windows, try from services.msc window)
  3. Connect to network.
  4. Try to start the mysql and see if it starts correctly.
  5. Check for system logs anyways to be sure that there is no error in starting mysql service.
  6. If all goes well try connecting.
  7. If fails, try to do a telnet localhost 3306 and see what output it shows.
  8. Try changing the port on which mysql is hosted, default 3306, you can change to some other port which is ununsed.

This should ideally resolve the issue you are facing.

How to predict input image using trained model in Keras?

Forwarding the example by @ritiek, I'm a beginner in ML too, maybe this kind of formatting will help see the name instead of just class number.

images = np.vstack([x, y])

prediction = model.predict(images)

print(prediction)

i = 1

for things in prediction:  
    if(things == 0):
        print('%d.It is cancer'%(i))
    else:
        print('%d.Not cancer'%(i))
    i = i + 1

how to display a div triggered by onclick event

You'll have to give an ID to the div you want to show/hide, then use this code:

html:

<div id="one">
    <div id="tow">
        This is text
    </div>
    <button onclick="javascript:showDiv();">Click to show div</button>
</div>

javascript:

function showDiv() {
    div = document.getElementById('tow');
    div.style.display = "block";
}

CSS:

?#tow { display: none; }?

Fiddle: http://jsfiddle.net/xkdNa/

How to fix Warning Illegal string offset in PHP

1.

 if(1 == @$manta_option['iso_format_recent_works']){
      $theme_img = 'recent_works_thumbnail';
 } else {
      $theme_img = 'recent_works_iso_thumbnail';
 }

2.

if(isset($manta_option['iso_format_recent_works']) && 1 == $manta_option['iso_format_recent_works']){
    $theme_img = 'recent_works_thumbnail';
} else {
    $theme_img = 'recent_works_iso_thumbnail';
}

3.

if (!empty($manta_option['iso_format_recent_works']) && $manta_option['iso_format_recent_works'] == 1){
}
else{
}

How to display a database table on to the table in the JSP page

Tracking ID Track
    <br>
    <%String id = request.getParameter("track_id");%>
       <%if (id.length() == 0) {%>
    <b><h1>Please Enter Tracking ID</h1></b>
    <% } else {%>
    <div class="container">
        <table border="1" class="table" >
            <thead>
                <tr class="warning" >
                    <td ><h4>Track ID</h4></td>
                    <td><h4>Source</h4></td>
                    <td><h4>Destination</h4></td>
                    <td><h4>Current Status</h4></td>

                </tr>
            </thead>
            <%
                try {
                    connection = DriverManager.getConnection(connectionUrl + database, userid, password);
                    statement = connection.createStatement();
                    String sql = "select * from track where track_id="+ id;
                    resultSet = statement.executeQuery(sql);
                    while (resultSet.next()) {
            %>
            <tr class="info">
                <td><%=resultSet.getString("track_id")%></td>
                <td><%=resultSet.getString("source")%></td>
                <td><%=resultSet.getString("destination")%></td>
                <td><%=resultSet.getString("status")%></td>
            </tr>
            <%
                    }
                    connection.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            %>
        </table>

        <%}%>
</body>

REST / SOAP endpoints for a WCF service

We must define the behavior configuration to REST endpoint

<endpointBehaviors>
  <behavior name="restfulBehavior">
   <webHttp defaultOutgoingResponseFormat="Json" defaultBodyStyle="Wrapped" automaticFormatSelectionEnabled="False" />
  </behavior>
</endpointBehaviors>

and also to a service

<serviceBehaviors>
   <behavior>
     <serviceMetadata httpGetEnabled="true" httpsGetEnabled="true" />
      <serviceDebug includeExceptionDetailInFaults="false" />
   </behavior>
</serviceBehaviors>

After the behaviors, next step is the bindings. For example basicHttpBinding to SOAP endpoint and webHttpBinding to REST.

<bindings>
   <basicHttpBinding>
     <binding name="soapService" />
   </basicHttpBinding>
   <webHttpBinding>
     <binding name="jsonp" crossDomainScriptAccessEnabled="true" />
   </webHttpBinding>
</bindings>

Finally we must define the 2 endpoint in the service definition. Attention for the address="" of endpoint, where to REST service is not necessary nothing.

<services>
  <service name="ComposerWcf.ComposerService">
    <endpoint address="" behaviorConfiguration="restfulBehavior" binding="webHttpBinding" bindingConfiguration="jsonp" name="jsonService" contract="ComposerWcf.Interface.IComposerService" />
    <endpoint address="soap" binding="basicHttpBinding" name="soapService" contract="ComposerWcf.Interface.IComposerService" />
    <endpoint address="mex" binding="mexHttpBinding" name="metadata" contract="IMetadataExchange" />
  </service>
</services>

In Interface of the service we define the operation with its attributes.

namespace ComposerWcf.Interface
{
    [ServiceContract]
    public interface IComposerService
    {
        [OperationContract]
        [WebInvoke(Method = "GET", UriTemplate = "/autenticationInfo/{app_id}/{access_token}", ResponseFormat = WebMessageFormat.Json,
            RequestFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.Wrapped)]
        Task<UserCacheComplexType_RootObject> autenticationInfo(string app_id, string access_token);
    }
}

Joining all parties, this will be our WCF system.serviceModel definition.

<system.serviceModel>

  <behaviors>
    <endpointBehaviors>
      <behavior name="restfulBehavior">
        <webHttp defaultOutgoingResponseFormat="Json" defaultBodyStyle="Wrapped" automaticFormatSelectionEnabled="False" />
      </behavior>
    </endpointBehaviors>
    <serviceBehaviors>
      <behavior>
        <serviceMetadata httpGetEnabled="true" httpsGetEnabled="true" />
        <serviceDebug includeExceptionDetailInFaults="false" />
      </behavior>
    </serviceBehaviors>
  </behaviors>

  <bindings>
    <basicHttpBinding>
      <binding name="soapService" />
    </basicHttpBinding>
    <webHttpBinding>
      <binding name="jsonp" crossDomainScriptAccessEnabled="true" />
    </webHttpBinding>
  </bindings>

  <protocolMapping>
    <add binding="basicHttpsBinding" scheme="https" />
  </protocolMapping>

  <serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="true" />

  <services>
    <service name="ComposerWcf.ComposerService">
      <endpoint address="" behaviorConfiguration="restfulBehavior" binding="webHttpBinding" bindingConfiguration="jsonp" name="jsonService" contract="ComposerWcf.Interface.IComposerService" />
      <endpoint address="soap" binding="basicHttpBinding" name="soapService" contract="ComposerWcf.Interface.IComposerService" />
      <endpoint address="mex" binding="mexHttpBinding" name="metadata" contract="IMetadataExchange" />
    </service>
  </services>

</system.serviceModel>

To test the both endpoint, we can use WCFClient to SOAP and PostMan to REST.

Git clone without .git directory

Use

git clone --depth=1 --branch=master git://someserver/somerepo dirformynewrepo
rm -rf ./dirformynewrepo/.git
  • The depth option will make sure to copy the least bit of history possible to get that repo.
  • The branch option is optional and if not specified would get master.
  • The second line will make your directory dirformynewrepo not a Git repository any more.
  • If you're doing recursive submodule clone, the depth and branch parameter don't apply to the submodules.

asp:TextBox ReadOnly=true or Enabled=false?

Readonly will allow the user to copy text from it. Disabled will not.

Height equal to dynamic width (CSS fluid layout)

Extremely simple method jsfiddle

HTML

<div id="container">
    <div id="element">
        some text
    </div>
</div>

CSS

#container {
    width: 50%; /* desired width */
}

#element {
    height: 0;
    padding-bottom: 100%;
}

Uncaught TypeError: Object #<Object> has no method 'movingBoxes'

It's also a good idea to make sure you're using the correct version of jQuery. I had recently acquired a project using jQuery 1.6.2 that wasn't working with the hoverIntent plugin. Upgrading it to the most recent version fixed that for me.

How do I initialize a TypeScript Object with a JSON-Object?

the best I found for this purpose is the class-transformer. github.com/typestack/class-transformer

That's how you use it:

Some class:

export class Foo {

    name: string;

    @Type(() => Bar)
    bar: Bar;

    public someFunction = (test: string): boolean => {
        ...
    }
}


import { plainToClass } from 'class-transformer';

export class SomeService {

  anyFunction() {
u = plainToClass(Foo, JSONobj);
 }

If you use the @Type decorator nested properties will be created, too.

How do I clear a C++ array?

Should you want to clear the array with something other than a value, std::file wont cut it; instead I found std::generate useful. e.g. I had a vector of lists I wanted to initialize

std::generate(v.begin(), v.end(), [] () { return std::list<X>(); });

You can do ints too e.g.

std::generate(v.begin(), v.end(), [n = 0] () mutable { return n++; });

or just

std::generate(v.begin(), v.end(), [] (){ return 0; });

but I imagine std::fill is faster for the simplest case

How to use gitignore command in git

on my mac i found this file .gitignore_global ..it was in my home directory hidden so do a ls -altr to see it.

I added eclipse files i wanted git to ignore. the contents looks like this:

 *~
.DS_Store
.project
.settings
.classpath
.metadata

Get attribute name value of <input>

var theName;

theName = $("input selector goes here").attr("name");

In Java, how do I check if a string contains a substring (ignoring case)?

If you are able to use org.apache.commons.lang.StringUtils, I suggest using the following:

String container = "aBcDeFg";
String content = "dE";
boolean containerContainsContent = StringUtils.containsIgnoreCase(container, content);

How do you comment an MS-access Query?

It is not possible to add comments to 'normal' Access queries, that is, a QueryDef in an mdb, which is why a number of people recommend storing the sql for queries in a table.

What is the difference between 'my' and 'our' in Perl?

print "package is: " . __PACKAGE__ . "\n";
our $test = 1;
print "trying to print global var from main package: $test\n";

package Changed;

{
        my $test = 10;
        my $test1 = 11;
        print "trying to print local vars from a closed block: $test, $test1\n";
}

&Check_global;

sub Check_global {
        print "trying to print global var from a function: $test\n";
}
print "package is: " . __PACKAGE__ . "\n";
print "trying to print global var outside the func and from \"Changed\" package:     $test\n";
print "trying to print local var outside the block $test1\n";

Will Output this:

package is: main
trying to print global var from main package: 1
trying to print local vars from a closed block: 10, 11
trying to print global var from a function: 1
package is: Changed
trying to print global var outside the func and from "Changed" package: 1
trying to print local var outside the block 

In case using "use strict" will get this failure while attempting to run the script:

Global symbol "$test1" requires explicit package name at ./check_global.pl line 24.
Execution of ./check_global.pl aborted due to compilation errors.

git ignore exception

Just add ! before an exclusion rule.

According to the gitignore man page:

Patterns have the following format:

...

  • An optional prefix ! which negates the pattern; any matching file excluded by a previous pattern will become included again. If a negated pattern matches, this will override lower precedence patterns sources.

How to draw rounded rectangle in Android UI?

You could just define a new xml background in the drawables folder

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
<solid android:color="enter_your_desired_color_here" />
<corners android:radius="enter_your_desired_radius_the_corners" />
</shape>  

After this just include it in your TextView or EditText by defining it in the background.

<TextView
 android:id="@+id/textView"
 android:layout_width="0dp"
 android:layout_height="80dp"
 android:background="YOUR_FILE_HERE"
 Android:layout_weight="1"
 android:gravity="center"
 android:text="TEXT_HERE"
 android:textSize="40sp" />

How to send a simple string between two programs using pipes?

This answer might be helpful for a future Googler.

#include <stdio.h>
#include <unistd.h>

int main(){     
     int p, f;  
     int rw_setup[2];   
     char message[20];      
     p = pipe(rw_setup);    
     if(p < 0){         
        printf("An error occured. Could not create the pipe.");  
        _exit(1);   
     }      
     f = fork();    
     if(f > 0){
        write(rw_setup[1], "Hi from Parent", 15);    
     }  
     else if(f == 0){       
        read(rw_setup[0],message,15);       
        printf("%s %d\n", message, r_return);   
     }  
     else{      
        printf("Could not create the child process");   
     }      
     return 0;

}

You can find an advanced two-way pipe call example here.

C# Help reading foreign characters using StreamReader

For swedish Å Ä Ö the only solution form the ones above working was:

Encoding.GetEncoding("iso-8859-1")

Hopefully this will save someone time.

Where can I get Google developer key

Go to https://code.google.com/p/google-api-php-client/wiki/OAuth2

Scroll down to where it says 'Visit the Google API Console to generate your developer key, OAuth2 client id, OAuth2 client secret, and register your OAuth2 redirect uri. Copy their values since your will need to input them in your application.'

Click on the 'Google API Console' link.

When it pops up and says 'Welcome to the new Google Developers Console! Prefer the old console? Go back | Dismiss' Click on 'GO BACK'

Check Postgres access for a user

Use this to list Grantee too and remove (PG_monitor and Public) for Postgres PaaS Azure.

SELECT grantee,table_catalog, table_schema, table_name, privilege_type
FROM   information_schema.table_privileges 
WHERE  grantee not in ('pg_monitor','PUBLIC');

How to count the number of occurrences of an element in a List

There is no native method in Java to do that for you. However, you can use IterableUtils#countMatches() from Apache Commons-Collections to do it for you.

Efficiently finding the last line in a text file

Seek to the end of the file minus 100 bytes or so. Do a read and search for a newline. If here is no newline, seek back another 100 bytes or so. Lather, rinse, repeat. Eventually you'll find a newline. The last line begins immediately after that newline.

Best case scenario you only do one read of 100 bytes.

How to get commit history for just one branch?

You can use a range to do that.

git log master..

If you've checked out your my_experiment branch. This will compare where master is at to HEAD (the tip of my_experiment).

How to view DLL functions?

Use the free DLL Export Viewer, it is very easy to use.

Array.push() if does not exist?

Not sure about speed, but stringification + indexOf is a simple approach. Start with turning your array into a string:

let strMyArray = JSON.stringify(myArray);

Then for a series of attribute-value pairs you can use:

if (strMyArray.indexOf('"name":"tom"') === -1 && strMyArray.indexOf('"text":"tasty"') === -1) {
   myArray.push({ name: "tom", text: "tasty" });
}

Finding a whole object is simpler:

if (strMyArray.indexOf(JSON.stringify(objAddMe) === -1) { 
   myArray.push(objAddMe);
}

Hiding and Showing TabPages in tabControl

I have my sample code working but want to make it somewhat more better refrencing the tab from list:

Public Class Form1
    Dim State1 As Integer = 1
    Dim AllTabs As List(Of TabPage) = New List(Of TabPage)

    Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
        Check1(State1)
        State1 = CInt(IIf(State1 = 1, 0, 1))
    End Sub

    Private Sub Form1_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        AllTabs.Add(TabControl1.TabPages("TabPage1"))
        AllTabs.Add(TabControl1.TabPages("TabPage2"))
    End Sub

    Sub Check1(ByVal No As Integer)
        If TabControl1.TabPages.ContainsKey("TabPage1") Then
            TabControl1.TabPages.Remove(TabControl1.TabPages("TabPage1"))
        End If
        If TabControl1.TabPages.ContainsKey("TabPage2") Then
            TabControl1.TabPages.Remove(TabControl1.TabPages("TabPage2"))
        End If
        TabControl1.TabPages.Add(AllTabs(No))
    End Sub
End Class

CSS rotate property in IE

Just a hint... think twice before using "transform: rotate()", or even "-ms-transform :rotate()" (IE9) with mobiles!

I've been knocking hard to the wall for days. I have a 'kinetic' system going on, that slides images and, on top of it, a command area. I did "transform" on an arrow button so it simulates pointing up and down... I've reviewd the 1.000 plus code lines for ages!!! ;-)

All ok, once I removed transform:rotate from the CSS. It's a bit (not to use bad words) tricky the way IE handles it, comparing to other borwsers.

Great answer @Spudley! Thanks for writing it!

Querying DynamoDB by date

Updated Answer:

DynamoDB allows for specification of secondary indexes to aid in this sort of query. Secondary indexes can either be global, meaning that the index spans the whole table across hash keys, or local meaning that the index would exist within each hash key partition, thus requiring the hash key to also be specified when making the query.

For the use case in this question, you would want to use a global secondary index on the "CreatedAt" field.

For more on DynamoDB secondary indexes see the secondary index documentation

Original Answer:

DynamoDB does not allow indexed lookups on the range key only. The hash key is required such that the service knows which partition to look in to find the data.

You can of course perform a scan operation to filter by the date value, however this would require a full table scan, so it is not ideal.

If you need to perform an indexed lookup of records by time across multiple primary keys, DynamoDB might not be the ideal service for you to use, or you might need to utilize a separate table (either in DynamoDB or a relational store) to store item metadata that you can perform an indexed lookup against.

Set transparent background of an imageview on Android

In addition to what Harshad mentioned:

Two hexadecimal characters can be appended to any hexadecimal color code. The first two characters in an 8-digit hex color code represents its opacity in Android.

The two hexadecimal characters can range from 00 to FF. For example,

  • Normal opaque black hex- "#000000"
  • Fully transparent - "#00000000"
  • Fully opaque - "#FF000000"
  • 50% transparent - "#7F000000"

This way you can change any color to any level of transparency.

To find the hexadecimal prefix from a percentage:

Divide the percentage number by 100 and multiply by 255 to get the decimal value. Convert the decimal to hexadecimal here.

For example, for 50%, 50/100 * 255 = 127. Using the link we get hexadecimal value 7F.

Source: Android: how to create a transparent or opaque background

Google Maps Android API v2 Authorization failure

I solved this error by checking the package name in manifest and app build.gradle.

In manifest:

I am using a package name as:

com.app.triapp

In app build.gradle:

 defaultConfig {

        applicationId "com.app.live"
    }

After changed to com.app.triapp in build.gradle, solved my issue.

React Native Responsive Font Size

import { Dimensions } from 'react-native';

const { width, fontScale } = Dimensions.get("window");

const styles = StyleSheet.create({
    fontSize: idleFontSize / fontScale,
});

fontScale get scale as per your device.

ORA-06550: line 1, column 7 (PL/SQL: Statement ignored) Error

If the value stored in PropertyLoader.RET_SECONDARY_V_ARRAY is not "V_ARRAY", then you are using different types; even if they are declared identically (e.g. both are table of number) this will not work.

You're hitting this data type compatibility restriction:

You can assign a collection to a collection variable only if they have the same data type. Having the same element type is not enough.

You're trying to call the procedure with a parameter that is a different type to the one it's expecting, which is what the error message is telling you.

PHP - remove all non-numeric characters from a string

You can use preg_replace in this case;

$res = preg_replace("/[^0-9]/", "", "Every 6 Months" );

$res return 6 in this case.

If want also to include decimal separator or thousand separator check this example:

$res = preg_replace("/[^0-9.]/", "", "$ 123.099");

$res returns "123.099" in this case

Include period as decimal separator or thousand separator: "/[^0-9.]/"

Include coma as decimal separator or thousand separator: "/[^0-9,]/"

Include period and coma as decimal separator and thousand separator: "/[^0-9,.]/"

Unsigned values in C

When you initialize unsigned int a to -1; it means that you are storing the 2's complement of -1 into the memory of a.
Which is nothing but 0xffffffff or 4294967295.

Hence when you print it using %x or %u format specifier you get that output.

By specifying signedness of a variable to decide on the minimum and maximum limit of value that can be stored.

Like with unsigned int: the range is from 0 to 4,294,967,295 and int: the range is from -2,147,483,648 to 2,147,483,647

For more info on signedness refer this

How to make a page redirect using JavaScript?

Use:

window.location = "http://my.url.here";

Here's some quick-n-dirty code that uses jQuery to do what you want. I highly recommend using jQuery. It'll make things a lot more easier for you, especially since you're new to JavaScript.

<select id = "pricingOptions" name = "pricingOptions">
    <option value = "500">Option A</option>
    <option value = "1000">Option B</option>
</select>

<script type = "text/javascript" language = "javascript">
    jQuery(document).ready(function() {
        jQuery("#pricingOptions").change(function() {
            if(this.options[this.selectedIndex].value == "500") {
                window.location = "http://example.com/foo.php?option=500";
            }
        });
    });
</script>

How to write :hover condition for a:before and a:after?

You can also restrict your action to just one class using the right pointed bracket (">"), as I have done in this code:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Document</title>
  <style type="text/css">
    span {
    font-size:12px;
    }
    a {
        color:green;
    }
    .test1>a:hover span {
        display:none;
    }
    .test1>a:hover:before {
        color:red;
        content:"Apple";
    }
  </style>
</head>

<body>
  <div class="test1">
    <a href="#"><span>Google</span></a>
  </div>
  <div class="test2">
    <a href="#"><span>Apple</span></a>
  </div>
</body>

</html>

Note: The hover:before switch works only on the .test1 class

Can Windows Containers be hosted on linux?

Windows containers are not running on Linux and also You can't run Linux containers on Windows directly.

ERROR Source option 1.5 is no longer supported. Use 1.6 or later

There can be corrupted jar file for which it may show error as "ZipFile invalid LOC header (bad signature)" You need to delete all jar files for which it shows the error and add this Dependency

 <dependency>
    <groupId>javax.servlet</groupId>
    <artifactId>servlet-api</artifactId>
    <version>3.0-alpha-1</version>
    <scope>provided</scope>
</dependency>

Convert integer to class Date

You can use ymd from lubridate

lubridate::ymd(v)
#[1] "2008-11-01"

Or anytime::anydate

anytime::anydate(v)
#[1] "2008-11-01"

How to split a string by spaces in a Windows batch file?

The following code will split a string with an arbitrary number of substrings:

@echo off
setlocal ENABLEDELAYEDEXPANSION

REM Set a string with an arbitrary number of substrings separated by semi colons
set teststring=The;rain;in;spain

REM Do something with each substring
:stringLOOP
    REM Stop when the string is empty
    if "!teststring!" EQU "" goto END

    for /f "delims=;" %%a in ("!teststring!") do set substring=%%a

        REM Do something with the substring - 
        REM we just echo it for the purposes of demo
        echo !substring!

REM Now strip off the leading substring
:striploop
    set stripchar=!teststring:~0,1!
    set teststring=!teststring:~1!

    if "!teststring!" EQU "" goto stringloop

    if "!stripchar!" NEQ ";" goto striploop

    goto stringloop
)

:END
endlocal

How can I change Eclipse theme?

The best way to Install new themes in any Eclipse platform is to use the Eclipse Marketplace.

1.Go to Help > Eclipse Marketplace

2.Search for "Color Themes"

3.Install and Restart

4.Go to Window > Preferences > General > Appearance > Color Themes

5.Select anyone and Apply. Restart.

Why do symbols like apostrophes and hyphens get replaced with black diamonds on my website?

It's an encoding problem. You have to set the correct encoding in the HTML head via meta tag:

<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">

Replace "ISO-8859-1" with whatever your encoding is (e.g. 'UTF-8'). You must find out what encoding your HTML files are. If you're on an Unix system, just type file file.html and it should show you the encoding. If this is not possible, you should be able to find out somewhere what encoding your editor produces.

Update elements in a JSONObject

public static JSONObject updateJson(JSONObject obj, String keyString, String newValue) throws Exception {
            JSONObject json = new JSONObject();
            // get the keys of json object
            Iterator iterator = obj.keys();
            String key = null;
            while (iterator.hasNext()) {
                key = (String) iterator.next();
                // if the key is a string, then update the value
                if ((obj.optJSONArray(key) == null) && (obj.optJSONObject(key) == null)) {
                    if ((key.equals(keyString))) {
                        // put new value
                        obj.put(key, newValue);
                        return obj;
                    }
                }

                // if it's jsonobject
                if (obj.optJSONObject(key) != null) {
                    updateJson(obj.getJSONObject(key), keyString, newValue);
                }

                // if it's jsonarray
                if (obj.optJSONArray(key) != null) {
                    JSONArray jArray = obj.getJSONArray(key);
                    for (int i = 0; i < jArray.length(); i++) {
                        updateJson(jArray.getJSONObject(i), keyString, newValue);
                    }
                }
            }
            return obj;
        }

iterating over and removing from a map

Java 8 support a more declarative approach to iteration, in that we specify the result we want rather than how to compute it. Benefits of the new approach are that it can be more readable, less error prone.

public static void mapRemove() {

    Map<Integer, String> map = new HashMap<Integer, String>() {
        {
            put(1, "one");
            put(2, "two");
            put(3, "three");
        }
    };

    map.forEach( (key, value) -> { 
        System.out.println( "Key: " + key + "\t" + " Value: " + value );  
    }); 

    map.keySet().removeIf(e->(e>2)); // <-- remove here

    System.out.println("After removing element");

    map.forEach( (key, value) -> { 
        System.out.println( "Key: " + key + "\t" + " Value: " + value ); 
    });
}

And result is as follows:

Key: 1   Value: one
Key: 2   Value: two
Key: 3   Value: three
After removing element
Key: 1   Value: one
Key: 2   Value: two

How can I de-install a Perl module installed via `cpan`?

There are scripts on CPAN which attempt to uninstall modules:

ExtUtils::Packlist shows sample module removing code, modrm.

how does array[100] = {0} set the entire array to 0?

It's not magic.

The behavior of this code in C is described in section 6.7.8.21 of the C specification (online draft of C spec): for the elements that don't have a specified value, the compiler initializes pointers to NULL and arithmetic types to zero (and recursively applies this to aggregates).

The behavior of this code in C++ is described in section 8.5.1.7 of the C++ specification (online draft of C++ spec): the compiler aggregate-initializes the elements that don't have a specified value.

Also, note that in C++ (but not C), you can use an empty initializer list, causing the compiler to aggregate-initialize all of the elements of the array:

char array[100] = {};

As for what sort of code the compiler might generate when you do this, take a look at this question: Strange assembly from array 0-initialization

AngularJS - $http.post send data as json

i think the most proper way is to use the same piece of code angular use when doing a "get" request using you $httpParamSerializer will have to inject it to your controller so you can simply do the following without having to use Jquery at all , $http.post(url,$httpParamSerializer({param:val}))

app.controller('ctrl',function($scope,$http,$httpParamSerializer){
  $http.post(url,$httpParamSerializer({param:val,secondParam:secondVal}));
}

Verifying that a string contains only letters in C#

I think is a good case to use Regular Expressions:

public bool IsAlpha(string input)
{
    return Regex.IsMatch(input, "^[a-zA-Z]+$");
}

public bool IsAlphaNumeric(string input)
{
    return Regex.IsMatch(input, "^[a-zA-Z0-9]+$");
}

public bool IsAlphaNumericWithUnderscore(string input)
{
    return Regex.IsMatch(input, "^[a-zA-Z0-9_]+$");
}

JavaScript get element by name

Method document.getElementsByName returns an array of elements. You should select first, for example.

document.getElementsByName('acc')[0].value

Detect if string contains any spaces

A secondary option would be to check otherwise, with not space (\S), using an expression similar to:

^\S+$

Test

_x000D_
_x000D_
function has_any_spaces(regex, str) {_x000D_
 if (regex.test(str) || str === '') {_x000D_
  return false;_x000D_
 }_x000D_
 return true;_x000D_
}_x000D_
_x000D_
const expression = /^\S+$/g;_x000D_
const string = 'foo  baz bar';_x000D_
_x000D_
console.log(has_any_spaces(expression, string));
_x000D_
_x000D_
_x000D_

Here, we can for instance push strings without spaces into an array:

_x000D_
_x000D_
const regex = /^\S+$/gm;_x000D_
const str = `_x000D_
foo_x000D_
foo baz_x000D_
bar_x000D_
foo baz bar_x000D_
abc_x000D_
abc abc_x000D_
abc abc abc_x000D_
`;_x000D_
let m, arr = [];_x000D_
_x000D_
while ((m = regex.exec(str)) !== null) {_x000D_
 // This is necessary to avoid infinite loops with zero-width matches_x000D_
 if (m.index === regex.lastIndex) {_x000D_
  regex.lastIndex++;_x000D_
 }_x000D_
_x000D_
 // Here, we push those strings without spaces in an array_x000D_
 m.forEach((match, groupIndex) => {_x000D_
  arr.push(match);_x000D_
 });_x000D_
}_x000D_
console.log(arr);
_x000D_
_x000D_
_x000D_


If you wish to simplify/modify/explore the expression, it's been explained on the top right panel of regex101.com. If you'd like, you can also watch in this link, how it would match against some sample inputs.


RegEx Circuit

jex.im visualizes regular expressions:

enter image description here

C++ Boost: undefined reference to boost::system::generic_category()

It's a linker problem. Include the static library path into your project.

For Qt Creator open the project file .pro and add the following line:

LIBS += -L<path for boost libraries in the system> -lboost_system

In my case Ubuntu x86_64:

LIBS += -L/usr/lib/x86_64-linux-gnu -lboost_system

For Codeblocks, open up Settings->Compiler...->Linker settings tab and add:

boost_system

to the Link libraries text widget and press OK button.

How to display special characters in PHP

So I try htmlspecialchars() or htmlentities() which outputs <p>Résumé<p> and the browser renders <p>Résumé<p>.

If you've got it working where it displays Résumé with <p></p> tags around it, then just don't convert the paragraph, only your string. Then the paragraph will be rendered as HTML and your string will be displayed within.

Excel Formula: Count cells where value is date

Total number of cells in a range minus the blank cells of the same range.

=(115 - (COUNTBLANK(C2:C116)))

This counts everything in the range so, maybe not what you're looking for.

Change UITextField and UITextView Cursor / Caret Color

For Interface Builder version with Swift

@IBOutlet weak var tvValue: UITextView! {
        didSet {
            tvValue.tintColor = .black
        }
    }

Python: How to get values of an array at certain index positions?

You can use index arrays, simply pass your ind_pos as an index argument as below:

a = np.array([0,88,26,3,48,85,65,16,97,83,91])
ind_pos = np.array([1,5,7])

print(a[ind_pos])
# [88,85,16]

Index arrays do not necessarily have to be numpy arrays, they can be also be lists or any sequence-like object (though not tuples).

SVN change username

I’ve had the exact same problem and found the solution in Where does SVN client store user authentication data?:

  1. cd to ~/.subversion/auth/.
  2. Do fgrep -l <yourworkmatesusernameORtheserverurl> */*.
  3. Delete the file found.
  4. The next operation on the repository will ask you again for username/password information.

(For Windows, the steps are analogous; the auth directory is in %APPDATA%\Subversion\).

Note that this will only work for SVN access schemes where the user name is part of the server login so it’s no use for repositories accessed using file://.

The type initializer for 'CrystalDecisions.CrystalReports.Engine.ReportDocument' threw an exception

What did the trick for me was to change the target machine from “ANY CPU” to “x64” or maybe in your case “x86” depending in your target machine’s architecture. I would try this first before moving into a more complex solution which indicates a more complex problem.

Is there a method to generate a UUID with go language

u[8] = (u[8] | 0x80) & 0xBF // what's the purpose ?
u[6] = (u[6] | 0x40) & 0x4F // what's the purpose ?

These lines clamp the values of byte 6 and 8 to a specific range. rand.Read returns random bytes in the range 0-255, which are not all valid values for a UUID. As far as I can tell, this should be done for all the values in the slice though.

If you are on linux, you can alternatively call /usr/bin/uuidgen.

package main

import (
    "fmt"
    "log"
    "os/exec"
)

func main() {
    out, err := exec.Command("uuidgen").Output()
    if err != nil {
        log.Fatal(err)
    }
    fmt.Printf("%s", out)
}

Which yields:

$ go run uuid.go 
dc9076e9-2fda-4019-bd2c-900a8284b9c4

MySQL stored procedure vs function, which would I use when?

The most general difference between procedures and functions is that they are invoked differently and for different purposes:

  1. A procedure does not return a value. Instead, it is invoked with a CALL statement to perform an operation such as modifying a table or processing retrieved records.
  2. A function is invoked within an expression and returns a single value directly to the caller to be used in the expression.
  3. You cannot invoke a function with a CALL statement, nor can you invoke a procedure in an expression.

Syntax for routine creation differs somewhat for procedures and functions:

  1. Procedure parameters can be defined as input-only, output-only, or both. This means that a procedure can pass values back to the caller by using output parameters. These values can be accessed in statements that follow the CALL statement. Functions have only input parameters. As a result, although both procedures and functions can have parameters, procedure parameter declaration differs from that for functions.
  2. Functions return value, so there must be a RETURNS clause in a function definition to indicate the data type of the return value. Also, there must be at least one RETURN statement within the function body to return a value to the caller. RETURNS and RETURN do not appear in procedure definitions.

    • To invoke a stored procedure, use the CALL statement. To invoke a stored function, refer to it in an expression. The function returns a value during expression evaluation.

    • A procedure is invoked using a CALL statement, and can only pass back values using output variables. A function can be called from inside a statement just like any other function (that is, by invoking the function's name), and can return a scalar value.

    • Specifying a parameter as IN, OUT, or INOUT is valid only for a PROCEDURE. For a FUNCTION, parameters are always regarded as IN parameters.

    If no keyword is given before a parameter name, it is an IN parameter by default. Parameters for stored functions are not preceded by IN, OUT, or INOUT. All function parameters are treated as IN parameters.

To define a stored procedure or function, use CREATE PROCEDURE or CREATE FUNCTION respectively:

CREATE PROCEDURE proc_name ([parameters])
 [characteristics]
 routine_body


CREATE FUNCTION func_name ([parameters])
 RETURNS data_type       // diffrent
 [characteristics]
 routine_body

A MySQL extension for stored procedure (not functions) is that a procedure can generate a result set, or even multiple result sets, which the caller processes the same way as the result of a SELECT statement. However, the contents of such result sets cannot be used directly in expression.

Stored routines (referring to both stored procedures and stored functions) are associated with a particular database, just like tables or views. When you drop a database, any stored routines in the database are also dropped.

Stored procedures and functions do not share the same namespace. It is possible to have a procedure and a function with the same name in a database.

In Stored procedures dynamic SQL can be used but not in functions or triggers.

SQL prepared statements (PREPARE, EXECUTE, DEALLOCATE PREPARE) can be used in stored procedures, but not stored functions or triggers. Thus, stored functions and triggers cannot use Dynamic SQL (where you construct statements as strings and then execute them). (Dynamic SQL in MySQL stored routines)

Some more interesting differences between FUNCTION and STORED PROCEDURE:

  1. (This point is copied from a blogpost.) Stored procedure is precompiled execution plan where as functions are not. Function Parsed and compiled at runtime. Stored procedures, Stored as a pseudo-code in database i.e. compiled form.

  2. (I'm not sure for this point.)
    Stored procedure has the security and reduces the network traffic and also we can call stored procedure in any no. of applications at a time. reference

  3. Functions are normally used for computations where as procedures are normally used for executing business logic.

  4. Functions Cannot affect the state of database (Statements that do explicit or implicit commit or rollback are disallowed in function) Whereas Stored procedures Can affect the state of database using commit etc.
    refrence: J.1. Restrictions on Stored Routines and Triggers

  5. Functions can't use FLUSH statements whereas Stored procedures can do.

  6. Stored functions cannot be recursive Whereas Stored procedures can be. Note: Recursive stored procedures are disabled by default, but can be enabled on the server by setting the max_sp_recursion_depth server system variable to a nonzero value. See Section 5.2.3, “System Variables”, for more information.

  7. Within a stored function or trigger, it is not permitted to modify a table that is already being used (for reading or writing) by the statement that invoked the function or trigger. Good Example: How to Update same table on deletion in MYSQL?

Note: that although some restrictions normally apply to stored functions and triggers but not to stored procedures, those restrictions do apply to stored procedures if they are invoked from within a stored function or trigger. For example, although you can use FLUSH in a stored procedure, such a stored procedure cannot be called from a stored function or trigger.

Restore a postgres backup file using the command line?

try:

pg_restore -h localhost -p 5432 -U <username> -d <dbname> -1 <filename>

JQuery datepicker not working

Datepicker is not part of jQuery. You have to get jQuery UI to use the datepicker.

How to call a MySQL stored procedure from within PHP code?

<?php
    $res = mysql_query('SELECT getTreeNodeName(1) AS result');
    if ($res === false) {
        echo mysql_errno().': '.mysql_error();
    }
    while ($obj = mysql_fetch_object($res)) {
        echo $obj->result;
    }

Return a value of '1' a referenced cell is empty

=if(a1="","1","0")

In this formula if the cell is empty then the result would be 1 else it would be 0

postgres: upgrade a user to be a superuser?

alter user username superuser;

How to Access Hive via Python?

Simplest method | Using sqlalchemy

Requirements:

  • pip install pyhive

Code:

import pandas as pd
from sqlalchemy import create_engine

SECRET = {'username':'lol', 'password': 'lol'}
user_name = SECRET.get('username')
passwd = SECRET.get('password')

host_server = 'x.x.x.x'
port = '10000'
database = 'default'
conn = f'hive://{user_name}:{passwd}@{host_server}:{port}/{database}'
engine = create_engine(conn, connect_args={'auth': 'LDAP'})

query = "select * from tablename limit 100"
data = pd.read_sql(query, con=engine)
print(data)

How to change owner of PostgreSql database?

ALTER DATABASE name OWNER TO new_owner;

See the Postgresql manual's entry on this for more details.

SQL Server date format yyyymmdd

In SQL Server, you can do:

select coalesce(format(try_convert(date, col, 112), 'yyyyMMdd'), col)

This attempts the conversion, keeping the previous value if available.

Note: I hope you learned a lesson about storing dates as dates and not strings.

How do I print bold text in Python?

print '\033[1m  Your Name  \033[0m'

\033[1m is the unicode for bold in the terminal \033[0m is the unicode for end the edited text and back default text formate!!!!!

if you do not use \033[0m than all upcoming text of the terminal will become bold!!!!!!!!!

System.Security.SecurityException when writing to Event Log

The solution was to give the "Network Service" account read permission on the EventLog/Security key.

SSL Proxy/Charles and Android trouble

for the Android7

refer to: How to get charles proxy work with Android 7 nougat?

for the Android version below Android7

From your computer, run Charles:

  1. Open Proxy Settings: Proxy -> Proxy Settings, Proxies Tab, check "Enable transparent HTTP proxying", and remember "Port" in heart. enter image description here

  2. SSL Proxy Settings:Proxy -> SSL Proxy Settings, SSL Proxying tab, Check “enable SSL Proxying”, and add . to Locations: enter image description here enter image description here

  3. Open Access Control Settings: Proxy -> Access Control Settings. Add your local subnet to authorize machines on you local network to use the proxy from another machine/mobile. enter image description here

In Android Phone:

  1. Configure your mobile: Go to Settings -> Wireless & networks -> WiFi -> Connect or modify your network, fill in the computer IP address and Port(8888): enter image description here

  2. Get Charles SSL Certificate. Visit this url from your mobile browser: http://charlesproxy.com/getssl enter image description here

  3. In “Name the certificate” enter whatever you want

  4. Accept the security warning and install the certificate. If you install it successful, then you probably see sth like that: In your phone, Settings -> Security -> Trusted credentials: enter image description here

Done.

then you can have some test on your mobile, the encrypted https request will be shown in Charles: enter image description here

How to export html table to excel using javascript

This might be a better answer copied from this question. Please try it and give opinion here. Please vote up if found useful. Thank you.

<script type="text/javascript">
function generate_excel(tableid) {
  var table= document.getElementById(tableid);
  var html = table.outerHTML;
  window.open('data:application/vnd.ms-excel;base64,' + base64_encode(html));
}

function base64_encode (data) {
  // http://kevin.vanzonneveld.net
  // +   original by: Tyler Akins (http://rumkin.com)
  // +   improved by: Bayron Guevara
  // +   improved by: Thunder.m
  // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
  // +   bugfixed by: Pellentesque Malesuada
  // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
  // +   improved by: Rafal Kukawski (http://kukawski.pl)
  // *     example 1: base64_encode('Kevin van Zonneveld');
  // *     returns 1: 'S2V2aW4gdmFuIFpvbm5ldmVsZA=='
  // mozilla has this native
  // - but breaks in 2.0.0.12!
  //if (typeof this.window['btoa'] == 'function') {
  //    return btoa(data);
  //}
  var b64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
  var o1, o2, o3, h1, h2, h3, h4, bits, i = 0,
    ac = 0,
    enc = "",
    tmp_arr = [];

  if (!data) {
    return data;
  }

  do { // pack three octets into four hexets
    o1 = data.charCodeAt(i++);
    o2 = data.charCodeAt(i++);
    o3 = data.charCodeAt(i++);

    bits = o1 << 16 | o2 << 8 | o3;

    h1 = bits >> 18 & 0x3f;
    h2 = bits >> 12 & 0x3f;
    h3 = bits >> 6 & 0x3f;
    h4 = bits & 0x3f;

    // use hexets to index into b64, and append result to encoded string
    tmp_arr[ac++] = b64.charAt(h1) + b64.charAt(h2) + b64.charAt(h3) + b64.charAt(h4);
  } while (i < data.length);

  enc = tmp_arr.join('');

  var r = data.length % 3;

  return (r ? enc.slice(0, r - 3) : enc) + '==='.slice(r || 3);

}
</script>

What is the path for the startup folder in windows 2008 server

In Server 2008 the startup folder for individual users is here:

C:\Users\username\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Startup

For All Users it's here:

C:\ProgramData\Microsoft\Windows\Start Menu\Programs\Startup

Hope that helps

Regex to validate date format dd/mm/yyyy

^(((([13578]|0[13578]|1[02])[-](0[1-9]|[1-9]|1[0-9]|2[0-9]|3[01]))|(([469]|0[469]|11)[-]([1-9]|1[0-9]|2[0-9]|3[0]))|((2|02)([-](0[1-9]|1[0-9]|2[0-8]))))[-](19([6-9][0-9])|20([0-9][0-9])))|((02)[-](29)[-](19(6[048]|7[26]|8[048]|9[26])|20(0[048]|1[26]|2[048])))

this regex will validate dates in format:

12-30-2016 (mm-dd-yyyy) or 12-3-2016 (mm-d-yyyy) or 1-3-2016 (m-d-yyyy) or 1-30-2016 (m-dd-yyyy)

XSS filtering function in PHP

Try using for Clean XSS

xss_clean($data): "><script>alert(String.fromCharCode(74,111,104,116,111,32,82,111,98,98,105,101))</script>

How can I convert a date to GMT?

You can simply use the toUTCString (or toISOString) methods of the date object.

Example:

new Date("Fri Jan 20 2012 11:51:36 GMT-0500").toUTCString()

// Output:  "Fri, 20 Jan 2012 16:51:36 GMT"

If you prefer better control of the output format, consider using a library such as date-fns or moment.js.

Also, in your question, you've actually converted the time incorrectly. When an offset is shown in a timestamp string, it means that the date and time values in the string have already been adjusted from UTC by that value. To convert back to UTC, invert the sign before applying the offset.

11:51:36 -0300  ==  14:51:36Z

Find out how much memory is being used by an object in Python

I haven't any personal experience with either of the following, but a simple search for a "Python [memory] profiler" yield:

  • PySizer, "a memory profiler for Python," found at http://pysizer.8325.org/. However the page seems to indicate that the project hasn't been updated for a while, and refers to...

  • Heapy, "support[ing] debugging and optimization regarding memory related issues in Python programs," found at http://guppy-pe.sourceforge.net/#Heapy.

Hope that helps.

How to show all rows by default in JQuery DataTable

Use:

$('#example').dataTable({
    aLengthMenu: [
        [25, 50, 100, 200, -1],
        [25, 50, 100, 200, "All"]
    ],
    iDisplayLength: -1
});

Or if using 1.10+

$('#example').dataTable({
    paging: false
});

The option you should use is iDisplayLength:

$('#adminProducts').dataTable({
  'iDisplayLength': 100
});

$('#table').DataTable({
   "lengthMenu": [ [5, 10, 25, 50, -1], [5, 10, 25, 50, "All"] ]
});

It will Load by default all entries.

$('#example').dataTable({
    aLengthMenu: [
        [25, 50, 100, 200, -1],
        [25, 50, 100, 200, "All"]
    ],
    iDisplayLength: -1
});

Or if using 1.10+

$('#example').dataTable({
    paging: false
});

If you want to load by default 25 not all do this.

$('#example').dataTable({
    aLengthMenu: [
        [25, 50, 100, 200, -1],
        [25, 50, 100, 200, "All"]
    ],
});

Iterate over elements of List and Map using JSTL <c:forEach> tag

Mark, this is already answered in your previous topic. But OK, here it is again:

Suppose ${list} points to a List<Object>, then the following

<c:forEach items="${list}" var="item">
    ${item}<br>
</c:forEach>

does basically the same as as following in "normal Java":

for (Object item : list) {
    System.out.println(item);
}

If you have a List<Map<K, V>> instead, then the following

<c:forEach items="${list}" var="map">
    <c:forEach items="${map}" var="entry">
        ${entry.key}<br>
        ${entry.value}<br>
    </c:forEach>
</c:forEach>

does basically the same as as following in "normal Java":

for (Map<K, V> map : list) {
    for (Entry<K, V> entry : map.entrySet()) {
        System.out.println(entry.getKey());
        System.out.println(entry.getValue());
    }
}

The key and value are here not special methods or so. They are actually getter methods of Map.Entry object (click at the blue Map.Entry link to see the API doc). In EL (Expression Language) you can use the . dot operator to access getter methods using "property name" (the getter method name without the get prefix), all just according the Javabean specification.

That said, you really need to cleanup the "answers" in your previous topic as they adds noise to the question. Also read the comments I posted in your "answers".

Import Libraries in Eclipse?

No, don't do it that way.

From your Eclipse workspace, right click your project on the left pane -> Properties -> Java Build Path -> Add Jars -> add your jars here.

Tadaa!! :)

How to prevent a browser from storing passwords

One way would be to generate random input names and work with them.

This way, browsers will be presented with the new form each time and won't be able to pre-populate the input fields.

If you provide us with some sample code (do you have a JavaScript single-page application (SPA) app or some server side rendering) I would be happy to help you in the implementation.

How do I print bytes as hexadecimal?

This is a modified version of the Nibble to Hex method

void hexArrayToStr(unsigned char* info, unsigned int infoLength, char **buffer) {
    const char* pszNibbleToHex = {"0123456789ABCDEF"};
    int nNibble, i;
    if (infoLength > 0) {
        if (info != NULL) {
            *buffer = (char *) malloc((infoLength * 2) + 1);
            buffer[0][(infoLength * 2)] = 0;
            for (i = 0; i < infoLength; i++) {
                nNibble = info[i] >> 4;
                buffer[0][2 * i] = pszNibbleToHex[nNibble];
                nNibble = info[i] & 0x0F;
                buffer[0][2 * i + 1] = pszNibbleToHex[nNibble];
            }
        } else {
            *buffer = NULL;
        }
    } else {
        *buffer = NULL;
    }
}

How to create a zip archive of a directory in Python?

The easiest way is to use shutil.make_archive. It supports both zip and tar formats.

import shutil
shutil.make_archive(output_filename, 'zip', dir_name)

If you need to do something more complicated than zipping the whole directory (such as skipping certain files), then you'll need to dig into the zipfile module as others have suggested.

Eclipse comment/uncomment shortcut?

For a Mac it is the following combination: Cmd + /

Count the cells with same color in google spreadsheet

You can use this working script:

/**
* @param {range} countRange Range to be evaluated
* @param {range} colorRef Cell with background color to be searched for in countRange
* @return {number}
* @customfunction
*/

function countColoredCells(countRange,colorRef) {
  var activeRange = SpreadsheetApp.getActiveRange();
  var activeSheet = activeRange.getSheet();
  var formula = activeRange.getFormula();

  var rangeA1Notation = formula.match(/\((.*)\,/).pop();
  var range = activeSheet.getRange(rangeA1Notation);
  var bg = range.getBackgrounds();
  var values = range.getValues();

  var colorCellA1Notation = formula.match(/\,(.*)\)/).pop();
  var colorCell = activeSheet.getRange(colorCellA1Notation);
  var color = colorCell.getBackground();

  var count = 0;

  for(var i=0;i<bg.length;i++)
    for(var j=0;j<bg[0].length;j++)
      if( bg[i][j] == color )
        count=count+1;
  return count;
};

Then call this function in your google sheets:

=countColoredCells(D5:D123,Z11)

Getting "unixtime" in Java

Java 8 added a new API for working with dates and times. With Java 8 you can use

import java.time.Instant
...
long unixTimestamp = Instant.now().getEpochSecond();

Instant.now() returns an Instant that represents the current system time. With getEpochSecond() you get the epoch seconds (unix time) from the Instant.

How to get the week day name from a date?

To do this for oracle sql, the syntax would be:

,SUBSTR(col,INSTR(col,'-',1,2)+1) AS new_field

for this example, I look for the second '-' and take the substring to the end

Hive insert query like SQL

You can use below approach. With this, You don't need to create temp table OR txt/csv file for further select and load respectively.

INSERT INTO TABLE tablename SELECT value1,value2 FROM tempTable_with_atleast_one_records LIMIT 1.

Where tempTable_with_atleast_one_records is any table with atleast one record.

But problem with this approach is that If you have INSERT statement which inserts multiple rows like below one.

INSERT INTO yourTable values (1 , 'value1') , (2 , 'value2') , (3 , 'value3') ;

Then, You need to have separate INSERT hive statement for each rows. See below.

INSERT INTO TABLE yourTable SELECT 1 , 'value1' FROM tempTable_with_atleast_one_records LIMIT 1;
INSERT INTO TABLE yourTable SELECT 2 , 'value2' FROM tempTable_with_atleast_one_records LIMIT 1;
INSERT INTO TABLE yourTable SELECT 3 , 'value3' FROM tempTable_with_atleast_one_records LIMIT 1;

How do I empty an array in JavaScript?

If you use constants then you have no choice:

const numbers = [1, 2, 3]

You can not reasign:

numbers = []

You can only truncate:

numbers.length = 0

bootstrap datepicker setDate format dd/mm/yyyy

You can use this code for bootstrap datepicker:

HTML Code:

<p>Date: <input type="text" id="datepicker" class="datepicker"></p>

Javascript:

$( ".datepicker" ).datepicker({
   format: 'yyyy-mm-dd'
});

How to list the certificates stored in a PKCS12 keystore with keytool?

If the keystore is PKCS12 type (.pfx) you have to specify it with -storetype PKCS12 (line breaks added for readability):

keytool -list -v -keystore <path to keystore.pfx> \
    -storepass <password> \
    -storetype PKCS12

Image Processing: Algorithm Improvement for 'Coca-Cola Can' Recognition

Looking at shape

Take a gander at the shape of the red portion of the can/bottle. Notice how the can tapers off slightly at the very top whereas the bottle label is straight. You can distinguish between these two by comparing the width of the red portion across the length of it.

Looking at highlights

One way to distinguish between bottles and cans is the material. A bottle is made of plastic whereas a can is made of aluminum metal. In sufficiently well-lit situations, looking at the specularity would be one way of telling a bottle label from a can label.

As far as I can tell, that is how a human would tell the difference between the two types of labels. If the lighting conditions are poor, there is bound to be some uncertainty in distinguishing the two anyways. In that case, you would have to be able to detect the presence of the transparent/translucent bottle itself.

Call-time pass-by-reference has been removed

Only call time pass-by-reference is removed. So change:

call_user_func($func, &$this, &$client ...

To this:

call_user_func($func, $this, $client ...

&$this should never be needed after PHP4 anyway period.

If you absolutely need $client to be passed by reference, update the function ($func) signature instead (function func(&$client) {)

How does the data-toggle attribute work? (What's its API?)

The data-* attributes is used to store custom data private to the page or application

So Bootstrap uses these attributes for saving states of objects

W3School data-* description

How to keep two folders automatically synchronized?

I use this free program to synchronize local files and directories: https://github.com/Fitus/Zaloha.sh. The repository contains a simple demo as well.

The good point: It is a bash shell script (one file only). Not a black box like other programs. Documentation is there as well. Also, with some technical talents, you can "bend" and "integrate" it to create the final solution you like.

Optimum way to compare strings in JavaScript?

You can use the localeCompare() method.

string_a.localeCompare(string_b);

/* Expected Returns:

 0:  exact match

-1:  string_a < string_b

 1:  string_a > string_b

 */

Further Reading:

Calling C/C++ from Python?

I think cffi for python can be an option.

The goal is to call C code from Python. You should be able to do so without learning a 3rd language: every alternative requires you to learn their own language (Cython, SWIG) or API (ctypes). So we tried to assume that you know Python and C and minimize the extra bits of API that you need to learn.

http://cffi.readthedocs.org/en/release-0.7/

How to implement the Softmax function in Python

The softmax function is an activation function that turns numbers into probabilities which sum to one. The softmax function outputs a vector that represents the probability distributions of a list of outcomes. It is also a core element used in deep learning classification tasks.

Softmax function is used when we have multiple classes.

It is useful for finding out the class which has the max. Probability.

The Softmax function is ideally used in the output layer, where we are actually trying to attain the probabilities to define the class of each input.

It ranges from 0 to 1.

Softmax function turns logits [2.0, 1.0, 0.1] into probabilities [0.7, 0.2, 0.1], and the probabilities sum to 1. Logits are the raw scores output by the last layer of a neural network. Before activation takes place. To understand the softmax function, we must look at the output of the (n-1)th layer.

The softmax function is, in fact, an arg max function. That means that it does not return the largest value from the input, but the position of the largest values.

For example:

Before softmax

X = [13, 31, 5]

After softmax

array([1.52299795e-08, 9.99999985e-01, 5.10908895e-12]

Code:

import numpy as np

# your solution:

def your_softmax(x): 

"""Compute softmax values for each sets of scores in x.""" 

e_x = np.exp(x - np.max(x)) 

return e_x / e_x.sum() 

# correct solution: 

def softmax(x): 

"""Compute softmax values for each sets of scores in x.""" 

e_x = np.exp(x - np.max(x)) 

return e_x / e_x.sum(axis=0) 

# only difference

Why are Python lambdas useful?

I use it quite often, mainly as a null object or to partially bind parameters to a function.

Here are examples:

to implement null object pattern:

{
    DATA_PACKET: self.handle_data_packets
    NET_PACKET: self.handle_hardware_packets
}.get(packet_type, lambda x : None)(payload)

for parameter binding:

let say that I have the following API

def dump_hex(file, var)
    # some code
    pass

class X(object):
    #...
    def packet_received(data):
        # some kind of preprocessing
        self.callback(data)
    #...

Then, when I wan't to quickly dump the recieved data to a file I do that:

dump_file = file('hex_dump.txt','w')
X.callback = lambda (x): dump_hex(dump_file, x)
...
dump_file.close()

How to go up a level in the src path of a URL in HTML?

Use .. to indicate the parent directory:

background-image: url('../images/bg.png');

What is resource-ref in web.xml used for?

You can always refer to resources in your application directly by their JNDI name as configured in the container, but if you do so, essentially you are wiring the container-specific name into your code. This has some disadvantages, for example, if you'll ever want to change the name later for some reason, you'll need to update all the references in all your applications, and then rebuild and redeploy them.

<resource-ref> introduces another layer of indirection: you specify the name you want to use in the web.xml, and, depending on the container, provide a binding in a container-specific configuration file.

So here's what happens: let's say you want to lookup the java:comp/env/jdbc/primaryDB name. The container finds that web.xml has a <resource-ref> element for jdbc/primaryDB, so it will look into the container-specific configuration, that contains something similar to the following:

<resource-ref>
  <res-ref-name>jdbc/primaryDB</res-ref-name>
  <jndi-name>jdbc/PrimaryDBInTheContainer</jndi-name>
</resource-ref>

Finally, it returns the object registered under the name of jdbc/PrimaryDBInTheContainer.

The idea is that specifying resources in the web.xml has the advantage of separating the developer role from the deployer role. In other words, as a developer, you don't have to know what your required resources are actually called in production, and as the guy deploying the application, you will have a nice list of names to map to real resources.

ImportError: No module named pythoncom

$ pip3 install pypiwin32

Sometimes using pip3 also works if just pip by itself is not working.

Where does forever store console.log output?

You need to add the log destination specifiers before the filename to run. So

forever -e /path/error.txt -o /path/output.txt start index.js

How to generate graphs and charts from mysql database in php

I use highcharts. They are very interactive (and very fancy I might add). You do have to get a little creative to access data from MySQL database, but if you have a general understanding of JavaScript and PHP, you should have no problems.

Node.js – events js 72 throw er unhandled 'error' event

Close nodejs app running in another shell. Restart the terminal and run the program again.


Another server might be also using the same port that you have used for nodejs. Kill the process that is using nodejs port and run the app.

To find the PID of the application that is using port:8000

$ fuser 8000/tcp
8000/tcp:            16708

Here PID is 16708 Now kill the process using the kill [PID] command

$ kill 16708

Eclipse keyboard shortcut to indent source code to the left?

In my copy, Shift + Tab does this, as long as I have a code selection, and am in a code window.

UIView Hide/Show with animation

If your view is set to hidden by default or you change the Hidden state which I think you should in many cases, then none of the approaches in this page will give you both FadeIn/FadeOut animation, it will only animate one of these states, the reason is you are setting the Hidden state to false before calling UIView.animate method which will cause a sudden visibility and if you only animate the alpha then the object space is still there but it's not visible which will result to some UI issues.

So the best approach is to check first if the view is hidden then set the alpha to 0.0, like this when you set the Hidden state to false you won't see a sudden visibility.

func hideViewWithFade(_ view: UIView) {
    if view.isHidden {
        view.alpha = 0.0
    }

    view.isHidden = false

    UIView.animate(withDuration: 0.3, delay: 0.0, options: .transitionCrossDissolve, animations: {
        view.alpha = view.alpha == 1.0 ? 0.0 : 1.0
    }, completion: { _ in
        view.isHidden = !Bool(truncating: view.alpha as NSNumber)
    })
}

jQuery ID starts with

Here you go:

$('td[id^="' + value +'"]')

so if the value is for instance 'foo', then the selector will be 'td[id^="foo"]'.

Note that the quotes are mandatory: [id^="...."].

Source: http://api.jquery.com/attribute-starts-with-selector/

SyntaxError: non-default argument follows default argument

You can't have a non-keyword argument after a keyword argument.

Make sure you re-arrange your function arguments like so:

def a(len1,til,hgt=len1,col=0):
    system('mode con cols='+len1,'lines='+hgt)
    system('title',til)
    system('color',col)

a(64,"hi",25,"0b")

What is ":-!!" in C code?

This is, in effect, a way to check whether the expression e can be evaluated to be 0, and if not, to fail the build.

The macro is somewhat misnamed; it should be something more like BUILD_BUG_OR_ZERO, rather than ...ON_ZERO. (There have been occasional discussions about whether this is a confusing name.)

You should read the expression like this:

sizeof(struct { int: -!!(e); }))
  1. (e): Compute expression e.

  2. !!(e): Logically negate twice: 0 if e == 0; otherwise 1.

  3. -!!(e): Numerically negate the expression from step 2: 0 if it was 0; otherwise -1.

  4. struct{int: -!!(0);} --> struct{int: 0;}: If it was zero, then we declare a struct with an anonymous integer bitfield that has width zero. Everything is fine and we proceed as normal.

  5. struct{int: -!!(1);} --> struct{int: -1;}: On the other hand, if it isn't zero, then it will be some negative number. Declaring any bitfield with negative width is a compilation error.

So we'll either wind up with a bitfield that has width 0 in a struct, which is fine, or a bitfield with negative width, which is a compilation error. Then we take sizeof that field, so we get a size_t with the appropriate width (which will be zero in the case where e is zero).


Some people have asked: Why not just use an assert?

keithmo's answer here has a good response:

These macros implement a compile-time test, while assert() is a run-time test.

Exactly right. You don't want to detect problems in your kernel at runtime that could have been caught earlier! It's a critical piece of the operating system. To whatever extent problems can be detected at compile time, so much the better.

How can you create pop up messages in a batch script?

It's easy to make a message, here's how:

First open notpad and type:

msg "Message",0,"Title"

and save it as Message.vbs.

Now in your batch file type:

Message.vbs %*

How to enable CORS on Firefox?

I was stucked with this problem for a long time (CORS does not work in FF, but works in Chrome and others). No advice could help. Finally, i found that my local dev subdomain (like sub.example.dev) was not explicitly mentioned in /etc/hosts, thus FF just is not able to find it and shows confusing error message 'Aborted...' in dev tools panel.

Putting the exact subdomain into my local /etc/hosts fixed the problem. /etc/hosts is just a plain-text file in unix systems, so you can open it under the root user and put your subdomain in front of '127.0.0.1' ip address.

Routing with Multiple Parameters using ASP.NET MVC

Starting with MVC 5, you can also use Attribute Routing to move the URL parameter configuration to your controllers.

A detailed discussion is available here: http://blogs.msdn.com/b/webdev/archive/2013/10/17/attribute-routing-in-asp-net-mvc-5.aspx

Summary:

First you enable attribute routing

 public class RouteConfig 
 {
     public static void RegisterRoutes(RouteCollection routes)
     {
         routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

         routes.MapMvcAttributeRoutes();
     } 
 }

Then you can use attributes to define parameters and optionally data types

public class BooksController : Controller
{
    // eg: /books
    // eg: /books/1430210079
    [Route("books/{isbn?}")]
    public ActionResult View(string isbn)

How can I convert a PFX certificate file for use with Apache on a linux server?

SSLSHopper has some pretty thorough articles about moving between different servers.

http://www.sslshopper.com/how-to-move-or-copy-an-ssl-certificate-from-one-server-to-another.html

Just pick the relevant link at bottom of this page.

Note: they have an online converter which gives them access to your private key. They can probably be trusted but it would be better to use the OPENSSL command (also shown on this site) to keep the private key private on your own machine.

What is cardinality in Databases?

In database, Cardinality number of rows in the table.

enter image description here img source


enter image description here img source


  • Relationships are named and classified by their cardinality (i.e. number of elements of the set).
  • Symbols which appears closes to the entity is Maximum cardinality and the other one is Minimum cardinality.
  • Entity relation, shows end of the relationship line as follows:
    enter image description here

enter image description here

image source

Count the number of Occurrences of a Word in a String

This will work

int word_count(String text,String key){
   int count=0;
   while(text.contains(key)){
      count++;
      text=text.substring(text.indexOf(key)+key.length());
   }
   return count;
}

Disable resizing of a Windows Forms form

Take a look at the FormBorderStyle property

form1.FormBorderStyle = FormBorderStyle.FixedSingle;

You may also want to remove the minimize and maximize buttons:

form1.MaximizeBox = false;
form1.MinimizeBox = false;

Convert a object into JSON in REST service by Spring MVC

Another simple solution is to add jackson-databind dependency in POM.

    <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-databind</artifactId>
        <version>2.8.1</version>
    </dependency>

Keep Rest of the code as it is.

What resources are shared between threads?

A process has code, data, heap and stack segments. Now, the Instruction Pointer (IP) of a thread OR threads points to the code segment of the process. The data and heap segments are shared by all the threads. Now what about the stack area? What is actually the stack area? Its an area created by the process just for its thread to use... because stacks can be used in a much faster way than heaps etc. The stack area of the process is divided among threads, i.e. if there are 3 threads, then the stack area of the process is divided into 3 parts and each is given to the 3 threads. In other words, when we say that each thread has its own stack, that stack is actually a part of the process stack area allocated to each thread. When a thread finishes its execution, the stack of the thread is reclaimed by the process. In fact, not only the stack of a process is divided among threads, but all the set of registers that a thread uses like SP, PC and state registers are the registers of the process. So when it comes to sharing, the code, data and heap areas are shared, while the stack area is just divided among threads.