Programs & Examples On #Uipicker

DO NOT USE. Please use the [tag:UIPickerView] tag

Using isKindOfClass with Swift

override func touchesBegan(touches: NSSet, withEvent event: UIEvent) {

    super.touchesBegan(touches, withEvent: event)
    let touch : UITouch = touches.anyObject() as UITouch

    if touch.view.isKindOfClass(UIPickerView)
    {

    }
}

Edit

As pointed out in @Kevin's answer, the correct way would be to use optional type cast operator as?. You can read more about it on the section Optional Chaining sub section Downcasting.

Edit 2

As pointed on the other answer by user @KPM, using the is operator is the right way to do it.

How to set a default Value of a UIPickerView

Swift solution:

Define an Outlet:

@IBOutlet weak var pickerView: UIPickerView!  // for example

Then in your viewWillAppear or your viewDidLoad, for example, you can use the following:

pickerView.selectRow(rowMin, inComponent: 0, animated: true)
pickerView.selectRow(rowSec, inComponent: 1, animated: true)

If you inspect the Swift 2.0 framework you'll see .selectRow defined as:

func selectRow(row: Int, inComponent component: Int, animated: Bool) 

option clicking .selectRow in Xcode displays the following:

enter image description here

How To Get Selected Value From UIPickerView

-(void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component
{
   weightSelected = [pickerArray objectAtIndex:row];
}

Add UIPickerView & a Button in Action sheet - How?

Even though this question is old, I'll quickly mention that I've thrown together an ActionSheetPicker class with a convenience function, so you can spawn an ActionSheet with a UIPickerView in one line. It's based on code from answers to this question.

Edit: It now also supports the use of a DatePicker and DistancePicker.


UPD:

This version is deprecated: use ActionSheetPicker-3.0 instead.

animation

How do I pass multiple parameters in Objective-C?

for create method:

-(void)mymethods:(NSString *)aCont withsecond:(NSString *)a-second {
//method definition...
}

for call the method:

[mymethods:self.contoCorrente withsecond:self.asecond];

How to change UIPickerView height

I am working with ios 7, Xcode 5. I was able to adjust the height of date picker indirectly by enclosing it in a view. The container views height can be adjusted.

SSIS - Text was truncated or one or more characters had no match in the target code page - Special Characters

If you go to the Flat file connection manager under Advanced and Look at the "OutputColumnWidth" description's ToolTip It will tell you that Composit characters may use more spaces. So the "é" in "Société" most likely occupies more than one character.

EDIT: Here's something about it: http://en.wikipedia.org/wiki/Precomposed_character

Run certain code every n seconds

Here's a version that doesn't create a new thread every n seconds:

from threading import Event, Thread

def call_repeatedly(interval, func, *args):
    stopped = Event()
    def loop():
        while not stopped.wait(interval): # the first call is in `interval` secs
            func(*args)
    Thread(target=loop).start()    
    return stopped.set

The event is used to stop the repetitions:

cancel_future_calls = call_repeatedly(5, print, "Hello, World")
# do something else here...
cancel_future_calls() # stop future calls

See Improve current implementation of a setInterval python

Memory address of an object in C#

You can use GCHandleType.Weak instead of Pinned. On the other hand, there is another way to get a pointer to an object:

object o = new object();
TypedReference tr = __makeref(o);
IntPtr ptr = **(IntPtr**)(&tr);

Requires unsafe block and is very, very dangerous and should not be used at all. ?


Back in the day when by-ref locals weren't possible in C#, there was one undocumented mechanism that could accomplish a similar thing – __makeref.

object o = new object();
ref object r = ref o;
//roughly equivalent to
TypedReference tr = __makeref(o);

There is one important difference in that TypedReference is "generic"; it can be used to store a reference to a variable of any type. Accessing such a reference requires to specify its type, e.g. __refvalue(tr, object), and if it doesn't match, an exception is thrown.

To implement the type checking, TypedReference must have two fields, one with the actual address to the variable, and one with a pointer to its type representation. It just so happens that the address is the first field.

Therefore, __makeref is used first to obtain a reference to the variable o. The cast (IntPtr**)(&tr) treats the structure as an array (represented via a pointer) of IntPtr* (pointers to a generic pointer type), accessed via a pointer to it. The pointer is first dereferenced to obtain the first field, then the pointer there is dereferenced again to obtain the value actually stored in the variable o – the pointer to the object itself.

However, since 2012, I have come up with a better and safer solution:

public static class ReferenceHelpers
{
    public static readonly Action<object, Action<IntPtr>> GetPinnedPtr;

    static ReferenceHelpers()
    {
        var dyn = new DynamicMethod("GetPinnedPtr", typeof(void), new[] { typeof(object), typeof(Action<IntPtr>) }, typeof(ReferenceHelpers).Module);
        var il = dyn.GetILGenerator();
        il.DeclareLocal(typeof(object), true);
        il.Emit(OpCodes.Ldarg_0);
        il.Emit(OpCodes.Stloc_0);
        il.Emit(OpCodes.Ldarg_1);
        il.Emit(OpCodes.Ldloc_0);
        il.Emit(OpCodes.Conv_I);
        il.Emit(OpCodes.Call, typeof(Action<IntPtr>).GetMethod("Invoke"));
        il.Emit(OpCodes.Ret);
        GetPinnedPtr = (Action<object, Action<IntPtr>>)dyn.CreateDelegate(typeof(Action<object, Action<IntPtr>>));
    }
}

This creates a dynamic method that first pins the object (so its storage doesn't move in the managed heap), then executes a delegate that receives its address. During the execution of the delegate, the object is still pinned and thus safe to be manipulated via the pointer:

object o = new object();
ReferenceHelpers.GetPinnedPtr(o, ptr => Console.WriteLine(Marshal.ReadIntPtr(ptr) == typeof(object).TypeHandle.Value)); //the first pointer in the managed object header in .NET points to its run-time type info

This is the easiest way to pin an object, since GCHandle requires the type to be blittable in order to pin it. It has the advantage of not using implementation details, undocumented keywords and memory hacking.

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

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

=RIGHT(A1, 4)

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

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

=RIGHT(TRIMSPACES(A1), 4)

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

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

Primary key or Unique index?

Foreign keys work with unique constraints as well as primary keys. From Books Online:

A FOREIGN KEY constraint does not have to be linked only to a PRIMARY KEY constraint in another table; it can also be defined to reference the columns of a UNIQUE constraint in another table

For transactional replication, you need the primary key. From Books Online:

Tables published for transactional replication must have a primary key. If a table is in a transactional replication publication, you cannot disable any indexes that are associated with primary key columns. These indexes are required by replication. To disable an index, you must first drop the table from the publication.

Both answers are for SQL Server 2005.

Description for event id from source cannot be found

Use PowerShell to create your event log and source:

New-EventLog -LogName MyApplicationLog `
    -Source MySource `
    -MessageResourceFile C:\windows\Microsoft.NET\Framework\v4.0.30319\EventLogMessages.dll

You'll need the messages dll to avoid the problem you are seeing.

How to get a parent element to appear above child

style:

.parent{
  overflow:hidden;
  width:100px;
}

.child{
  width:200px;
}

body:

<div class="parent">
   <div class="child"></div>
</div>

View content of H2 or HSQLDB in-memory database

I don't know why is it working fine at yours machines, but I had to spend a day in order to get it is working.

The server works with Intellij Idea U via url "jdbc:h2:tcp://localhost:9092/~/default".

"localhost:8082" in the browser alse works fine.

I added this into the mvc-dispatcher-servlet.xml

<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close" depends-on="h2Server">
    <property name="driverClassName" value="org.h2.Driver"/>
    <property name="url" value="jdbc:h2:tcp://localhost:9092/~/default"/>
    <property name="username" value="sa"/>
    <property name="password" value=""/>
</bean>

<bean id="h2Server" class="org.h2.tools.Server" factory-method="createTcpServer" init-method="start" destroy-method="stop" depends-on="h2WebServer">
    <constructor-arg>
        <array>
            <value>-tcp</value>
            <value>-tcpAllowOthers</value>
            <value>-tcpPort</value>
            <value>9092</value>
        </array>
    </constructor-arg>
</bean>

<bean id="h2WebServer" class="org.h2.tools.Server" factory-method="createWebServer" init-method="start" destroy-method="stop">
    <constructor-arg>
        <array>
            <value>-web</value>
            <value>-webAllowOthers</value>
            <value>-webPort</value>
            <value>8082</value>
        </array>
    </constructor-arg>
</bean>

Get a list of checked checkboxes in a div using jQuery

Combination of two previous answers:

var selected = [];
$('#checkboxes input:checked').each(function() {
    selected.push($(this).attr('name'));
});

Binary Data Posting with curl

You don't need --header "Content-Length: $LENGTH".

curl --request POST --data-binary "@template_entry.xml" $URL

Note that GET request does not support content body widely.

Also remember that POST request have 2 different coding schema. This is first form:

  $ nc -l -p 6666 &
  $ curl  --request POST --data-binary "@README" http://localhost:6666

POST / HTTP/1.1
User-Agent: curl/7.21.0 (x86_64-pc-linux-gnu) libcurl/7.21.0 OpenSSL/0.9.8o zlib/1.2.3.4 libidn/1.15 libssh2/1.2.6
Host: localhost:6666
Accept: */*
Content-Length: 9309
Content-Type: application/x-www-form-urlencoded
Expect: 100-continue

.. -*- mode: rst; coding: cp1251; fill-column: 80 -*-
.. rst2html.py README README.html
.. contents::

You probably request this:

-F/--form name=content
           (HTTP) This lets curl emulate a filled-in form in
              which a user has pressed the submit button. This
              causes curl to POST data using the Content- Type
              multipart/form-data according to RFC2388. This
              enables uploading of binary files etc. To force the
              'content' part to be a file, prefix the file name
              with an @ sign. To just get the content part from a
              file, prefix the file name with the symbol <. The
              difference between @ and < is then that @ makes a
              file get attached in the post as a file upload,
              while the < makes a text field and just get the
              contents for that text field from a file.

How do I use vim registers?

I think the secret guru register is the expression = register. It can be used for creative mappings.

:inoremap  \d The current date <c-r>=system("date")<cr>

You can use it in conjunction with your system as above or get responses from custom VimL functions etc.

or just ad hoc stuff like

<c-r>=35+7<cr>

X-UA-Compatible is set to IE=edge, but it still doesn't stop Compatibility Mode

As NEOSWF points out above, the Paul Irish conditional comments stops the meta tag having any affect.

There are several fixes all here (http://nicolasgallagher.com/better-conditional-classnames-for-hack-free-css/)

These include:

Adding two HTML classes, using server headers and adding a conditional comment above the doctype.

On my latest project I decided to remove the Paul Irish conditional comments. I didn't like the idea of adding anything before the html without doing LOTS of testing first and it's nice to see what has been set just by looking at the HTML.

In the end I surrounded a div straight after the body and used conditional comments eg

  <!--[if IE 7]><div class="ie7"><!--<![endif]-->
  ... regular body stuff
  <!--[if IE 7]></div><!--<![endif]-->

I could have done this around the body but its more difficult with CMSs like Wordpress.

Obviously its another DIV inside the markup, but its only for older browsers.

I think it could be a per project based decision though.

I've also read something about the charset meta tag needing to come in the first 1024 bytes so this ensures that.

Sometimes the simplest, easiest to read ideas are the best and its definitely worth thinking about! Thanks to the 6th comment on the link above for pointing this out.

Storing Data in MySQL as JSON

I believe that storing JSON in a mysql database does in fact defeat the purpose of using RDBMS as it is intended to be used. I would not use it in any data that would be manipulated at some point or reported on, since it not only adds complexity but also could easily impact performance depending on how it is used.

However, I was curious if anyone else thought of a possible reason to actually do this. I was thinking to make an exception for logging purposes. In my case, I want to log requests that have a variable amount of parameters and errors. In this situation, I want to use tables for the type of requests, and the requests themselves with a JSON string of different values that were obtained.

In the above situation, the requests are logged and never manipulated or indexed within the JSON string field. HOWEVER, in a more complex environment, I would probably try to use something that has more of an intention for this type of data and store it with that system. As others have said, it really depends on what you are trying to accomplish, but following standards always helps longevity and reliability!

Jenkins - how to build a specific branch

enter image description here

There will be an option in configure under Build Triggers

Check the GitHub Branches

A hook will be created and then you can build any branch you like from Jenkins when you select github Branches enter image description here

Hope it helps :)

What is the default root pasword for MySQL 5.7

As of Ubuntu 20.04 with MySql 8.0 : you can set the password that way:

  1. login to mysql with sudo mysql -u root

  2. change the password:

USE mysql;
UPDATE user set authentication_string=NULL where User='root';
FLUSH privileges;
ALTER USER 'root'@'localhost' IDENTIFIED WITH caching_sha2_password BY 'My-N7w_And.5ecure-P@s5w0rd';
FLUSH privileges;
QUIT

now you should be able to login with mysql -u root -p (or to phpMyAdmin with username root) and your chosen password.

P,S:

You can also login with user debian-sys-maint, the password is written in the file /etc/mysql/debian.cnf

List all employee's names and their managers by manager name using an inner join

Your query is close you need to join using the mgr and the empid

on e1.mgr = e2.empid

So the full query is:

select e1.ename Emp,
  e2.eName Mgr
from employees e1
inner join employees e2
  on e1.mgr = e2.empid

See SQL Fiddle with Demo

If you want to return all rows including those without a manager then you would change it to a LEFT JOIN (for example the president):

select e1.ename Emp,
  e2.eName Mgr
from employees e1
left join employees e2
  on e1.mgr = e2.empid

See SQL Fiddle with Demo

The president in your sample data will return a null value for the manager because they do not have a manager.

How do I get the application exit code from a Windows command line?

At one point I needed to accurately push log events from Cygwin to the Windows Event log. I wanted the messages in WEVL to be custom, have the correct exit code, details, priorities, message, etc. So I created a little Bash script to take care of this. Here it is on GitHub, logit.sh.

Some excerpts:

usage: logit.sh [-h] [-p] [-i=n] [-s] <description>
example: logit.sh -p error -i 501 -s myscript.sh "failed to run the mount command"

Here is the temporary file contents part:

LGT_TEMP_FILE="$(mktemp --suffix .cmd)"
cat<<EOF>$LGT_TEMP_FILE
    @echo off
    set LGT_EXITCODE="$LGT_ID"
    exit /b %LGT_ID%
EOF
unix2dos "$LGT_TEMP_FILE"

Here is a function to to create events in WEVL:

__create_event () {
    local cmd="eventcreate /ID $LGT_ID /L Application /SO $LGT_SOURCE /T $LGT_PRIORITY /D "
    if [[ "$1" == *';'* ]]; then
        local IFS=';'
        for i in "$1"; do
            $cmd "$i" &>/dev/null
        done
    else
        $cmd "$LGT_DESC" &>/dev/null
    fi
}

Executing the batch script and calling on __create_event:

cmd /c "$(cygpath -wa "$LGT_TEMP_FILE")"
__create_event

How to get difference between two dates in Year/Month/Week/Day?

DateTime startTime = DateTime.Now;

DateTime endTime = DateTime.Now.AddSeconds( 75 );

TimeSpan span = endTime.Subtract ( startTime );
 Console.WriteLine( "Time Difference (seconds): " + span.Seconds );
 Console.WriteLine( "Time Difference (minutes): " + span.Minutes );
 Console.WriteLine( "Time Difference (hours): " + span.Hours );
 Console.WriteLine( "Time Difference (days): " + span.Days );

Output:

Time Difference (seconds): 15
Time Difference (minutes): 1
Time Difference (hours): 0
Time Difference (days): 0

Using git commit -a with vim

Try ZZ to save and close. Here is a bit more info on using vim with Git

How to display Oracle schema size with SQL query?

SELECT table_name as Table_Name, row_cnt as Row_Count, SUM(mb) as Size_MB
FROM
  (SELECT in_tbl.table_name,   to_number(extractvalue(xmltype(dbms_xmlgen.getxml('select count(*) c from ' ||ut.table_name)),'/ROWSET/ROW/C')) AS row_cnt , mb
FROM
(SELECT CASE WHEN lob_tables IS NULL THEN table_name WHEN lob_tables IS NOT NULL THEN lob_tables END AS table_name , mb
FROM (SELECT ul.table_name AS lob_tables, us.segment_name AS table_name , us.bytes/1024/1024 MB FROM user_segments us
LEFT JOIN user_lobs ul ON us.segment_name = ul.segment_name ) ) in_tbl INNER JOIN user_tables ut ON in_tbl.table_name = ut.table_name ) GROUP BY table_name, row_cnt ORDER BY 3 DESC;``

Above query will give, Table_name, Row_count, Size_in_MB(includes lob column size) of specific user.

Using onBlur with JSX and React

There are a few problems here.

1: onBlur expects a callback, and you are calling renderPasswordConfirmError and using the return value, which is null.

2: you need a place to render the error.

3: you need a flag to track "and I validating", which you would set to true on blur. You can set this to false on focus if you want, depending on your desired behavior.

handleBlur: function () {
  this.setState({validating: true});
},
render: function () {
  return <div>
    ...
    <input
        type="password"
        placeholder="Password (confirm)"
        valueLink={this.linkState('password2')}
        onBlur={this.handleBlur}
     />
    ...
    {this.renderPasswordConfirmError()}
  </div>
},
renderPasswordConfirmError: function() {
  if (this.state.validating && this.state.password !== this.state.password2) {
    return (
      <div>
        <label className="error">Please enter the same password again.</label>
      </div>
    );
  }  
  return null;
},

VB.net Need Text Box to Only Accept Numbers

You must first validate if the input is actually an integer. You can do it with Integer.TryParse:

Dim intValue As Integer
If Integer.TryParse(TxtBox.Text, intValue) AndAlso intValue > 0 AndAlso intValue < 11 Then
    MessageBox.Show("Thank You, your rating was " & TxtBox.Text)
Else
    MessageBox.Show("Please Enter a Number from 1 to 10")
End If

Change the color of glyphicons to blue in some- but not at all places using Bootstrap 2

The icon will adopt the color from value of the color css property of it's parent.

You can either add this directly to the style:

<span class="glyphicon glyphicon-user" style="color:blue"></span>

Or you can add it as a class to your icon and then set the font color to it in CSS

HTML

<span class="glyphicon glyphicon-search"></span>
<span class="glyphicon glyphicon-user blue"></span>
<span class="glyphicon glyphicon-trash"></span>

CSS

.blue {
    color: blue;
}

This fiddle has an example.

Group query results by month and year in postgresql

I can't believe the accepted answer has so many upvotes -- it's a horrible method.

Here's the correct way to do it, with date_trunc:

   SELECT date_trunc('month', txn_date) AS txn_month, sum(amount) as monthly_sum
     FROM yourtable
 GROUP BY txn_month

It's bad practice but you might be forgiven if you use

 GROUP BY 1

in a very simple query.

You can also use

 GROUP BY date_trunc('month', txn_date)

if you don't want to select the date.

Reusing a PreparedStatement multiple times

The second way is a tad more efficient, but a much better way is to execute them in batches:

public void executeBatch(List<Entity> entities) throws SQLException { 
    try (
        Connection connection = dataSource.getConnection();
        PreparedStatement statement = connection.prepareStatement(SQL);
    ) {
        for (Entity entity : entities) {
            statement.setObject(1, entity.getSomeProperty());
            // ...

            statement.addBatch();
        }

        statement.executeBatch();
    }
}

You're however dependent on the JDBC driver implementation how many batches you could execute at once. You may for example want to execute them every 1000 batches:

public void executeBatch(List<Entity> entities) throws SQLException { 
    try (
        Connection connection = dataSource.getConnection();
        PreparedStatement statement = connection.prepareStatement(SQL);
    ) {
        int i = 0;

        for (Entity entity : entities) {
            statement.setObject(1, entity.getSomeProperty());
            // ...

            statement.addBatch();
            i++;

            if (i % 1000 == 0 || i == entities.size()) {
                statement.executeBatch(); // Execute every 1000 items.
            }
        }
    }
}

As to the multithreaded environments, you don't need to worry about this if you acquire and close the connection and the statement in the shortest possible scope inside the same method block according the normal JDBC idiom using try-with-resources statement as shown in above snippets.

If those batches are transactional, then you'd like to turn off autocommit of the connection and only commit the transaction when all batches are finished. Otherwise it may result in a dirty database when the first bunch of batches succeeded and the later not.

public void executeBatch(List<Entity> entities) throws SQLException { 
    try (Connection connection = dataSource.getConnection()) {
        connection.setAutoCommit(false);

        try (PreparedStatement statement = connection.prepareStatement(SQL)) {
            // ...

            try {
                connection.commit();
            } catch (SQLException e) {
                connection.rollback();
                throw e;
            }
        }
    }
}

MySQL create stored procedure syntax with delimiter

MY SQL STORED PROCEDURE CREATION

DELIMiTER $$
create procedure GetUserRolesEnabled(in UserId int)
Begin

select * from users
where id=UserId ;
END $$
DELIMITER ;

jQuery using append with effects

It is possible to show smooth if you use Animation. In style just add "animation: show 1s" and the whole appearance discribe in keyframes.

How to manually trigger validation with jQuery validate?

i tried it worked tnx @Anastasiosyal i want to share it on this thread.

I'm not positive how the input fields did not trigger when I emptied the fields. But I managed to trigger each required field individually using:

$(".setting-p input").bind("change", function () {
        //Seven.NetOps.validateSettings(Seven.NetOps.saveSettings);
        /*$.validator.unobtrusive.parse($('#saveForm'));*/
        $('#NodeZoomLevel').valid();
        $('#ZoomLevel').valid();
        $('#CenterLatitude').valid();
        $('#CenterLongitude').valid();
        $('#NodeIconSize').valid();
        $('#SaveDashboard').valid();
        $('#AutoRefresh').valid();
    });

here's my view

@using (Html.BeginForm("SaveSettings", "Settings", FormMethod.Post, new {id = "saveForm"}))
{
    <div id="sevenRightBody">
        <div id="mapMenuitemPanel" class="setingsPanelStyle" style="display: block;">
            <div class="defaultpanelTitleStyle">Map Settings</div>
            Customize the map view upon initial navigation to the map view page.
            <p class="setting-p">@Html.LabelFor(x => x.NodeZoomLevel)</p>
            <p class="setting-p">@Html.EditorFor(x => x.NodeZoomLevel) @Html.ValidationMessageFor(x => x.NodeZoomLevel)</p>
            <p class="setting-p">@Html.LabelFor(x => x.ZoomLevel)</p>
            <p class="setting-p">@Html.EditorFor(x => x.ZoomLevel) @Html.ValidationMessageFor(x => x.ZoomLevel)</p>
            <p class="setting-p">@Html.LabelFor(x => x.CenterLatitude)</p>
            <p class="setting-p">@Html.EditorFor(x => x.CenterLatitude) @Html.ValidationMessageFor(x => x.CenterLatitude)</p>
            <p class="setting-p">@Html.LabelFor(x => x.CenterLongitude)</p>
            <p class="setting-p">@Html.EditorFor(x => x.CenterLongitude) @Html.ValidationMessageFor(x => x.CenterLongitude)</p>
            <p class="setting-p">@Html.LabelFor(x => x.NodeIconSize)</p>
            <p class="setting-p">@Html.SliderSelectFor(x => x.NodeIconSize) @Html.ValidationMessageFor(x => x.NodeIconSize)</p>
        </div>

and my Entity

   public class UserSetting : IEquatable<UserSetting>
    {
        [Required(ErrorMessage = "Missing Node Zoom Level.")]
        [Range(200, 10000000, ErrorMessage = "Node Zoom Level must be between {1} and {2}.")]
        [DefaultValue(100000)]
        [Display(Name = "Node Zoom Level")]
        public double NodeZoomLevel { get; set; }

        [Required(ErrorMessage = "Missing Zoom Level.")]
        [Range(200, 10000000, ErrorMessage = "Zoom Level must be between {1} and {2}.")]
        [DefaultValue(1000000)]
        [Display(Name = "Zoom Level")]
        public double ZoomLevel { get; set; }

        [Range(-90, 90, ErrorMessage = "Latitude degrees must be between {1} and {2}.")]
        [Required(ErrorMessage = "Missing Latitude.")]
        [DefaultValue(-200)]
        [Display(Name = "Latitude")]
        public double CenterLatitude { get; set; }

        [Range(-180, 180, ErrorMessage = "Longitude degrees must be between {1} and {2}.")]
        [Required(ErrorMessage = "Missing Longitude.")]
        [DefaultValue(-200)]
        [Display(Name = "Longitude")]
        public double CenterLongitude { get; set; }

        [Display(Name = "Save Dashboard")]
        public bool SaveDashboard { get; set; }
.....
}

Checkout Jenkins Pipeline Git SCM with credentials?

You can use the following in a pipeline:

git branch: 'master',
    credentialsId: '12345-1234-4696-af25-123455',
    url: 'ssh://[email protected]:company/repo.git'

If you're using the ssh url then your credentials must be username + private key. If you're using the https clone url instead of the ssh one, then your credentials should be username + password.

Declaration of Methods should be Compatible with Parent Methods in PHP

childClass::customMethod() has different arguments, or a different access level (public/private/protected) than parentClass::customMethod().

How to specify a editor to open crontab file? "export EDITOR=vi" does not work

You can use below command to open it in VIM editor.

export VISUAL=vim; crontab -e

Note: Please make sure VIM editor is installed on your server.

Downloading a large file using curl

when curl is used to download a large file then CURLOPT_TIMEOUT is the main option you have to set for.

CURLOPT_RETURNTRANSFER has to be true in case you are getting file like pdf/csv/image etc.

You may find the further detail over here(correct url) Curl Doc

From that page:

curl_setopt($request, CURLOPT_TIMEOUT, 300); //set timeout to 5 mins

curl_setopt($request, CURLOPT_RETURNTRANSFER, true); // true to get the output as string otherwise false

How to permanently remove few commits from remote branch

 git reset --soft commit_id
 git stash save "message"
 git reset --hard commit_id
 git stash apply stash stash@{0}
 git push --force

How do I split a string in Rust?

split returns an Iterator, which you can convert into a Vec using collect: split_line.collect::<Vec<_>>(). Going through an iterator instead of returning a Vec directly has several advantages:

  • split is lazy. This means that it won't really split the line until you need it. That way it won't waste time splitting the whole string if you only need the first few values: split_line.take(2).collect::<Vec<_>>(), or even if you need only the first value that can be converted to an integer: split_line.filter_map(|x| x.parse::<i32>().ok()).next(). This last example won't waste time attempting to process the "23.0" but will stop processing immediately once it finds the "1".
  • split makes no assumption on the way you want to store the result. You can use a Vec, but you can also use anything that implements FromIterator<&str>, for example a LinkedList or a VecDeque, or any custom type that implements FromIterator<&str>.

How to choose the right bean scope?

Since JSF 2.3 all the bean scopes defined in package javax.faces.bean package have been deprecated to align the scopes with CDI. Moreover they're only applicable if your bean is using @ManagedBean annotation. If you are using JSF versions below 2.3 refer to the legacy answer at the end.


From JSF 2.3 here are scopes that can be used on JSF Backing Beans:

1. @javax.enterprise.context.ApplicationScoped: The application scope persists for the entire duration of the web application. That scope is shared among all requests and all sessions. This is useful when you have data for whole application.

2. @javax.enterprise.context.SessionScoped: The session scope persists from the time that a session is established until session termination. The session context is shared between all requests that occur in the same HTTP session. This is useful when you wont to save data for a specific client for a particular session.

3. @javax.enterprise.context.ConversationScoped: The conversation scope persists as log as the bean lives. The scope provides 2 methods: Conversation.begin() and Conversation.end(). These methods should called explicitly, either to start or end the life of a bean.

4. @javax.enterprise.context.RequestScoped: The request scope is short-lived. It starts when an HTTP request is submitted and ends after the response is sent back to the client. If you place a managed bean into request scope, a new instance is created with each request. It is worth considering request scope if you are concerned about the cost of session scope storage.

5. @javax.faces.flow.FlowScoped: The Flow scope persists as long as the Flow lives. A flow may be defined as a contained set of pages (or views) that define a unit of work. Flow scoped been is active as long as user navigates with in the Flow.

6. @javax.faces.view.ViewScoped: A bean in view scope persists while the same JSF page is redisplayed. As soon as the user navigates to a different page, the bean goes out of scope.


The following legacy answer applies JSF version before 2.3

As of JSF 2.x there are 4 Bean Scopes:

  • @SessionScoped
  • @RequestScoped
  • @ApplicationScoped
  • @ViewScoped

Session Scope: The session scope persists from the time that a session is established until session termination. A session terminates if the web application invokes the invalidate method on the HttpSession object, or if it times out.

RequestScope: The request scope is short-lived. It starts when an HTTP request is submitted and ends after the response is sent back to the client. If you place a managed bean into request scope, a new instance is created with each request. It is worth considering request scope if you are concerned about the cost of session scope storage.

ApplicationScope: The application scope persists for the entire duration of the web application. That scope is shared among all requests and all sessions. You place managed beans into the application scope if a single bean should be shared among all instances of a web application. The bean is constructed when it is first requested by any user of the application, and it stays alive until the web application is removed from the application server.

ViewScope: View scope was added in JSF 2.0. A bean in view scope persists while the same JSF page is redisplayed. (The JSF specification uses the term view for a JSF page.) As soon as the user navigates to a different page, the bean goes out of scope.

Choose the scope you based on your requirement.

Source: Core Java Server Faces 3rd Edition by David Geary & Cay Horstmann [Page no. 51 - 54] enter image description here

Align text in JLabel to the right

This can be done in two ways.

JLabel Horizontal Alignment

You can use the JLabel constructor:

JLabel(String text, int horizontalAlignment) 

To align to the right:

JLabel label = new JLabel("Telephone", SwingConstants.RIGHT);

JLabel also has setHorizontalAlignment:

label.setHorizontalAlignment(SwingConstants.RIGHT);

This assumes the component takes up the whole width in the container.

Using Layout

A different approach is to use the layout to actually align the component to the right, whilst ensuring they do not take the whole width. Here is an example with BoxLayout:

    Box box = Box.createVerticalBox();
    JLabel label1 = new JLabel("test1, the beginning");
    label1.setAlignmentX(Component.RIGHT_ALIGNMENT);
    box.add(label1);

    JLabel label2 = new JLabel("test2, some more");
    label2.setAlignmentX(Component.RIGHT_ALIGNMENT);
    box.add(label2);

    JLabel label3 = new JLabel("test3");
    label3.setAlignmentX(Component.RIGHT_ALIGNMENT);
    box.add(label3);


    add(box);

In Python, what happens when you import inside of a function?

Might I suggest in general that instead of asking, "Will X improve my performance?" you use profiling to determine where your program is actually spending its time and then apply optimizations according to where you'll get the most benefit?

And then you can use profiling to assure that your optimizations have actually benefited you, too.

Understanding `scale` in R

I thought I would contribute by providing a concrete example of the practical use of the scale function. Say you have 3 test scores (Math, Science, and English) that you want to compare. Maybe you may even want to generate a composite score based on each of the 3 tests for each observation. Your data could look as as thus:

student_id <- seq(1,10)
math <- c(502,600,412,358,495,512,410,625,573,522)
science <- c(95,99,80,82,75,85,80,95,89,86)
english <- c(25,22,18,15,20,28,15,30,27,18)
df <- data.frame(student_id,math,science,english)

Obviously it would not make sense to compare the means of these 3 scores as the scale of the scores are vastly different. By scaling them however, you have more comparable scoring units:

z <- scale(df[,2:4],center=TRUE,scale=TRUE)

You could then use these scaled results to create a composite score. For instance, average the values and assign a grade based on the percentiles of this average. Hope this helped!

Note: I borrowed this example from the book "R In Action". It's a great book! Would definitely recommend.

How to refresh app upon shaking the device?

I have written a small example for detecting vertical and horizontal shakes and showing a Toast.

public class Accelerometerka2Activity extends Activity implements SensorEventListener { 
    private float mLastX, mLastY, mLastZ;
    private boolean mInitialized;
    private SensorManager mSensorManager;
    private Sensor mAccelerometer;
    private final float NOISE = (float) 8.0;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        mInitialized = false;
        mSensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
        mAccelerometer = mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
        mSensorManager.registerListener(this, mAccelerometer , SensorManager.SENSOR_DELAY_NORMAL);
    }

    protected void onResume() {
        super.onResume();
        mSensorManager.registerListener(this, mAccelerometer, SensorManager.SENSOR_DELAY_NORMAL);
    }

    protected void onPause() {
        super.onPause();
        mSensorManager.unregisterListener(this);
    }


    public void onAccuracyChanged(Sensor sensor, int accuracy) {
        // can be safely ignored for this demo
    }


    public void onSensorChanged(SensorEvent event) {
        float x = event.values[0];
        float y = event.values[1];
        float z = event.values[2];
        if (!mInitialized) {
            mLastX = x;
            mLastY = y;
            mLastZ = z;
            mInitialized = true;
        } else {
            float deltaX = Math.abs(mLastX - x);
            float deltaY = Math.abs(mLastY - y);
            float deltaZ = Math.abs(mLastZ - z);
            if (deltaX < NOISE) deltaX = (float)0.0;
            if (deltaY < NOISE) deltaY = (float)0.0;
            if (deltaZ < NOISE) deltaZ = (float)0.0;
            mLastX = x;
            mLastY = y;
            mLastZ = z;
            if (deltaX > deltaY) {
                Toast.makeText(getBaseContext(), "Horizental", Toast.LENGTH_SHORT).show();
            } else if (deltaY > deltaX) {
                Toast.makeText(getBaseContext(), "Vertical", Toast.LENGTH_SHORT).show();
            }
        }
    }
}

Linux command to check if a shell script is running or not

I was quite inspired by the last answer by mklement0 - I have few scripts/small programs I run at every reboot via /etc/crontab. I built on his answer and built a login script, which shows if my programs are still running. I execute this scripts.sh via .profile -file on every login, to get instant notification on each login.

cat scripts.sh 
#!/bin/bash

getscript() {
  pgrep -lf ".[ /]$1( |\$)"
}

script1=keepalive.sh
script2=logger_v3.py

# test if script 1 is running
if getscript "$script1" >/dev/null; then
  echo "$script1" is RUNNING
  else
    echo "$script1" is NOT running
fi

# test if script 2 is running:
if getscript "$script2" >/dev/null; then
  echo "$script2" is RUNNING
  else
    echo "$script2" is NOT running
fi

Can (a== 1 && a ==2 && a==3) ever evaluate to true?

I couldn't resist - the other answers are undoubtedly true, but you really can't walk past the following code:

_x000D_
_x000D_
var a? = 1;_x000D_
var a = 2;_x000D_
var ?a = 3;_x000D_
if(a?==1 && a== 2 &&?a==3) {_x000D_
    console.log("Why hello there!")_x000D_
}
_x000D_
_x000D_
_x000D_

Note the weird spacing in the if statement (that I copied from your question). It is the half-width Hangul (that's Korean for those not familiar) which is an Unicode space character that is not interpreted by ECMA script as a space character - this means that it is a valid character for an identifier. Therefore there are three completely different variables, one with the Hangul after the a, one with it before and the last one with just a. Replacing the space with _ for readability, the same code would look like this:

_x000D_
_x000D_
var a_ = 1;_x000D_
var a = 2;_x000D_
var _a = 3;_x000D_
if(a_==1 && a== 2 &&_a==3) {_x000D_
    console.log("Why hello there!")_x000D_
}
_x000D_
_x000D_
_x000D_

Check out the validation on Mathias' variable name validator. If that weird spacing was actually included in their question, I feel sure that it's a hint for this kind of answer.

Don't do this. Seriously.

Edit: It has come to my attention that (although not allowed to start a variable) the Zero-width joiner and Zero-width non-joiner characters are also permitted in variable names - see Obfuscating JavaScript with zero-width characters - pros and cons?.

This would look like the following:

_x000D_
_x000D_
var a= 1;_x000D_
var a?= 2; //one zero-width character_x000D_
var a??= 3; //two zero-width characters (or you can use the other one)_x000D_
if(a==1&&a?==2&&a??==3) {_x000D_
    console.log("Why hello there!")_x000D_
}
_x000D_
_x000D_
_x000D_

Efficiently updating database using SQLAlchemy ORM

If it is because of the overhead in terms of creating objects, then it probably can't be sped up at all with SA.

If it is because it is loading up related objects, then you might be able to do something with lazy loading. Are there lots of objects being created due to references? (IE, getting a Company object also gets all of the related People objects).

How can I open a popup window with a fixed size using the HREF tag?

Since many browsers block popups by default and popups are really ugly, I recommend using lightbox or thickbox.

They are prettier and are not popups. They are extra HTML markups that are appended to your document's body with the appropriate CSS content.

http://jquery.com/demo/thickbox/

difference between System.out.println() and System.err.println()

Those commands use different output streams. By default both messages will be printed on console but it's possible for example to redirect one or both of these to a file.

java MyApp 2>errors.txt

This will redirect System.err to errors.txt file.

Is it possible to simulate key press events programmatically?

The critical part of getting this to work is to realize that charCode, keyCode and which are all deprecated methods. Therefore if the code processing the key press event uses any of these three, then it'll receive a bogus answer (e.g. a default of 0).

As long as you access the key press event with a non-deprecated method, such as key, you should be OK.

For completion, I've added the basic Javascript code for triggering the event:

_x000D_
_x000D_
const rightArrowKey = 39
const event = new KeyboardEvent('keydown',{'key':rightArrowKey})
document.dispatchEvent(event)
_x000D_
_x000D_
_x000D_

Why binary_crossentropy and categorical_crossentropy give different performances for the same problem?

It all depends on the type of classification problem you are dealing with. There are three main categories

  • binary classification (two target classes),
  • multi-class classification (more than two exclusive targets),
  • multi-label classification (more than two non exclusive targets), in which multiple target classes can be on at the same time.

In the first case, binary cross-entropy should be used and targets should be encoded as one-hot vectors.

In the second case, categorical cross-entropy should be used and targets should be encoded as one-hot vectors.

In the last case, binary cross-entropy should be used and targets should be encoded as one-hot vectors. Each output neuron (or unit) is considered as a separate random binary variable, and the loss for the entire vector of outputs is the product of the loss of single binary variables. Therefore it is the product of binary cross-entropy for each single output unit.

The binary cross-entropy is defined as

enter image description here

and categorical cross-entropy is defined as

enter image description here

where c is the index running over the number of classes C.

Selecting last element in JavaScript array

This worked:

array.reverse()[0]

HTTP Ajax Request via HTTPS Page

This is not possible due to the Same Origin Policy.

You will need to switch the Ajax requests to https, too.

SQL Server "AFTER INSERT" trigger doesn't see the just-inserted row

You can reverse the logic. Instead of deleting an invalid row after it has been inserted, write an INSTEAD OF trigger to insert only if you verify the row is valid.

CREATE TRIGGER mytrigger ON sometable
INSTEAD OF INSERT
AS BEGIN
  DECLARE @isnum TINYINT;

  SELECT @isnum = ISNUMERIC(somefield) FROM inserted;

  IF (@isnum = 1)
    INSERT INTO sometable SELECT * FROM inserted;
  ELSE
    RAISERROR('somefield must be numeric', 16, 1)
      WITH SETERROR;
END

If your application doesn't want to handle errors (as Joel says is the case in his app), then don't RAISERROR. Just make the trigger silently not do an insert that isn't valid.

I ran this on SQL Server Express 2005 and it works. Note that INSTEAD OF triggers do not cause recursion if you insert into the same table for which the trigger is defined.

Network tools that simulate slow network connection

For Linux or OSX, you can use ipfw.

From Quora (http://www.quora.com/What-is-the-best-tool-to-simulate-a-slow-internet-connection-on-a-Mac)

Essentially using a firewall to throttle all network data:

Define a rule that uses a pipe to reroute all traffic from any source address to any destination address, execute the following command (as root, or using sudo):

$ ipfw add pipe 1 all from any to any

To configure this rule to limit bandwidth to 300Kbit/s and impose 200ms of latency each way:

$ ipfw pipe 1 config bw 300Kbit/s delay 200ms

To remove all rules and recover your original network connection:

$ ipfw flush

Is there a way to cast float as a decimal without rounding and preserving its precision?

Try SELECT CAST(field1 AS DECIMAL(10,2)) field1 and replace 10,2 with whatever precision you need.

What does java:comp/env/ do?

After several attempts and going deep in Tomcat's source code I found out that the simple property useNaming="false" did the trick!! Now Tomcat resolves names java:/liferay instead of java:comp/env/liferay

How to define custom configuration variables in rails

In Rails 3.0.5, the following approach worked for me:

In config/environments/development.rb, write

config.custom_config_key = :config_value

The value custom_config_key can then be referenced from other files using

Rails.application.config.custom_config_key

Android Drawing Separator/Divider Line in Layout?

Easiest Way:

Vertical divider :

<View style="@style/Divider.Vertical"/>

Vertical divider view

Horizontal divider :

<View style="@style/Divider.Horizontal"/>

Horizontal divider view

That's all yes!

Just put this in res>values>styles.xml

<style name="Divider">
    <item name="android:background">?android:attr/listDivider</item> //you can give your color here. that will change all divider color in your app.
</style>

<style name="Divider.Horizontal" parent="Divider">
    <item name="android:layout_width">match_parent</item>
    <item name="android:layout_height">1dp</item> // You can change thickness here.

</style>

<style name="Divider.Vertical" parent="Divider">
    <item name="android:layout_width">1dp</item>
    <item name="android:layout_height">match_parent</item>
</style>

Table cell widths - fixing width, wrapping/truncating long words

As long as you fix the width of the table itself and set the table-layout property, this is pretty simple :

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <style type="text/css">
        td { width: 30px; overflow: hidden; }
        table { width : 90px; table-layout: fixed; }
    </style>
</head>
<body>

    <table border="2">
        <tr>
            <td>word</td>
            <td>two words</td>
            <td>onereallylongword</td>

        </tr>
    </table>
</body>
</html>

I've tested this in IE6 and 7 and it seems to work fine.

Difference between Python's Generators and Iterators

It's difficult to answer the question without 2 other concepts: iterable and iterator protocol.

  1. What is difference between iterator and iterable? Conceptually you iterate over iterable with the help of corresponding iterator. There are a few differences that can help to distinguish iterator and iterable in practice:
    • One difference is that iterator has __next__ method, iterable does not.
    • Another difference - both of them contain __iter__ method. In case of iterable it returns the corresponding iterator. In case of iterator it returns itself. This can help to distinguish iterator and iterable in practice.
>>> x = [1, 2, 3]
>>> dir(x) 
[... __iter__ ...]
>>> x_iter = iter(x)
>>> dir(x_iter)
[... __iter__ ... __next__ ...]
>>> type(x_iter)
list_iterator
  1. What are iterables in python? list, string, range etc. What are iterators? enumerate, zip, reversed etc. We may check this using the approach above. It's kind of confusing. Probably it would be easier if we have only one type. Is there any difference between range and zip? One of the reasons to do this - range has a lot of additional functionality - we may index it or check if it contains some number etc. (see details here).

  2. How can we create an iterator ourselves? Theoretically we may implement Iterator Protocol (see here). We need to write __next__ and __iter__ methods and raise StopIteration exception and so on (see Alex Martelli's answer for an example and possible motivation, see also here). But in practice we use generators. It seems to be by far the main method to create iterators in python.

I can give you a few more interesting examples that show somewhat confusing usage of those concepts in practice:

  • in keras we have tf.keras.preprocessing.image.ImageDataGenerator; this class doesn't have __next__ and __iter__ methods; so it's not an iterator (or generator);
  • if you call its flow_from_dataframe() method you'll get DataFrameIterator that has those methods; but it doesn't implement StopIteration (which is not common in build-in iterators in python); in documentation we may read that "A DataFrameIterator yielding tuples of (x, y)" - again confusing usage of terminology;
  • we also have Sequence class in keras and that's custom implementation of a generator functionality (regular generators are not suitable for multithreading) but it doesn't implement __next__ and __iter__, rather it's a wrapper around generators (it uses yield statement);

How to remove all white space from the beginning or end of a string?

String.Trim() removes all whitespace from the beginning and end of a string. To remove whitespace inside a string, or normalize whitespace, use a Regular Expression.

shell script to remove a file if it already exist

You can use this:

#!/bin/bash

file="file_you_want_to_delete"

if [ -f "$file" ] ; then
    rm "$file"
fi

Printing all variables value from a class

From Implementing toString:

public String toString() {
  StringBuilder result = new StringBuilder();
  String newLine = System.getProperty("line.separator");

  result.append( this.getClass().getName() );
  result.append( " Object {" );
  result.append(newLine);

  //determine fields declared in this class only (no fields of superclass)
  Field[] fields = this.getClass().getDeclaredFields();

  //print field names paired with their values
  for ( Field field : fields  ) {
    result.append("  ");
    try {
      result.append( field.getName() );
      result.append(": ");
      //requires access to private field:
      result.append( field.get(this) );
    } catch ( IllegalAccessException ex ) {
      System.out.println(ex);
    }
    result.append(newLine);
  }
  result.append("}");

  return result.toString();
}

Getting current date and time in JavaScript

.getMonth() returns a zero-based number so to get the correct month you need to add 1, so calling .getMonth() in may will return 4 and not 5.

So in your code we can use currentdate.getMonth()+1 to output the correct value. In addition:

  • .getDate() returns the day of the month <- this is the one you want
  • .getDay() is a separate method of the Date object which will return an integer representing the current day of the week (0-6) 0 == Sunday etc

so your code should look like this:

var currentdate = new Date(); 
var datetime = "Last Sync: " + currentdate.getDate() + "/"
                + (currentdate.getMonth()+1)  + "/" 
                + currentdate.getFullYear() + " @ "  
                + currentdate.getHours() + ":"  
                + currentdate.getMinutes() + ":" 
                + currentdate.getSeconds();

JavaScript Date instances inherit from Date.prototype. You can modify the constructor's prototype object to affect properties and methods inherited by JavaScript Date instances

You can make use of the Date prototype object to create a new method which will return today's date and time. These new methods or properties will be inherited by all instances of the Date object thus making it especially useful if you need to re-use this functionality.

// For todays date;
Date.prototype.today = function () { 
    return ((this.getDate() < 10)?"0":"") + this.getDate() +"/"+(((this.getMonth()+1) < 10)?"0":"") + (this.getMonth()+1) +"/"+ this.getFullYear();
}

// For the time now
Date.prototype.timeNow = function () {
     return ((this.getHours() < 10)?"0":"") + this.getHours() +":"+ ((this.getMinutes() < 10)?"0":"") + this.getMinutes() +":"+ ((this.getSeconds() < 10)?"0":"") + this.getSeconds();
}

You can then simply retrieve the date and time by doing the following:

var newDate = new Date();
var datetime = "LastSync: " + newDate.today() + " @ " + newDate.timeNow();

Or call the method inline so it would simply be -

var datetime = "LastSync: " + new Date().today() + " @ " + new Date().timeNow();

Prevent onmouseout when hovering child element of the parent absolute div WITHOUT jQuery

Use onmouseleave.

Or, in jQuery, use mouseleave()

It is the exact thing you are looking for. Example:

<div class="outer" onmouseleave="yourFunction()">
    <div class="inner">
    </div>
</div>

or, in jQuery:

$(".outer").mouseleave(function(){
    //your code here
});

an example is here.

AttributeError("'str' object has no attribute 'read'")

You need to open the file first. This doesn't work:

json_file = json.load('test.json')

But this works:

f = open('test.json')
json_file = json.load(f)

How to change webservice url endpoint?

I wouldn't go so far as @Femi to change the existing address property. You can add new services to the definitions section easily.

<wsdl:service name="serviceMethodName_2">
  <wsdl:port binding="tns:serviceMethodNameSoapBinding" name="serviceMethodName">
    <soap:address location="http://new_end_point_adress"/>
  </wsdl:port>
</wsdl:service>

This doesn't require a recompile of the WSDL to Java and making updates isn't any more difficult than if you used the BindingProvider option (which didn't work for me btw).

using facebook sdk in Android studio

People using Android Studio 0.8.6 could do these:

  1. Download Facebook-android-sdk-xxx.zip & Unzip it
  2. Copy ONLY facebook dir under the Facebook-android-sdk-xxx dir into your project along with app/

    • ImAnApp/
      • |-- app/
      • |-- build/
      • |-- facebook/
  3. Now you should see Android Studio showing facebook as module

  4. Modify the build.gradle of facebook into this.
    • provided files('../libs/bolts.jar') to provided files('./libs/bolts.jar')
    • compileSdkVersion Integer.parseInt(project.ANDROID_BUILD_SDK_VERSION) to compileSdkVersion 20 or other version you defined in the app
    • buildToolsVersion project.ANDROID_BUILD_TOOLS_VERSION to buildToolsVersion '20.0.0'
    • minSdkVersion Integer.parseInt(project.ANDROID_BUILD_MIN_SDK_VERSION) to minSdkVersion 14
    • targetSdkVersion Integer.parseInt(project.ANDROID_BUILD_TARGET_SDK_VERSION) to targetSdkVersion 20

    apply plugin: 'android-library'

    dependencies {
        compile 'com.android.support:support-v4:19.1.+'
        provided files('./libs/bolts.jar')
    }

    android {
        compileSdkVersion 20
        buildToolsVersion '20.0.0'

        defaultConfig {
            minSdkVersion 14
            targetSdkVersion 20
        }

        lintOptions {
            abortOnError false
        }

        sourceSets {
            main {
                manifest.srcFile 'AndroidManifest.xml'
                java.srcDirs = ['src']
                res.srcDirs = ['res']
            }
        }
    }

Resync your gradle file & it should just work fine!

Date validation with ASP.NET validator

I believe that the dates have to be specified in the current culture of the application. You might want to experiment with setting CultureInvariantValues to true and see if that solves your problem. Otherwise you may need to change the DateTimeFormat for the current culture (or the culture itself) to get what you want.

Remove part of a string

Maybe the most intuitive solution is probably to use the stringr function str_remove which is even easier than str_replace as it has only 1 argument instead of 2.

The only tricky part in your example is that you want to keep the underscore but its possible: You must match the regular expression until it finds the specified string pattern (?=pattern).

See example:

strings = c("TGAS_1121", "MGAS_1432", "ATGAS_1121")
strings %>% stringr::str_remove(".+?(?=_)")

[1] "_1121" "_1432" "_1121"

Database Diagram Support Objects cannot be Installed ... no valid owner

you must enter as administrator right click to microsofft sql server management studio and run as admin

Auto-increment on partial primary key with Entity Framework Core

To anyone who came across this question who are using SQL Server Database and still having an exception thrown even after adding the following annotation on the int primary key

[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int Id { get; set; }

Please check your SQL, make sure your the primary key has 'IDENTITY(startValue, increment)' next to it,

CREATE TABLE [dbo].[User]
(
    [Id] INT IDENTITY(1,1) NOT NULL PRIMARY KEY
)

This will make the database increments the id every time a new row is added, with a starting value of 1 and increments of 1.

I accidentally overlooked that in my SQL which cost me an hour of my life, so hopefully this helps someone!!!

Showing/Hiding Table Rows with Javascript - can do with ID - how to do with Class?

JQuery 10.1.2 has a nice show and hide functions that encapsulate the behavior you are talking about. This would save you having to write a new function or keep track of css classes.

$("new").show();

$("new").hide();

w3cSchool link to JQuery show and hide

Get value from a string after a special character

_x000D_
_x000D_
//var val = $("#FieldId").val()_x000D_
//Get Value of hidden field by val() jquery function I'm using example string._x000D_
var val = "String to find after - DEMO"_x000D_
var foundString = val.substr(val.indexOf(' - ')+3,)_x000D_
console.log(foundString);
_x000D_
_x000D_
_x000D_ Assuming you need to find DEMO string after - by above code you can able to access DEMO string substr will return the string from whaterver the value indexOf return till the end of string it will return everything.

How to prevent tensorflow from allocating the totality of a GPU memory?

Shameless plug: If you install the GPU supported Tensorflow, the session will first allocate all GPU whether you set it to use only CPU or GPU. I may add my tip that even you set the graph to use CPU only you should set the same configuration(as answered above:) ) to prevent the unwanted GPU occupation.

And in an interactive interface like IPython and Jupyter, you should also set that configure, otherwise, it will allocate all memory and left almost none for others. This is sometimes hard to notice.

history.replaceState() example?

Suppose https://www.mozilla.org/foo.html executes the following JavaScript:

const stateObj = { foo: 'bar' };

history.pushState(stateObj, '', 'bar.html');

This will cause the URL bar to display https://www.mozilla.org/bar2.html, but won't cause the browser to load bar2.html or even check that bar2.html exists.

Checking if a list of objects contains a property with a specific value

myList.Where(item=>item.Name == nameToExtract)

How can I scale an image in a CSS sprite

2018 here. Use background-size with percentage.

SHEET:

This assumes a single row of sprites. The width of your sheet should be a number that is evenly divisible by 100 + width of one sprite. If you have 30 sprites that are 108x108 px, then add extra blank space to the end to make the final width 5508px (50*108 + 108).

CSS:

.icon{
    height: 30px;  /* Set this to anything. It will scale. */
    width: 30px; /* Match height. This assumes square sprites. */
    background:url(<mysheeturl>);
    background-size: 5100% 100%; /*  5100% because 51 sprites. */
}

/* Each image increases by 2% because we used 50+1 sprites. 
   If we had used 20+1 sprites then % increase would be 5%. */

.first_image{
    background-position: 0% 0;
}

.ninth_image{
    background-position: 16% 0; /* (9-1) x 2 = 16 */
}

HTML:

<div class ="icon first_image"></div>
<div class ="icon ninth_image"></div>

How to create a zip file in Java

Given exportPath and queryResults as String variables, the following block creates a results.zip file under exportPath and writes the content of queryResults to a results.txt file inside the zip.

URI uri = URI.create("jar:file:" + exportPath + "/results.zip");
Map<String, String> env = Collections.singletonMap("create", "true");

try (FileSystem zipfs = FileSystems.newFileSystem(uri, env)) {
  Path filePath = zipfs.getPath("/results.txt");
  byte[] fileContent = queryResults.getBytes();

  Files.write(filePath, fileContent, StandardOpenOption.CREATE);
}

Verilog: How to instantiate a module

This is all generally covered by Section 23.3.2 of SystemVerilog IEEE Std 1800-2012.

The simplest way is to instantiate in the main section of top, creating a named instance and wiring the ports up in order:

module top(
   input        clk,
   input        rst_n,
   input        enable,
   input  [9:0] data_rx_1,
   input  [9:0] data_rx_2,
   output [9:0] data_tx_2
);

subcomponent subcomponent_instance_name (
  clk, rst_n, data_rx_1, data_tx ); 

endmodule

This is described in Section 23.3.2.1 of SystemVerilog IEEE Std 1800-2012.

This has a few draw backs especially regarding the port order of the subcomponent code. simple refactoring here can break connectivity or change behaviour. for example if some one else fixs a bug and reorders the ports for some reason, switching the clk and reset order. There will be no connectivity issue from your compiler but will not work as intended.

module subcomponent(
  input        rst_n,       
  input        clk,
  ...

It is therefore recommended to connect using named ports, this also helps tracing connectivity of wires in the code.

module top(
   input        clk,
   input        rst_n,
   input        enable,
   input  [9:0] data_rx_1,
   input  [9:0] data_rx_2,
   output [9:0] data_tx_2
);

subcomponent subcomponent_instance_name (
  .clk(clk), .rst_n(rst_n), .data_rx(data_rx_1), .data_tx(data_tx) ); 

endmodule

This is described in Section 23.3.2.2 of SystemVerilog IEEE Std 1800-2012.

Giving each port its own line and indenting correctly adds to the readability and code quality.

subcomponent subcomponent_instance_name (
  .clk      ( clk       ), // input
  .rst_n    ( rst_n     ), // input
  .data_rx  ( data_rx_1 ), // input  [9:0]
  .data_tx  ( data_tx   )  // output [9:0]
);

So far all the connections that have been made have reused inputs and output to the sub module and no connectivity wires have been created. What happens if we are to take outputs from one component to another:

clk_gen( 
  .clk      ( clk_sub   ), // output
  .en       ( enable    )  // input

subcomponent subcomponent_instance_name (
  .clk      ( clk_sub   ), // input
  .rst_n    ( rst_n     ), // input 
  .data_rx  ( data_rx_1 ), // input  [9:0]
  .data_tx  ( data_tx   )  // output [9:0]
);

This nominally works as a wire for clk_sub is automatically created, there is a danger to relying on this. it will only ever create a 1 bit wire by default. An example where this is a problem would be for the data:

Note that the instance name for the second component has been changed

subcomponent subcomponent_instance_name (
  .clk      ( clk_sub   ), // input
  .rst_n    ( rst_n     ), // input 
  .data_rx  ( data_rx_1 ), // input  [9:0]
  .data_tx  ( data_temp )  // output [9:0]
);
subcomponent subcomponent_instance_name2 (
  .clk      ( clk_sub   ), // input
  .rst_n    ( rst_n     ), // input 
  .data_rx  ( data_temp ), // input  [9:0]
  .data_tx  ( data_tx   )  // output [9:0]
);

The issue with the above code is that data_temp is only 1 bit wide, there would be a compile warning about port width mismatch. The connectivity wire needs to be created and a width specified. I would recommend that all connectivity wires be explicitly written out.

wire [9:0] data_temp
subcomponent subcomponent_instance_name (
  .clk      ( clk_sub   ), // input
  .rst_n    ( rst_n     ), // input 
  .data_rx  ( data_rx_1 ), // input  [9:0]
  .data_tx  ( data_temp )  // output [9:0]
);
subcomponent subcomponent_instance_name2 (
  .clk      ( clk_sub   ), // input
  .rst_n    ( rst_n     ), // input 
  .data_rx  ( data_temp ), // input  [9:0]
  .data_tx  ( data_tx   )  // output [9:0]
);

Moving to SystemVerilog there are a few tricks available that save typing a handful of characters. I believe that they hinder the code readability and can make it harder to find bugs.

Use .port with no brackets to connect to a wire/reg of the same name. This can look neat especially with lots of clk and resets but at some levels you may generate different clocks or resets or you actually do not want to connect to the signal of the same name but a modified one and this can lead to wiring bugs that are not obvious to the eye.

module top(
   input        clk,
   input        rst_n,
   input        enable,
   input  [9:0] data_rx_1,
   input  [9:0] data_rx_2,
   output [9:0] data_tx_2
);

subcomponent subcomponent_instance_name (
  .clk,                    // input **Auto connect**
  .rst_n,                  // input **Auto connect**
  .data_rx  ( data_rx_1 ), // input  [9:0]
  .data_tx  ( data_tx   )  // output [9:0]
);

endmodule

This is described in Section 23.3.2.3 of SystemVerilog IEEE Std 1800-2012.

Another trick that I think is even worse than the one above is .* which connects unmentioned ports to signals of the same wire. I consider this to be quite dangerous in production code. It is not obvious when new ports have been added and are missing or that they might accidentally get connected if the new port name had a counter part in the instancing level, they get auto connected and no warning would be generated.

subcomponent subcomponent_instance_name (
  .*,                      // **Auto connect**
  .data_rx  ( data_rx_1 ), // input  [9:0]
  .data_tx  ( data_tx   )  // output [9:0]
);

This is described in Section 23.3.2.4 of SystemVerilog IEEE Std 1800-2012.

Removing input background colour for Chrome autocomplete?

Google Chrome user agent prevent developers' CSS, So for changing autofill UI must use another property like these:

input:-webkit-autofill,
textarea:-webkit-autofill,
select:-webkit-autofill {
    -webkit-box-shadow: 0 0 0 1000px #d500ff inset !important;
    /*use inset box-shadow to cover background-color*/
    -webkit-text-fill-color: #ffa400 !important;
    /*use text fill color to cover font color*/
}

Slidedown and slideup layout with animation

I use these easy functions, it work like jquery slideUp slideDown, use it in an helper class, just pass your view :

public static void expand(final View v) {
    v.measure(WindowManager.LayoutParams.MATCH_PARENT, WindowManager.LayoutParams.WRAP_CONTENT);
    final int targetHeight = v.getMeasuredHeight();

    // Older versions of android (pre API 21) cancel animations for views with a height of 0.
    v.getLayoutParams().height = 1;
    v.setVisibility(View.VISIBLE);
    Animation a = new Animation()
    {
        @Override
        protected void applyTransformation(float interpolatedTime, Transformation t) {
            v.getLayoutParams().height = interpolatedTime == 1
                    ? WindowManager.LayoutParams.WRAP_CONTENT
                    : (int)(targetHeight * interpolatedTime);
            v.requestLayout();
        }

        @Override
        public boolean willChangeBounds() {
            return true;
        }
    };

    // 1dp/ms
    a.setDuration((int) (targetHeight / v.getContext().getResources().getDisplayMetrics().density));
    v.startAnimation(a);
}

public static void collapse(final View v) {
    final int initialHeight = v.getMeasuredHeight();

    Animation a = new Animation()
    {
        @Override
        protected void applyTransformation(float interpolatedTime, Transformation t) {
            if(interpolatedTime == 1){
                v.setVisibility(View.GONE);
            }else{
                v.getLayoutParams().height = initialHeight - (int)(initialHeight * interpolatedTime);
                v.requestLayout();
            }
        }

        @Override
        public boolean willChangeBounds() {
            return true;
        }
    };

    // 1dp/ms
    a.setDuration((int)(initialHeight / v.getContext().getResources().getDisplayMetrics().density));
    v.startAnimation(a);
}

android fragment- How to save states of views in a fragment when another fragment is pushed on top of it

Fragment's onSaveInstanceState(Bundle outState) will never be called unless fragment's activity call it on itself and attached fragments. Thus this method won't be called until something (typically rotation) force activity to SaveInstanceState and restore it later. But if you have only one activity and large set of fragments inside it (with intensive usage of replace) and application runs only in one orientation activity's onSaveInstanceState(Bundle outState) may not be called for a long time.

I know three possible workarounds.

The first:

use fragment's arguments to hold important data:

public class FragmentA extends Fragment {
    private static final String PERSISTENT_VARIABLE_BUNDLE_KEY = "persistentVariable";

    private EditText persistentVariableEdit;

    public FragmentA() {
        setArguments(new Bundle());
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_a, null);

        persistentVariableEdit = (EditText) view.findViewById(R.id.editText);

        TextView proofTextView = (TextView) view.findViewById(R.id.textView);

        Bundle mySavedInstanceState = getArguments();
        String persistentVariable = mySavedInstanceState.getString(PERSISTENT_VARIABLE_BUNDLE_KEY);

        proofTextView.setText(persistentVariable);


        view.findViewById(R.id.btnPushFragmentB).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                getFragmentManager()
                        .beginTransaction()
                        .replace(R.id.frameLayout, new FragmentB())
                        .addToBackStack(null)
                        .commit();
            }
        });

        return view;
    }

    @Override
    public void onPause() {
        super.onPause();
        String persistentVariable = persistentVariableEdit.getText().toString();

        getArguments().putString(PERSISTENT_VARIABLE_BUNDLE_KEY, persistentVariable);
    }
}

The second but less pedantic way - hold variables in singletons

The third - don't replace() fragments but add()/show()/hide() them instead.

Schedule automatic daily upload with FileZilla

FileZilla does not have any command line arguments (nor any other way) that allow an automatic transfer.

Some references:


Though you can use any other client that allows automation.

You have not specified, what protocol you are using. FTP or SFTP? You will definitely be able to use WinSCP, as it supports all protocols that FileZilla does (and more).

Combine WinSCP scripting capabilities with Windows Scheduler:

A typical WinSCP script for upload (with SFTP) looks like:

open sftp://user:[email protected]/ -hostkey="ssh-rsa 2048 xxxxxxxxxxx...="
put c:\mypdfs\*.pdf /home/user/
close

With FTP, just replace the sftp:// with the ftp:// and remove the -hostkey="..." switch.


Similarly for download: How to schedule an automatic FTP download on Windows?


WinSCP can even generate a script from an imported FileZilla session.

For details, see the guide to FileZilla automation.

(I'm the author of WinSCP)


Another option, if you are using SFTP, is the psftp.exe client from PuTTY suite.

Creating a zero-filled pandas data frame

If you would like the new data frame to have the same index and columns as an existing data frame, you can just multiply the existing data frame by zero:

df_zeros = df * 0

Change first commit of project with Git?

As mentioned by ecdpalma below, git 1.7.12+ (August 2012) has enhanced the option --root for git rebase:

"git rebase [-i] --root $tip" can now be used to rewrite all the history leading to "$tip" down to the root commit.

That new behavior was initially discussed here:

I personally think "git rebase -i --root" should be made to just work without requiring "--onto" and let you "edit" even the first one in the history.
It is understandable that nobody bothered, as people are a lot less often rewriting near the very beginning of the history than otherwise.

The patch followed.


(original answer, February 2010)

As mentioned in the Git FAQ (and this SO question), the idea is:

  1. Create new temporary branch
  2. Rewind it to the commit you want to change using git reset --hard
  3. Change that commit (it would be top of current HEAD, and you can modify the content of any file)
  4. Rebase branch on top of changed commit, using:

    git rebase --onto <tmp branch> <commit after changed> <branch>`
    

The trick is to be sure the information you want to remove is not reintroduced by a later commit somewhere else in your file. If you suspect that, then you have to use filter-branch --tree-filter to make sure the content of that file does not contain in any commit the sensible information.

In both cases, you end up rewriting the SHA1 of every commit, so be careful if you have already published the branch you are modifying the contents of. You probably shouldn’t do it unless your project isn’t yet public and other people haven’t based work off the commits you’re about to rewrite.

Android ListView with Checkbox and all clickable

holder.checkbox.setTag(row_id);

and

holder.checkbox.setOnClickListener( new OnClickListener() {

                @Override
                public void onClick(View v) {
                    CheckBox c = (CheckBox) v;

                    int row_id = (Integer) v.getTag();

                    checkboxes.put(row_id, c.isChecked());


                }
        });

PHP How to find the time elapsed since a date time?

One option that'll work with any version of PHP is to do what's already been suggested, which is something like this:

$eventTime = '2010-04-28 17:25:43';
$age = time() - strtotime($eventTime);

That will give you the age in seconds. From there, you can display it however you wish.

One problem with this approach, however, is that it won't take into account time shifts causes by DST. If that's not a concern, then go for it. Otherwise, you'll probably want to use the diff() method in the DateTime class. Unfortunately, this is only an option if you're on at least PHP 5.3.

How to disable the resize grabber of <textarea>?

Just use resize: none

textarea {
   resize: none;
}

You can also decide to resize your textareas only horizontal or vertical, this way:

textarea { resize: vertical; }

textarea { resize: horizontal; }

Finally, resize: both enables the resize grabber.

C++ Pass A String

Just cast it as a const char *. print((const char *)"Yo!") will work fine.

Exec : display stdout "live"

I'd just like to add that one small issue with outputting the buffer strings from a spawned process with console.log() is that it adds newlines, which can spread your spawned process output over additional lines. If you output stdout or stderr with process.stdout.write() instead of console.log(), then you'll get the console output from the spawned process 'as is'.

I saw that solution here: Node.js: printing to console without a trailing newline?

Hope that helps someone using the solution above (which is a great one for live output, even if it is from the documentation).

Saving image to file

If you are drawing on the Graphics of the Control than you should do something draw on the Bitmap everything you are drawing on the canvas, but have in mind that Bitmap needs to be the exact size of the control you are drawing on:

  Bitmap bmp = new Bitmap(myControl.ClientRectangle.Width,myControl.ClientRectangle.Height);
  Graphics gBmp = Graphics.FromImage(bmp);
  gBmp.DrawEverything(); //this is your code for drawing
  gBmp.Dispose();
  bmp.Save("image.png", ImageFormat.Png);

Or you can use a DrawToBitmap method of the Control. Something like this:

Bitmap bmp = new Bitmap(myControl.ClientRectangle.Width, myControl.ClientRectangle.Height);
myControl.DrawToBitmap(bmp,new Rectangle(0,0,bmp.Width,bmp.Height));
bmp.Save("image.png", ImageFormat.Png);

Blurring an image via CSS?

This code is working for blur effect for all browsers.

filter: blur(10px);
-webkit-filter: blur(10px);
-moz-filter: blur(10px);
-o-filter: blur(10px);
-ms-filter: blur(10px);

Change primary key column in SQL Server

Necromancing.
It looks you have just as good a schema to work with as me... Here is how to do it correctly:

In this example, the table name is dbo.T_SYS_Language_Forms, and the column name is LANG_UID

-- First, chech if the table exists...
IF 0 < (
    SELECT COUNT(*) FROM INFORMATION_SCHEMA.TABLES 
    WHERE TABLE_TYPE = 'BASE TABLE'
    AND TABLE_SCHEMA = 'dbo'
    AND TABLE_NAME = 'T_SYS_Language_Forms'
)
BEGIN
    -- Check for NULL values in the primary-key column
    IF 0 = (SELECT COUNT(*) FROM T_SYS_Language_Forms WHERE LANG_UID IS NULL)
    BEGIN
        ALTER TABLE T_SYS_Language_Forms ALTER COLUMN LANG_UID uniqueidentifier NOT NULL 

        -- No, don't drop, FK references might already exist...
        -- Drop PK if exists 
        -- ALTER TABLE T_SYS_Language_Forms DROP CONSTRAINT pk_constraint_name 
        --DECLARE @pkDropCommand nvarchar(1000) 
        --SET @pkDropCommand = N'ALTER TABLE T_SYS_Language_Forms DROP CONSTRAINT ' + QUOTENAME((SELECT CONSTRAINT_NAME FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS 
        --WHERE CONSTRAINT_TYPE = 'PRIMARY KEY' 
        --AND TABLE_SCHEMA = 'dbo' 
        --AND TABLE_NAME = 'T_SYS_Language_Forms' 
        ----AND CONSTRAINT_NAME = 'PK_T_SYS_Language_Forms' 
        --))
        ---- PRINT @pkDropCommand 
        --EXECUTE(@pkDropCommand) 

        -- Instead do
        -- EXEC sp_rename 'dbo.T_SYS_Language_Forms.PK_T_SYS_Language_Forms1234565', 'PK_T_SYS_Language_Forms';


        -- Check if they keys are unique (it is very possible they might not be) 
        IF 1 >= (SELECT TOP 1 COUNT(*) AS cnt FROM T_SYS_Language_Forms GROUP BY LANG_UID ORDER BY cnt DESC)
        BEGIN

            -- If no Primary key for this table
            IF 0 =  
            (
                SELECT COUNT(*) FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS 
                WHERE CONSTRAINT_TYPE = 'PRIMARY KEY' 
                AND TABLE_SCHEMA = 'dbo' 
                AND TABLE_NAME = 'T_SYS_Language_Forms' 
                -- AND CONSTRAINT_NAME = 'PK_T_SYS_Language_Forms' 
            )
                ALTER TABLE T_SYS_Language_Forms ADD CONSTRAINT PK_T_SYS_Language_Forms PRIMARY KEY CLUSTERED (LANG_UID ASC)
            ;

            -- Adding foreign key
            IF 0 = (SELECT COUNT(*) FROM INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS WHERE CONSTRAINT_NAME = 'FK_T_ZO_SYS_Language_Forms_T_SYS_Language_Forms') 
                ALTER TABLE T_ZO_SYS_Language_Forms WITH NOCHECK ADD CONSTRAINT FK_T_ZO_SYS_Language_Forms_T_SYS_Language_Forms FOREIGN KEY(ZOLANG_LANG_UID) REFERENCES T_SYS_Language_Forms(LANG_UID); 
        END -- End uniqueness check
        ELSE
            PRINT 'FSCK, this column has duplicate keys, and can thus not be changed to primary key...' 
    END -- End NULL check
    ELSE
        PRINT 'FSCK, need to figure out how to update NULL value(s)...' 
END 

How to get file extension from string in C++

Or you can use this:

    char *ExtractFileExt(char *FileName)
    {
        std::string s = FileName;
        int Len = s.length();
        while(TRUE)
        {
            if(FileName[Len] != '.')
                Len--;
            else
            {
                char *Ext = new char[s.length()-Len+1];
                for(int a=0; a<s.length()-Len; a++)
                    Ext[a] = FileName[s.length()-(s.length()-Len)+a];
                Ext[s.length()-Len] = '\0';
                return Ext;
            }
        }
    }

This code is cross-platform

$(document).ready(function() is not working

I just had this issue and it was because of me trying to included jQuery via http while my page was loaded as https.

How can I use std::maps with user-defined types as key?

class key
{
    int m_value;
public:
    bool operator<(const key& src)const
    {
        return (this->m_value < src.m_value);
    }

};
int main()
{
    key key1;
    key key2;
    map<key,int> mymap;
    mymap.insert(pair<key,int>(key1,100));
    mymap.insert(pair<key,int>(key2,200));
    map<key,int>::iterator iter=mymap.begin();
    for(;iter!=mymap.end();++iter)
    {
        cout<<iter->second<<endl;
    }


}

Get the current year in JavaScript

You can simply use javascript like this. Otherwise you can use momentJs Plugin which helps in large application.

new Date().getDate()          // Get the day as a number (1-31)
new Date().getDay()           // Get the weekday as a number (0-6)
new Date().getFullYear()      // Get the four digit year (yyyy)
new Date().getHours()         // Get the hour (0-23)
new Date().getMilliseconds()  // Get the milliseconds (0-999)
new Date().getMinutes()       // Get the minutes (0-59)
new Date().getMonth()         // Get the month (0-11)
new Date().getSeconds()       // Get the seconds (0-59)
new Date().getTime()          // Get the time (milliseconds since January 1, 1970)

_x000D_
_x000D_
function generate(type,element)_x000D_
{_x000D_
 var value = "";_x000D_
 var date = new Date();_x000D_
 switch (type) {_x000D_
  case "Date":_x000D_
   value = date.getDate();  // Get the day as a number (1-31)_x000D_
   break;_x000D_
  case "Day":_x000D_
   value = date.getDay();  // Get the weekday as a number (0-6)_x000D_
   break;_x000D_
  case "FullYear":_x000D_
   value = date.getFullYear(); // Get the four digit year (yyyy)_x000D_
   break;_x000D_
  case "Hours":_x000D_
   value = date.getHours(); // Get the hour (0-23)_x000D_
   break;_x000D_
  case "Milliseconds":_x000D_
   value = date.getMilliseconds(); // Get the milliseconds (0-999)_x000D_
   break;_x000D_
  case "Minutes":_x000D_
   value = date.getMinutes();     // Get the minutes (0-59)_x000D_
   break;_x000D_
  case "Month":_x000D_
   value = date.getMonth(); // Get the month (0-11)_x000D_
   break;_x000D_
  case "Seconds":_x000D_
   value = date.getSeconds(); // Get the seconds (0-59)_x000D_
   break;_x000D_
  case "Time":_x000D_
   value = date.getTime();  // Get the time (milliseconds since January 1, 1970)_x000D_
   break;_x000D_
 }_x000D_
_x000D_
 $(element).siblings('span').text(value);_x000D_
}
_x000D_
li{_x000D_
  list-style-type: none;_x000D_
  padding: 5px;_x000D_
}_x000D_
_x000D_
button{_x000D_
  width: 150px;_x000D_
}_x000D_
_x000D_
span{_x000D_
  margin-left: 100px;_x000D_
}
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
_x000D_
_x000D_
<ul>_x000D_
 <li>_x000D_
  <button type="button" onclick="generate('Date',this)">Get Date</button>_x000D_
  <span></span>_x000D_
 </li>_x000D_
 <li>_x000D_
  <button type="button" onclick="generate('Day',this)">Get Day</button>_x000D_
  <span></span>_x000D_
 </li>_x000D_
 <li>_x000D_
  <button type="button" onclick="generate('FullYear',this)">Get Full Year</button>_x000D_
  <span></span>_x000D_
 </li>_x000D_
 <li>_x000D_
  <button type="button" onclick="generate('Hours',this)">Get Hours</button>_x000D_
  <span></span>_x000D_
 </li>_x000D_
 <li>_x000D_
  <button type="button" onclick="generate('Milliseconds',this)">Get Milliseconds</button>_x000D_
  <span></span>_x000D_
 </li>_x000D_
_x000D_
 <li>_x000D_
  <button type="button" onclick="generate('Minutes',this)">Get Minutes</button>_x000D_
  <span></span>_x000D_
 </li>_x000D_
 <li>_x000D_
  <button type="button" onclick="generate('Month',this)">Get Month</button>_x000D_
  <span></span>_x000D_
 </li>_x000D_
 <li>_x000D_
  <button type="button" onclick="generate('Seconds',this)">Get Seconds</button>_x000D_
  <span></span>_x000D_
 </li>_x000D_
 <li>_x000D_
  <button type="button" onclick="generate('Time',this)">Get Time</button>_x000D_
  <span></span>_x000D_
 </li>_x000D_
</ul>
_x000D_
_x000D_
_x000D_

How to change fonts in matplotlib (python)?

You can also use rcParams to change the font family globally.

 import matplotlib.pyplot as plt
 plt.rcParams["font.family"] = "cursive"
 # This will change to your computer's default cursive font

The list of matplotlib's font family arguments is here.

Bubble Sort Homework

Your use of the Unsorted variable is wrong; you want to have a variable that tells you if you have swapped two elements; if you have done that, you can exit your loop, otherwise, you need to loop again. To fix what you've got here, just put the "unsorted = false" in the body of your if case; remove your else case; and put "unsorted = true before your for loop.

How do I get my C# program to sleep for 50 msec?

System.Threading.Thread.Sleep(50);

Remember though, that doing this in the main GUI thread will block your GUI from updating (it will feel "sluggish")

Just remove the ; to make it work for VB.net as well.

Handle ModelState Validation in ASP.NET Web API

You can also throw exceptions as documented here: http://blogs.msdn.com/b/youssefm/archive/2012/06/28/error-handling-in-asp-net-webapi.aspx

Note, to do what that article suggests, remember to include System.Net.Http

java.lang.NoClassDefFoundError: javax/mail/Authenticator, whats wrong?

You need to add two jars into the WEB-INF/lib directory or your webapp (or lib directory of the server):

Iterating through directories with Python

The actual walk through the directories works as you have coded it. If you replace the contents of the inner loop with a simple print statement you can see that each file is found:

import os
rootdir = 'C:/Users/sid/Desktop/test'

for subdir, dirs, files in os.walk(rootdir):
    for file in files:
        print os.path.join(subdir, file)

If you still get errors when running the above, please provide the error message.


Updated for Python3

import os
rootdir = 'C:/Users/sid/Desktop/test'

for subdir, dirs, files in os.walk(rootdir):
    for file in files:
        print(os.path.join(subdir, file))

CSS vertical-align: text-bottom;

Modern solution

Flexbox was created for exactly these kind of problems:

_x000D_
_x000D_
#container {_x000D_
    height: 150px;/*Only for the demo.*/_x000D_
    background-color:green;/*Only for the demo.*/_x000D_
    display: flex;_x000D_
    justify-content: center;_x000D_
    align-items: flex-end;_x000D_
}
_x000D_
<div id="container">_x000D_
    <span>Text align to center bottom.</span>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Old school solution

If you don't want to mess with table displays, then you can create a <div> inside a relatively positioned parent container, place it to the bottom with absolute positioning, then make it 100% wide, so you can text-align it to the center:

_x000D_
_x000D_
#container {_x000D_
    height: 150px;/*Only for the demo.*/_x000D_
    background-color:green;/*Only for the demo.*/_x000D_
    position: relative;_x000D_
}_x000D_
_x000D_
#text {_x000D_
    position: absolute;_x000D_
    bottom: 0;_x000D_
    width: 100%;_x000D_
    text-align: center;_x000D_
}
_x000D_
<div id="container">_x000D_
    <span id="text">Text align to center bottom.</span>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Regex remove all special characters except numbers?

If you don't mind including the underscore as an allowed character, you could try simply:

result = subject.replace(/\W+/g, "");

If the underscore must be excluded also, then

result = subject.replace(/[^A-Z0-9]+/ig, "");

(Note the case insensitive flag)

Java ArrayList of Doubles

You can use Arrays.asList to get some list (not necessarily ArrayList) and then use addAll() to add it to an ArrayList:

new ArrayList<Double>().addAll(Arrays.asList(1.38L, 2.56L, 4.3L));

If you're using Java6 (or higher) you can also use the ArrayList constructor that takes another list:

new ArrayList<Double>(Arrays.asList(1.38L, 2.56L, 4.3L));

Running the new Intel emulator for Android

  1. Download HAXM from the Intel site.

  2. Install it.

  3. And then run the AVD from AndroidStudio, menu -> Tools -> AVD. Choose x86.

It works!

SQL SELECT everything after a certain character

Try this in MySQL.

right(field,((CHAR_LENGTH(field))-(InStr(field,','))))

Adding to an ArrayList Java

If you have an arraylist of String called 'foo', you can easily append (add) it to another ArrayList, 'list', using the following method:

ArrayList<String> list = new ArrayList<String>();
list.addAll(foo);

that way you don't even need to loop through anything.

How do I count the number of occurrences of a char in a String?

Okay, inspired by Yonatan's solution, here's one which is purely recursive - the only library methods used are length() and charAt(), neither of which do any looping:

public static int countOccurrences(String haystack, char needle)
{
    return countOccurrences(haystack, needle, 0);
}

private static int countOccurrences(String haystack, char needle, int index)
{
    if (index >= haystack.length())
    {
        return 0;
    }

    int contribution = haystack.charAt(index) == needle ? 1 : 0;
    return contribution + countOccurrences(haystack, needle, index+1);
}

Whether recursion counts as looping depends on which exact definition you use, but it's probably as close as you'll get.

I don't know whether most JVMs do tail-recursion these days... if not you'll get the eponymous stack overflow for suitably long strings, of course.

Properties file in python (similar to Java Properties)

i have used this, this library is very useful

from pyjavaproperties import Properties
p = Properties()
p.load(open('test.properties'))
p.list()
print(p)
print(p.items())
print(p['name3'])
p['name3'] = 'changed = value'

How do I repair an InnoDB table?

stop your application...or stop your slave so no new rows are being added

create table <new table> like <old table>;
insert <new table> select * from <old table>;
truncate table  <old table>;
insert <old table> select * from <new table>;

restart your server or slave

Using %s in C correctly - very basic level

%s will get all the values until it gets NULL i.e. '\0'.

char str1[] = "This is the end\0";
printf("%s",str1);

will give

This is the end

char str2[] = "this is\0 the end\0";
printf("%s",str2);

will give

this is

Completely removing phpMyAdmin

I was having a similar problem. PHP was working on my sites configured by virtualmin but not for phpmyadmin. PHPMyAdmin would not execute and the file was being downloaded by the browser. Everything I was reading was saying that libapache2-mod-php5 was not installed but I knew it was... so the thing to do was to purge it and reinstall.

sudo apt-get purge libapache2-mod-php5

sudo apt-get install libapache2-mod-php5

sudo apt-get purge phpmyadmin

sudo apt-get install phpmyadmin

sudo /etc/init.d/apache2 restart

Linq select objects in list where exists IN (A,B,C)

NB: this is LINQ to objects, I am not 100% sure if it work in LINQ to entities, and have no time to check it right now. In fact it isn't too difficult to translate it to x in [A, B, C] but you have to check for yourself.

So, instead of Contains as a replacement of the ???? in your code you can use Any which is more LINQ-uish:

// Filter the orders based on the order status
var filteredOrders = from order in orders.Order
                     where new[] { "A", "B", "C" }.Any(s => s == order.StatusCode)
                     select order;

It's the opposite to what you know from SQL this is why it is not so obvious.

Of course, if you prefer fluent syntax here it is:

var filteredOrders = orders.Order.Where(order => new[] {"A", "B", "C"}.Any(s => s == order.StatusCode));

Here we again see one of the LINQ surprises (like Joda-speech which puts select at the end). However it is quite logical in this sense that it checks if at least one of the items (that is any) in a list (set, collection) matches a single value.

React-Redux: Actions must be plain objects. Use custom middleware for async actions

I had same issue as I had missed adding composeEnhancers. Once this is setup then you can take a look into action creators. You get this error when this is not setup as well.

const composeEnhancers = window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ || compose;

const store = createStore(
  rootReducer,
  composeEnhancers(applyMiddleware(thunk))
);

keyCode values for numeric keypad?

keyCode is different for numbers on numeric keypad and numbers on top of keyboard.

keyCodes :

numbers on top of keyboard ( 0 - 9 ) : 48 - 57
numbers on numeric keypad ( 0 - 9 ) : 96 - 105

JavaScript condition :

if((e.keyCode >= 48 && e.keyCode <=57) || (e.keyCode >= 96 && e.keyCode <=105)) { 
    // entered key is a number
}

Reference for all keycodes ( with demo ) : http://www.codeforeach.com/javascript/keycode-for-each-key-and-usage-with-demo

Detect if HTML5 Video element is playing

This is my code - by calling the function play() the video plays or pauses and the button image is changed.

By calling the function volume() the volume is turned on/off and the button image also changes.

function play() { 
  var video = document.getElementById('slidevideo'); 
  if (video.paused) {
    video.play()
    play_img.src = 'img/pause.png'; 
  }
  else {
    video.pause()
    play_img.src = 'img/play.png';
  }
}

function volume() { 
  var video = document.getElementById('slidevideo');
  var img = document.getElementById('volume_img');
  if (video.volume > 0) {
    video.volume = 0
    volume_img.src = 'img/volume_off.png';  
  }
  else {
    video.volume = 1
    volume_img.src = 'img/volume_on.png';
  }
}

How to unescape HTML character entities in Java?

Incase you want to mimic what php function htmlspecialchars_decode does use php function get_html_translation_table() to dump the table and then use the java code like,

static Map<String,String> html_specialchars_table = new Hashtable<String,String>();
static {
        html_specialchars_table.put("&lt;","<");
        html_specialchars_table.put("&gt;",">");
        html_specialchars_table.put("&amp;","&");
}
static String htmlspecialchars_decode_ENT_NOQUOTES(String s){
        Enumeration en = html_specialchars_table.keys();
        while(en.hasMoreElements()){
                String key = en.nextElement();
                String val = html_specialchars_table.get(key);
                s = s.replaceAll(key, val);
        }
        return s;
}

Get response from PHP file using AJAX

The good practice is to use like this:

$.ajax({
    type: "POST",
    url: "/ajax/request.html",
    data: {action: 'test'},
    dataType:'JSON', 
    success: function(response){
        console.log(response.blablabla);
        // put on console what server sent back...
    }
});

and the php part is:

<?php
    if(isset($_POST['action']) && !empty($_POST['action'])) {
        echo json_encode(array("blablabla"=>$variable));
    }
?>

How to combine 2 plots (ggplot) into one plot?

Just combine them. I think this should work but it's untested:

p <- ggplot(visual1, aes(ISSUE_DATE,COUNTED)) + geom_point() + 
     geom_smooth(fill="blue", colour="darkblue", size=1)

p <- p + geom_point(data=visual2, aes(ISSUE_DATE,COUNTED)) + 
     geom_smooth(data=visual2, fill="red", colour="red", size=1)

print(p)

How to resolve "git pull,fatal: unable to access 'https://github.com...\': Empty reply from server"

If unsetting using

git config --global --unset-all https.proxy

doesn't work for you .

Then check if the environment variable http_proxy and https_proxy are set . Check using this command : -

env | grep -i proxy

If this variable is set to something , then you can just unset it using :-

   https_proxy=""

jQuery limit to 2 decimal places

You could use a variable to make the calculation and use toFixed when you set the #diskamountUnit element value:

var amount = $("#disk").slider("value") * 1.60;
$("#diskamountUnit").val('$' + amount.toFixed(2));

You can also do that in one step, in the val method call but IMO the first way is more readable:

$("#diskamountUnit").val('$' + ($("#disk").slider("value") * 1.60).toFixed(2));

How to pass a value from one jsp to another jsp page?

Use below code for passing string from one jsp to another jsp

A.jsp

   <% String userid="Banda";%>
    <form action="B.jsp" method="post">
    <%
    session.setAttribute("userId", userid);
        %>
        <input type="submit"
                            value="Login">
    </form>

B.jsp

    <%String userid = session.getAttribute("userId").toString(); %>
    Hello<%=userid%>

Finding Number of Cores in Java

int cores = Runtime.getRuntime().availableProcessors();

If cores is less than one, either your processor is about to die, or your JVM has a serious bug in it, or the universe is about to blow up.

How to show a GUI message box from a bash script in linux?

Everyone mentions zenity, there seem to be many others. A mixed up but interesting list is at http://alternativeto.net/software/zenity/

First, an example of zenity featuring text formatting markup, window title, button label.

zenity \
--info \
--text="<span size=\"xx-large\">Time is $(date +%Hh%M).</span>\n\nGet your <b>coffee</b>." \
--title="Coffee time" \
--ok-label="Sip"

gxmessage

gxmessage "my text"

xmessage

xmessage is very old so it is stable and probably available in all distributions that use X (since it's distributed with X). It is customizable through X resources, for those that have been using Linux or Unix for long enough to know what it means (.Xdefaults, anyone ?).

xmessage -buttons Ok:0,"Not sure":1,Cancel:2 -default Ok -nearmouse "Is xmessage enough for the job ?" -timeout 10

kdialog

(not tested)

In a PPA

YAD: Zenity On Steroids [Display Graphical Dialogs From Shell Scripts] ~ Web Upd8: Ubuntu / Linux blog. Does not seem to auto-size dialogs.

echo My text | yad \
--text-info \
--width=400 \
--height=200

An bigger example

yad \
--title="Desktop entry editor" \
--text="Simple desktop entry editor" \
--form \
--field="Type:CB" \
--field="Name" \
--field="Generic name" \
--field="Comment" \
--field="Command:FL" \
--field="Icon" \
--field="In terminal:CHK" \
--field="Startup notify:CHK" "Application" "Name" "Generic name" "This is the comment" "/usr/bin/yad" "yad" FALSE TRUE \
--button="WebUpd8:2" \
--button="gtk-ok:0" \
--button="gtk-cancel:1"

Others not in Ubuntu standard repositories

  • shellgui
  • xdialog
  • gtkdialog

Off-topic (for terminal)

whiptail --msgbox "my text" 10 20
dialog --msgbox "my text" 10 20

Feel free to edit.

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

I have tested that some days ago, after reading the very clear explanation of Vonc.

My steps

Start

  • Branch dev : A B C D E F G H I J
  • Branch target: A B C D
  • I don't want E nor H

Steps to copy features without the step E and H in the branch dev_feature_wo_E_H

  • git checkout dev
  • git checkout -b dev_feature_wo_E_H
  • git rebase --interactive --rebase-merges --no-ff D where I put drop front of E and H in the rebase editor
  • resolve conflicts, continue and commit

Steps to copy the the branch dev_feature_wo_E_H on target.

  • git checkout target
  • git merge --no-ff --no-commit dev_feature_wo_E_H
  • resolve conflicts, continue and commit

Some remarks

  • I've done that because of too much cherry-pick in the days before
  • git cherry-pick is powerful and simple but

    • it creates duplicates commits
    • and when I want to merge I have to resolve conflicts of the initial commits and duplicates commits, so for one or two cherry-pick, it's OK to "cherry-picking" but for more it's too verbose and the branch will become too complex
  • In my mind the steps I've done are more clear than git rebase --onto

background:none vs background:transparent what is the difference?

To complement the other answers: if you want to reset all background properties to their initial value (which includes background-color: transparent and background-image: none) without explicitly specifying any value such as transparent or none, you can do so by writing:

background: initial;

Subtract two variables in Bash

Use Python:

#!/bin/bash
# home/victoria/test.sh

START=$(date +"%s")                                     ## seconds since Epoch
for i in $(seq 1 10)
do
  sleep 1.5
  END=$(date +"%s")                                     ## integer
  TIME=$((END - START))                                 ## integer
  AVG_TIME=$(python -c "print(float($TIME/$i))")        ## int to float
  printf 'i: %i | elapsed time: %0.1f sec | avg. time: %0.3f\n' $i $TIME $AVG_TIME
  ((i++))                                               ## increment $i
done

Output

$ ./test.sh 
i: 1 | elapsed time: 1.0 sec | avg. time: 1.000
i: 2 | elapsed time: 3.0 sec | avg. time: 1.500
i: 3 | elapsed time: 5.0 sec | avg. time: 1.667
i: 4 | elapsed time: 6.0 sec | avg. time: 1.500
i: 5 | elapsed time: 8.0 sec | avg. time: 1.600
i: 6 | elapsed time: 9.0 sec | avg. time: 1.500
i: 7 | elapsed time: 11.0 sec | avg. time: 1.571
i: 8 | elapsed time: 12.0 sec | avg. time: 1.500
i: 9 | elapsed time: 14.0 sec | avg. time: 1.556
i: 10 | elapsed time: 15.0 sec | avg. time: 1.500
$

Does Android support near real time push notification?

If you can depend on the Google libraries being there for you target market, then you may want to piggy back on GTalk functionality (registering a resource on the existing username - the intercepting it the messages as they come in with a BroadcastReceiver).

If not, and I expect you can't, then you're into bundling your own versions of XMPP. This is a pain, but may be made easier if XMPP is bundled separately as a standalone library.

You may also consider PubSubHubub, but I have no idea the network usage of it. I believe it is built atop of XMPP.

How to disable Google asking permission to regularly check installed apps on my phone?

If you want to turn off app verification programmatically, you can do so with the following code:

boolean success = true;
boolean enabled = Settings.Secure.getInt(context.getContentResolver(), "package_verifier_enable", 1) == 1;
if (enabled) {
    success = Settings.Secure.putString(context.getContentResolver(), "package_verifier_enable", "0");
}

You will also need the following system permissions:

<uses-permission android:name="android.permission.WRITE_SETTINGS" />
<uses-permission android:name="android.permission.WRITE_SECURE_SETTINGS" />

Also worth noting is that the "package_verifier_enable" string comes from the Settings.Glabal.PACKAGE_VERIFIER_ENABLE member which seems to be inaccessible.

What is the symbol for whitespace in C?

make use of isspace function .

The C library function int isspace(int c) checks whether the passed character is white-space.

sample code:

    int main()
    {

       char var= ' ';

       if( isspace(var) )
       {
          printf("var1 = |%c| is a white-space character\n", var );
       }
/*instead you can easily compare character with ' '  
  */     
    }
Standard white-space characters are -

' '   (0x20)    space (SPC)
'\t'    (0x09)  horizontal tab (TAB)
'\n'    (0x0a)  newline (LF)
'\v'    (0x0b)  vertical tab (VT)
'\f'    (0x0c)  feed (FF)
'\r'    (0x0d)  carriage return (CR)

source : tutorialpoint

How can I read numeric strings in Excel cells as string (not numbers)?

cast to an int then do a .toString(). It is ugly but it works.

Python way to clone a git repository

For python 3

First install module:

pip3 install gitpython

and later, code it :)

import os
from git.repo.base import Repo
Repo.clone_from("https://github.com/*****", "folderToSave")

I hope this helps you

Python: Removing spaces from list objects

Strings in Python are immutable (meaning that their data cannot be modified) so the replace method doesn't modify the string - it returns a new string. You could fix your code as follows:

for i in hello:
    j = i.replace(' ','')
    k.append(j)

However a better way to achieve your aim is to use a list comprehension. For example the following code removes leading and trailing spaces from every string in the list using strip:

hello = [x.strip(' ') for x in hello]

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

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

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

SpecialFolder.Personal: /home/$USER

Output on Ubuntu 16.04 with mono 4.2.1

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

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

where $USER is the current user

Output on Ubuntu 16.04 using dotnet core (3.0.100)

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

Output on Android 6 using Xamarin 7.2

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

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

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

Output on iOS Simulator 10.3 using Xamarin 7.2

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

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

Output on ipad 10.3 using Xamarin 7.2

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

Output on ipad 13.3 using Xamarin 16.4

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

Output on windows 10 using .net core 3.1

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

Output on Ubuntu 18.04 using .net core 3.1

SpecialFolder.MyDocuments: /home/$USER

Output on MacOS Catalina using .net core 3.1

SpecialFolder.MyDocuments: /Users/$USER

Is mathematics necessary for programming?

Of course it depends on what kind of programmer you want to be, or better what kind of programmer your employers want you to be. I think calculus and algebra are essentials, statistic and linear programming is indeed a good tool to have in your briefcase, maybe analysis (derivative, integrals, functions...) could be done without. But if you want to know how things work skin-deep (electronics, for example, or some non trivial algorhytms) "advanced" math is something you'd better not go without anywhere.

Regular Expression for password validation

You may try this method:

    private bool ValidatePassword(string password, out string ErrorMessage)
        {
            var input = password;
            ErrorMessage = string.Empty;

            if (string.IsNullOrWhiteSpace(input))
            {
                throw new Exception("Password should not be empty");
            }

            var hasNumber = new Regex(@"[0-9]+");
            var hasUpperChar = new Regex(@"[A-Z]+");
            var hasMiniMaxChars = new Regex(@".{8,15}");
            var hasLowerChar = new Regex(@"[a-z]+");
            var hasSymbols = new Regex(@"[!@#$%^&*()_+=\[{\]};:<>|./?,-]");

            if (!hasLowerChar.IsMatch(input))
            {
                ErrorMessage = "Password should contain at least one lower case letter.";
                return false;
            }
            else if (!hasUpperChar.IsMatch(input))
            {
                ErrorMessage = "Password should contain at least one upper case letter.";
                return false;
            }
            else if (!hasMiniMaxChars.IsMatch(input))
            {
                ErrorMessage = "Password should not be lesser than 8 or greater than 15 characters.";
                return false;
            }
            else if (!hasNumber.IsMatch(input))
            {
                ErrorMessage = "Password should contain at least one numeric value.";
                return false;
            }

            else if (!hasSymbols.IsMatch(input))
            {
                ErrorMessage = "Password should contain at least one special case character.";
                return false;
            }
            else
            {
                return true;
            }
        }

How to automatically update an application without ClickOnce?

There are a lot of questions already about this, so I will refer you to those.

One thing you want to make sure to prevent the need for uninstallation, is that you use the same upgrade code on every release, but change the product code. These values are located in the Installshield project properties.

Some references:

How to add dividers and spaces between items in RecyclerView?

Use this class to set divider in your RecyclerView.

 public class GridSpacingItemDecoration extends RecyclerView.ItemDecoration {

        private int spanCount;
        private int spacing;
        private boolean includeEdge;

        public GridSpacingItemDecoration(int spanCount, int spacing, boolean includeEdge) {
            this.spanCount = spanCount;
            this.spacing = spacing;
            this.includeEdge = includeEdge;
        }

        @Override
        public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
            int position = parent.getChildAdapterPosition(view); // item position
            int column = position % spanCount; // item column

            if (includeEdge) {
                outRect.left = spacing - column * spacing / spanCount; // spacing - column * ((1f / spanCount) * spacing)
                outRect.right = (column + 1) * spacing / spanCount; // (column + 1) * ((1f / spanCount) * spacing)

                if (position < spanCount) { // top edge
                    outRect.top = spacing;
                }
                outRect.bottom = spacing; // item bottom
            } else {
                outRect.left = column * spacing / spanCount; // column * ((1f / spanCount) * spacing)
                outRect.right = spacing - (column + 1) * spacing / spanCount; // spacing - (column + 1) * ((1f /    spanCount) * spacing)
                if (position >= spanCount) {
                    outRect.top = spacing; // item top
                }
            }
        }
    }

Get difference between two lists

We can calculate intersection minus union of lists:

temp1 = ['One', 'Two', 'Three', 'Four']
temp2 = ['One', 'Two', 'Five']

set(temp1+temp2)-(set(temp1)&set(temp2))

Out: set(['Four', 'Five', 'Three']) 

Node.js: get path from the request

You can use this in app.js file .

var apiurl = express.Router();
apiurl.use(function(req, res, next) {
    var fullUrl = req.protocol + '://' + req.get('host') + req.originalUrl;
    next();
});
app.use('/', apiurl);

jQuery check if attr = value

Just remove the .val(). Like:

if ( $('html').attr('lang') == 'fr-FR' ) {
    // do this
} else {
    // do that
}

Return Result from Select Query in stored procedure to a List

 SqlConnection connection = new SqlConnection(ConnectionString);

 command = new SqlCommand("TestProcedure", connection);
 command.CommandType = System.Data.CommandType.StoredProcedure;

 connection.Open();

 DataTable dt = new DataTable();

 dt.Load(command.ExecuteReader());

 gvGrid.DataSource = dt;
 gvGrid.DataBind();

Inline list initialization in VB.NET

Collection initializers are only available in VB.NET 2010, released 2010-04-12:

Dim theVar = New List(Of String) From { "one", "two", "three" }

Write applications in C or C++ for Android?

Native C/c++ Files libstdc++.* from your Ubuntu are x86 (or x86_64) binaries but Android devices and emulators are ARM. Of course, this will not work anyway, even if you'll set correct soname. This is very naive way which leads nowhere. Android has very limited support of C++ meaning there is no exceptions, standard C++ library (including STL) and RTTI. If you need such functionality, use my custom NDK distribution from

http://crystax.net/android/ndk.php - it support full C++ features listed above.

Why is there error: undefined reference to '__cxa_end_cleanup' link error. Android stlport

time. Because there is no link to libstdc + +. A. So wrong.

Because it uses some static library, it is necessary to link the full libstdc + +. A. Can

http://crystax.net/android/ndk.php here to download the package

sources \ cxx-stl \ gnu-libstdc + + \ libs \ armeabi directory.

Android on its own libstdc + + support is limited, it must be linked to a complete libstdc + +. A the job.

Add file in Android.mk LOCAL_LDFLAGS = $ (LOCAL_PATH) / libs / libcurl.a \

 $ (LOCAL_PATH) / libs / liblua.a \
 `$ (LOCAL_PATH) / libs / libstdc + +. A`  

And LOCAL_CPPFLAGS + =-lstdc + +-fexceptions can be compiled

What are the most-used vim commands/keypresses?

@Greg Hewgill's cheatsheet is very good. I started my switch from TextMate a few months ago. Now I'm as productive as I was with TM and constantly amazed by Vim's power.

Here is how I switched. Maybe it can be useful to you.

Grosso modo, I don't think it's a good idea to do a radical switch. Vim is very different and it's best to go progressively.

And to answer your subquestion, yes, I use all of iaIAoO everyday to enter insert mode. It certainly seems weird at first but you don't really think about it after a while.

Some commands incredibly useful for any programming related tasks:

  • r and R to replace characters
  • <C-a> and <C-x>to increase and decrease numbers
  • cit to change the content of an HTML tag, and its variants (cat, dit, dat, ci(, etc.)
  • <C-x><C-o> (mapped to ,,) for omnicompletion
  • visual block selection with <C-v>
  • and so on…

Once you are accustomed to the Vim way it becomes really hard to not hit o or x all the time when editing text in some other editor or textfield.

How to specify the current directory as path in VBA?

If the path you want is the one to the workbook running the macro, and that workbook has been saved, then

ThisWorkbook.Path

is what you would use.

Increase max execution time for php

Try to set a longer max_execution_time:

<IfModule mod_php5.c>
    php_value max_execution_time 300
</IfModule>

<IfModule mod_php7.c>
    php_value max_execution_time 300
</IfModule>

Unknown URL content://downloads/my_downloads

The exception is caused by disabled Download Manager. And there is no way to activate/deactivate Download Manager directly, since it's system application and we don't have access to it.

Only alternative way is redirect user to settings of Download Manager Application.

try {
     //Open the specific App Info page:
     Intent intent = new Intent(android.provider.Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
     intent.setData(Uri.parse("package:" + "com.android.providers.downloads"));
     startActivity(intent);

} catch ( ActivityNotFoundException e ) {
     e.printStackTrace();

     //Open the generic Apps page:
     Intent intent = new Intent(android.provider.Settings.ACTION_MANAGE_APPLICATIONS_SETTINGS);
     startActivity(intent);
}

How to select Python version in PyCharm?

I think you are saying that you have python2 and python3 installed and have added a reference to each version under Pycharm > Settings > Project Interpreter

What I think you are asking is how do you have some projects run with Python 2 and some projects running with Python 3.

If so, you can look under Run > Edit Configurations

PyCharm Run > Edit Configurations

How to get HttpRequestMessage data

In case you want to cast to a class and not just a string:

YourClass model = await request.Content.ReadAsAsync<YourClass>();

How to use a variable from a cursor in the select statement of another cursor in pl/sql

You can certainly do something like

SQL> ed
Wrote file afiedt.buf

  1  begin
  2    for d in (select * from dept)
  3    loop
  4      for e in (select * from emp where deptno=d.deptno)
  5      loop
  6        dbms_output.put_line( 'Employee ' || e.ename ||
  7                              ' in department ' || d.dname );
  8      end loop;
  9    end loop;
 10* end;
SQL> /
Employee CLARK in department ACCOUNTING
Employee KING in department ACCOUNTING
Employee MILLER in department ACCOUNTING
Employee smith in department RESEARCH
Employee JONES in department RESEARCH
Employee SCOTT in department RESEARCH
Employee ADAMS in department RESEARCH
Employee FORD in department RESEARCH
Employee ALLEN in department SALES
Employee WARD in department SALES
Employee MARTIN in department SALES
Employee BLAKE in department SALES
Employee TURNER in department SALES
Employee JAMES in department SALES

PL/SQL procedure successfully completed.

Or something equivalent using explicit cursors.

SQL> ed
Wrote file afiedt.buf

  1  declare
  2    cursor dept_cur
  3        is select *
  4             from dept;
  5    d dept_cur%rowtype;
  6    cursor emp_cur( p_deptno IN dept.deptno%type )
  7        is select *
  8             from emp
  9            where deptno = p_deptno;
 10    e emp_cur%rowtype;
 11  begin
 12    open dept_cur;
 13    loop
 14      fetch dept_cur into d;
 15      exit when dept_cur%notfound;
 16      open emp_cur( d.deptno );
 17      loop
 18        fetch emp_cur into e;
 19        exit when emp_cur%notfound;
 20        dbms_output.put_line( 'Employee ' || e.ename ||
 21                              ' in department ' || d.dname );
 22      end loop;
 23      close emp_cur;
 24    end loop;
 25    close dept_cur;
 26* end;
 27  /
Employee CLARK in department ACCOUNTING
Employee KING in department ACCOUNTING
Employee MILLER in department ACCOUNTING
Employee smith in department RESEARCH
Employee JONES in department RESEARCH
Employee SCOTT in department RESEARCH
Employee ADAMS in department RESEARCH
Employee FORD in department RESEARCH
Employee ALLEN in department SALES
Employee WARD in department SALES
Employee MARTIN in department SALES
Employee BLAKE in department SALES
Employee TURNER in department SALES
Employee JAMES in department SALES

PL/SQL procedure successfully completed.

However, if you find yourself using nested cursor FOR loops, it is almost always more efficient to let the database join the two results for you. After all, relational databases are really, really good at joining. I'm guessing here at what your tables look like and how they relate based on the code you posted but something along the lines of

FOR x IN (SELECT *
            FROM all_users,
                 org
           WHERE length(all_users.username) = 3
             AND all_users.username = org.username )
LOOP
  <<do something>>
END LOOP;

Filtering JSON array using jQuery grep()

var data = {
    "items": [{
        "id": 1,
        "category": "cat1"
    }, {
        "id": 2,
        "category": "cat2"
    }, {
        "id": 3,
        "category": "cat1"
    }]
};

var returnedData = $.grep(data.items, function (element, index) {
    return element.id == 1;
});


alert(returnedData[0].id + "  " + returnedData[0].category);

The returnedData is returning an array of objects, so you can access it by array index.

http://jsfiddle.net/wyfr8/913/

IOCTL Linux device driver

The ioctl function is useful for implementing a device driver to set the configuration on the device. e.g. a printer that has configuration options to check and set the font family, font size etc. ioctl could be used to get the current font as well as set the font to a new one. A user application uses ioctl to send a code to a printer telling it to return the current font or to set the font to a new one.

int ioctl(int fd, int request, ...)
  1. fd is file descriptor, the one returned by open;
  2. request is request code. e.g GETFONT will get the current font from the printer, SETFONT will set the font on the printer;
  3. the third argument is void *. Depending on the second argument, the third may or may not be present, e.g. if the second argument is SETFONT, the third argument can be the font name such as "Arial";

int request is not just a macro. A user application is required to generate a request code and the device driver module to determine which configuration on device must be played with. The application sends the request code using ioctl and then uses the request code in the device driver module to determine which action to perform.

A request code has 4 main parts

    1. A Magic number - 8 bits
    2. A sequence number - 8 bits
    3. Argument type (typically 14 bits), if any.
    4. Direction of data transfer (2 bits).  

If the request code is SETFONT to set font on a printer, the direction for data transfer will be from user application to device driver module (The user application sends the font name "Arial" to the printer). If the request code is GETFONT, direction is from printer to the user application.

In order to generate a request code, Linux provides some predefined function-like macros.

1._IO(MAGIC, SEQ_NO) both are 8 bits, 0 to 255, e.g. let us say we want to pause printer. This does not require a data transfer. So we would generate the request code as below

#define PRIN_MAGIC 'P'
#define NUM 0
#define PAUSE_PRIN __IO(PRIN_MAGIC, NUM) 

and now use ioctl as

ret_val = ioctl(fd, PAUSE_PRIN);

The corresponding system call in the driver module will receive the code and pause the printer.

  1. __IOW(MAGIC, SEQ_NO, TYPE) MAGIC and SEQ_NO are the same as above, and TYPE gives the type of the next argument, recall the third argument of ioctl is void *. W in __IOW indicates that the data flow is from user application to driver module. As an example, suppose we want to set the printer font to "Arial".
#define PRIN_MAGIC 'S'
#define SEQ_NO 1
#define SETFONT __IOW(PRIN_MAGIC, SEQ_NO, unsigned long)

further,

char *font = "Arial";
ret_val = ioctl(fd, SETFONT, font); 

Now font is a pointer, which means it is an address best represented as unsigned long, hence the third part of _IOW mentions type as such. Also, this address of font is passed to corresponding system call implemented in device driver module as unsigned long and we need to cast it to proper type before using it. Kernel space can access user space and hence this works. other two function-like macros are __IOR(MAGIC, SEQ_NO, TYPE) and __IORW(MAGIC, SEQ_NO, TYPE) where the data flow will be from kernel space to user space and both ways respectively.

Please let me know if this helps!

How to accept Date params in a GET request to Spring MVC Controller?

This is what I did to get formatted date from front end

  @RequestMapping(value = "/{dateString}", method = RequestMethod.GET)
  @ResponseBody
  public HttpStatus getSomething(@PathVariable @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) String dateString) {
   return OK;
  }

You can use it to get what you want.

Split Strings into words with multiple word boundary delimiters

I had a similar dilemma and didn't want to use 're' module.

def my_split(s, seps):
    res = [s]
    for sep in seps:
        s, res = res, []
        for seq in s:
            res += seq.split(sep)
    return res

print my_split('1111  2222 3333;4444,5555;6666', [' ', ';', ','])
['1111', '', '2222', '3333', '4444', '5555', '6666']

How to remove all the occurrences of a char in c++ string

Basically, replace replaces a character with another and '' is not a character. What you're looking for is erase.

See this question which answers the same problem. In your case:

#include <algorithm>
str.erase(std::remove(str.begin(), str.end(), 'a'), str.end());

Or use boost if that's an option for you, like:

#include <boost/algorithm/string.hpp>
boost::erase_all(str, "a");

All of this is well-documented on reference websites. But if you didn't know of these functions, you could easily do this kind of things by hand:

std::string output;
output.reserve(str.size()); // optional, avoids buffer reallocations in the loop
for(size_t i = 0; i < str.size(); ++i)
  if(str[i] != 'a') output += str[i];

No line-break after a hyphen

Late to the party, but I think this is actually the most elegant. Use the WORD JOINER Unicode character &#8288; on either side of your hyphen, or em dash, or any character.

So, like so:

&#8288;—&#8288;

This will join the symbol on both ends to its neighbors (without adding a space) and prevent line breaking.

Good tool to visualise database schema?

SchemaBall is doing visualisation its own interesting way.

When do you use the "this" keyword?

Any time you need a reference to the current object.

One particularly handy scenario is when your object is calling a function and wants to pass itself into it.

Example:

void onChange()
{
    screen.draw(this);
}

Spacing between elements

It depends on what exactly you want to accomplish. Let's assume you have this structure:

<p style="width:400px;">
    Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Donec quam felis, ultricies nec, pellentesque eu, pretium quis, sem. Nulla consequat massa quis enim. Donec pede justo, fringilla vel, aliquet nec, vulputate eget, arcu. In enim justo, rhoncus ut, imperdiet a, venenatis vitae, justo. Nullam dictum felis eu pede mollis pretium. Integer tincidunt. Cras dapibus. Vivamus elementum semper nisi. Aenean vulputate eleifend tellus. Aenean leo ligula, porttitor eu, consequat vitae, eleifend ac, enim. Aliquam lorem ante, dapibus in, viverra quis, feugiat a, tellus. Phasellus viverra nulla ut metus varius laoreet.
</p>

If you want the space between the single lines to be bigger, you should increase

line-height

If you want the space at the end to be bigger, you should increase

margin-bottom

If you want the space at the end to be bigger, but have the background fill the space (or the border around the space) use

padding-bottom

Of course, there are also the corresponding values for space on the top:

padding-top
margin-top

Some examples:

<p style="line-height: 30px; width: 300px; border: 1px solid black;">
     Space between single lines 
     Space between single lines
     Space between single lines
     Space between single lines
     Space between single lines
     Space between single lines
     Space between single lines
     Space between single lines
</p>
<p style="margin-bottom: 30px; width: 300px; border: 1px solid black;">
     Space at the bottom, outside of the border
     Space at the bottom, outside of the border
     Space at the bottom, outside of the border
     Space at the bottom, outside of the border
     Space at the bottom, outside of the border
     Space at the bottom, outside of the border
     Space at the bottom, outside of the border
     Space at the bottom, outside of the border
     Space at the bottom, outside of the border
</p>
<p style="padding-bottom: 30px; width: 300px; border: 1px solid black;">
     Space at the bottom, inside of the border
     Space at the bottom, inside of the border
     Space at the bottom, inside of the border
     Space at the bottom, inside of the border
     Space at the bottom, inside of the border
     Space at the bottom, inside of the border
     Space at the bottom, inside of the border
     Space at the bottom, inside of the border
     Space at the bottom, inside of the border
</p>

here you can see this code in action: http://jsfiddle.net/ramsesoriginal/H7qxd/

Of course you should put your styles in a separate stylesheet, the inline code was just to show the effect.

here you have a little schematic demonstration of what which value affects:

                                   line-height
           content                 +
                                   |      padding-bottom
                  <----------------+      +
           content                        |    border-bottom
                                          |    +
                                          |    |
        +-------------+<------------------+    |       margin-bottom
                                               |       +
     +===================+ <-------------------+       |
                                                       |
  +-------------------------+ <------------------------+

What is "Connect Timeout" in sql server connection string?

By default connection timeout is 240 but if you are faceing the problem of connection time out then you can increase upto "300" "Connection Timeout=300"

NUnit Unit tests not showing in Test Explorer with Test Adapter installed

If you are using VS 2017 and .net core ,as said here, you should add references to the test framework NUnit 3.6.1, to the test runner NUnit3TestAdapter 3.8.0-alpha1 and to the test SDK Microsoft.NET.Test.Sdk 15.0.0.

How to deploy a war file in JBoss AS 7?

Actually, for the latest JBOSS 7 AS, we need a .dodeploy marker even for archives. So add a marker to trigger the deployment.

In my case, I added a Hello.war.deployed file in the same directory and then everything worked fine.

Hope this helps someone!

Using atan2 to find angle between two vectors

angle(vector.b,vector.a)=pi/2*((1+sgn(xa))*(1-sgn(ya^2))-(1+sgn(xb))*(1-sgn(yb^2)))

+pi/4*((2+sgn(xa))*sgn(ya)-(2+sgn(xb))*sgn(yb))

+sgn(xa*ya)*atan((abs(xa)-abs(ya))/(abs(xa)+abs(ya)))

-sgn(xb*yb)*atan((abs(xb)-abs(yb))/(abs(xb)+abs(yb)))

xb,yb and xa,ya are the coordinates of the two vectors

Set attribute without value

The attr() function is also a setter function. You can just pass it an empty string.

$('body').attr('data-body','');

An empty string will simply create the attribute with no value.

<body data-body>

Reference - http://api.jquery.com/attr/#attr-attributeName-value

attr( attributeName , value )

Is there a way to get the git root directory in one command?

Here is a script that I've written that handles both cases: 1) repository with a workspace, 2) bare repository.

https://gist.github.com/jdsumsion/6282953

git-root (executable file in your path):

#!/bin/bash
GIT_DIR=`git rev-parse --git-dir` &&
(
  if [ `basename $GIT_DIR` = ".git" ]; then
    # handle normal git repos (with a .git dir)
    cd $GIT_DIR/..
  else
    # handle bare git repos (the repo IS a xxx.git dir)
    cd $GIT_DIR
  fi
  pwd
)

Hopefully this is helpful.

How SQL query result insert in temp table?

In MySQL:

create table temp as select * from original_table

Systrace for Windows

strace is available from Cygwin in the cygwin package. You can download it from a Cygwin mirror, for example:

http://mirrors.sonic.net/cygwin/x86_64/release/cygwin/cygwin-2.0.2-1.tar.xz
#      |                      |                              |     |
#      +-----------+----------+                              +--+--+
#                  |                                            |
#               mirror                                       version

strace is one of the few Cygwin programs that does not rely on the Cygwin DLL, so you should be able to just copy strace.exe to where you want and use it.

What causes a java.lang.StackOverflowError

One of the (optional) arguments to the JVM is the stack size. It's -Xss. I don't know what the default value is, but if the total amount of stuff on the stack exceeds that value, you'll get that error.

Generally, infinite recursion is the cause of this, but if you were seeing that, your stack trace would have more than 5 frames.

Try adding a -Xss argument (or increasing the value of one) to see if this goes away.

ModelState.AddModelError - How can I add an error that isn't for a property?

Putting the model dot property in strings worked for me: ModelState.AddModelError("Item1.Month", "This is not a valid date");

TypeError: Converting circular structure to JSON in nodejs

I came across this issue when not using async/await on a asynchronous function (api call). Hence adding them / using the promise handlers properly cleared the error.

Is it possible to opt-out of dark mode on iOS 13?

Here are a few tips and tricks which you can use in your app to support or bypass the dark mode.

First tip: To override the ViewController style

you can override the interface style of UIViewController by

1: overrideUserInterfaceStyle = .dark //For dark mode

2: overrideUserInterfaceStyle = .light //For light mode

class ViewController: UIViewController {
    override func viewDidLoad() {
        super.viewDidLoad()
        overrideUserInterfaceStyle = .light    
    }
}

Second tip: Adding a key in info.plist

Simply you can add a new key

UIUserInterfaceStyle

in your app info.plist and set its value to Light or Dark. this will override the app default style to the value you provide. You don't have to add overrideUserInterfaceStyle = .light this line in every viewController, just one line in info.plist that’s it.

Check if value exists in the array (AngularJS)

You can use indexOf(). Like:

var Color = ["blue", "black", "brown", "gold"];
var a = Color.indexOf("brown");
alert(a);

The indexOf() method searches the array for the specified item, and returns its position. And return -1 if the item is not found.


If you want to search from end to start, use the lastIndexOf() method:

    var Color = ["blue", "black", "brown", "gold"];
    var a = Color.lastIndexOf("brown");
    alert(a);

The search will start at the specified position, or at the end if no start position is specified, and end the search at the beginning of the array.

Returns -1 if the item is not found.

Validate SSL certificates with Python

pyOpenSSL is an interface to the OpenSSL library. It should provide everything you need.

What is code coverage and how do YOU measure it?

In the previous answers Code coverage has been explained well . I am just adding some knowledge related to tools if your are working on iOS and OSX platforms, Xcode provides the facility to test and monitor code coverage.

Reference Links:

https://developer.apple.com/library/archive/documentation/DeveloperTools/Conceptual/testing_with_xcode/chapters/07-code_coverage.html

https://medium.com/zendesk-engineering/code-coverage-and-xcode-6b2fb8756a51

Both are helpful links for learning and exploring code coverage with Xcode.

Android Studio: Default project directory

I found an easy way:

  1. Open a new project;
  2. Change the project location name by typing and not the Browse... button;
  3. The Next button will appear now.

How to solve SyntaxError on autogenerated manage.py?

Its a simple solution actually one i just ran into. Did you activate your virtual environment?

my terminal screenshot

Redirect output of mongo query to a csv file

I use the following technique. It makes it easy to keep the column names in sync with the content:

var cursor = db.getCollection('Employees.Details').find({})

var header = []
var rows = []

var firstRow = true
cursor.forEach((doc) => 
{
    var cells = []
    
    if (firstRow) header.push("employee_number")
    cells.push(doc.EmpNum.valueOf())

    if (firstRow) header.push("name")
    cells.push(doc.FullName.valueOf())    

    if (firstRow) header.push("dob")
    cells.push(doc.DateOfBirth.valueOf())   
    
    row = cells.join(',')
    rows.push(row)    

    firstRow =  false
})

print(header.join(','))
print(rows.join('\n'))

Operand type clash: int is incompatible with date + The INSERT statement conflicted with the FOREIGN KEY constraint

This expression 12-4-2005 is a calculated int and the value is -1997. You should do like this instead '2005-04-12' with the ' before and after.

How can you get the active users connected to a postgreSQL database via SQL?

(question) Don't you get that info in

select * from pg_user;

or using the view pg_stat_activity:

select * from pg_stat_activity;

Added:

the view says:

One row per server process, showing database OID, database name, process ID, user OID, user name, current query, query's waiting status, time at which the current query began execution, time at which the process was started, and client's address and port number. The columns that report data on the current query are available unless the parameter stats_command_string has been turned off. Furthermore, these columns are only visible if the user examining the view is a superuser or the same as the user owning the process being reported on.

can't you filter and get that information? that will be the current users on the Database, you can use began execution time to get all queries from last 5 minutes for example...

something like that.

Nodejs cannot find installed module on Windows

if you are in the windows7 platform maybe you should change the NODE_PATH like this: %AppData%\npm\node_modules

How to generate a random number between 0 and 1?

Have you tried with: replacing ((rand() % 10000) / 10000.0), with:(rand() % 2). This worked for me!

So you could do something like this:

double r2()
{
     srand(time(NULL));
     return(rand() % 2);
}

SQL Not Like Statement not working

Just come across this, the answer is simple, use ISNULL. SQL won't return rows if the field you are testing has no value (in some of the records) when doing a text comparison search, eg:

WHERE wpp.comment NOT LIKE '%CORE%'

So, you have temporarily substitute a value in the null (empty) records by using the ISNULL command, eg

WHERE (ISNULL(wpp.comment,'')) NOT LIKE '%CORE%'

This will then show all your records that have nulls and omit any that have your matching criteria. If you wanted, you could put something in the commas to help you remember, eg

WHERE (ISNULL(wpp.comment,'some_records_have_no_value')) NOT LIKE '%CORE%'

?: operator (the 'Elvis operator') in PHP

See the docs:

Since PHP 5.3, it is possible to leave out the middle part of the ternary operator. Expression expr1 ?: expr3 returns expr1 if expr1 evaluates to TRUE, and expr3 otherwise.

How to get calendar Quarter from a date in TSQL

Here is another option. Use a CTE to define the months of the quarter and then join to it to determine the quarter:

WITH Quarters AS (
   SELECT Q = 'Q1', MonthBegin = 1, MonthEnd = 3 UNION
   SELECT Q = 'Q2', MonthBegin = 4, MonthEnd = 6 UNION
   SELECT Q = 'Q3', MonthBegin = 7, MonthEnd = 9 UNION
   SELECT Q = 'Q4', MonthBegin = 10, MonthEnd = 12
)
SELECT
   [Year] = DATEPART(yyyy, CONVERT(DATETIME, Dates.[date])),
   [Quarter] = CONVERT(VARCHAR(4), DATEPART(yyyy, CONVERT(DATETIME, Dates.[date]))) + '-' + q.Q
FROM
   (VALUES
       ('20080102'),
       ('20070821')
   ) AS Dates ([date])
   INNER JOIN Quarters q ON
      DATEPART(m, CONVERT(DATETIME, Dates.[date])) >= q.MonthBegin AND
      DATEPART(m, CONVERT(DATETIME, Dates.[date])) <= q.MonthEnd;

Returns:

Year  Quarter
----- ----------
2008  2008-Q1
2007  2007-Q3

SQL Fiddle

Handle column type of int (04/23/2014):

WITH Quarters AS (
    SELECT Q = 'Q1', MonthBegin = 1, MonthEnd = 3 UNION
    SELECT Q = 'Q2', MonthBegin = 4, MonthEnd = 6 UNION
    SELECT Q = 'Q3', MonthBegin = 7, MonthEnd = 9 UNION
    SELECT Q = 'Q4', MonthBegin = 10, MonthEnd = 12
)
SELECT
    [Year] = DATEPART(yyyy, CONVERT(DATETIME, CONVERT(VARCHAR(8), Dates.[date]))),
    [Quarter] = CONVERT(VARCHAR(4), DATEPART(yyyy, CONVERT(DATETIME, CONVERT(VARCHAR(8), Dates.[date])))) + '-' + q.Q
FROM
    (VALUES
        (20080102),
        (20070821)
    ) AS Dates ([date])
    INNER JOIN Quarters q ON
        DATEPART(m, CONVERT(DATETIME, CONVERT(VARCHAR(8), Dates.[date]))) >= q.MonthBegin AND
        DATEPART(m, CONVERT(DATETIME, CONVERT(VARCHAR(8), Dates.[date]))) <= q.MonthEnd;

Postgres password authentication fails

Assuming, that you have root access on the box you can do:

sudo -u postgres psql

If that fails with a database "postgres" does not exists this block.

sudo -u postgres psql template1

Then sudo nano /etc/postgresql/11/main/pg_hba.conf file

local   all         postgres                          ident

For newer versions of PostgreSQL ident actually might be peer.

Inside the psql shell you can give the DB user postgres a password:

ALTER USER postgres PASSWORD 'newPassword';

is there any PHP function for open page in new tab

You can use both PHP and javascript. Perform your php codes in the backend and redirect to a php page. On the php page you redirected to add the code below:

<?php if(condition_to_check_for){ ?>

    <script type="text/javascript">
       window.open('url_goes_here', '_blank');
    </script>

<?  } ?>

Difference between scaling horizontally and vertically for databases

Let's start with the need for scaling that is increasing resources so that your system can now handle more requests than it earlier could.

When you realise your system is getting slow and is unable to handle the current number of requests, you need to scale the system.

This provides you with two options. Either you increase the resources in the server which you are using currently, i.e, increase the amount of RAM, CPU, GPU and other resources. This is known as vertical scaling.

Vertical scaling is typically costly. It does not make the system fault tolerant, i.e if you are scaling application running with single server, if that server goes down, your system will go down. Also the amount of threads remains the same in vertical scaling. Vertical scaling may require your system to go down for a moment when process takes place. Increasing resources on a server requires a restart and put your system down.

Another solution to this problem is increasing the amount of servers present in the system. This solution is highly used in the tech industry. This will eventually decrease the request per second rate in each server. If you need to scale the system, just add another server, and you are done. You would not be required to restart the system. Number of threads in each system decreases leading to high throughput. To segregate the requests, equally to each of the application server, you need to add load balancer which would act as reverse proxy to the web servers. This whole system can be called as a single cluster. Your system may contain a large number of requests which would require more amount of clusters like this.

Hope you get the whole concept of introducing scaling to the system.

How can I divide one column of a data frame through another?

There are a plethora of ways in which this can be done. The problem is how to make R aware of the locations of the variables you wish to divide.

Assuming

d <- read.table(text = "263807.0    1582
196190.5    1016
586689.0    3479
")
names(d) <- c("min", "count2.freq")
> d
       min count2.freq
1 263807.0        1582
2 196190.5        1016
3 586689.0        3479

My preferred way

To add the desired division as a third variable I would use transform()

> d <- transform(d, new = min / count2.freq)
> d
       min count2.freq      new
1 263807.0        1582 166.7554
2 196190.5        1016 193.1009
3 586689.0        3479 168.6373

The basic R way

If doing this in a function (i.e. you are programming) then best to avoid the sugar shown above and index. In that case any of these would do what you want

## 1. via `[` and character indexes
d[, "new"] <- d[, "min"] / d[, "count2.freq"]

## 2. via `[` with numeric indices
d[, 3] <- d[, 1] / d[, 2]

## 3. via `$`
d$new <- d$min / d$count2.freq

All of these can be used at the prompt too, but which is easier to read:

d <- transform(d, new = min / count2.freq)

or

d$new <- d$min / d$count2.freq ## or any of the above examples

Hopefully you think like I do and the first version is better ;-)

The reason we don't use the syntactic sugar of tranform() et al when programming is because of how they do their evaluation (look for the named variables). At the top level (at the prompt, working interactively) transform() et al work just fine. But buried in function calls or within a call to one of the apply() family of functions they can and often do break.

Likewise, be careful using numeric indices (## 2. above); if you change the ordering of your data, you will select the wrong variables.

The preferred way if you don't need replacement

If you are just wanting to do the division (rather than insert the result back into the data frame, then use with(), which allows us to isolate the simple expression you wish to evaluate

> with(d, min / count2.freq)
[1] 166.7554 193.1009 168.6373

This is again much cleaner code than the equivalent

> d$min / d$count2.freq
[1] 166.7554 193.1009 168.6373

as it explicitly states that "using d, execute the code min / count2.freq. Your preference may be different to mine, so I have shown all options.

Resizing a button

Another alternative is that you are allowed to have multiple classes in a tag. Consider:

 <div class="button big">This is a big button</div>
 <div class="button small">This is a small button</div>

And the CSS:

 .button {
     /* all your common button styles */
 }

 .big {
     height: 60px;
     width: 100px;
 }
 .small {
     height: 40px;
     width: 70px;
 }

and so on.

Where are logs located?

You should be checking the root directory and not the app directory.

Look in $ROOT/storage/laravel.log not app/storage/laravel.log, where root is the top directory of the project.

What REST PUT/POST/DELETE calls should return by a convention?

I like Alfonso Tienda responce from HTTP status code for update and delete?

Here are some Tips:

DELETE

  • 200 (if you want send some additional data in the Response) or 204 (recommended).

  • 202 Operation deleted has not been committed yet.

  • If there's nothing to delete, use 204 or 404 (DELETE operation is idempotent, delete an already deleted item is operation successful, so you can return 204, but it's true that idempotent doesn't necessarily imply the same response)

Other errors:

  • 400 Bad Request (Malformed syntax or a bad query is strange but possible).
  • 401 Unauthorized Authentication failure
  • 403 Forbidden: Authorization failure or invalid Application ID.
  • 405 Not Allowed. Sure.
  • 409 Resource Conflict can be possible in complex systems.
  • And 501, 502 in case of errors.

PUT

If you're updating an element of a collection

  • 200/204 with the same reasons as DELETE above.
  • 202 if the operation has not been commited yet.

The referenced element doesn't exists:

  • PUT can be 201 (if you created the element because that is your behaviour)

  • 404 If you don't want to create elements via PUT.

  • 400 Bad Request (Malformed syntax or a bad query more common than in case of DELETE).

  • 401 Unauthorized

  • 403 Forbidden: Authentication failure or invalid Application ID.

  • 405 Not Allowed. Sure.

  • 409 Resource Conflict can be possible in complex systems, as in DELETE.

  • 422 Unprocessable entity It helps to distinguish between a "Bad request" (e.g. malformed XML/JSON) and invalid field values

  • And 501, 502 in case of errors.

ssh: Could not resolve hostname [hostname]: nodename nor servname provided, or not known

It seems that some apps won't read symlinked /etc/hosts (on macOS at least), you need to hardlink it.

ln /path/to/hosts_file /etc/hosts

How to change the commit author for one specific commit?

You can change author of last commit using the command below.

git commit --amend --author="Author Name <[email protected]>"

However, if you want to change more than one commits author name, it's a bit tricky. You need to start an interactive rebase then mark commits as edit then amend them one by one and finish.

Start rebasing with git rebase -i. It will show you something like this.

https://monosnap.com/file/G7sdn66k7JWpT91uiOUAQWMhPrMQVT.png

Change the pick keyword to edit for the commits you want to change the author name.

https://monosnap.com/file/dsq0AfopQMVskBNknz6GZZwlWGVwWU.png

Then close the editor. For the beginners, hit Escape then type :wq and hit Enter.

Then you will see your terminal like nothing happened. Actually you are in the middle of an interactive rebase. Now it's time to amend your commit's author name using the command above. It will open the editor again. Quit and continue rebase with git rebase --continue. Repeat the same for the commit count you want to edit. You can make sure that interactive rebase finished when you get the No rebase in progress? message.

Difference between e.target and e.currentTarget

  • e.target is element, which you f.e. click
  • e.currentTarget is element with added event listener.

If you click on child element of button, its better to use currentTarget to detect buttons attributes, in CH its sometimes problem to use e.target.

HTML5 Video not working in IE 11

I believe IE requires the H.264 or MPEG-4 codec, which it seems like you don't specify/include. You can always check for browser support by using HTML5Please and Can I use.... Both sites usually have very up-to-date information about support, polyfills, and advice on how to take advantage of new technology.

Angular2 router (@angular/router), how to set default route?

V2.0.0 and later

See also see https://angular.io/guide/router#the-default-route-to-heroes

RouterConfig = [
  { path: '', redirectTo: '/heroes', pathMatch: 'full' },
  { path: 'heroes', component: HeroComponent,
    children: [
      { path: '', redirectTo: '/detail', pathMatch: 'full' },
      { path: 'detail', component: HeroDetailComponent }
    ] 
  }
];

There is also the catch-all route

{ path: '**', redirectTo: '/heroes', pathMatch: 'full' },

which redirects "invalid" urls.

V3-alpha (vladivostok)

Use path / and redirectTo

RouterConfig = [
  { path: '/', redirectTo: 'heroes', terminal: true },
  { path: 'heroes', component: HeroComponent,
    children: [
      { path: '/', redirectTo: 'detail', terminal: true },
      { path: 'detail', component: HeroDetailComponent }
    ] 
  }
];

RC.1 @angular/router

The RC router doesn't yet support useAsDefault. As a workaround you can navigate explicitely.

In the root component

export class AppComponent {
  constructor(router:Router) {
    router.navigate(['/Merge']);
  }
}

for other components

export class OtherComponent {
  constructor(private router:Router) {}

  routerOnActivate(curr: RouteSegment, prev?: RouteSegment, currTree?: RouteTree, prevTree?: RouteTree) : void {
    this.router.navigate(['SomeRoute'], curr);
  }
}

What is the fastest way to compare two sets in Java?

I would put the secondSet in a HashMap before the comparison. This way you will reduce the second list's search time to n(1). Like this:

HashMap<Integer,Record> hm = new HashMap<Integer,Record>(secondSet.size());
int i = 0;
for(Record secondRecord : secondSet){
    hm.put(i,secondRecord);
    i++;
}
for(Record firstRecord : firstSet){
    for(int i=0; i<secondSet.size(); i++){
    //use hm for comparison
    }
}

Origin http://localhost is not allowed by Access-Control-Allow-Origin

There are 2 calls that need to set the correct headers. Initially there is a preflight check so you need something like...

app.get('/item', item.list);
app.options('/item', item.preflight);

and then have the following functions...

exports.list = function (req, res) {
Items.allItems(function (err, items) {
    ...
        res.header('Access-Control-Allow-Origin', "*");     // TODO - Make this more secure!!
        res.header('Access-Control-Allow-Methods', 'GET,PUT,POST');
        res.header('Access-Control-Allow-Headers', 'Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept');
        res.send(items);
      }
   );
};

and for the pre-flight checks

exports.preflight = function (req, res) {
Items.allItems(function (err, items) {
        res.header('Access-Control-Allow-Origin', "*");     // TODO - Make this more secure!!
        res.header('Access-Control-Allow-Methods', 'GET,PUT,POST');
        res.header('Access-Control-Allow-Headers', 'Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept');
        res.send(200);
    }
  );
};

You can consolidate the res.header() code into a single function if you want.

Also as stated above, be careful of using res.header('Access-Control-Allow-Origin', "*") this means anyone can access your site!