Programs & Examples On #Floppy

Shortened from Floppy Disk(FD) or Floppy Disk Drive(FDD). Mainly referring to FDD - a device for reading and writing data to a floppy disk.

How to get the full path of the file from a file input

You cannot do so - the browser will not allow this because of security concerns. Although there are workarounds, the fact is that you shouldn't count on this working. The following Stack Overflow questions are relevant here:

In addition to these, the new HTML5 specification states that browsers will need to feed a Windows compatible fakepath into the input type="file" field, ostensibly for backward compatibility reasons.

So trying to obtain the path is worse then useless in newer browsers - you'll actually get a fake one instead.

Fully custom validation error message with Rails

Now, the accepted way to set the humanized names and custom error messages is to use locales.

# config/locales/en.yml
en:
  activerecord:
    attributes:
      user:
        email: "E-mail address"
    errors:
      models:
        user:
          attributes:
            email:
              blank: "is required"

Now the humanized name and the presence validation message for the "email" attribute have been changed.

Validation messages can be set for a specific model+attribute, model, attribute, or globally.

Is it possible to get only the first character of a String?

Answering for C++ 14,

Yes, you can get the first character of a string simply by the following code snippet.

string s = "Happynewyear";
cout << s[0];

if you want to store the first character in a separate string,

string s = "Happynewyear";
string c = "";
c.push_back(s[0]);
cout << c;

How to detect query which holds the lock in Postgres?

This modification of a_horse_with_no_name's answer will give you the blocking queries in addition to just the blocked sessions:

SELECT
    activity.pid,
    activity.usename,
    activity.query,
    blocking.pid AS blocking_id,
    blocking.query AS blocking_query
FROM pg_stat_activity AS activity
JOIN pg_stat_activity AS blocking ON blocking.pid = ANY(pg_blocking_pids(activity.pid));

Initialize a string variable in Python: "" or None?

Another way to initialize an empty string is by using the built-in str() function with no arguments.

str(object='')

Return a string containing a nicely printable representation of an object.

...

If no argument is given, returns the empty string, ''.

In the original example, that would look like this:

def __init__(self, mystr=str())
   self.mystr = mystr

Personally, I believe that this better conveys your intentions.

Notice by the way that str() itself sets a default parameter value of ''.

How do I install cURL on Windows?

You may find XAMPP at http://www.apachefriends.org/en/xampp.html

http://www.apachefriends.org/en/xampp-windows.html explains XMAPP for Windows.

Yes, there are 3 php.ini files after installation, one is for php4, one is for php5, and one is for apache. Please modify them accordingly.

WebDriver - wait for element using Java

We're having a lot of race conditions with elementToBeClickable. See https://github.com/angular/protractor/issues/2313. Something along these lines worked reasonably well even if a little brute force

Awaitility.await()
        .atMost(timeout)
        .ignoreException(NoSuchElementException.class)
        .ignoreExceptionsMatching(
            Matchers.allOf(
                Matchers.instanceOf(WebDriverException.class),
                Matchers.hasProperty(
                    "message",
                    Matchers.containsString("is not clickable at point")
                )
            )
        ).until(
            () -> {
                this.driver.findElement(locator).click();
                return true;
            },
            Matchers.is(true)
        );

SELECT with a Replace()

SELECT *
FROM Contacts
WHERE ContactId IN
    (SELECT a.ContactID
    FROM
        (SELECT ContactId, Replace(Postcode, ' ', '') AS P
        FROM Contacts
        WHERE Postcode LIKE '%N%W%1%0%1%') a
    WHERE a.P LIKE 'NW101%')

How to pass boolean parameter value in pipeline to downstream jobs?

In addition to Jesse Glick answer, if you want to pass string parameter then use:

build job: 'your-job-name', 
    parameters: [
        string(name: 'passed_build_number_param', value: String.valueOf(BUILD_NUMBER)),
        string(name: 'complex_param', value: 'prefix-' + String.valueOf(BUILD_NUMBER))
    ]

How to send cookies in a post request with the Python Requests library?

The latest release of Requests will build CookieJars for you from simple dictionaries.

import requests

cookies = {'enwiki_session': '17ab96bd8ffbe8ca58a78657a918558'}

r = requests.post('http://wikipedia.org', cookies=cookies)

Enjoy :)

Visual Studio Code always asking for git credentials

apart from adding the ssh config entries above

if windows

Set-Service ssh-agent -StartupType Automatic 

in powershell now the vs code should not prompt...

How to clear Flutter's Build cache?

Same issue with mine.

New to Flutter. I'm using VS build-in terminal to do flutter run, to run the app in iPhone. It gives me error Error when reading 'lib/student_model.dart': No such file..., which is an old code version in my code. I have changed it to lib/model/student_model.dart.

And I search this line 'lib/student_model.dart'in the project, it appears filekernel_snapshot.d` containing it. So, it build the project with old code version.

For me, Flutter clean is not working. Restart VS fix the issue, not sure the problem is due to Flutter or VS?

And I'm wondering if there is some command to just build flutter project without run?

Resource interpreted as stylesheet but transferred with MIME type text/html (seems not related with web server)

My issue was simpler than all the answers in this post.

I had to setup IIS to include static content.

enter image description here

Entity Framework: table without primary key

From a practical standpoint, every table--even a denormalized table like a warehouse table--should have a primary key. Or, failing that, it should at least have a unique, non-nullable index.

Without some kind of unique key, duplicate records can (and will) appear in the table, which is very problematic both for ORM layers and also for basic comprehension of the data. A table that has duplicate records is probably a symptom of bad design.

At the very least, the table should at least have an identity column. Adding an auto-generating ID column takes about 2 minutes in SQL Server and 5 minutes in Oracle. For that extra bit of effort, many, many problems will be avoided.

UnicodeEncodeError: 'charmap' codec can't encode characters

In Python 3.7, and running Windows 10 this worked (I am not sure whether it will work on other platforms and/or other versions of Python)

Replacing this line:

with open('filename', 'w') as f:

With this:

with open('filename', 'w', encoding='utf-8') as f:

The reason why it is working is because the encoding is changed to UTF-8 when using the file, so characters in UTF-8 are able to be converted to text, instead of returning an error when it encounters a UTF-8 character that is not suppord by the current encoding.

LINQ query to find if items in a list are contained in another list

bool doesL1ContainsL2 = l1.Intersect(l2).Count() == l2.Count;

L1 and L2 are both List<T>

How to use MapView in android using google map V2?

yes you can use MapView in v2... for further details you can get help from this

https://gist.github.com/joshdholtz/4522551


SomeFragment.java

public class SomeFragment extends Fragment implements OnMapReadyCallback{
 
    MapView mapView;
    GoogleMap map;
 
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View v = inflater.inflate(R.layout.some_layout, container, false);
 
        // Gets the MapView from the XML layout and creates it
        mapView = (MapView) v.findViewById(R.id.mapview);
        mapView.onCreate(savedInstanceState);
 
    
        mapView.getMapAsync(this);
        
 
        return v;
    }
 
   @Override
   public void onMapReady(GoogleMap googleMap) {
       map = googleMap;
       map.getUiSettings().setMyLocationButtonEnabled(false);
       map.setMyLocationEnabled(true);
       /*
       //in old Api Needs to call MapsInitializer before doing any CameraUpdateFactory call
        try {
            MapsInitializer.initialize(this.getActivity());
        } catch (GooglePlayServicesNotAvailableException e) {
            e.printStackTrace();
        } 
       */
        
        // Updates the location and zoom of the MapView
        /*CameraUpdate cameraUpdate = CameraUpdateFactory.newLatLngZoom(new LatLng(43.1, -87.9), 10);
        map.animateCamera(cameraUpdate);*/
        map.moveCamera(CameraUpdateFactory.newLatLng(new LatLng(43.1, -87.9)));

    }

    @Override
    public void onResume() {
        mapView.onResume();
        super.onResume();
    }


    @Override
    public void onPause() {
        super.onPause();
        mapView.onPause();
    }
 
    @Override
    public void onDestroy() {
        super.onDestroy();
        mapView.onDestroy();
    }
 
    @Override
    public void onLowMemory() {
        super.onLowMemory();
        mapView.onLowMemory();
    }
 
}

AndroidManifest.xml

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example"
    android:versionCode="1"
    android:versionName="1.0" >
    
    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="15" />
    
    <uses-permission android:name="android.permission.INTERNET"/>
    <uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES"/>
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
    
    <uses-feature
        android:glEsVersion="0x00020000"
        android:required="true"/>
    
    <permission
        android:name="com.example.permission.MAPS_RECEIVE"
        android:protectionLevel="signature"/>
    <uses-permission android:name="com.example.permission.MAPS_RECEIVE"/>
    
    <application
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        
        <meta-data
            android:name="com.google.android.maps.v2.API_KEY"
            android:value="your_key"/>
        
        <activity
            android:name=".HomeActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    
    </application>
 
</manifest>

some_layout.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent" >
    
    <com.google.android.gms.maps.MapView android:id="@+id/mapview"
        android:layout_width="fill_parent" 
        android:layout_height="fill_parent" />
 
</LinearLayout>

Can jQuery get all CSS styles associated with an element?

Why not use .style of the DOM element? It's an object which contains members such as width and backgroundColor.

Node Version Manager (NVM) on Windows

An alternative to nvm-windows, which is mentioned in other answers would be Nodist.

I've had some issues with nvm-windows and admin privileges, which Nodist doesn't seem to have.

How to modify list entries during for loop?

One more for loop variant, looks cleaner to me than one with enumerate():

for idx in range(len(list)):
    list[idx]=... # set a new value
    # some other code which doesn't let you use a list comprehension

Insert json file into mongodb

It happened to me couple of weeks back. The version of mongoimport was too old. Once i Updated to latest version it ran successfully and imported all documents.

Reference: http://docs.mongodb.org/master/tutorial/install-mongodb-on-ubuntu/?_ga=1.11365492.1588529687.1434379875

How can I pass a member function where a free function is expected?

There isn't anything wrong with using function pointers. However, pointers to non-static member functions are not like normal function pointers: member functions need to be called on an object which is passed as an implicit argument to the function. The signature of your member function above is, thus

void (aClass::*)(int, int)

rather than the type you try to use

void (*)(int, int)

One approach could consist in making the member function static in which case it doesn't require any object to be called on and you can use it with the type void (*)(int, int).

If you need to access any non-static member of your class and you need to stick with function pointers, e.g., because the function is part of a C interface, your best option is to always pass a void* to your function taking function pointers and call your member through a forwarding function which obtains an object from the void* and then calls the member function.

In a proper C++ interface you might want to have a look at having your function take templated argument for function objects to use arbitrary class types. If using a templated interface is undesirable you should use something like std::function<void(int, int)>: you can create a suitably callable function object for these, e.g., using std::bind().

The type-safe approaches using a template argument for the class type or a suitable std::function<...> are preferable than using a void* interface as they remove the potential for errors due to a cast to the wrong type.

To clarify how to use a function pointer to call a member function, here is an example:

// the function using the function pointers:
void somefunction(void (*fptr)(void*, int, int), void* context) {
    fptr(context, 17, 42);
}

void non_member(void*, int i0, int i1) {
    std::cout << "I don't need any context! i0=" << i0 << " i1=" << i1 << "\n";
}

struct foo {
    void member(int i0, int i1) {
        std::cout << "member function: this=" << this << " i0=" << i0 << " i1=" << i1 << "\n";
    }
};

void forwarder(void* context, int i0, int i1) {
    static_cast<foo*>(context)->member(i0, i1);
}

int main() {
    somefunction(&non_member, nullptr);
    foo object;
    somefunction(&forwarder, &object);
}

How to set custom JsonSerializerSettings for Json.NET in ASP.NET Web API?

Answer is adding this 2 lines of code to Global.asax.cs Application_Start method

var json = GlobalConfiguration.Configuration.Formatters.JsonFormatter;
json.SerializerSettings.PreserveReferencesHandling = 
    Newtonsoft.Json.PreserveReferencesHandling.All;

Reference: Handling Circular Object References

The target ... overrides the `OTHER_LDFLAGS` build setting defined in `Pods/Pods.xcconfig

The first line of link below saved my day:

To add values to options from your project’s build settings, prepend the value list with $(inherited).

https://github.com/CocoaPods/CocoaPods/wiki/Creating-a-project-that-uses-CocoaPods#faq

Also, do not forget to insert this line at the beginning of your pod file:

platform :iOS, '5.0'

How to parse XML and count instances of a particular node attribute?

Python has an interface to the expat XML parser.

xml.parsers.expat

It's a non-validating parser, so bad XML will not be caught. But if you know your file is correct, then this is pretty good, and you'll probably get the exact info you want and you can discard the rest on the fly.

stringofxml = """<foo>
    <bar>
        <type arg="value" />
        <type arg="value" />
        <type arg="value" />
    </bar>
    <bar>
        <type arg="value" />
    </bar>
</foo>"""
count = 0
def start(name, attr):
    global count
    if name == 'type':
        count += 1

p = expat.ParserCreate()
p.StartElementHandler = start
p.Parse(stringofxml)

print count # prints 4

How to iterate over columns of pandas dataframe to run regression

You can use iteritems():

for name, values in df.iteritems():
    print('{name}: {value}'.format(name=name, value=values[0]))

How do I load the contents of a text file into a javascript variable?

One thing to keep in mind is that Javascript runs on the client, and not on the server. You can't really "load a file" from the server in Javascript. What happens is that Javascript sends a request to the server, and the server sends back the contents of the requested file. How does Javascript receive the contents? That's what the callback function is for. In Edward's case, that is

    client.onreadystatechange = function() {

and in danb's case, it is

 function(data) {

This function is called whenever the data happen to arrive. The jQuery version implicitly uses Ajax, it just makes the coding easier by encapsulating that code in the library.

Location of sqlite database on the device

For this, what I did is

File f=new File("/data/data/your.app.package/databases/your_db.db3");
FileInputStream fis=null;
FileOutputStream fos=null;

try
{
  fis=new FileInputStream(f);
  fos=new FileOutputStream("/mnt/sdcard/db_dump.db");
  while(true)
  {
    int i=fis.read();
    if(i!=-1)
    {fos.write(i);}
    else
    {break;}
  }
  fos.flush();
  Toast.makeText(this, "DB dump OK", Toast.LENGTH_LONG).show();
}
catch(Exception e)
{
  e.printStackTrace();
  Toast.makeText(this, "DB dump ERROR", Toast.LENGTH_LONG).show();
}
finally
{
  try
  {
    fos.close();
    fis.close();
  }
  catch(IOException ioe)
  {}
}

And to do this, your app must have permission to access SD card, add following setting to your manifest.xml

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

Not a brilliant way, but works.

How do you reverse a string in place in C or C++?

#include <cstdio>
#include <cstdlib>
#include <string>

void strrev(char *str)
{
        if( str == NULL )
                return;

        char *end_ptr = &str[strlen(str) - 1];
        char temp;
        while( end_ptr > str )
        {
                temp = *str;
                *str++ = *end_ptr;
                *end_ptr-- = temp;
        }
}

int main(int argc, char *argv[])
{
        char buffer[32];

        strcpy(buffer, "testing");
        strrev(buffer);
        printf("%s\n", buffer);

        strcpy(buffer, "a");
        strrev(buffer);
        printf("%s\n", buffer);

        strcpy(buffer, "abc");
        strrev(buffer);
        printf("%s\n", buffer);

        strcpy(buffer, "");
        strrev(buffer);
        printf("%s\n", buffer);

        strrev(NULL);

        return 0;
}

This code produces this output:

gnitset
a
cba

Can't open and lock privilege tables: Table 'mysql.user' doesn't exist

I had the same problem. For some reason --initialize did not work. After about 5 hours of trial and error with different parameters, configs and commands I found out that the problem was caused by the file system.

I wanted to run a database on a large USB HDD drive. Drives larger than 2 TB are GPT partitioned! Here is a bug report with a solution:

https://bugs.mysql.com/bug.php?id=28913

In short words: Add the following line to your my.ini:

innodb_flush_method=normal

I had this problem with mysql 5.7 on Windows.

Passing ArrayList through Intent

Suppose you need to pass an arraylist of following class from current activity to next activity // class of the objects those in the arraylist // remember to implement the class from Serializable interface // Serializable means it converts the object into stream of bytes and helps to transfer that object

public class Question implements Serializable {
... 
... 
...
}

in your current activity you probably have an ArrayList as follows

ArrayList<Question> qsList = new ArrayList<>();
qsList.add(new Question(1));
qsList.add(new Question(2));
qsList.add(new Question(3));

// intialize Bundle instance
Bundle b = new Bundle();
// putting questions list into the bundle .. as key value pair.
// so you can retrieve the arrayList with this key
b.putSerializable("questions", (Serializable) qsList);
Intent i = new Intent(CurrentActivity.this, NextActivity.class);
i.putExtras(b);
startActivity(i);

in order to get the arraylist within the next activity

//get the bundle
Bundle b = getIntent().getExtras();
//getting the arraylist from the key
ArrayList<Question> q = (ArrayList<Question>) b.getSerializable("questions");

How to properly exit a C# application?

By the way. whenever my forms call the formclosed or form closing event I close the applciation with a this.Hide() function. Does that affect how my application is behaving now?

In short, yes. The entire application will end when the main form (the form started via Application.Run in the Main method) is closed (not hidden).

If your entire application should always fully terminate whenever your main form is closed then you should just remove that form closed handler. By not canceling that event and just letting them form close when the user closes it you will get your desired behavior. As for all of the other forms, if you don't intend to show that same instance of the form again you just just let them close, rather than preventing closure and hiding them. If you are showing them again, then hiding them may be fine.

If you want to be able to have the user click the "x" for your main form, but have another form stay open and, in effect, become the "new" main form, then it's a bit more complicated. In such a case you will need to just hide your main form rather than closing it, but you'll need to add in some sort of mechanism that will actually close the main form when you really do want your app to end. If this is the situation that you're in then you'll need to add more details to your question describing what types of applications should and should not actually end the program.

WaitAll vs WhenAll

What do they do:

  • Internally both do the same thing.

What's the difference:

  • WaitAll is a blocking call
  • WhenAll - not - code will continue executing

Use which when:

  • WaitAll when cannot continue without having the result
  • WhenAll when what just to be notified, not blocked

MySQL SELECT AS combine two columns into one

If both columns can contain NULL, but you still want to merge them to a single string, the easiest solution is to use CONCAT_WS():

SELECT FirstName AS First_Name
     , LastName AS Last_Name
     , CONCAT_WS('', ContactPhoneAreaCode1, ContactPhoneNumber1) AS Contact_Phone 
  FROM TABLE1

This way you won't have to check for NULL-ness of each column separately.

Alternatively, if both columns are actually defined as NOT NULL, CONCAT() will be quite enough:

SELECT FirstName AS First_Name
     , LastName AS Last_Name
     , CONCAT(ContactPhoneAreaCode1, ContactPhoneNumber1) AS Contact_Phone 
  FROM TABLE1

As for COALESCE, it's a bit different beast: given the list of arguments, it returns the first that's not NULL.

Should jQuery's $(form).submit(); not trigger onSubmit within the form tag?

The easiest solution to workaround this is to create 'temporary' input with type submit and trigger click:

var submitInput = $("<input type='submit' />");
$("#aspnetForm").append(submitInput);
submitInput.trigger("click");

Sending an HTTP POST request on iOS

Sending an HTTP POST request on iOS (Objective c):

-(NSString *)postexample{

// SEND POST
NSString *url = [NSString stringWithFormat:@"URL"];
NSString *post = [NSString stringWithFormat:@"param=value"];
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:@"%d",[postData length]];


NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setHTTPMethod:@"POST"];
[request setURL:[NSURL URLWithString:url]];
[request setValue:postLength forHTTPHeaderField:@"Content-Length"];
[request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
[request setHTTPBody:postData];

NSError *error = nil;
NSHTTPURLResponse *responseCode = nil;

//RESPONDE DATA 
NSData *oResponseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&responseCode error:&error];

if([responseCode statusCode] != 200){
    NSLog(@"Error getting %@, HTTP status code %li", url, (long)[responseCode statusCode]);
    return nil;
}

//SEE RESPONSE DATA
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Response" message:[[NSString alloc] initWithData:oResponseData encoding:NSUTF8StringEncoding] delegate:nil cancelButtonTitle:@"OK" otherButtonTitles: nil];
[alert show];

return [[NSString alloc] initWithData:oResponseData encoding:NSUTF8StringEncoding];
}

Converting Columns into rows with their respective data in sql server

declare @T table (ScripName varchar(50), ScripCode varchar(50), Price int)
insert into @T values ('20 MICRONS', '533022', 39)

select 
  'ScripName' as ColName,
  ScripName as ColValue
from @T
union all
select 
  'ScripCode' as ColName,
  ScripCode as ColValue
from @T
union all
select 
  'Price' as ColName,
  cast(Price as varchar(50)) as ColValue
from @T

Hello World in Python

In python 3.x. you use

print("Hello, World")

In Python 2.x. you use

print "Hello, World!"

How can I position my div at the bottom of its container?

Likely not.

Assign position:relative to #container, and then position:absolute; bottom:0; to #copyright.


_x000D_
_x000D_
#container {_x000D_
    position: relative;_x000D_
}_x000D_
#copyright {_x000D_
    position: absolute;_x000D_
    bottom: 0;_x000D_
}
_x000D_
<div id="container">_x000D_
  <!-- Other elements here -->_x000D_
  <div id="copyright">_x000D_
    Copyright Foo web designs_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Update records using LINQ

public ActionResult OrderDel(int id)
    {
        string a = Session["UserSession"].ToString();
        var s = (from test in ob.Order_Details where test.Email_ID_Fk == a && test.Order_ID == id select test).FirstOrDefault();
        s.Status = "Order Cancel By User";
        ob.SaveChanges();
        //foreach(var updter in s)
        //{
        //    updter.Status = "Order Cancel By User";
        //}


        return Json("Sucess", JsonRequestBehavior.AllowGet);
    } <script>
            function Cancel(id) {
                if (confirm("Are your sure ? Want to Cancel?")) {
                    $.ajax({

                        type: 'POST',
                        url: '@Url.Action("OrderDel", "Home")/' + id,
                        datatype: 'JSON',
                        success: function (Result) {
                            if (Result == "Sucess")
                            {
                                alert("Your Order has been Canceled..");
                                window.location.reload();
                            }
                        },
                        error: function (Msgerror) {
                            alert(Msgerror.responseText);
                        }


                    })
                }
            }

        </script>

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

For big objects you may use a somewhat crude but effective method: check how much memory your Python process occupies in the system, then delete the object and compare.

This method has many drawbacks but it will give you a very fast estimate for very big objects.

Errors in SQL Server while importing CSV file despite varchar(MAX) being used for each column

This answer may not apply universally, but it fixed the occurrence of this error I was encountering when importing a small text file. The flat file provider was importing based on fixed 50-character text columns in the source, which was incorrect. No amount of remapping the destination columns affected the issue.

To solve the issue, in the "Choose a Data Source" for the flat-file provider, after selecting the file, a "Suggest Types.." button appears beneath the input column list. After hitting this button, even if no changes were made to the enusing dialog, the Flat File provider then re-queried the source .csv file and then correctly determined the lengths of the fields in the source file.

Once this was done, the import proceeded with no further issues.

How can I select records ONLY from yesterday?

to_char(tran_date, 'yyyy-mm-dd') = to_char(sysdate-1, 'yyyy-mm-dd')

Using fonts with Rails asset pipeline

If you don't want to keep track of moving your fonts around:

# Adding Webfonts to the Asset Pipeline
config.assets.precompile << Proc.new { |path|
  if path =~ /\.(eot|svg|ttf|woff)\z/
    true
  end
}

Remove table row after clicking table row delete button

Using pure Javascript:

Don't need to pass this to the SomeDeleteRowFunction():

<td><input type="button" value="Delete Row" onclick="SomeDeleteRowFunction()"></td>

The onclick function:

function SomeDeleteRowFunction() {
      // event.target will be the input element.
      var td = event.target.parentNode; 
      var tr = td.parentNode; // the row to be removed
      tr.parentNode.removeChild(tr);
}

When can I use a forward declaration?

In file in which you use only Pointer or Reference to a class.And no member/member function should be invoked thought those Pointer/ reference.

with class Foo;//forward declaration

We can declare data members of type Foo* or Foo&.

We can declare (but not define) functions with arguments, and/or return values, of type Foo.

We can declare static data members of type Foo. This is because static data members are defined outside the class definition.

How to grep with a list of words

You need to use the option -f:

$ grep -f A B

The option -F does a fixed string search where as -f is for specifying a file of patterns. You may want both if the file only contains fixed strings and not regexps.

$ grep -Ff A B

You may also want the -w option for matching whole words only:

$ grep -wFf A B

Read man grep for a description of all the possible arguments and what they do.

setTimeout / clearTimeout problems

Practical example Using Jquery for a dropdown menu ! On mouse over on #IconLoggedinUxExternal shows div#ExternalMenuLogin and set time out to hide the div#ExternalMenuLogin

On mouse over on div#ExternalMenuLogin it cancels the timeout. On mouse out on div#ExternalMenuLogin it sets the timeout.

The point here is always to invoke clearTimeout before set the timeout, as so, avoiding double calls

var ExternalMenuLoginTO;
$('#IconLoggedinUxExternal').on('mouseover mouseenter', function () {

    clearTimeout( ExternalMenuLoginTO )
    $("#ExternalMenuLogin").show()
});

$('#IconLoggedinUxExternal').on('mouseleave mouseout', function () {

    clearTimeout( ExternalMenuLoginTO )    
    ExternalMenuLoginTO = setTimeout(
        function () {

            $("#ExternalMenuLogin").hide()

        }
        ,1000
    );
    $("#ExternalMenuLogin").show()
});

$('#ExternalMenuLogin').on('mouseover mouseenter', function () {

    clearTimeout( ExternalMenuLoginTO )
});
$('#ExternalMenuLogin').on('mouseleave mouseout', function () {

    clearTimeout( ExternalMenuLoginTO )
    ExternalMenuLoginTO = setTimeout(
        function () {

            $("#ExternalMenuLogin").hide()

        }
        ,500
    );
});

How to get text with Selenium WebDriver in Python

Python

element.text

Java

element.getText()

C#

element.Text

Ruby

element.text

How to start IDLE (Python editor) without using the shortcut on Windows Vista?

In Python 3.2.2, I found \Python32\Lib\idlelib\idle.bat which was useful because it would let me open python files supplied as args in IDLE.

What is the Simplest Way to Reverse an ArrayList?

Another recursive solution

 public static String reverse(ArrayList<Float> list) {
   if (list.size() == 1) {
       return " " +list.get(0);
   }
   else {
       return " "+ list.remove(list.size() - 1) + reverse(list);
   } 
 }

Difference between <context:annotation-config> and <context:component-scan>

you can find more information in spring context schema file. following is in spring-context-4.3.xsd

<conxtext:annotation-config />
Activates various annotations to be detected in bean classes: Spring's @Required and
@Autowired, as well as JSR 250's @PostConstruct, @PreDestroy and @Resource (if available),
JAX-WS's @WebServiceRef (if available), EJB 3's @EJB (if available), and JPA's
@PersistenceContext and @PersistenceUnit (if available). Alternatively, you may
choose to activate the individual BeanPostProcessors for those annotations.

Note: This tag does not activate processing of Spring's @Transactional or EJB 3's
@TransactionAttribute annotation. Consider the use of the <tx:annotation-driven>
tag for that purpose.
<context:component-scan>
Scans the classpath for annotated components that will be auto-registered as
Spring beans. By default, the Spring-provided @Component, @Repository, @Service, @Controller, @RestController, @ControllerAdvice, and @Configuration stereotypes    will be detected.

Note: This tag implies the effects of the 'annotation-config' tag, activating @Required,
@Autowired, @PostConstruct, @PreDestroy, @Resource, @PersistenceContext and @PersistenceUnit
annotations in the component classes, which is usually desired for autodetected components
(without external configuration). Turn off the 'annotation-config' attribute to deactivate
this default behavior, for example in order to use custom BeanPostProcessor definitions
for handling those annotations.

Note: You may use placeholders in package paths, but only resolved against system
properties (analogous to resource paths). A component scan results in new bean definitions
being registered; Spring's PropertySourcesPlaceholderConfigurer will apply to those bean
definitions just like to regular bean definitions, but it won't apply to the component
scan settings themselves.

Adding attributes to an XML node

There is also a way to add an attribute to an XmlNode object, that can be useful in some cases.

I found this other method on msdn.microsoft.com.

using System.Xml;

[...]

//Assuming you have an XmlNode called node
XmlNode node;

[...]

//Get the document object
XmlDocument doc = node.OwnerDocument;

//Create a new attribute
XmlAttribute attr = doc.CreateAttribute("attributeName");
attr.Value = "valueOfTheAttribute";

//Add the attribute to the node     
node.Attributes.SetNamedItem(attr);

[...]

403 Forbidden error when making an ajax Post request in Django framework

Try including this decorator on your dispatch code

from django.utils.decorators import method_decorator
from django.views.decorators.csrf import csrf_exempt     
@method_decorator(csrf_exempt, name='dispatch')
def dispatch(self, request, *args, **kwargs):
     return super(LessonUploadWorkView,self).dispatch(request,*args,**kwargs)

How do I remove quotes from a string?

str_replace('"', "", $string);
str_replace("'", "", $string);

I assume you mean quotation marks?

Otherwise, go for some regex, this will work for html quotes for example:

preg_replace("/<!--.*?-->/", "", $string);

C-style quotes:

preg_replace("/\/\/.*?\n/", "\n", $string);

CSS-style quotes:

preg_replace("/\/*.*?\*\//", "", $string);

bash-style quotes:

preg-replace("/#.*?\n/", "\n", $string);

Etc etc...

How can I see the specific value of the sql_mode?

You can also try this to determine the current global sql_mode value:

SELECT @@GLOBAL.sql_mode;

or session sql_mode value:

SELECT @@SESSION.sql_mode;

I also had the feeling that the SQL mode was indeed empty.

Android Studio: Module won't show up in "Edit Configuration"

The following are methods to help you:

  1. Close and Open Project again
  2. Close and Open Android Studio
  3. Clean Project
  4. Rebuild Project
  5. Instantiate and Restart
  6. Make sure you have included :app
  7. Import the Project

Does adding a duplicate value to a HashSet/HashMap replace the previous value

The first thing you need to know is that HashSet acts like a Set, which means you add your object directly to the HashSet and it cannot contain duplicates. You just add your value directly in HashSet.

However, HashMap is a Map type. That means every time you add an entry, you add a key-value pair.

In HashMap you can have duplicate values, but not duplicate keys. In HashMap the new entry will replace the old one. The most recent entry will be in the HashMap.

Understanding Link between HashMap and HashSet:

Remember, HashMap can not have duplicate keys. Behind the scene HashSet uses a HashMap.

When you attempt to add any object into a HashSet, this entry is actually stored as a key in the HashMap - the same HashMap that is used behind the scene of HashSet. Since this underlying HashMap needs a key-value pair, a dummy value is generated for us.

Now when you try to insert another duplicate object into the same HashSet, it will again attempt to be insert it as a key in the HashMap lying underneath. However, HashMap does not support duplicates. Hence, HashSet will still result in having only one value of that type. As a side note, for every duplicate key, since the value generated for our entry in HashSet is some random/dummy value, the key is not replaced at all. it will be ignored as removing the key and adding back the same key (the dummy value is the same) would not make any sense at all.

Summary:

HashMap allows duplicate values, but not keys. HashSet cannot contains duplicates.

To play with whether the addition of an object is successfully completed or not, you can check the boolean value returned when you call .add() and see if it returns true or false. If it returned true, it was inserted.

Can I apply the required attribute to <select> fields in HTML5?

In html5 you can do using the full expression:

<select required="required">

I don't know why the short expression doesn't work, but try this one. It will solve.

Convert HH:MM:SS string to seconds only in javascript

Javascript's static method Date.UTC() does the trick:

alert(getSeconds('00:22:17'));

function getSeconds(time)
{
    var ts = time.split(':');
    return Date.UTC(1970, 0, 1, ts[0], ts[1], ts[2]) / 1000;
}

How to run SQL in shell script

You can use a heredoc. e.g. from a prompt:

$ sqlplus -s username/password@oracle_instance <<EOF
set feed off
set pages 0
select count(*) from table;
exit
EOF

so sqlplus will consume everything up to the EOF marker as stdin.

SSH -L connection successful, but localhost port forwarding not working "channel 3: open failed: connect failed: Connection refused"

This means the remote vm is not listening to current port i solved this by adding the port in the vm server

What is the question mark for in a Typescript parameter name

This is to make the variable of Optional type. Otherwise declared variables shows "undefined" if this variable is not used.

export interface ISearchResult {  
  title: string;  
  listTitle:string;
  entityName?: string,
  lookupName?:string,
  lookupId?:string  
}

addID in jQuery?

ID is an attribute, you can set it with the attr function:

$(element).attr('id', 'newID');

I'm not sure what you mean about adding IDs since an element can only have one identifier and this identifier must be unique.

Phone: numeric keyboard for text input

In 2018:

<input type="number" pattern="\d*">

is working for both Android and iOS.

I tested on Android (^4.2) and iOS (11.3)

Calling JavaScript Function From CodeBehind

ScriptManager.RegisterStartupScript(this, this.Page.GetType(),"updatePanel1Script", "javascript:ConfirmExecute()",true/>

Rendering HTML inside textarea

This is not possible to do with a textarea. What you are looking for is an content editable div, which is very easily done:

<div contenteditable="true"></div>

jsFiddle

_x000D_
_x000D_
div.editable {_x000D_
    width: 300px;_x000D_
    height: 200px;_x000D_
    border: 1px solid #ccc;_x000D_
    padding: 5px;_x000D_
}_x000D_
_x000D_
strong {_x000D_
  font-weight: bold;_x000D_
}
_x000D_
<div contenteditable="true">This is the first line.<br>_x000D_
See, how the text fits here, also if<br>there is a <strong>linebreak</strong> at the end?_x000D_
<br>It works nicely._x000D_
<br>_x000D_
<br><span style="color: lightgreen">Great</span>._x000D_
</div>
_x000D_
_x000D_
_x000D_

How to assign name for a screen?

I am a beginner to screen but I find it immensely useful while restoring lost connections. Your question has already been answered but this information might serve as an add on - I use putty with putty connection manager and name my screens - "tab1", "tab2", etc. - as for me the overall picture of the 8-10 tabs is more important than each individual tab name. I use the 8th tab for connecting to db, the 7th for viewing logs, etc. So when I want to reattach my screens I have written a simple wrapper which says:

#!/bin/bash
screen -d -r tab$1

where first argument is the tab number.

Compare two date formats in javascript/jquery

It's quite simple:

if(new Date(fit_start_time) <= new Date(fit_end_time))
{//compare end <=, not >=
    //your code here
}

Comparing 2 Date instances will work just fine. It'll just call valueOf implicitly, coercing the Date instances to integers, which can be compared using all comparison operators. Well, to be 100% accurate: the Date instances will be coerced to the Number type, since JS doesn't know of integers or floats, they're all signed 64bit IEEE 754 double precision floating point numbers.

What is the maximum characters for the NVARCHAR(MAX)?

The max size for a column of type NVARCHAR(MAX) is 2 GByte of storage.

Since NVARCHAR uses 2 bytes per character, that's approx. 1 billion characters.

Leo Tolstoj's War and Peace is a 1'440 page book, containing about 600'000 words - so that might be 6 million characters - well rounded up. So you could stick about 166 copies of the entire War and Peace book into each NVARCHAR(MAX) column.

Is that enough space for your needs? :-)

get string value from HashMap depending on key name

If you are storing keys/values as strings, then this will work:

HashMap<String, String> newMap = new HashMap<String, String>();
newMap.put("my_code", "shhh_secret");
String value = newMap.get("my_code");

The question is what gets populated in the HashMap (key & value)

Typing Greek letters etc. in Python plots

Why not just use the literal characters?

fig.gca().set_xlabel("wavelength, (Ã…)")
fig.gca().set_ylabel("?")

You might have to add this to the file if you are using python 2:

# -*- coding: utf-8 -*-
from __future__ import unicode literals  # or use u"unicode strings"

It might be easier to define constants for characters that are not easy to type on your keyboard.

ANGSTROM, LAMDBA = "Ã…?"

Then you can reuse them elsewhere.

fig.gca().set_xlabel("wavelength, (%s)" % ANGSTROM)
fig.gca().set_ylabel(LAMBDA)

libz.so.1: cannot open shared object file

After checking to which package does the libz.so.1 belongs (http://packages.ubuntu.com/lucid/i386/zlib1g/filelist) you should try to install zlib1g:

sudo apt-get install zlib1g

As pointed by @E-rich, it may be required to add a :i386 suffix to the package name for the package manager correctly identify it:

sudo apt-get install zlib1g:i386


EDIT (for CentOS or other distro that makes use of yum):

If someone using CentOS (or any other distro that makes use of yum) that may end up reading this question, @syslogic proposed the following solution in the comments:

yum install zlib.i686

or, for 32-bit binaries:

yum install zlib.i386

Meaning of tilde in Linux bash (not home directory)

It's possible you're seeing OpenDirectory/ActiveDirectory/LDAP users "automounted" into your home directory.

In *nix, ~ will resolve to your home directory. Likewise ~X will resolve to 'user X'.

Similar to automount for directories, OpenDirectory/ActiveDirectory/LDAP is used in larger/corporate environments to automount user directories. These users may be actual people or they can be machine accounts created to provide various features.

If you type ~Tab you'll see a list of the users on your machine.

What are some uses of template template parameters?

This is what I ran into:

template<class A>
class B
{
  A& a;
};

template<class B>
class A
{
  B b;
};

class AInstance : A<B<A<B<A<B<A<B<... (oh oh)>>>>>>>>
{

};

Can be solved to:

template<class A>
class B
{
  A& a;
};

template< template<class> class B>
class A
{
  B<A> b;
};

class AInstance : A<B> //happy
{

};

or (working code):

template<class A>
class B
{
public:
    A* a;
    int GetInt() { return a->dummy; }
};

template< template<class> class B>
class A
{
public:
    A() : dummy(3) { b.a = this; }
    B<A> b;
    int dummy;
};

class AInstance : public A<B> //happy
{
public:
    void Print() { std::cout << b.GetInt(); }
};

int main()
{
    std::cout << "hello";
    AInstance test;
    test.Print();
}

Get user profile picture by Id

today I found a problem, the profile images was returning the default profile picture because a new requirement from Facebook to all the UID based queries, so just add &access_token=[apptoken] to the url, you can obtain your app token from here

Convert laravel object to array

$res = ActivityServer::query()->select('channel_id')->where(['id' => $id])->first()->attributesToArray();

I use get(), it returns an object, I use the attributesToArray() to change the object attribute to an array.

Refreshing all the pivot tables in my excel workbook with a macro

Yes.

ThisWorkbook.RefreshAll

Or, if your Excel version is old enough,

Dim Sheet as WorkSheet, Pivot as PivotTable
For Each Sheet in ThisWorkbook.WorkSheets
    For Each Pivot in Sheet.PivotTables
        Pivot.RefreshTable
        Pivot.Update
    Next
Next

Installing Java 7 on Ubuntu

Oracle as well as modern versions of Ubuntu have moved to newer versions of Java. The default for Ubuntu 20.04 is OpenJDK 11 which is good enough for most purposes.

If you really need it for running legacy programs, OpenJDK 8 is also available for Ubuntu 20.04 from the official repositories.

If you really need exactly Java 7, the best bet as of 2020 is to download a Zulu distribution. The easiest to install if you have root privileges is the .DEB version, otherwise download the .ZIP one.

https://www.azul.com/downloads/zulu-community/?version=java-7-lts&os=ubuntu&architecture=x86-64-bit&package=jdk

HTML img align="middle" doesn't align an image

remove float left.

Edited: removed reference to align center on an image tag.

Commit only part of a file in Git

Intellij IDEA (and I guess all other products of the series) has built in support for partial commits since v2018.1

enter image description here

Multiple file upload in php

$property_images = $_FILES['property_images']['name'];
    if(!empty($property_images))
    {
        for($up=0;$up<count($property_images);$up++)
        {
            move_uploaded_file($_FILES['property_images']['tmp_name'][$up],'../images/property_images/'.$_FILES['property_images']['name'][$up]);
        }
    }

How to echo shell commands as they are executed

shuckc's answer for echoing select lines has a few downsides: you end up with the following set +x command being echoed as well, and you lose the ability to test the exit code with $? since it gets overwritten by the set +x.

Another option is to run the command in a subshell:

echo "getting URL..."
( set -x ; curl -s --fail $URL -o $OUTFILE )

if [ $? -eq 0 ] ; then
    echo "curl failed"
    exit 1
fi

which will give you output like:

getting URL...
+ curl -s --fail http://example.com/missing -o /tmp/example
curl failed

This does incur the overhead of creating a new subshell for the command, though.

How do I drop a function if it already exists?

IF EXISTS 
(SELECT * FROM sys.objects 
WHERE object_id = OBJECT_ID(N'functionName') 
AND type in (N'FN', N'IF', N'TF', N'FS', N'FT'))

DROP FUNCTION functionName
GO

How to make a variadic macro (variable number of arguments)

__VA_ARGS__ is the standard way to do it. Don't use compiler-specific hacks if you don't have to.

I'm really annoyed that I can't comment on the original post. In any case, C++ is not a superset of C. It is really silly to compile your C code with a C++ compiler. Don't do what Donny Don't does.

Where to download visual studio express 2005?

For somebody like me who lands onto this page from Google ages after this question had been posted, you can find VS2005 here: http://apdubey.blogspot.com/2009/04/microsoft-visual-studio-2005-express.html

EDIT: In case that blog dies, here are the links from the blog.

All the bellow files are more them 400MB.

Visual Web Developer 2005 Express Edition
449,848 KB
.IMG File | .ISO File

Visual Basic 2005 Express Edition
445,282 KB
.IMG File | .ISO File

Visual C# 2005 Express Edition
445,282 KB
.IMG File | .ISO File

Visual C++ 2005 Express Edition
474,686 KB
.IMG File | .ISO File

Visual J# 2005 Express Edition
448,702 KB
.IMG File | .ISO File

Error: Jump to case label

JohannesD's answer is correct, but I feel it isn't entirely clear on an aspect of the problem.

The example he gives declares and initializes the variable i in case 1, and then tries to use it in case 2. His argument is that if the switch went straight to case 2, i would be used without being initialized, and this is why there's a compilation error. At this point, one could think that there would be no problem if variables declared in a case were never used in other cases. For example:

switch(choice) {
    case 1:
        int i = 10; // i is never used outside of this case
        printf("i = %d\n", i);
        break;
    case 2:
        int j = 20; // j is never used outside of this case
        printf("j = %d\n", j);
        break;
}

One could expect this program to compile, since both i and j are used only inside the cases that declare them. Unfortunately, in C++ it doesn't compile: as Ciro Santilli ???? ???? ??? explained, we simply can't jump to case 2:, because this would skip the declaration with initialization of i, and even though case 2 doesn't use i at all, this is still forbidden in C++.

Interestingly, with some adjustments (an #ifdef to #include the appropriate header, and a semicolon after the labels, because labels can only be followed by statements, and declarations do not count as statements in C), this program does compile as C:

// Disable warning issued by MSVC about scanf being deprecated
#ifdef _MSC_VER
#define _CRT_SECURE_NO_WARNINGS
#endif

#ifdef __cplusplus
#include <cstdio>
#else
#include <stdio.h>
#endif

int main() {

    int choice;
    printf("Please enter 1 or 2: ");
    scanf("%d", &choice);

    switch(choice) {
        case 1:
            ;
            int i = 10; // i is never used outside of this case
            printf("i = %d\n", i);
            break;
        case 2:
            ;
            int j = 20; // j is never used outside of this case
            printf("j = %d\n", j);
            break;
    }
}

Thanks to an online compiler like http://rextester.com you can quickly try to compile it either as C or C++, using MSVC, GCC or Clang. As C it always works (just remember to set STDIN!), as C++ no compiler accepts it.

Converting integer to digit list

Convert the integer to string first, and then use map to apply int on it:

>>> num = 132
>>> map(int, str(num))    #note, This will return a map object in python 3.
[1, 3, 2]

or using a list comprehension:

>>> [int(x) for x in str(num)]
[1, 3, 2]

Laravel Migration table already exists, but I want to add new not the older

I solved your problem by deleting the "user" table in sequel-pro (there is no data in my user table) and then you can run php artisan migrate

Here are before and after screen shots

before I delete the user table user

enter image description here

after I delete the table user enter image description here

Programmatically register a broadcast receiver

In your onCreate method you can register a receiver like this:

private BroadcastReceiver receiver;

@Override
public void onCreate(Bundle savedInstanceState){

  // your oncreate code should be

  IntentFilter filter = new IntentFilter();
  filter.addAction("SOME_ACTION");
  filter.addAction("SOME_OTHER_ACTION");

  receiver = new BroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent intent) {
      //do something based on the intent's action
    }
  };
     registerReceiver(receiver, filter);
}

Remember to run this in the onDestroy method:

 @Override
 protected void onDestroy() {
  if (receiver != null) {
   unregisterReceiver(receiver);
   receiver = null;
  }
  super.onDestroy();
 }

login failed for user 'sa'. The user is not associated with a trusted SQL Server connection. (Microsoft SQL Server, Error: 18452) in sql 2008

I faced the very same error when I was trying to connect to my SQL Server 2014 instance using sa user using SQL Server Management Studio (SSMS). I was facing this error even when security settings for sa user was all good and SQL authentication mode was enabled on the SQL Server instance.

Finally, the issue turned out to be that Named Pipes protocol was disabled. Here is how you can enable it:

Open SQL Server Configuration Manager application from start menu. Now, enable Named Pipes protocol for both Client Protocols and Protocols for <SQL Server Instance Name> nodes as shown in the snapshot below:

enter image description here

Note: Make sure you restart the SQL Server instance after making changes.

P.S. I'm not very sure but there is a possibility that the Named Pipes enabling was required under only one of the two nodes that I've advised. So you can try it one after the other to reach to a more precise solution.

Python str vs unicode types

Unicode and encodings are completely different, unrelated things.

Unicode

Assigns a numeric ID to each character:

  • 0x41 ? A
  • 0xE1 ? á
  • 0x414 ? ?

So, Unicode assigns the number 0x41 to A, 0xE1 to á, and 0x414 to ?.

Even the little arrow ? I used has its Unicode number, it's 0x2192. And even emojis have their Unicode numbers, is 0x1F602.

You can look up the Unicode numbers of all characters in this table. In particular, you can find the first three characters above here, the arrow here, and the emoji here.

These numbers assigned to all characters by Unicode are called code points.

The purpose of all this is to provide a means to unambiguously refer to a each character. For example, if I'm talking about , instead of saying "you know, this laughing emoji with tears", I can just say, Unicode code point 0x1F602. Easier, right?

Note that Unicode code points are usually formatted with a leading U+, then the hexadecimal numeric value padded to at least 4 digits. So, the above examples would be U+0041, U+00E1, U+0414, U+2192, U+1F602.

Unicode code points range from U+0000 to U+10FFFF. That is 1,114,112 numbers. 2048 of these numbers are used for surrogates, thus, there remain 1,112,064. This means, Unicode can assign a unique ID (code point) to 1,112,064 distinct characters. Not all of these code points are assigned to a character yet, and Unicode is extended continuously (for example, when new emojis are introduced).

The important thing to remember is that all Unicode does is to assign a numerical ID, called code point, to each character for easy and unambiguous reference.

Encodings

Map characters to bit patterns.

These bit patterns are used to represent the characters in computer memory or on disk.

There are many different encodings that cover different subsets of characters. In the English-speaking world, the most common encodings are the following:

ASCII

Maps 128 characters (code points U+0000 to U+007F) to bit patterns of length 7.

Example:

  • a ? 1100001 (0x61)

You can see all the mappings in this table.

ISO 8859-1 (aka Latin-1)

Maps 191 characters (code points U+0020 to U+007E and U+00A0 to U+00FF) to bit patterns of length 8.

Example:

  • a ? 01100001 (0x61)
  • á ? 11100001 (0xE1)

You can see all the mappings in this table.

UTF-8

Maps 1,112,064 characters (all existing Unicode code points) to bit patterns of either length 8, 16, 24, or 32 bits (that is, 1, 2, 3, or 4 bytes).

Example:

  • a ? 01100001 (0x61)
  • á ? 11000011 10100001 (0xC3 0xA1)
  • ? ? 11100010 10001001 10100000 (0xE2 0x89 0xA0)
  • ? 11110000 10011111 10011000 10000010 (0xF0 0x9F 0x98 0x82)

The way UTF-8 encodes characters to bit strings is very well described here.

Unicode and Encodings

Looking at the above examples, it becomes clear how Unicode is useful.

For example, if I'm Latin-1 and I want to explain my encoding of á, I don't need to say:

"I encode that a with an aigu (or however you call that rising bar) as 11100001"

But I can just say:

"I encode U+00E1 as 11100001"

And if I'm UTF-8, I can say:

"Me, in turn, I encode U+00E1 as 11000011 10100001"

And it's unambiguously clear to everybody which character we mean.

Now to the often arising confusion

It's true that sometimes the bit pattern of an encoding, if you interpret it as a binary number, is the same as the Unicode code point of this character.

For example:

  • ASCII encodes a as 1100001, which you can interpret as the hexadecimal number 0x61, and the Unicode code point of a is U+0061.
  • Latin-1 encodes á as 11100001, which you can interpret as the hexadecimal number 0xE1, and the Unicode code point of á is U+00E1.

Of course, this has been arranged like this on purpose for convenience. But you should look at it as a pure coincidence. The bit pattern used to represent a character in memory is not tied in any way to the Unicode code point of this character.

Nobody even says that you have to interpret a bit string like 11100001 as a binary number. Just look at it as the sequence of bits that Latin-1 uses to encode the character á.

Back to your question

The encoding used by your Python interpreter is UTF-8.

Here's what's going on in your examples:

Example 1

The following encodes the character á in UTF-8. This results in the bit string 11000011 10100001, which is saved in the variable a.

>>> a = 'á'

When you look at the value of a, its content 11000011 10100001 is formatted as the hex number 0xC3 0xA1 and output as '\xc3\xa1':

>>> a
'\xc3\xa1'

Example 2

The following saves the Unicode code point of á, which is U+00E1, in the variable ua (we don't know which data format Python uses internally to represent the code point U+00E1 in memory, and it's unimportant to us):

>>> ua = u'á'

When you look at the value of ua, Python tells you that it contains the code point U+00E1:

>>> ua
u'\xe1'

Example 3

The following encodes Unicode code point U+00E1 (representing character á) with UTF-8, which results in the bit pattern 11000011 10100001. Again, for output this bit pattern is represented as the hex number 0xC3 0xA1:

>>> ua.encode('utf-8')
'\xc3\xa1'

Example 4

The following encodes Unicode code point U+00E1 (representing character á) with Latin-1, which results in the bit pattern 11100001. For output, this bit pattern is represented as the hex number 0xE1, which by coincidence is the same as the initial code point U+00E1:

>>> ua.encode('latin1')
'\xe1'

There's no relation between the Unicode object ua and the Latin-1 encoding. That the code point of á is U+00E1 and the Latin-1 encoding of á is 0xE1 (if you interpret the bit pattern of the encoding as a binary number) is a pure coincidence.

Java Immutable Collections

Collection<String> c1 = new ArrayList<String>();
c1.add("foo");
Collection<String> c2 = Collections.unmodifiableList(c1);

c1 is mutable (i.e. neither unmodifiable nor immutable).
c2 is unmodifiable: it can't be changed itself, but if later on I change c1 then that change will be visible in c2.

This is because c2 is simply a wrapper around c1 and not really an independent copy. Guava provides the ImmutableList interface and some implementations. Those work by actually creating a copy of the input (unless the input is an immutable collection on its own).

Regarding your second question:

The mutability/immutability of a collection does not depend on the mutability/immutability of the objects contained therein. Modifying an object contained in a collection does not count as a "modification of the collection" for this description. Of course if you need a immutable collection, you usually also want it to contain immutable objects.

Changing default encoding of Python?

Here is a simpler method (hack) that gives you back the setdefaultencoding() function that was deleted from sys:

import sys
# sys.setdefaultencoding() does not exist, here!
reload(sys)  # Reload does the trick!
sys.setdefaultencoding('UTF8')

(Note for Python 3.4+: reload() is in the importlib library.)

This is not a safe thing to do, though: this is obviously a hack, since sys.setdefaultencoding() is purposely removed from sys when Python starts. Reenabling it and changing the default encoding can break code that relies on ASCII being the default (this code can be third-party, which would generally make fixing it impossible or dangerous).

How to print table using Javascript?

You can also use a jQuery plugin to do that

jQuery PrintPage plugin

Demo

Change the background color in a twitter bootstrap modal?

CSS

If this doesn't work:

.modal-backdrop {
   background-color: red;
}

try this:

.modal { 
   background-color: red !important; 
}

How to remove time portion of date in C# in DateTime object only?

The Date property will return the date at midnight.

One option could be to get the individual values (day/month/year) separately and store it in the type you want.

var dateAndTime = DateTime.Now; 
int year = dateAndTime.Year;
int month = dateAndTime.Month;
int day = dateAndTime.Day;

string.Format("{0}/{1}/{2}", month, day, year);

How should I set the default proxy to use default credentials?

This thread is old, but I just recently stumbled over the defaultProxy issue and maybe it helps others.

I used the config setting as Andrew suggested. When deploying it, my customer got an error saying, there weren't sufficient rights to set the configuration 'defaultProxy'.

Not knowing why I do not have the right to set this configuration and what to do about it, I just removed it and it still worked. So it seems that in VS2013 this issue is fixed.

And while we're at it:

    WebRequest.DefaultWebProxy.Credentials = new NetworkCredential("ProxyUsername", "ProxyPassword");

uses the default proxy with your credentials. If you want to force not using a proxy just set the DefaultWebProxy to null (though I don't know if one wants that).

How to enable or disable an anchor using jQuery?

The app I'm currently working on does it with a CSS style in combination with javascript.

a.disabled { color:gray; }

Then whenever I want to disable a link I call

$('thelink').addClass('disabled');

Then, in the click handler for 'thelink' a tag I always run a check first thing

if ($('thelink').hasClass('disabled')) return;

Mobile overflow:scroll and overflow-scrolling: touch // prevent viewport "bounce"

I've managed to find a CSS workaround to preventing bouncing of the viewport. The key was to wrap the content in 3 divs with -webkit-touch-overflow:scroll applied to them. The final div should have a min-height of 101%. In addition, you should explicitly set fixed widths/heights on the body tag representing the size of your device. I've added a red background on the body to demonstrate that it is the content that is now bouncing and not the mobile safari viewport.

Source code below and here is a plunker (this has been tested on iOS7 GM too). http://embed.plnkr.co/NCOFoY/preview

If you intend to run this as a full-screen app on iPhone 5, modify the height to 1136px (when apple-mobile-web-app-status-bar-style is set to 'black-translucent' or 1096px when set to 'black'). 920x is the height of the viewport once the chrome of mobile safari has been taken into account).

<!doctype html>
<html>

<head>
    <meta name="viewport" content="initial-scale=0.5,maximum-scale=0.5,minimum-scale=0.5,user-scalable=no" />
    <style>
        body { width: 640px; height: 920px; overflow: hidden; margin: 0; padding: 0; background: red; }
        .no-bounce { width: 100%; height: 100%; overflow-y: scroll; -webkit-overflow-scrolling: touch; }
        .no-bounce > div { width: 100%; height: 100%; overflow-y: scroll; -webkit-overflow-scrolling: touch; }
        .no-bounce > div > div { width: 100%; min-height: 101%; font-size: 30px; }
        p { display: block; height: 50px; }
    </style>
</head>

<body>

    <div class="no-bounce">
        <div>
            <div>
                <h1>Some title</h1>
                <p>item 1</p>
                <p>item 2</p>
                <p>item 3</p>
                <p>item 4</p>
                <p>item 5</p>
                <p>item 6</p>
                <p>item 7</p>
                <p>item 8</p>
                <p>item 9</p>
                <p>item 10</p>
                <p>item 11</p>
                <p>item 12</p>
                <p>item 13</p>
                <p>item 14</p>
                <p>item 15</p>
                <p>item 16</p>
                <p>item 17</p>
                <p>item 18</p>
                <p>item 19</p>
                <p>item 20</p>
            </div>
        </div>
    </div>

</body>

</html>

Remove duplicated rows

The data.table package also has unique and duplicated methods of it's own with some additional features.

Both the unique.data.table and the duplicated.data.table methods have an additional by argument which allows you to pass a character or integer vector of column names or their locations respectively

library(data.table)
DT <- data.table(id = c(1,1,1,2,2,2),
                 val = c(10,20,30,10,20,30))

unique(DT, by = "id")
#    id val
# 1:  1  10
# 2:  2  10

duplicated(DT, by = "id")
# [1] FALSE  TRUE  TRUE FALSE  TRUE  TRUE

Another important feature of these methods is a huge performance gain for larger data sets

library(microbenchmark)
library(data.table)
set.seed(123)
DF <- as.data.frame(matrix(sample(1e8, 1e5, replace = TRUE), ncol = 10))
DT <- copy(DF)
setDT(DT)

microbenchmark(unique(DF), unique(DT))
# Unit: microseconds
#       expr       min         lq      mean    median        uq       max neval cld
# unique(DF) 44708.230 48981.8445 53062.536 51573.276 52844.591 107032.18   100   b
# unique(DT)   746.855   776.6145  2201.657   864.932   919.489  55986.88   100  a 


microbenchmark(duplicated(DF), duplicated(DT))
# Unit: microseconds
#           expr       min         lq       mean     median        uq        max neval cld
# duplicated(DF) 43786.662 44418.8005 46684.0602 44925.0230 46802.398 109550.170   100   b
# duplicated(DT)   551.982   558.2215   851.0246   639.9795   663.658   5805.243   100  a 

REST API - Bulk Create or Update in single request

I think that you could use a POST or PATCH method to handle this since they typically design for this.

  • Using a POST method is typically used to add an element when used on list resource but you can also support several actions for this method. See this answer: How to Update a REST Resource Collection. You can also support different representation formats for the input (if they correspond to an array or a single elements).

    In the case, it's not necessary to define your format to describe the update.

  • Using a PATCH method is also suitable since corresponding requests correspond to a partial update. According to RFC5789 (http://tools.ietf.org/html/rfc5789):

    Several applications extending the Hypertext Transfer Protocol (HTTP) require a feature to do partial resource modification. The existing HTTP PUT method only allows a complete replacement of a document. This proposal adds a new HTTP method, PATCH, to modify an existing HTTP resource.

    In the case, you have to define your format to describe the partial update.

I think that in this case, POST and PATCH are quite similar since you don't really need to describe the operation to do for each element. I would say that it depends on the format of the representation to send.

The case of PUT is a bit less clear. In fact, when using a method PUT, you should provide the whole list. As a matter of fact, the provided representation in the request will be in replacement of the list resource one.

You can have two options regarding the resource paths.

  • Using the resource path for doc list

In this case, you need to explicitely provide the link of docs with a binder in the representation you provide in the request.

Here is a sample route for this /docs.

The content of such approach could be for method POST:

[
    { "doc_number": 1, "binder": 4, (other fields in the case of creation) },
    { "doc_number": 2, "binder": 4, (other fields in the case of creation) },
    { "doc_number": 3, "binder": 5, (other fields in the case of creation) },
    (...)
]
  • Using sub resource path of binder element

In addition you could also consider to leverage sub routes to describe the link between docs and binders. The hints regarding the association between a doc and a binder doesn't have now to be specified within the request content.

Here is a sample route for this /binder/{binderId}/docs. In this case, sending a list of docs with a method POST or PATCH will attach docs to the binder with identifier binderId after having created the doc if it doesn't exist.

The content of such approach could be for method POST:

[
    { "doc_number": 1, (other fields in the case of creation) },
    { "doc_number": 2, (other fields in the case of creation) },
    { "doc_number": 3, (other fields in the case of creation) },
    (...)
]

Regarding the response, it's up to you to define the level of response and the errors to return. I see two levels: the status level (global level) and the payload level (thinner level). It's also up to you to define if all the inserts / updates corresponding to your request must be atomic or not.

  • Atomic

In this case, you can leverage the HTTP status. If everything goes well, you get a status 200. If not, another status like 400 if the provided data aren't correct (for example binder id not valid) or something else.

  • Non atomic

In this case, a status 200 will be returned and it's up to the response representation to describe what was done and where errors eventually occur. ElasticSearch has an endpoint in its REST API for bulk update. This could give you some ideas at this level: http://www.elasticsearch.org/guide/en/elasticsearch/guide/current/bulk.html.

  • Asynchronous

You can also implement an asynchronous processing to handle the provided data. In this case, the HTTP status returns will be 202. The client needs to pull an additional resource to see what happens.

Before finishing, I also would want to notice that the OData specification addresses the issue regarding relations between entities with the feature named navigation links. Perhaps could you have a look at this ;-)

The following link can also help you: https://templth.wordpress.com/2014/12/15/designing-a-web-api/.

Hope it helps you, Thierry

A failure occurred while executing com.android.build.gradle.internal.tasks

Clean Project -> Invalidate caches/restart. My problem resolved with this.

Declaring and initializing arrays in C

Why can't you initialize when you declare?

Which C compiler are you using? Does it support C99?

If it does support C99, you can declare the variable where you need it and initialize it when you declare it.

The only excuse I can think of for not doing that would be because you need to declare it but do an early exit before using it, so the initializer would be wasted. However, I suspect that any such code is not as cleanly organized as it should be and could be written so it was not a problem.

Conversion from byte array to base64 and back

The reason the encoded array is longer by about a quarter is that base-64 encoding uses only six bits out of every byte; that is its reason of existence - to encode arbitrary data, possibly with zeros and other non-printable characters, in a way suitable for exchange through ASCII-only channels, such as e-mail.

The way you get your original array back is by using Convert.FromBase64String:

 byte[] temp_backToBytes = Convert.FromBase64String(temp_inBase64);

Array slices in C#

Here's a simple extension method that returns a slice as a new array:

public static T[] Slice<T>(this T[] arr, uint indexFrom, uint indexTo) {
    if (indexFrom > indexTo) {
        throw new ArgumentOutOfRangeException("indexFrom is bigger than indexTo!");
    }

    uint length = indexTo - indexFrom;
    T[] result = new T[length];
    Array.Copy(arr, indexFrom, result, 0, length);

    return result;
}

Then you can use it as:

byte[] slice = foo.Slice(0, 40);

How do I draw a grid onto a plot in Python?

Here is a small example how to add a matplotlib grid in Gtk3 with Python 2 (not working in Python 3):

#!/usr/bin/env python
#-*- coding: utf-8 -*-

import gi
gi.require_version('Gtk', '3.0')
from gi.repository import Gtk
from matplotlib.figure import Figure
from matplotlib.backends.backend_gtk3agg import FigureCanvasGTK3Agg as FigureCanvas

win = Gtk.Window()
win.connect("delete-event", Gtk.main_quit)
win.set_title("Embedding in GTK3")

f = Figure(figsize=(1, 1), dpi=100)
ax = f.add_subplot(111)
ax.grid()

canvas = FigureCanvas(f)
canvas.set_size_request(400, 400)
win.add(canvas)

win.show_all()
Gtk.main()

enter image description here

Resize image proportionally with CSS?

Control size and maintain proportion :

#your-img {
    height: auto; 
    width: auto; 
    max-width: 300px; 
    max-height: 300px;
}

Connecting to Oracle Database through C#?

First off you need to download and install ODP from this site http://www.oracle.com/technetwork/topics/dotnet/index-085163.html

After installation add a reference of the assembly Oracle.DataAccess.dll.

Your are good to go after this.

using System; 
using Oracle.DataAccess.Client; 

class OraTest
{ 
    OracleConnection con; 
    void Connect() 
    { 
        con = new OracleConnection(); 
        con.ConnectionString = "User Id=<username>;Password=<password>;Data Source=<datasource>"; 
        con.Open(); 
        Console.WriteLine("Connected to Oracle" + con.ServerVersion); 
    }

    void Close() 
    {
        con.Close(); 
        con.Dispose(); 
    } 

    static void Main() 
    { 
        OraTest ot= new OraTest(); 
        ot.Connect(); 
        ot.Close(); 
    } 
}

When to use Common Table Expression (CTE)

It is very useful when you want to perform an "ordered update".

MS SQL does not allow you to use ORDER BY with UPDATE, but with help of CTE you can do it that way:

WITH cte AS
(
    SELECT TOP(5000) message_compressed, message, exception_compressed, exception
    FROM logs
    WHERE Id >= 5519694 
    ORDER BY Id
)
UPDATE  cte
SET     message_compressed = COMPRESS(message), exception_compressed = COMPRESS(exception)

Look here for more info: How to update and order by using ms sql

Failed to serialize the response in Web API with Json

While all these answers above are correct, one may want to check the InnerException > ExceptionMessage.

If it says something like this "The ObjectContext instance has been disposed and can no longer be used for operations that require a connection.". This could be an issue because of default behavior of the EF.

By assigning LazyLoadingEnabled = false in your DbContext constructor will do the trick.

public class MyDbContext : DbContext
{
  public MyDbContext()
  {
    this.Configuration.LazyLoadingEnabled = false;
  }
}

For more detailed reading about EagerLoading and LazyLoading behavior of EF refer this MSDN Article.

Why is Chrome showing a "Please Fill Out this Field" tooltip on empty fields?

Put novalidate="novalidate" on <form> tag.

<form novalidate="novalidate">
...
</form>

In XHTML, attribute minimization is forbidden, and the novalidate attribute must be defined as <form novalidate="novalidate">.

http://www.w3schools.com/tags/att_form_novalidate.asp

How do I obtain the frequencies of each value in an FFT?

Your kth FFT result's frequency is 2*pi*k/N.

How to make a jquery function call after "X" seconds

You can just use the normal setTimeout method in JavaScript.

ie...

setTimeout( function(){ 
    // Do something after 1 second 
  }  , 1000 );

In your example, you might want to use showStickySuccessToast directly.

java build path problems

From the Package Explorer in Eclipse, you can right click the project, choose Build Path, Configure Build Path to get the build path dialog. From there you can remove the JRE reference for the 1.5 JRE and 'Add Library' to add a reference to your installed JRE.

UIView Infinite 360 degree rotation animation?

I think you should better add a UIVIew Category:

#import <QuartzCore/QuartzCore.h>
#import "UIView+Rotate.h"

Implementation UIView (Rotate)

  • (void)remrotate360WithDuration:(CGFloat)duration repeatCount: (float)repeatCount
    {
        CABasicAnimation *fullRotation;
        fullRotation = [CABasicAnimation animationWithKeyPath:@"transform.rotation"];
        fullRotation.fromValue = [NSNumber numberWithFloat:0];
        fullRotation.toValue = [NSNumber numberWithFloat:(2*M_PI)];
        // fullRotation.toValue = [NSNumber numberWithFloat:-(2*M_PI)]; // added this minus sign as i want to rotate it to anticlockwise
        fullRotation.duration = duration;
        fullRotation.speed = 2.0f; // Changed rotation speed
        if (repeatCount == 0)
            fullRotation.repeatCount = MAXFLOAT;
        else
            fullRotation.repeatCount = repeatCount;
    
        [self.layer addAnimation:fullRotation forKey:@"360"];
    }
    

Not using this methods :)

  • (void)remstopAllAnimations
    {
        [self.layer removeAllAnimations];
    };
    
  • (void)rempauseAnimations
    {
        [self rempauseLayer:self.layer];
    }
    
  • (void)remresumeAnimations
    {
        [self remresumeLayer:self.layer];
    }
    
  • (void)rempauseLayer:(CALayer *)layer
    {
        CFTimeInterval pausedTime = [layer convertTime:CACurrentMediaTime() fromLayer:nil];
        layer.speed = 0.0;
        layer.timeOffset = pausedTime;
    }
    
  • (void)remresumeLayer:(CALayer *)layer
    {
        CFTimeInterval pausedTime = [layer timeOffset];
        layer.speed = 1.0;
        layer.timeOffset = 0.0;
        layer.beginTime = 0.0;
        CFTimeInterval timeSincePause = [layer convertTime:CACurrentMediaTime() fromLayer:nil] - pausedTime;
        layer.beginTime = timeSincePause;
    }
    

How to decode jwt token in javascript without using a library?

I found this code at jwt.io and it works well.

//this is used to parse base64
function url_base64_decode(str) {
  var output = str.replace(/-/g, '+').replace(/_/g, '/');
  switch (output.length % 4) {
    case 0:
      break;
    case 2:
      output += '==';
      break;
    case 3:
      output += '=';
      break;
    default:
      throw 'Illegal base64url string!';
  }
  var result = window.atob(output); //polifyll https://github.com/davidchambers/Base64.js
  try{
    return decodeURIComponent(escape(result));
  } catch (err) {
    return result;
  }
}

In some cases(certain development platforms),
the best answer(for now) faces a problem of invalid base64 length.
So, I needed a more stable way.

I hope it would help you.

get UTC timestamp in python with datetime

If input datetime object is in UTC:

>>> dt = datetime(2008, 1, 1, 0, 0, 0, 0)
>>> timestamp = (dt - datetime(1970, 1, 1)).total_seconds()
1199145600.0

Note: it returns float i.e., microseconds are represented as fractions of a second.

If input date object is in UTC:

>>> from datetime import date
>>> utc_date = date(2008, 1, 1)
>>> timestamp = (utc_date.toordinal() - date(1970, 1, 1).toordinal()) * 24*60*60
1199145600

See more details at Converting datetime.date to UTC timestamp in Python.

Get DOS path instead of Windows path

if via a batch file use:

set SHORT_DIR=%~dsp0%

you can use the echo command to check:

echo %SHORT_DIR%

Why is IoC / DI not common in Python?

I back "Jörg W Mittag" answer: "The Python implementation of DI/IoC is so lightweight that it completely vanishes".

To back up this statement, take a look at the famous Martin Fowler's example ported from Java to Python: Python:Design_Patterns:Inversion_of_Control

As you can see from the above link, a "Container" in Python can be written in 8 lines of code:

class Container:
    def __init__(self, system_data):
        for component_name, component_class, component_args in system_data:
            if type(component_class) == types.ClassType:
                args = [self.__dict__[arg] for arg in component_args]
                self.__dict__[component_name] = component_class(*args)
            else:
                self.__dict__[component_name] = component_class

How to split a string with any whitespace chars as delimiters

String string = "Ram is going to school";
String[] arrayOfString = string.split("\\s+");

Bash foreach loop

cat `cat filenames.txt`

will do the trick

How to change a css class style through Javascript?

Since classList is supported in all major browsers and jQuery drops support for IE<9 (in 2.x branch as Stormblack points in the comment), considering this HTML

<div id="mydiv" class="oldclass">text</div>

you can comfortably use this syntax:

document.getElementById('mydiv').classList.add("newClass");

This will also result in:

<div id="mydiv" class="oldclass newclass">text</div>

plus you can also use remove, toggle, contains methods.

Today's Date in Perl in MM/DD/YYYY format

use Time::Piece;
...
my $t = localtime;
print $t->mdy("/");# 02/29/2000

How to convert string to integer in C#

int myInt = System.Convert.ToInt32(myString);

As several others have mentioned, you can also use int.Parse() and int.TryParse().

If you're certain that the string will always be an int:

int myInt = int.Parse(myString);

If you'd like to check whether string is really an int first:

int myInt;
bool isValid = int.TryParse(myString, out myInt); // the out keyword allows the method to essentially "return" a second value
if (isValid)
{
    int plusOne = myInt + 1;
}

Which HTML elements can receive focus?

There isn't a definite list, it's up to the browser. The only standard we have is DOM Level 2 HTML, according to which the only elements that have a focus() method are HTMLInputElement, HTMLSelectElement, HTMLTextAreaElement and HTMLAnchorElement. This notably omits HTMLButtonElement and HTMLAreaElement.

Today's browsers define focus() on HTMLElement, but an element won't actually take focus unless it's one of:

  • HTMLAnchorElement/HTMLAreaElement with an href
  • HTMLInputElement/HTMLSelectElement/HTMLTextAreaElement/HTMLButtonElement but not with disabled (IE actually gives you an error if you try), and file uploads have unusual behaviour for security reasons
  • HTMLIFrameElement (though focusing it doesn't do anything useful). Other embedding elements also, maybe, I haven't tested them all.
  • Any element with a tabindex

There are likely to be other subtle exceptions and additions to this behaviour depending on browser.

Remove category & tag base from WordPress url - without a plugin

Adding "." or "/" won't work if you want a consolidated blog view. Also, I have know idea what that solutions would do for the RSS or XML feeds. I feel better sticking with the WP convention. However, I did come up with a more elegant approach.

First, I name the base category url "blog"

Then I created a category called "all". Finally, I but all my subcategories under "all". So I get a url structure like this.

/blog - 404 - recommend 301 redirect to /blog/all/    
/blog/all/ -  all posts combined.
/blog/all/category1/ - posts filtered by category1
/blog/all/category2/ - posts filterer by category2

I put a custom label on the menu item called "Blog", but it goes to blog/all. It would be a good idea to 301 redirect /blog to /blog/all in the .htaccess file to avoid the 404 on /blog.

Multipart File upload Spring Boot

@RequestBody MultipartFile[] submissions

should be

@RequestParam("file") MultipartFile[] submissions

The files are not the request body, they are part of it and there is no built-in HttpMessageConverter that can convert the request to an array of MultiPartFile.

You can also replace HttpServletRequest with MultipartHttpServletRequest, which gives you access to the headers of the individual parts.

Spring Rest POST Json RequestBody Content type not supported

Really! after spending 4 hours and insane debugging I found this very strange code at com.fasterxml.jackson.databind.deser.DeserializerCache

if (deser == null) {
    try {
        deser = _createAndCacheValueDeserializer(ctxt, factory, type);
    } catch (Exception e) {
        return false;
    }
}

Ya, the problem was double setter.

How do I "Add Existing Item" an entire directory structure in Visual Studio?

The cleanest way that I've found to do this is to create a new Class Library project in the target folder, and redirect all of its build output elsewhere. It still leaves a .csproj file sitting in that folder, but it does let you see it in Visual Studio and pick which files to include in your project.

Is there a <meta> tag to turn off caching in all browsers?

Try using

    <META HTTP-EQUIV="Pragma" CONTENT="no-cache">
    <META HTTP-EQUIV="Expires" CONTENT="-1">

How can I use Async with ForEach?

Add this extension method

public static class ForEachAsyncExtension
{
    public static Task ForEachAsync<T>(this IEnumerable<T> source, int dop, Func<T, Task> body)
    {
        return Task.WhenAll(from partition in Partitioner.Create(source).GetPartitions(dop) 
            select Task.Run(async delegate
            {
                using (partition)
                    while (partition.MoveNext())
                        await body(partition.Current).ConfigureAwait(false);
            }));
    }
}

And then use like so:

Task.Run(async () =>
{
    var s3 = new AmazonS3Client(Config.Instance.Aws.Credentials, Config.Instance.Aws.RegionEndpoint);
    var buckets = await s3.ListBucketsAsync();

    foreach (var s3Bucket in buckets.Buckets)
    {
        if (s3Bucket.BucketName.StartsWith("mybucket-"))
        {
            log.Information("Bucket => {BucketName}", s3Bucket.BucketName);

            ListObjectsResponse objects;
            try
            {
                objects = await s3.ListObjectsAsync(s3Bucket.BucketName);
            }
            catch
            {
                log.Error("Error getting objects. Bucket => {BucketName}", s3Bucket.BucketName);
                continue;
            }

            // ForEachAsync (4 is how many tasks you want to run in parallel)
            await objects.S3Objects.ForEachAsync(4, async s3Object =>
            {
                try
                {
                    log.Information("Bucket => {BucketName} => {Key}", s3Bucket.BucketName, s3Object.Key);
                    await s3.DeleteObjectAsync(s3Bucket.BucketName, s3Object.Key);
                }
                catch
                {
                    log.Error("Error deleting bucket {BucketName} object {Key}", s3Bucket.BucketName, s3Object.Key);
                }
            });

            try
            {
                await s3.DeleteBucketAsync(s3Bucket.BucketName);
            }
            catch
            {
                log.Error("Error deleting bucket {BucketName}", s3Bucket.BucketName);
            }
        }
    }
}).Wait();

How to add new contacts in android

It's not that above answers are incorrect, but I find this code extremely easy to understand and therefore I am sharing it here with everyone. And there is also the check for WRITE_CONTACTS permission.

Here is the complete code for how to add phone number, email, website etc to an existing contact.

public static void addNumberToContact(Context context, Long contactRawId, String number) throws RemoteException, OperationApplicationException {
    addInfoToAddressBookContact(
            context,
            contactRawId,
            ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE,
            ContactsContract.CommonDataKinds.Phone.NUMBER,
            ContactsContract.CommonDataKinds.Phone.TYPE,
            ContactsContract.CommonDataKinds.Phone.TYPE_OTHER,
            number
    );
}

public static void addEmailToContact(Context context, Long contactRawId, String email) throws RemoteException, OperationApplicationException {
    addInfoToAddressBookContact(
            context,
            contactRawId,
            ContactsContract.CommonDataKinds.Email.CONTENT_ITEM_TYPE,
            ContactsContract.CommonDataKinds.Email.ADDRESS,
            ContactsContract.CommonDataKinds.Email.TYPE,
            ContactsContract.CommonDataKinds.Email.TYPE_OTHER,
            email
    );
}

public static void addURLToContact(Context context, Long contactRawId, String url) throws RemoteException, OperationApplicationException {
    addInfoToAddressBookContact(
            context,
            contactRawId,
            ContactsContract.CommonDataKinds.Website.CONTENT_ITEM_TYPE,
            ContactsContract.CommonDataKinds.Website.URL,
            ContactsContract.CommonDataKinds.Website.TYPE,
            ContactsContract.CommonDataKinds.Website.TYPE_OTHER,
            url
    );
}

private static void addInfoToAddressBookContact(Context context, Long contactRawId, String mimeType, String whatToAdd, String typeKey, int type, String data) throws RemoteException, OperationApplicationException {
    if(ActivityCompat.checkSelfPermission(context, Manifest.permission.WRITE_CONTACTS) == PackageManager.PERMISSION_DENIED) {
        return;
    }
    ArrayList<ContentProviderOperation> ops = new ArrayList<>();
    ops.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI)
            .withValue(ContactsContract.Data.RAW_CONTACT_ID, contactRawId)
            .withValue(ContactsContract.Data.MIMETYPE, mimeType)
            .withValue(whatToAdd, data)
            .withValue(typeKey, type)
            .build());
    getContentResolver().applyBatch(ContactsContract.AUTHORITY, ops);
}

AngularJS : Factory and Service?

  • If you use a service you will get the instance of a function ("this" keyword).
  • If you use a factory you will get the value that is returned by invoking the function reference (the return statement in factory)

Factory and Service are the most commonly used recipes. The only difference between them is that Service recipe works better for objects of custom type, while Factory can produce JavaScript primitives and functions.

Reference

How to save a dictionary to a file?

We can also use the json module in the case when dictionaries or some other data can be easily mapped to JSON format.

import json

# Serialize data into file:
json.dump( data, open( "file_name.json", 'w' ) )

# Read data from file:
data = json.load( open( "file_name.json" ) )

This solution brings many benefits, eg works for Python 2.x and Python 3.x in an unchanged form and in addition, data saved in JSON format can be easily transferred between many different platforms or programs. This data are also human-readable.

Asynchronous Process inside a javascript for loop

JavaScript code runs on a single thread, so you cannot principally block to wait for the first loop iteration to complete before beginning the next without seriously impacting page usability.

The solution depends on what you really need. If the example is close to exactly what you need, @Simon's suggestion to pass i to your async process is a good one.

How do I get started with Node.js

First, learn the core concepts of Node.js:

Then, you're going to want to see what the community has to offer:

The gold standard for Node.js package management is NPM.

Finally, you're going to want to know what some of the more popular packages are for various tasks:

Useful Tools for Every Project:

  • Underscore contains just about every core utility method you want.
  • Lo-Dash is a clone of Underscore that aims to be faster, more customizable, and has quite a few functions that underscore doesn't have. Certain versions of it can be used as drop-in replacements of underscore.
  • TypeScript makes JavaScript considerably more bearable, while also keeping you out of trouble!
  • JSHint is a code-checking tool that'll save you loads of time finding stupid errors. Find a plugin for your text editor that will automatically run it on your code.

Unit Testing:

  • Mocha is a popular test framework.
  • Vows is a fantastic take on asynchronous testing, albeit somewhat stale.
  • Expresso is a more traditional unit testing framework.
  • node-unit is another relatively traditional unit testing framework.
  • AVA is a new test runner with Babel built-in and runs tests concurrently.

Web Frameworks:

  • Express.js is by far the most popular framework.
  • Koa is a new web framework designed by the team behind Express.js, which aims to be a smaller, more expressive, and more robust foundation for web applications and APIs.
  • sails.js the most popular MVC framework for Node.js, and is based on express. It is designed to emulate the familiar MVC pattern of frameworks like Ruby on Rails, but with support for the requirements of modern apps: data-driven APIs with a scalable, service-oriented architecture.
  • Meteor bundles together jQuery, Handlebars, Node.js, WebSocket, MongoDB, and DDP and promotes convention over configuration without being a Ruby on Rails clone.
  • Tower (deprecated) is an abstraction of a top of Express.js that aims to be a Ruby on Rails clone.
  • Geddy is another take on web frameworks.
  • RailwayJS is a Ruby on Rails inspired MVC web framework.
  • Sleek.js is a simple web framework, built upon Express.js.
  • Hapi is a configuration-centric framework with built-in support for input validation, caching, authentication, etc.
  • Trails is a modern web application framework. It builds on the pedigree of Rails and Grails to accelerate development by adhering to a straightforward, convention-based, API-driven design philosophy.

  • Danf is a full-stack OOP framework providing many features in order to produce a scalable, maintainable, testable and performant applications and allowing to code the same way on both the server (Node.js) and client (browser) sides.

  • Derbyjs is a reactive full-stack JavaScript framework. They are using patterns like reactive programming and isomorphic JavaScript for a long time.

  • Loopback.io is a powerful Node.js framework for creating APIs and easily connecting to backend data sources. It has an Angular.js SDK and provides SDKs for iOS and Android.

Web Framework Tools:

Networking:

  • Connect is the Rack or WSGI of the Node.js world.
  • Request is a very popular HTTP request library.
  • socket.io is handy for building WebSocket servers.

Command Line Interaction:

  • minimist just command line argument parsing.
  • Yargs is a powerful library for parsing command-line arguments.
  • Commander.js is a complete solution for building single-use command-line applications.
  • Vorpal.js is a framework for building mature, immersive command-line applications.
  • Chalk makes your CLI output pretty.

Code Generators:

  • Yeoman Scaffolding tool from the command-line.
  • Skaffolder Code generator with visual and command-line interface. It generates a customizable CRUD application starting from the database schema or an OpenAPI 3.0 YAML file.

Work with streams:

Adding a guideline to the editor in Visual Studio

This is originally from Sara's blog.

It also works with almost any version of Visual Studio, you just need to change the "8.0" in the registry key to the appropriate version number for your version of Visual Studio.

The guide line shows up in the Output window too. (Visual Studio 2010 corrects this, and the line only shows up in the code editor window.)

You can also have the guide in multiple columns by listing more than one number after the color specifier:

RGB(230,230,230), 4, 80

Puts a white line at column 4 and column 80. This should be the value of a string value Guides in "Text Editor" key (see bellow).

Be sure to pick a line color that will be visisble on your background. This color won't show up on the default background color in VS. This is the value for a light grey: RGB(221, 221, 221).

Here are the registry keys that I know of:

Visual Studio 2010: HKCU\Software\Microsoft\VisualStudio\10.0\Text Editor

Visual Studio 2008: HKCU\Software\Microsoft\VisualStudio\9.0\Text Editor

Visual Studio 2005: HKCU\Software\Microsoft\VisualStudio\8.0\Text Editor

Visual Studio 2003: HKCU\Software\Microsoft\VisualStudio\7.1\Text Editor

For those running Visual Studio 2010, you may want to install the following extensions rather than changing the registry yourself:

These are also part of the Productivity Power Tools, which includes many other very useful extensions.

Add Items to ListView - Android

ListView myListView = (ListView) rootView.findViewById(R.id.myListView);
ArrayList<String> myStringArray1 = new ArrayList<String>();
myStringArray1.add("something");
adapter = new CustomAdapter(getActivity(), R.layout.row, myStringArray1);
myListView.setAdapter(adapter);

Try it like this

public OnClickListener moreListener = new OnClickListener() {

    @Override
    public void onClick(View v) {
        adapter = null;
        myStringArray1.add("Andrea");
        adapter = new CustomAdapter(getActivity(), R.layout.row, myStringArray1);
        myListView.setAdapter(adapter);
        adapter.notifyDataSetChanged();
    }       
};

How to calculate a Mod b in Casio fx-991ES calculator

This calculator does not have any modulo function. However there is quite simple way how to compute modulo using display mode ab/c (instead of traditional d/c).

How to switch display mode to ab/c:

  • Go to settings (Shift + Mode).
  • Press arrow down (to view more settings).
  • Select ab/c (number 1).

Now do your calculation (in comp mode), like 50 / 3 and you will see 16 2/3, thus, mod is 2. Or try 54 / 7 which is 7 5/7 (mod is 5). If you don't see any fraction then the mod is 0 like 50 / 5 = 10 (mod is 0).

The remainder fraction is shown in reduced form, so 60 / 8 will result in 7 1/2. Remainder is 1/2 which is 4/8 so mod is 4.

EDIT: As @lawal correctly pointed out, this method is a little bit tricky for negative numbers because the sign of the result would be negative.

For example -121 / 26 = -4 17/26, thus, mod is -17 which is +9 in mod 26. Alternatively you can add the modulo base to the computation for negative numbers: -121 / 26 + 26 = 21 9/26 (mod is 9).

EDIT2: As @simpatico pointed out, this method will not work for numbers that are out of calculator's precision. If you want to compute say 200^5 mod 391 then some tricks from algebra are needed. For example, using rule (A * B) mod C = ((A mod C) * B) mod C we can write:

200^5 mod 391 = (200^3 * 200^2) mod 391 = ((200^3 mod 391) * 200^2) mod 391 = 98

How do Mockito matchers work?

Just a small addition to Jeff Bowman's excellent answer, as I found this question when searching for a solution to one of my own problems:

If a call to a method matches more than one mock's when trained calls, the order of the when calls is important, and should be from the most wider to the most specific. Starting from one of Jeff's examples:

when(foo.quux(anyInt(), anyInt())).thenReturn(true);
when(foo.quux(anyInt(), eq(5))).thenReturn(false);

is the order that ensures the (probably) desired result:

foo.quux(3 /*any int*/, 8 /*any other int than 5*/) //returns true
foo.quux(2 /*any int*/, 5) //returns false

If you inverse the when calls then the result would always be true.

Beautiful way to remove GET-variables with PHP?

basename($_SERVER['REQUEST_URI']) returns everything after and including the '?',

In my code sometimes I need only sections, so separate it out so I can get the value of what I need on the fly. Not sure on the performance speed compared to other methods, but it's really useful for me.

$urlprotocol = 'http'; if ($_SERVER["HTTPS"] == "on") {$urlprotocol .= "s";} $urlprotocol .= "://";
$urldomain = $_SERVER["SERVER_NAME"];
$urluri = $_SERVER['REQUEST_URI'];
$urlvars = basename($urluri);
$urlpath = str_replace($urlvars,"",$urluri);

$urlfull = $urlprotocol . $urldomain . $urlpath . $urlvars;

Python: Converting string into decimal number

If you are converting string to float:

import re
A1 = [' "29.0" ',' "65.2" ',' "75.2" ']
float_values = [float(re.search(r'\d+.\d+',number).group()) for number in A1]
print(float_values)
>>> [29.0, 65.2, 75.2]

Passing an array to a query using a WHERE clause

You may have table texts (T_ID (int), T_TEXT (text)) and table test (id (int), var (varchar(255)))

In insert into test values (1, '1,2,3') ; the following will output rows from table texts where T_ID IN (1,2,3):

SELECT * FROM `texts` WHERE (SELECT FIND_IN_SET( T_ID, ( SELECT var FROM test WHERE id =1 ) ) AS tm) >0

This way you can manage a simple n2m database relation without an extra table and using only SQL without the need to use PHP or some other programming language.

Gradle failed to resolve library in Android Studio

To be able to use a lib project you need to include it in your application's settings.gradle add:

include '..:ExpandableButtonMenu:library'

and then in your build.gradle add:

compile project(':..:ExpandableButtonMenu:library') 

place ExpandableButtonMenu project along side your own (same folder)

see this How to build an android library with Android Studio and gradle? for more details.

How do I force a favicon refresh?

Here's how I managed it with a simply animated favicon and FireFox 3.6.13 (beta version) It will probably work for other versions of FireFox as well, let me know if it doesn't. It's basically artlung's solution, but addressing the .gif file as well:

  1. I opened by FTP program, downloaded my favicon.ico AND favicon.gif files,
  2. then DELETED them from my server's files.
  3. Then I opened them in my browser as artlung suggested: http://mysite.com/favicon.ico AND http://mysite.com/favicon.gif Once those addresses loaded and displayed 404 error pages ("page not found")
  4. I THEN uploaded both files back onto my server, and PRESTO - the correct icons were instantly displayed.

Python 3 string.join() equivalent?

'.'.join() or ".".join().. So any string instance has the method join()

Node/Express file upload

Here is an easier way that worked for me:

const express = require('express');
var app = express();
var fs = require('fs');

app.post('/upload', async function(req, res) {

  var file = JSON.parse(JSON.stringify(req.files))

  var file_name = file.file.name

  //if you want just the buffer format you can use it
  var buffer = new Buffer.from(file.file.data.data)

  //uncomment await if you want to do stuff after the file is created

  /*await*/
  fs.writeFile(file_name, buffer, async(err) => {

    console.log("Successfully Written to File.");


    // do what you want with the file it is in (__dirname + "/" + file_name)

    console.log("end  :  " + new Date())

    console.log(result_stt + "")

    fs.unlink(__dirname + "/" + file_name, () => {})
    res.send(result_stt)
  });


});

Test or check if sheet exists

Compact wsExists function (without reliance on Error Handling!)

Here's a short & simple function that doesn't rely on error handling to determine whether a worksheet exists (and is properly declared to work in any situation!)

Function wsExists(wsName As String) As Boolean
    Dim ws: For Each ws In Sheets
    wsExists = (wsName = ws.Name): If wsExists Then Exit Function
    Next ws
End Function

Example Usage:

The following example adds a new worksheet named myNewSheet, if it doesn't already exist:

If Not wsExists("myNewSheet") Then Sheets.Add.Name = "myNewSheet"

More Information:

SQL recursive query on self referencing table (Oracle)

It's a little on the cumbersome side, but I believe this should work (without the extra join). This assumes that you can choose a character that will never appear in the field in question, to act as a separator.

You can do it without nesting the select, but I find this a little cleaner that having four references to SYS_CONNECT_BY_PATH.

select id, 
       parent_id, 
       case 
         when lvl <> 1 
         then substr(name_path,
                     instr(name_path,'|',1,lvl-1)+1,
                     instr(name_path,'|',1,lvl)
                      -instr(name_path,'|',1,lvl-1)-1) 
         end as name 
from (
  SELECT id, parent_id, sys_connect_by_path(name,'|') as name_path, level as lvl
  FROM tbl 
  START WITH id = 1 
  CONNECT BY PRIOR id = parent_id)

How does PHP 'foreach' actually work?

foreach supports iteration over three different kinds of values:

In the following, I will try to explain precisely how iteration works in different cases. By far the simplest case is Traversable objects, as for these foreach is essentially only syntax sugar for code along these lines:

foreach ($it as $k => $v) { /* ... */ }

/* translates to: */

if ($it instanceof IteratorAggregate) {
    $it = $it->getIterator();
}
for ($it->rewind(); $it->valid(); $it->next()) {
    $v = $it->current();
    $k = $it->key();
    /* ... */
}

For internal classes, actual method calls are avoided by using an internal API that essentially just mirrors the Iterator interface on the C level.

Iteration of arrays and plain objects is significantly more complicated. First of all, it should be noted that in PHP "arrays" are really ordered dictionaries and they will be traversed according to this order (which matches the insertion order as long as you didn't use something like sort). This is opposed to iterating by the natural order of the keys (how lists in other languages often work) or having no defined order at all (how dictionaries in other languages often work).

The same also applies to objects, as the object properties can be seen as another (ordered) dictionary mapping property names to their values, plus some visibility handling. In the majority of cases, the object properties are not actually stored in this rather inefficient way. However, if you start iterating over an object, the packed representation that is normally used will be converted to a real dictionary. At that point, iteration of plain objects becomes very similar to iteration of arrays (which is why I'm not discussing plain-object iteration much in here).

So far, so good. Iterating over a dictionary can't be too hard, right? The problems begin when you realize that an array/object can change during iteration. There are multiple ways this can happen:

  • If you iterate by reference using foreach ($arr as &$v) then $arr is turned into a reference and you can change it during iteration.
  • In PHP 5 the same applies even if you iterate by value, but the array was a reference beforehand: $ref =& $arr; foreach ($ref as $v)
  • Objects have by-handle passing semantics, which for most practical purposes means that they behave like references. So objects can always be changed during iteration.

The problem with allowing modifications during iteration is the case where the element you are currently on is removed. Say you use a pointer to keep track of which array element you are currently at. If this element is now freed, you are left with a dangling pointer (usually resulting in a segfault).

There are different ways of solving this issue. PHP 5 and PHP 7 differ significantly in this regard and I'll describe both behaviors in the following. The summary is that PHP 5's approach was rather dumb and lead to all kinds of weird edge-case issues, while PHP 7's more involved approach results in more predictable and consistent behavior.

As a last preliminary, it should be noted that PHP uses reference counting and copy-on-write to manage memory. This means that if you "copy" a value, you actually just reuse the old value and increment its reference count (refcount). Only once you perform some kind of modification a real copy (called a "duplication") will be done. See You're being lied to for a more extensive introduction on this topic.

PHP 5

Internal array pointer and HashPointer

Arrays in PHP 5 have one dedicated "internal array pointer" (IAP), which properly supports modifications: Whenever an element is removed, there will be a check whether the IAP points to this element. If it does, it is advanced to the next element instead.

While foreach does make use of the IAP, there is an additional complication: There is only one IAP, but one array can be part of multiple foreach loops:

// Using by-ref iteration here to make sure that it's really
// the same array in both loops and not a copy
foreach ($arr as &$v1) {
    foreach ($arr as &$v) {
        // ...
    }
}

To support two simultaneous loops with only one internal array pointer, foreach performs the following shenanigans: Before the loop body is executed, foreach will back up a pointer to the current element and its hash into a per-foreach HashPointer. After the loop body runs, the IAP will be set back to this element if it still exists. If however the element has been removed, we'll just use wherever the IAP is currently at. This scheme mostly-kinda-sort of works, but there's a lot of weird behavior you can get out of it, some of which I'll demonstrate below.

Array duplication

The IAP is a visible feature of an array (exposed through the current family of functions), as such changes to the IAP count as modifications under copy-on-write semantics. This, unfortunately, means that foreach is in many cases forced to duplicate the array it is iterating over. The precise conditions are:

  1. The array is not a reference (is_ref=0). If it's a reference, then changes to it are supposed to propagate, so it should not be duplicated.
  2. The array has refcount>1. If refcount is 1, then the array is not shared and we're free to modify it directly.

If the array is not duplicated (is_ref=0, refcount=1), then only its refcount will be incremented (*). Additionally, if foreach by reference is used, then the (potentially duplicated) array will be turned into a reference.

Consider this code as an example where duplication occurs:

function iterate($arr) {
    foreach ($arr as $v) {}
}

$outerArr = [0, 1, 2, 3, 4];
iterate($outerArr);

Here, $arr will be duplicated to prevent IAP changes on $arr from leaking to $outerArr. In terms of the conditions above, the array is not a reference (is_ref=0) and is used in two places (refcount=2). This requirement is unfortunate and an artifact of the suboptimal implementation (there is no concern of modification during iteration here, so we don't really need to use the IAP in the first place).

(*) Incrementing the refcount here sounds innocuous, but violates copy-on-write (COW) semantics: This means that we are going to modify the IAP of a refcount=2 array, while COW dictates that modifications can only be performed on refcount=1 values. This violation results in user-visible behavior change (while a COW is normally transparent) because the IAP change on the iterated array will be observable -- but only until the first non-IAP modification on the array. Instead, the three "valid" options would have been a) to always duplicate, b) do not increment the refcount and thus allowing the iterated array to be arbitrarily modified in the loop or c) don't use the IAP at all (the PHP 7 solution).

Position advancement order

There is one last implementation detail that you have to be aware of to properly understand the code samples below. The "normal" way of looping through some data structure would look something like this in pseudocode:

reset(arr);
while (get_current_data(arr, &data) == SUCCESS) {
    code();
    move_forward(arr);
}

However foreach, being a rather special snowflake, chooses to do things slightly differently:

reset(arr);
while (get_current_data(arr, &data) == SUCCESS) {
    move_forward(arr);
    code();
}

Namely, the array pointer is already moved forward before the loop body runs. This means that while the loop body is working on element $i, the IAP is already at element $i+1. This is the reason why code samples showing modification during iteration will always unset the next element, rather than the current one.

Examples: Your test cases

The three aspects described above should provide you with a mostly complete impression of the idiosyncrasies of the foreach implementation and we can move on to discuss some examples.

The behavior of your test cases is simple to explain at this point:

  • In test cases 1 and 2 $array starts off with refcount=1, so it will not be duplicated by foreach: Only the refcount is incremented. When the loop body subsequently modifies the array (which has refcount=2 at that point), the duplication will occur at that point. Foreach will continue working on an unmodified copy of $array.

  • In test case 3, once again the array is not duplicated, thus foreach will be modifying the IAP of the $array variable. At the end of the iteration, the IAP is NULL (meaning iteration has done), which each indicates by returning false.

  • In test cases 4 and 5 both each and reset are by-reference functions. The $array has a refcount=2 when it is passed to them, so it has to be duplicated. As such foreach will be working on a separate array again.

Examples: Effects of current in foreach

A good way to show the various duplication behaviors is to observe the behavior of the current() function inside a foreach loop. Consider this example:

foreach ($array as $val) {
    var_dump(current($array));
}
/* Output: 2 2 2 2 2 */

Here you should know that current() is a by-ref function (actually: prefer-ref), even though it does not modify the array. It has to be in order to play nice with all the other functions like next which are all by-ref. By-reference passing implies that the array has to be separated and thus $array and the foreach-array will be different. The reason you get 2 instead of 1 is also mentioned above: foreach advances the array pointer before running the user code, not after. So even though the code is at the first element, foreach already advanced the pointer to the second.

Now lets try a small modification:

$ref = &$array;
foreach ($array as $val) {
    var_dump(current($array));
}
/* Output: 2 3 4 5 false */

Here we have the is_ref=1 case, so the array is not copied (just like above). But now that it is a reference, the array no longer has to be duplicated when passing to the by-ref current() function. Thus current() and foreach work on the same array. You still see the off-by-one behavior though, due to the way foreach advances the pointer.

You get the same behavior when doing by-ref iteration:

foreach ($array as &$val) {
    var_dump(current($array));
}
/* Output: 2 3 4 5 false */

Here the important part is that foreach will make $array an is_ref=1 when it is iterated by reference, so basically you have the same situation as above.

Another small variation, this time we'll assign the array to another variable:

$foo = $array;
foreach ($array as $val) {
    var_dump(current($array));
}
/* Output: 1 1 1 1 1 */

Here the refcount of the $array is 2 when the loop is started, so for once we actually have to do the duplication upfront. Thus $array and the array used by foreach will be completely separate from the outset. That's why you get the position of the IAP wherever it was before the loop (in this case it was at the first position).

Examples: Modification during iteration

Trying to account for modifications during iteration is where all our foreach troubles originated, so it serves to consider some examples for this case.

Consider these nested loops over the same array (where by-ref iteration is used to make sure it really is the same one):

foreach ($array as &$v1) {
    foreach ($array as &$v2) {
        if ($v1 == 1 && $v2 == 1) {
            unset($array[1]);
        }
        echo "($v1, $v2)\n";
    }
}

// Output: (1, 1) (1, 3) (1, 4) (1, 5)

The expected part here is that (1, 2) is missing from the output because element 1 was removed. What's probably unexpected is that the outer loop stops after the first element. Why is that?

The reason behind this is the nested-loop hack described above: Before the loop body runs, the current IAP position and hash is backed up into a HashPointer. After the loop body it will be restored, but only if the element still exists, otherwise the current IAP position (whatever it may be) is used instead. In the example above this is exactly the case: The current element of the outer loop has been removed, so it will use the IAP, which has already been marked as finished by the inner loop!

Another consequence of the HashPointer backup+restore mechanism is that changes to the IAP through reset() etc. usually do not impact foreach. For example, the following code executes as if the reset() were not present at all:

$array = [1, 2, 3, 4, 5];
foreach ($array as &$value) {
    var_dump($value);
    reset($array);
}
// output: 1, 2, 3, 4, 5

The reason is that, while reset() temporarily modifies the IAP, it will be restored to the current foreach element after the loop body. To force reset() to make an effect on the loop, you have to additionally remove the current element, so that the backup/restore mechanism fails:

$array = [1, 2, 3, 4, 5];
$ref =& $array;
foreach ($array as $value) {
    var_dump($value);
    unset($array[1]);
    reset($array);
}
// output: 1, 1, 3, 4, 5

But, those examples are still sane. The real fun starts if you remember that the HashPointer restore uses a pointer to the element and its hash to determine whether it still exists. But: Hashes have collisions, and pointers can be reused! This means that, with a careful choice of array keys, we can make foreach believe that an element that has been removed still exists, so it will jump directly to it. An example:

$array = ['EzEz' => 1, 'EzFY' => 2, 'FYEz' => 3];
$ref =& $array;
foreach ($array as $value) {
    unset($array['EzFY']);
    $array['FYFY'] = 4;
    reset($array);
    var_dump($value);
}
// output: 1, 4

Here we should normally expect the output 1, 1, 3, 4 according to the previous rules. How what happens is that 'FYFY' has the same hash as the removed element 'EzFY', and the allocator happens to reuse the same memory location to store the element. So foreach ends up directly jumping to the newly inserted element, thus short-cutting the loop.

Substituting the iterated entity during the loop

One last odd case that I'd like to mention, it is that PHP allows you to substitute the iterated entity during the loop. So you can start iterating on one array and then replace it with another array halfway through. Or start iterating on an array and then replace it with an object:

$arr = [1, 2, 3, 4, 5];
$obj = (object) [6, 7, 8, 9, 10];

$ref =& $arr;
foreach ($ref as $val) {
    echo "$val\n";
    if ($val == 3) {
        $ref = $obj;
    }
}
/* Output: 1 2 3 6 7 8 9 10 */

As you can see in this case PHP will just start iterating the other entity from the start once the substitution has happened.

PHP 7

Hashtable iterators

If you still remember, the main problem with array iteration was how to handle removal of elements mid-iteration. PHP 5 used a single internal array pointer (IAP) for this purpose, which was somewhat suboptimal, as one array pointer had to be stretched to support multiple simultaneous foreach loops and interaction with reset() etc. on top of that.

PHP 7 uses a different approach, namely, it supports creating an arbitrary amount of external, safe hashtable iterators. These iterators have to be registered in the array, from which point on they have the same semantics as the IAP: If an array element is removed, all hashtable iterators pointing to that element will be advanced to the next element.

This means that foreach will no longer use the IAP at all. The foreach loop will be absolutely no effect on the results of current() etc. and its own behavior will never be influenced by functions like reset() etc.

Array duplication

Another important change between PHP 5 and PHP 7 relates to array duplication. Now that the IAP is no longer used, by-value array iteration will only do a refcount increment (instead of duplication the array) in all cases. If the array is modified during the foreach loop, at that point a duplication will occur (according to copy-on-write) and foreach will keep working on the old array.

In most cases, this change is transparent and has no other effect than better performance. However, there is one occasion where it results in different behavior, namely the case where the array was a reference beforehand:

$array = [1, 2, 3, 4, 5];
$ref = &$array;
foreach ($array as $val) {
    var_dump($val);
    $array[2] = 0;
}
/* Old output: 1, 2, 0, 4, 5 */
/* New output: 1, 2, 3, 4, 5 */

Previously by-value iteration of reference-arrays was special cases. In this case, no duplication occurred, so all modifications of the array during iteration would be reflected by the loop. In PHP 7 this special case is gone: A by-value iteration of an array will always keep working on the original elements, disregarding any modifications during the loop.

This, of course, does not apply to by-reference iteration. If you iterate by-reference all modifications will be reflected by the loop. Interestingly, the same is true for by-value iteration of plain objects:

$obj = new stdClass;
$obj->foo = 1;
$obj->bar = 2;
foreach ($obj as $val) {
    var_dump($val);
    $obj->bar = 42;
}
/* Old and new output: 1, 42 */

This reflects the by-handle semantics of objects (i.e. they behave reference-like even in by-value contexts).

Examples

Let's consider a few examples, starting with your test cases:

  • Test cases 1 and 2 retain the same output: By-value array iteration always keep working on the original elements. (In this case, even refcounting and duplication behavior is exactly the same between PHP 5 and PHP 7).

  • Test case 3 changes: Foreach no longer uses the IAP, so each() is not affected by the loop. It will have the same output before and after.

  • Test cases 4 and 5 stay the same: each() and reset() will duplicate the array before changing the IAP, while foreach still uses the original array. (Not that the IAP change would have mattered, even if the array was shared.)

The second set of examples was related to the behavior of current() under different reference/refcounting configurations. This no longer makes sense, as current() is completely unaffected by the loop, so its return value always stays the same.

However, we get some interesting changes when considering modifications during iteration. I hope you will find the new behavior saner. The first example:

$array = [1, 2, 3, 4, 5];
foreach ($array as &$v1) {
    foreach ($array as &$v2) {
        if ($v1 == 1 && $v2 == 1) {
            unset($array[1]);
        }
        echo "($v1, $v2)\n";
    }
}

// Old output: (1, 1) (1, 3) (1, 4) (1, 5)
// New output: (1, 1) (1, 3) (1, 4) (1, 5)
//             (3, 1) (3, 3) (3, 4) (3, 5)
//             (4, 1) (4, 3) (4, 4) (4, 5)
//             (5, 1) (5, 3) (5, 4) (5, 5) 

As you can see, the outer loop no longer aborts after the first iteration. The reason is that both loops now have entirely separate hashtable iterators, and there is no longer any cross-contamination of both loops through a shared IAP.

Another weird edge case that is fixed now, is the odd effect you get when you remove and add elements that happen to have the same hash:

$array = ['EzEz' => 1, 'EzFY' => 2, 'FYEz' => 3];
foreach ($array as &$value) {
    unset($array['EzFY']);
    $array['FYFY'] = 4;
    var_dump($value);
}
// Old output: 1, 4
// New output: 1, 3, 4

Previously the HashPointer restore mechanism jumped right to the new element because it "looked" like it's the same as the removed element (due to colliding hash and pointer). As we no longer rely on the element hash for anything, this is no longer an issue.

alternative to "!is.null()" in R

I have also seen:

if(length(obj)) {
  # do this if object has length
  # NULL has no length
}

I don't think it's great though. Because some vectors can be of length 0. character(0), logical(0), integer(0) and that might be treated as a NULL instead of an error.

Servlet returns "HTTP Status 404 The requested resource (/servlet) is not available"

Check if you have entered the correct URL Mapping as specified in the Web.xml

For example:

In the web.xml, your servlet declaration maybe:

<servlet>
        <servlet-name>ControllerA</servlet-name>
        <servlet-class>PackageName.ControllerA</servlet-class>
</servlet>

<servlet-mapping>
        <servlet-name>ControllerA</servlet-name>
        <url-pattern>/theController</url-pattern>
</servlet-mapping>

What this snippet does is <url-pattern>/theController</url-pattern>will set the name that will be used to call the servlet from the front end (eg: form) through the URL. Therefore when you reference the servlet in the front end, in order to ensure that the request goes to the servlet "ControllerA", it should refer the specified URL Pattern "theController" from the form.

eg:

<form action="theController" method="POST">
</form>

XPath Query: get attribute href from a tag

The answer shared by @mockinterface is correct. Although I would like to add my 2 cents to it.

If someone is using frameworks like scrapy the you will have to use /html/body//a[contains(@href,'com')][2]/@href along with get() like this:

response.xpath('//a[contains(@href,'com')][2]/@href').get()

X-Frame-Options: ALLOW-FROM in firefox and chrome

For Chrome, instead of

response.AppendHeader("X-Frame-Options", "ALLOW-FROM " + host);

you need to add Content-Security-Policy

string selfAuth = System.Web.HttpContext.Current.Request.Url.Authority;
string refAuth = System.Web.HttpContext.Current.Request.UrlReferrer.Authority;
response.AppendHeader("Content-Security-Policy", "default-src 'self' 'unsafe-inline' 'unsafe-eval' data: *.msecnd.net vortex.data.microsoft.com " + selfAuth + " " + refAuth);

to the HTTP-response-headers.
Note that this assumes you checked on the server whether or not refAuth is allowed.
And also, note that you need to do browser-detection in order to avoid adding the allow-from header for Chrome (outputs error on console).

For details, see my answer here.

What is the use of ObservableCollection in .net?

ObservableCollection Caveat

Mentioned above (Said Roohullah Allem)

What makes the ObservableCollection class unique is that this class supports an event named CollectionChanged.

Keep this in mind...If you adding a large number of items to an ObservableCollection the UI will also update that many times. This can really gum up or freeze your UI. A work around would be to create a new list, add all the items then set your property to the new list. This hits the UI once. Again...this is for adding a large number of items.

Android Studio - Unable to find valid certification path to requested target

Check proxy application like fiddler in your system, If its running close that application and restart your android studio

How to use code to open a modal in Angular 2?

@ng-bootstrap/ng-bootstrap npm I m using for this as in the project bootstrap is used, for material, we used dialog

HTML Code

  <span (click)="openModal(modalRef)" class="form-control input-underline pl-3 ">Open Abc Modal
 </span>

Modal template

<ng-template class="custom-modal"  #modalRef let-c="close" let-d="dismiss">
   <div class="modal-header custom-modal-head"><h4 class="modal-title">List of Countries</h4>
     <button type="button" class="close" aria-label="Close" (click)="d('Cross click')">
         <img src="assets/actor/images/close.png" alt="">
      </button>
  </div>
  <div class="modal-body country-select">
       <div class="serch-field">
           <div class="row">
               <div class="col-md-12">
                 <input type="text"  class="form-control input-underline pl-3" placeholder="Search Country"
                    [(ngModel)]="countryWorkQuery" [ngModelOptions]="{standalone: true}">
                 <ul *ngIf="countries" class="ng-star-inserted">
                   <li (click)="setSelectedCountry(cntry, 'work');d('Cross click');" class="cursor-pointer"
                   *ngFor="let cntry of countries | filterNames:countryWorkQuery ">{{cntry.name}}</li>
                 </ul>
                 <span *ngIf="!modalSpinner && (!countries || countries.length<=0)">No country found</span>
                 <span *ngIf="modalSpinner" class="loader">
                     <img src="assets/images/loader.gif" alt="loader">
                 </span>
               </div>
             </div>
       </div>
 </div>
</ng-template>

Ts File

import {NgbModal, ModalDismissReasons} from '@ng-bootstrap/ng-bootstrap';

constructor(
    private modalService: NgbModal
  ) { }

  openModal(modalContent){
     this.modalService.open(modalContent, { centered: true});
   }

SQL Query to add a new column after an existing column in SQL Server 2005

If you want to alter order for columns in Sql server, There is no direct way to do this in SQL Server currently.

Have a look at http://blog.sqlauthority.com/2008/04/08/sql-server-change-order-of-column-in-database-tables/

You can change order while edit design for table.

MySQL "between" clause not inclusive?

The problem is that 2011-01-31 really is 2011-01-31 00:00:00. That is the beginning of the day. Everything during the day is not included.

How to set "value" to input web element using selenium?

driver.findElement(By.id("invoice_supplier_id")).setAttribute("value", "your value");

Error Handler - Exit Sub vs. End Sub

Your ProcExit label is your place where you release all the resources whether an error happened or not. For instance:

Public Sub SubA()
  On Error Goto ProcError

  Connection.Open
  Open File for Writing
  SomePreciousResource.GrabIt

ProcExit:  
  Connection.Close
  Connection = Nothing
  Close File
  SomePreciousResource.Release

  Exit Sub

ProcError:  
  MsgBox Err.Description  
  Resume ProcExit
End Sub

Warning: The method assertEquals from the type Assert is deprecated

this method also encounter a deprecate warning:

org.junit.Assert.assertEquals(float expected,float actual) //deprecated

It is because currently junit prefer a third parameter rather than just two float variables input.

The third parameter is delta:

public static void assertEquals(double expected,double actual,double delta) //replacement

this is mostly used to deal with inaccurate Floating point calculations

for more information, please refer this problem: Meaning of epsilon argument of assertEquals for double values

Twig for loop for arrays with keys

There's this example in the SensioLab page on the for tag:

<h1>Members</h1>
<ul>
    {% for key, user in users %}
        <li>{{ key }}: {{ user.username|e }}</li>
    {% endfor %}
</ul>

http://twig.sensiolabs.org/doc/tags/for.html#iterating-over-keys

Error: ANDROID_HOME is not set and "android" command not in your PATH. You must fulfill at least one of these conditions.

For those who are working with Ionic Framework on windows and doesn't have andorid studio installed on their PCs, you must have either download Android Studio or at list download the SDK Manager.

If you choose the SDK Manager option you have to set the path for the Enviroment Variable:

  1. Variable name: ANDROID_HOME, Variable value: the path where you installed the android SDK, in my case is, C:\Android\android-sdk.

  2. You have to add the variable to the Path variable system by adding this: ;%ANDROID_HOME%\platform-tools;%ANDROID_HOME%\tools;.

  3. Then if you got the "JDK error" just download it from the Oracle website and create a system variable like the Android SDK: Variable name: JAVA_HOME, Variable value: the path where you installed the JDK, in my case is, C:\Program Files\Java\jdk1.8.0_144. Then add it to the Path variable system by adding ;%JAVA_HOME%\bin.

  4. Then if you got the "Gradle error" just fallow the installations steps on the official website of gradle.

  5. Finally you can continue to creating your ionic app's apk.

Note: you have to reopen the cmd window several times or restart your pc after making those changes. Hope this work for you.

MySQL Event Scheduler on a specific time everyday

This might be too late for your work, but here is how I did it. I want something run everyday at 1AM - I believe this is similar to what you are doing. Here is how I did it:

CREATE EVENT event_name
  ON SCHEDULE
    EVERY 1 DAY
    STARTS (TIMESTAMP(CURRENT_DATE) + INTERVAL 1 DAY + INTERVAL 1 HOUR)
  DO
    # Your awesome query

Encoding conversion in java

UTF-8 and UCS-2/UTF-16 can be distinguished reasonably easily via a byte order mark at the start of the file. If this exists then it's a pretty good bet that the file is in that encoding - but it's not a dead certainty. You may well also find that the file is in one of those encodings, but doesn't have a byte order mark.

I don't know much about ISO-8859-2, but I wouldn't be surprised if almost every file is a valid text file in that encoding. The best you'll be able to do is check it heuristically. Indeed, the Wikipedia page talking about it would suggest that only byte 0x7f is invalid.

There's no idea of reading a file "as it is" and yet getting text out - a file is a sequence of bytes, so you have to apply a character encoding in order to decode those bytes into characters.

Source by stackoverflow

Angular js init ng-model from default values

You can also use within your HTML code: ng-init="card.description = 12345"

It is not recommended by Angular, and as mentioned above you should use exclusively your controller.

But it works :)

How can I shuffle an array?

You could use the Fisher-Yates Shuffle (code adapted from this site):

function shuffle(array) {
    let counter = array.length;

    // While there are elements in the array
    while (counter > 0) {
        // Pick a random index
        let index = Math.floor(Math.random() * counter);

        // Decrease counter by 1
        counter--;

        // And swap the last element with it
        let temp = array[counter];
        array[counter] = array[index];
        array[index] = temp;
    }

    return array;
}

How to write multiple conditions in Makefile.am with "else if"

I would accept ldav1s' answer if I were you, but I just want to point out that 'else if' can be written in terms of 'else's and 'if's in any language:

if HAVE_CLIENT
  libtest_LIBS = $(top_builddir)/libclient.la
else
  if HAVE_SERVER
    libtest_LIBS = $(top_builddir)/libserver.la
  else
    libtest_LIBS = 
  endif
endif

(The indentation is for clarity. Don't indent the lines, they won't work.)

Java and HTTPS url connection without downloading certificate

Use the latest X509ExtendedTrustManager instead of X509Certificate as advised here: java.security.cert.CertificateException: Certificates does not conform to algorithm constraints

    package javaapplication8;

    import java.io.InputStream;
    import java.net.Socket;
    import java.net.URL;
    import java.net.URLConnection;
    import java.security.cert.CertificateException;
    import java.security.cert.X509Certificate;
    import javax.net.ssl.HostnameVerifier;
    import javax.net.ssl.HttpsURLConnection;
    import javax.net.ssl.SSLContext;
    import javax.net.ssl.SSLEngine;
    import javax.net.ssl.SSLSession;
    import javax.net.ssl.TrustManager;
    import javax.net.ssl.X509ExtendedTrustManager;

    /**
     *
     * @author hoshantm
     */
    public class JavaApplication8 {

        /**
         * @param args the command line arguments
         * @throws java.lang.Exception
         */
        public static void main(String[] args) throws Exception {
            /*
             *  fix for
             *    Exception in thread "main" javax.net.ssl.SSLHandshakeException:
             *       sun.security.validator.ValidatorException:
             *           PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException:
             *               unable to find valid certification path to requested target
             */
            TrustManager[] trustAllCerts = new TrustManager[]{
                new X509ExtendedTrustManager() {
                    @Override
                    public java.security.cert.X509Certificate[] getAcceptedIssuers() {
                        return null;
                    }

                    @Override
                    public void checkClientTrusted(X509Certificate[] certs, String authType) {
                    }

                    @Override
                    public void checkServerTrusted(X509Certificate[] certs, String authType) {
                    }

                    @Override
                    public void checkClientTrusted(X509Certificate[] xcs, String string, Socket socket) throws CertificateException {

                    }

                    @Override
                    public void checkServerTrusted(X509Certificate[] xcs, String string, Socket socket) throws CertificateException {

                    }

                    @Override
                    public void checkClientTrusted(X509Certificate[] xcs, String string, SSLEngine ssle) throws CertificateException {

                    }

                    @Override
                    public void checkServerTrusted(X509Certificate[] xcs, String string, SSLEngine ssle) throws CertificateException {

                    }

                }
            };

            SSLContext sc = SSLContext.getInstance("SSL");
            sc.init(null, trustAllCerts, new java.security.SecureRandom());
            HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());

            // Create all-trusting host name verifier
            HostnameVerifier allHostsValid = new HostnameVerifier() {
                @Override
                public boolean verify(String hostname, SSLSession session) {
                    return true;
                }
            };
            // Install the all-trusting host verifier
            HttpsURLConnection.setDefaultHostnameVerifier(allHostsValid);
            /*
             * end of the fix
             */

            URL url = new URL("https://10.52.182.224/cgi-bin/dynamic/config/panel.bmp");
            URLConnection con = url.openConnection();
            //Reader reader = new ImageStreamReader(con.getInputStream());

            InputStream is = new URL(url.toString()).openStream();

            // Whatever you may want to do next

        }

    }

iPhone and WireShark

You can use Paros to sniff the network traffic from your iPhone. See this excellent step by step post for more information: http://blog.jerodsanto.net/2009/06/sniff-your-iphones-network-traffic/. Also, look in the comments for some advice for using other proxies to get the same job done.

One caveat is that Paras only sniffs HTTP GET/POST requests using the method above, so to sniff all network traffic, try the following:

  1. Just turn on network sharing over WiFi and run a packet sniffer like Cocoa Packet Analyzer (in OSX).
  2. Then connect to the new network from iPhone over WiFi. (SystemPreferences->Sharing->InternetSharing)

If you're after sniffing these packets on Windows, connect to the internet using Ethernet, share your internet connection, and use the Windows computer as your access point. Then, just run Wireshark as normal and intercept the packets flowing through, filtering by their startpoints. Alternatively, try using a network hub as Wireshark can trace all packets flowing through a network if they are using the same router endpoint address (as in a hub).

Android Studio emulator does not come with Play Store for API 23

Just want to add another solution for React Native users that just need the Expo app.

  1. Install the Expo app
  2. Open you project
  3. Click Device -> Open on Android - In this stage Expo will install the expo android app and you'll be able to open it.

Why do I get AttributeError: 'NoneType' object has no attribute 'something'?

Others have explained what NoneType is and a common way of ending up with it (i.e., failure to return a value from a function).

Another common reason you have None where you don't expect it is assignment of an in-place operation on a mutable object. For example:

mylist = mylist.sort()

The sort() method of a list sorts the list in-place, that is, mylist is modified. But the actual return value of the method is None and not the list sorted. So you've just assigned None to mylist. If you next try to do, say, mylist.append(1) Python will give you this error.

SQL Server: IF EXISTS ; ELSE

I know its been a while since the original post but I like using CTE's and this worked for me:

WITH cte_table_a
AS
(
    SELECT [id] [id]
    , MAX([value]) [value]
    FROM table_a
    GROUP BY [id]
)
UPDATE table_b
SET table_b.code = CASE WHEN cte_table_a.[value] IS NOT NULL THEN cte_table_a.[value] ELSE 124 END
FROM table_b
LEFT OUTER JOIN  cte_table_a
ON table_b.id = cte_table_a.id

The parameters dictionary contains a null entry for parameter 'id' of non-nullable type 'System.Int32'

Just change your line of code to

<a href="~/Required/[email protected]">Edit</a>

from where you are calling this function that will pass corect id

Disabling enter key for form

if you use jQuery, its quite simple. Here you go

$(document).keypress(
  function(event){
    if (event.which == '13') {
      event.preventDefault();
    }
});

git rebase merge conflict

If you have a lot of commits to rebase, and some part of them are giving conflicts, that really hurts. But I can suggest a less-known approach how to "squash all the conflicts".

First, checkout temp branch and start standard merge

git checkout -b temp
git merge origin/master

You will have to resolve conflicts, but only once and only real ones. Then stage all files and finish merge.

git commit -m "Merge branch 'origin/master' into 'temp'"

Then return to your branch (let it be alpha) and start rebase, but with automatical resolving any conflicts.

git checkout alpha
git rebase origin/master -X theirs

Branch has been rebased, but project is probably in invalid state. That's OK, we have one final step. We just need to restore project state, so it will be exact as on branch 'temp'. Technically we just need to copy its tree (folder state) via low-level command git commit-tree. Plus merging into current branch just created commit.

git merge --ff $(git commit-tree temp^{tree} -m "Fix after rebase" -p HEAD)

And delete temporary branch

git branch -D temp

That's all. We did a rebase via hidden merge.

Also I wrote a script, so that can be done in a dialog manner, you can find it here.

Why does "pip install" inside Python raise a SyntaxError?

To run pip in Python 3.x, just follow the instructions on Python's page: Installing Python Modules.

python -m pip install SomePackage

Note that this is run from the command line and not the python shell (the reason for syntax error in the original question).

Java logical operator short-circuiting

Logical OR :- returns true if at least one of the operands evaluate to true. Both operands are evaluated before apply the OR operator.

Short Circuit OR :- if left hand side operand returns true, it returns true without evaluating the right hand side operand.

jQuery animate margin top

use the following code to apply some margin

$(".button").click(function() {
  $('html, body').animate({
    scrollTop: $(".scrolltothis").offset().top + 50;
  }, 500);
});

See this ans: Scroll down to div + a certain margin

Adding elements to a C# array

What's abaut this one:

List<int> tmpList = intArry.ToList(); tmpList.Add(anyInt); intArry = tmpList.ToArray();

"Connection for controluser as defined in your configuration failed" with phpMyAdmin in XAMPP

  1. Open phpMyAdmin in a browser and log in as root.
  2. Create a database called phpmyadmin
  3. Create a user called pma and set the "host" to the hostname or IP address of your web server (if the web server and MySQL are on the same box use localhost), make a note of the password, and grant the new user full control over the phpmyadmin database. It is recommended that this user does not have access to anything other than this database.
  4. Go to the phpMyAdmin installation directory, where you should find a sub-directory called sql.
  5. In sql you will find a file called create_tables.sql. Open it in a text editor.
  6. In phpMyAdmin, select the phpmyadmin database and click on the "SQL" tab.
  7. Copy/paste the entire text from create_tables.sql into the text box, and run the query.
  8. Open the config.inc.php file in the phpMyAdmin install directory, and add the following lines (or change the existing settings if they are already there):

    $cfg['Servers'][1]['pmadb'] = 'phpmyadmin';
    $cfg['Servers'][1]['controluser'] = 'pma';
    $cfg['Servers'][1]['controlpass'] = '<your password>';
    
    // Note: The list below may grow as PMA evolves and more control tables are added
    // Use your common sense! Don't just blindly copypasta, look at what it means!
    $cfg['Servers'][1]['bookmarktable'] = 'pma_bookmark';
    $cfg['Servers'][1]['relation'] = 'pma_relation';
    $cfg['Servers'][1]['userconfig'] = 'pma_userconfig';
    $cfg['Servers'][1]['table_info'] = 'pma_table_info';
    $cfg['Servers'][1]['column_info'] = 'pma_column_info';
    $cfg['Servers'][1]['history'] = 'pma_history';
    $cfg['Servers'][1]['recent'] = 'pma_recent';
    $cfg['Servers'][1]['table_uiprefs'] = 'pma_table_uiprefs';
    $cfg['Servers'][1]['tracking'] = 'pma_tracking';
    $cfg['Servers'][1]['table_coords'] = 'pma_table_coords';
    $cfg['Servers'][1]['pdf_pages'] = 'pma_pdf_pages';
    $cfg['Servers'][1]['designer_coords'] = 'pma_designer_coords';
    
  9. Save and close the file.

IMPORTANT - PMA loads the config on login, evaluates it and stores it into the session data so the message will not disappear until you do this:

  1. Log out of phpMyAdmin and log in again

Problem solved.

How to remove pip package after deleting it manually

I met the same issue while experimenting with my own Python library and what I've found out is that pip freeze will show you the library as installed if your current directory contains lib.egg-info folder. And pip uninstall <lib> will give you the same error message.

  1. Make sure your current directory doesn't have any egg-info folders
  2. Check pip show <lib-name> to see the details about the location of the library, so you can remove files manually.

Edit a commit message in SourceTree Windows (already pushed to remote)

Here are the steps to edit the commit message of a previous commit (which is not the most recent commit) using SourceTree for Windows version 1.5.2.0:

Step 1

Select the commit immediately before the commit that you want to edit. For example, if I want to edit the commit with message "FOOBAR!" then I need to select the commit that comes right before it:

Selecting commit before the one that I want to edit.

Step 2

Right-click on the selected commit and click Rebase children...interactively:

Selecting "Rebase children interactively".

Step 3

Select the commit that you want to edit, then click Edit Message at the bottom. In this case, I'm selecting the commit with the message "FOOBAR!":

Select the commit that you want to edit.

Step 4

Edit the commit message, and then click OK. In my example, I've added "SHAZBOT! SKADOOSH!"

Edit the commit message

Step 5

When you return to interactive rebase window, click on OK to finish the rebase:

Click OK to finish.

Step 6

At this point, you'll need to force-push your new changes since you've rebased commits that you've already pushed. However, the current 1.5.2.0 version of SourceTree for Windows does not allow you to force-push through the GUI, so you'll need to use Git from the command line anyways in order to do that.

Click Terminal from the GUI to open up a terminal.

Click Terminal

Step 7

From the terminal force-push with the following command,

git push origin <branch> -f

where <branch> is the name of the branch that you want to push, and -f means to force the push. The force push will overwrite your commits on your remote repo, but that's OK in your case since you said that you're not sharing your repo with other people.

That's it! You're done!

how to execute a scp command with the user name and password in one line

Using sshpass works best. To just include your password in scp use the ' ':

scp user1:'password'@xxx.xxx.x.5:sys_config /var/www/dev/

Get GMT Time in Java

This is pretty simple and straight forward.

Date date = new Date();
TimeZone.setDefault(TimeZone.getTimeZone("GMT"));
Calendar cal = Calendar.getInstance(TimeZone.getDefault());
date = cal.getTime();

Now date will contain the current GMT time.

How do you find out the caller function in JavaScript?

Just want to let you know that on PhoneGap/Android the name doesnt seem to be working. But arguments.callee.caller.toString() will do the trick.

Confirm deletion using Bootstrap 3 modal box

You can use Bootbox dialog boxes

$(document).ready(function() {

  $('#btnDelete').click(function() {
    bootbox.confirm("Are you sure want to delete?", function(result) {
      alert("Confirm result: " + result);
    });
  });
});

Plunker Demo

Change the Blank Cells to "NA"

My function takes into account factor, character vector and potential attributes, if you use haven or foreign package to read external files. Also it allows matching different self-defined na.strings. To transform all columns, simply use lappy: df[] = lapply(df, blank2na, na.strings=c('','NA','na','N/A','n/a','NaN','nan'))

See more the comments:

#' Replaces blank-ish elements of a factor or character vector to NA
#' @description Replaces blank-ish elements of a factor or character vector to NA
#' @param x a vector of factor or character or any type
#' @param na.strings case sensitive strings that will be coverted to NA. The function will do a trimws(x,'both') before conversion. If NULL, do only trimws, no conversion to NA.
#' @return Returns a vector trimws (always for factor, character) and NA converted (if matching na.strings). Attributes will also be kept ('label','labels', 'value.labels').
#' @seealso \code{\link{ez.nan2na}}
#' @export
blank2na = function(x,na.strings=c('','.','NA','na','N/A','n/a','NaN','nan')) {
    if (is.factor(x)) {
        lab = attr(x, 'label', exact = T)
        labs1 <- attr(x, 'labels', exact = T)
        labs2 <- attr(x, 'value.labels', exact = T)

        # trimws will convert factor to character
        x = trimws(x,'both')
        if (! is.null(lab)) lab = trimws(lab,'both')
        if (! is.null(labs1)) labs1 = trimws(labs1,'both')
        if (! is.null(labs2)) labs2 = trimws(labs2,'both')

        if (!is.null(na.strings)) {
            # convert to NA
            x[x %in% na.strings] = NA
            # also remember to remove na.strings from value labels 
            labs1 = labs1[! labs1 %in% na.strings]
            labs2 = labs2[! labs2 %in% na.strings]
        }

        # the levels will be reset here
        x = factor(x)

        if (! is.null(lab)) attr(x, 'label') <- lab
        if (! is.null(labs1)) attr(x, 'labels') <- labs1
        if (! is.null(labs2)) attr(x, 'value.labels') <- labs2
    } else if (is.character(x)) {
        lab = attr(x, 'label', exact = T)
        labs1 <- attr(x, 'labels', exact = T)
        labs2 <- attr(x, 'value.labels', exact = T)

        # trimws will convert factor to character
        x = trimws(x,'both')
        if (! is.null(lab)) lab = trimws(lab,'both')
        if (! is.null(labs1)) labs1 = trimws(labs1,'both')
        if (! is.null(labs2)) labs2 = trimws(labs2,'both')

        if (!is.null(na.strings)) {
            # convert to NA
            x[x %in% na.strings] = NA
            # also remember to remove na.strings from value labels 
            labs1 = labs1[! labs1 %in% na.strings]
            labs2 = labs2[! labs2 %in% na.strings]
        }

        if (! is.null(lab)) attr(x, 'label') <- lab
        if (! is.null(labs1)) attr(x, 'labels') <- labs1
        if (! is.null(labs2)) attr(x, 'value.labels') <- labs2
    } else {
        x = x
    }
    return(x)
}

Count of "Defined" Array Elements

No, the only way to know how many elements are not undefined is to loop through and count them. That doesn't mean you have to write the loop, though, just that something, somewhere has to do it. (See #3 below for why I added that caveat.)

How you loop through and count them is up to you. There are lots of ways:

  1. A standard for loop from 0 to arr.length - 1 (inclusive).
  2. A for..in loop provided you take correct safeguards.
  3. Any of several of the new array features from ECMAScript5 (provided you're using a JavaScript engine that supports them, or you've included an ES5 shim, as they're all shim-able), like some, filter, or reduce, passing in an appropriate function. This is handy not only because you don't have to explicitly write the loop, but because using these features gives the JavaScript engine the opportunity to optimize the loop it does internally in various ways. (Whether it actually does will vary on the engine.)

...but it all amounts to looping, either explicitly or (in the case of the new array features) implicitly.

Creating Unicode character from its number

The other answers here either only support unicode up to U+FFFF (the answers dealing with just one instance of char) or don't tell how to get to the actual symbol (the answers stopping at Character.toChars() or using incorrect method after that), so adding my answer here, too.

To support supplementary code points also, this is what needs to be done:

// this character:
// http://www.isthisthingon.org/unicode/index.php?page=1F&subpage=4&glyph=1F495
// using code points here, not U+n notation
// for equivalence with U+n, below would be 0xnnnn
int codePoint = 128149;
// converting to char[] pair
char[] charPair = Character.toChars(codePoint);
// and to String, containing the character we want
String symbol = new String(charPair);

// we now have str with the desired character as the first item
// confirm that we indeed have character with code point 128149
System.out.println("First code point: " + symbol.codePointAt(0));

I also did a quick test as to which conversion methods work and which don't

int codePoint = 128149;
char[] charPair = Character.toChars(codePoint);

System.out.println(new String(charPair, 0, 2).codePointAt(0)); // 128149, worked
System.out.println(charPair.toString().codePointAt(0));        // 91, didn't work
System.out.println(new String(charPair).codePointAt(0));       // 128149, worked
System.out.println(String.valueOf(codePoint).codePointAt(0));  // 49, didn't work
System.out.println(new String(new int[] {codePoint}, 0, 1).codePointAt(0));
                                                               // 128149, worked

Plot a horizontal line using matplotlib

A nice and easy way for those people who always forget the command axhline is the following

plt.plot(x, [y]*len(x))

In your case xs = x and y = 40. If len(x) is large, then this becomes inefficient and you should really use axhline.

In HTML5, can the <header> and <footer> tags appear outside of the <body> tag?

Let's get a canonical answer here. I will reference the HTML5 spec.

First of all, 12.1.2.4 Optional tags:

A head element's start tag may be omitted if the element is empty, or if the first thing inside the head element is an element.

A head element's end tag may be omitted if the head element is not immediately followed by a space character or a comment.

A body element's start tag may be omitted if the element is empty, or if the first thing inside the body element is not a space character or a comment, except if the first thing inside the body element is a script or style element.

A body element's end tag may be omitted if the body element is not immediately followed by a comment.

Then, the 4.1.1 The html element:

Content model: A head element followed by a body element.

Having the cited restrictions and strictly defined element order, we can easily work out what are the rules for placing implicit <body> tag.

Since <head/> must come first, and it can contain elements only (and not direct text), all elements suitable for <head/> will become the part of implicit <head/>, up to the first stray text or <body/>-specific element. At that moment, all remaining elements and text nodes will be placed in <body/>.


Now let's consider your second snippet:

<html>
  <header>...</header>
  <body>
    <section>...</section>
    <section>...</section>
    <section>...</section>
  </body>
  <footer>...</footer>
</html>

Here, the <header/> element is not suitable for <head/> (it's flow content), the <body> tag will be placed immediately before it. In other words, the document will be understood by browser as following:

<html>
  <head/>
  <body>
    <header>...</header>
    <body>
      <section>...</section>
      <section>...</section>
      <section>...</section>
    </body>
    <footer>...</footer>
  </body>
</html>

And that's certainly not what you were expecting. And as a note, it is invalid as well; see 4.4.1 The body element:

Contexts in which this element can be used: As the second element in an html element.

[...]

In conforming documents, there is only one body element.


Thus, the <header/> or <footer/> will be correctly used in this context. Well, they will be practically equivalent to the first snippet. But this will cause an additional <body/> element in middle of a <body/> which is invalid.


As a side note, you're probably confusing <body/> here with the main part of the content which has no specific element. You could look up that page for other solutions on getting what you want.

Quoting 4.4.1 The body element once again:

The body element represents the main content of the document.

which means all the content. And both header and footer are part of this content.

How to stop "setInterval"

setInterval returns an id that you can use to cancel the interval with clearInterval()

Modifying the "Path to executable" of a windows service

It involves editing the registry, but service information can be found in HKEY_LOCAL_MACHINE\System\CurrentControlSet\Services. Find the service you want to redirect, locate the ImagePath subkey and change that value.

Assign format of DateTime with data annotations?

Try tagging it with:

[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:MM/dd/yyyy}")]

"getaddrinfo failed", what does that mean?

It most likely means the hostname can't be resolved.

import socket
socket.getaddrinfo('localhost', 8080)

If it doesn't work there, it's not going to work in the Bottle example. You can try '127.0.0.1' instead of 'localhost' in case that's the problem.

Counting number of words in a file

So easy we can get the String from files by method: getText();

public class Main {

    static int countOfWords(String str) {
        if (str.equals("") || str == null) {
            return 0;
        }else{
            int numberWords = 0;
            for (char c : str.toCharArray()) {
                if (c == ' ') {
                    numberWords++;
                }
            }

            return ++numberWordss;
        }
    }
}