Programs & Examples On #Eregi

PHP function for case insensitive regular expression matching

Android Gradle 5.0 Update:Cause: org.jetbrains.plugins.gradle.tooling.util

In gradle-wrapper.properties I changed back from gradle-5.1.1 to distributionUrl=https://services.gradle.org/distributions/gradle-4.10.3-all.zip

How to use addTarget method in swift 3

Try this

button.addTarget(self, action:#selector(handleRegister()), for: .touchUpInside). 

Just add parenthesis with name of method.

Also you can refer link : Value of type 'CustomButton' has no member 'touchDown'

Unable to create requested service [org.hibernate.engine.jdbc.env.spi.JdbcEnvironment]

I had this error with MySQL as my database and the only solution was reinstall all components of MySQL, because before I installed just the server.

So try to download other versions of PostgreSQL and get all the components

HikariCP - connection is not available

I managed to fix it finally. The problem is not related to HikariCP. The problem persisted because of some complex methods in REST controllers executing multiple changes in DB through JPA repositories. For some reasons calls to these interfaces resulted in a growing number of "freezed" active connections, exhausting the pool. Either annotating these methods as @Transactional or enveloping all the logic in a single call to transactional service method seem to solve the problem.

How to set TLS version on apache HttpClient

This is how I got it working on httpClient 4.5 (as per Olive Tree request):

CredentialsProvider credsProvider = new BasicCredentialsProvider();
credsProvider.setCredentials(
        new AuthScope(AuthScope.ANY_HOST, 443),
        new UsernamePasswordCredentials(this.user, this.password));

SSLContext sslContext = SSLContexts.createDefault();

SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext,
        new String[]{"TLSv1", "TLSv1.1"},
        null,
        new NoopHostnameVerifier());

CloseableHttpClient httpclient = HttpClients.custom()
        .setDefaultCredentialsProvider(credsProvider)
        .setSSLSocketFactory(sslsf)
        .build();

return httpclient;

org.hibernate.HibernateException: Access to DialectResolutionInfo cannot be null when 'hibernate.dialect' not set

I had the same issue and it was caused by being unable to connect to the database instance. Look for hibernate error HHH000342 in the log above that error, it should give you an idea to where the db connection is failing (incorrect username/pass, url, etc.)

org.hibernate.MappingException: Unknown entity: annotations.Users

Instead of using HibernateUtil.java, to create sessionfactory object, you should use this:

SessionFactory sessionFactory=new AnnotationConfiguration().configure().buildSessionFactory();

Because in order to avoid the exception, you'll have to declare the class object in HibernateUtil.java file as configuration.addAnnotatedClass(Student_Info.class); which looks dumb because we have provided the entry already in hibernate.cfg.xml file.

To use the AnnotationConfiguration class you'll have to add a jar to your project build path: http://www.java2s.com/Code/Jar/h/Downloadhibernate353jar.htm

org.hibernate.QueryException: could not resolve property: filename

Hibernate queries are case sensitive with property names (because they end up relying on getter/setter methods on the @Entity).

Make sure you refer to the property as fileName in the Criteria query, not filename.

Specifically, Hibernate will call the getter method of the filename property when executing that Criteria query, so it will look for a method called getFilename(). But the property is called FileName and the getter getFileName().

So, change the projection like so:

criteria.setProjection(Projections.property("fileName"));

UnexpectedRollbackException: Transaction rolled back because it has been marked as rollback-only

This is the normal behavior and the reason is that your sqlCommandHandlerService.persist method needs a TX when being executed (because it is marked with @Transactional annotation). But when it is called inside processNextRegistrationMessage, because there is a TX available, the container doesn't create a new one and uses existing TX. So if any exception occurs in sqlCommandHandlerService.persist method, it causes TX to be set to rollBackOnly (even if you catch the exception in the caller and ignore it).

To overcome this you can use propagation levels for transactions. Have a look at this to find out which propagation best suits your requirements.

Update; Read this!

Well after a colleague came to me with a couple of questions about a similar situation, I feel this needs a bit of clarification.
Although propagations solve such issues, you should be VERY careful about using them and do not use them unless you ABSOLUTELY understand what they mean and how they work. You may end up persisting some data and rolling back some others where you don't expect them to work that way and things can go horribly wrong.


EDIT Link to current version of the documentation

Eclipse will not start and I haven't changed anything

Removing workbench.xmi under workspace/.metadata/.plugins/org.eclipse.e4.workbench/ worked for me. It did not remove the existing projects.

Google Maps v2 - set both my location and zoom in

You also could set both parameters like,

mMap.moveCamera( CameraUpdateFactory.newLatLngZoom(new LatLng(21.000000, -101.400000) ,4) );

This locates your map on a specific position and zoom. I use this on the setting up my map.

Exception : javax.net.ssl.SSLPeerUnverifiedException: peer not authenticated

You can get this if the client specifies "https" but the server is only running "http". So, the server isn't expecting to make a secure connection.

The source was not found, but some or all event logs could not be searched

If you just want to sniff if a Source exists on the local machine but don't have ability to get authorization to do this, you can finger it through the following example (VB).

This bypasses the security error. You could similarly modify this function to return the LogName for the Source.

Public Shared Function eventLogSourceExists(sSource as String) as Boolean
    Try
        EventLog.LogNameFromSourceName(sSource, ".")
        Return True
    Catch
        Return False
    End Try
End Function

Is the buildSessionFactory() Configuration method deprecated in Hibernate

Yes, it is deprecated. http://docs.jboss.org/hibernate/core/4.0/javadocs/org/hibernate/cfg/Configuration.html#buildSessionFactory() specifically tells you to use the other method you found instead (buildSessionFactory(ServiceRegistry serviceRegistry)) - so use it.

The documentation is copied over from release to release, and likely just hasn't been updated yet (they don't rewrite the manual with every release) - so trust the Javadocs.

The specifics of this change can be viewed at:

Some additional references:

Create session factory in Hibernate 4

The method buildSessionFactory is deprecated from the Hibernate 4 release and it is replaced with the new API. If you are using the Hibernate 4.3.0 and above, your code has to be:

Configuration configuration = new Configuration().configure();

StandardServiceRegistryBuilder builder = new StandardServiceRegistryBuilder()
        .applySettings(configuration.getProperties());

SessionFactory factory = configuration.buildSessionFactory(builder.build());

C++11 introduced a standardized memory model. What does it mean? And how is it going to affect C++ programming?

For languages not specifying a memory model, you are writing code for the language and the memory model specified by the processor architecture. The processor may choose to re-order memory accesses for performance. So, if your program has data races (a data race is when it's possible for multiple cores / hyper-threads to access the same memory concurrently) then your program is not cross platform because of its dependence on the processor memory model. You may refer to the Intel or AMD software manuals to find out how the processors may re-order memory accesses.

Very importantly, locks (and concurrency semantics with locking) are typically implemented in a cross platform way... So if you are using standard locks in a multithreaded program with no data races then you don't have to worry about cross platform memory models.

Interestingly, Microsoft compilers for C++ have acquire / release semantics for volatile which is a C++ extension to deal with the lack of a memory model in C++ http://msdn.microsoft.com/en-us/library/12a04hfd(v=vs.80).aspx. However, given that Windows runs on x86 / x64 only, that's not saying much (Intel and AMD memory models make it easy and efficient to implement acquire / release semantics in a language).

Setting SMTP details for php mail () function

Check out your php.ini, you can set these values there.

Here's the description in the php manual: http://php.net/manual/en/mail.configuration.php

If you want to use several different SMTP servers in your application, I recommend using a "bigger" mailing framework, p.e. Swiftmailer

How to validate an Email in PHP?

Use:

var_dump(filter_var('[email protected]', FILTER_VALIDATE_EMAIL));
$validator = new EmailValidator();
$multipleValidations = new MultipleValidationWithAnd([
    new RFCValidation(),
    new DNSCheckValidation()
]);
$validator->isValid("[email protected]", $multipleValidations); //true

Using Apache httpclient for https

According to the documentation you need to specify the key store:

Protocol authhttps = new Protocol("https",  
      new AuthSSLProtocolSocketFactory(
          new URL("file:my.keystore"), "mypassword",
          new URL("file:my.truststore"), "mypassword"), 443); 

 HttpClient client = new HttpClient();
 client.getHostConfiguration().setHost("localhost", 443, authhttps);

setting system property

System.setProperty("gate.home", "/some/directory"); 

After that you can retrieve its value later by calling

String value =  System.getProperty("gate.home");

Zooming MKMapView to fit annotation pins?

All the answers on this page assume that the map occupies the full screen. I actually have a HUD display (ie buttons scattered at the top and bottom) that give information ontop of the map.. and so the algorithms on the page will display the pins all right, but some of them will appear under the HUD display buttons.

My solution zooms the map in to display the annotations in a subset of the screen and works for different screen sizes (ie 3.5" vs 4.0" etc):

// create a UIView placeholder and throw it on top of the original mapview
// position the UIView to fit the maximum area not hidden by the HUD display buttons
// add an *other* mapview in that uiview, 
// get the MKCoordinateRegion that fits the pins from that fake mapview
// kill the fake mapview and set the region of the original map 
// to that MKCoordinateRegion.

Here is what I did in code (note: i use NSConstraints with some helper methods to make my code work in different screen sizes.. while the code is quite readable.. my answer here explains it better.. it's basically the same workflow:)

// position smallerMap to fit available space
// don't store this map, it will slow down things if we keep it hidden or even in memory
[@[_smallerMapPlaceholder] mapObjectsApplyingBlock:^(UIView *view) {
    [view removeFromSuperview];
    [view setTranslatesAutoresizingMaskIntoConstraints:NO];
    [view setHidden:NO];
    [self.view addSubview:view];
}];

NSDictionary *buttonBindingDict = @{ @"mapPlaceholder": _smallerMapPlaceholder};

NSArray *constraints = [@[@"V:|-225-[mapPlaceholder(>=50)]-176-|",
                          @"|-40-[mapPlaceholder(<=240)]-40-|"
                          ] mapObjectsUsingBlock:^id(NSString *formatString, NSUInteger idx){
                              return [NSLayoutConstraint constraintsWithVisualFormat:formatString options:0 metrics:nil views:buttonBindingDict];
                          }];

[self.view addConstraints:[constraints flattenArray]];
[self.view layoutIfNeeded];

MKMapView *smallerMap = [[MKMapView alloc] initWithFrame:self.smallerMapPlaceholder.frame];
[_smallerMapPlaceholder addSubview:smallerMap];

MKCoordinateRegion regionThatFits = [smallerMap getRegionThatFits:self.mapView.annotations];
[smallerMap removeFromSuperview];
smallerMap = nil;
[_smallerMapPlaceholder setHidden:YES];

[self.mapView setRegion:regionThatFits animated:YES];

here is the code that gets region that fits:

- (MKCoordinateRegion)getRegionThatFits:(NSArray *)routes {
    MKCoordinateRegion region;
    CLLocationDegrees maxLat = -90.0;
    CLLocationDegrees maxLon = -180.0;
    CLLocationDegrees minLat = 90.0;
    CLLocationDegrees minLon = 180.0;
    for(int idx = 0; idx < routes.count; idx++)
    {
        CLLocation* currentLocation = [routes objectAtIndex:idx];
        if(currentLocation.coordinate.latitude > maxLat)
            maxLat = currentLocation.coordinate.latitude;
        if(currentLocation.coordinate.latitude < minLat)
            minLat = currentLocation.coordinate.latitude;
        if(currentLocation.coordinate.longitude > maxLon)
            maxLon = currentLocation.coordinate.longitude;
        if(currentLocation.coordinate.longitude < minLon)
            minLon = currentLocation.coordinate.longitude;
    }
    region.center.latitude     = (maxLat + minLat) / 2.0;
    region.center.longitude    = (maxLon + minLon) / 2.0;
    region.span.latitudeDelta = 0.01;
    region.span.longitudeDelta = 0.01;

    region.span.latitudeDelta  = ((maxLat - minLat)<0.0)?100.0:(maxLat - minLat);
    region.span.longitudeDelta = ((maxLon - minLon)<0.0)?100.0:(maxLon - minLon);

    MKCoordinateRegion regionThatFits = [self regionThatFits:region];
    return regionThatFits;
}

HTTP Status 405 - HTTP method POST is not supported by this URL java servlet

if you are using tomcat you may try this

<servlet-mapping>

    <http-method>POST</http-method>

</servlet-mapping>

in addition to <servlet-name> and <url-mapping>

"No such file or directory" error when executing a binary

You get this error when you try to run a 32-bit build on your 64-bit Linux.

Also contrast what file had to say on the binary you tried (ie: 32-bit) with what you get for your /bin/gzip:

$ file /bin/gzip
/bin/gzip: ELF 64-bit LSB executable, x64-64, version 1 (SYSV), \
dynamically linked (uses shared libs), for GNU/Linux 2.6.15, stripped

which is what I get on Ubuntu 9.10 for amd64 aka x86_64.

Edit: Your expanded post shows that as the readelf output also reflects a 32-bit build.

Trusting all certificates using HttpClient over HTTPS

Add this code before the HttpsURLConnection and it will be done. I got it.

private void trustEveryone() { 
    try { 
            HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier(){ 
                    public boolean verify(String hostname, SSLSession session) { 
                            return true; 
                    }}); 
            SSLContext context = SSLContext.getInstance("TLS"); 
            context.init(null, new X509TrustManager[]{new X509TrustManager(){ 
                    public void checkClientTrusted(X509Certificate[] chain, 
                                    String authType) throws CertificateException {} 
                    public void checkServerTrusted(X509Certificate[] chain, 
                                    String authType) throws CertificateException {} 
                    public X509Certificate[] getAcceptedIssuers() { 
                            return new X509Certificate[0]; 
                    }}}, new SecureRandom()); 
            HttpsURLConnection.setDefaultSSLSocketFactory( 
                            context.getSocketFactory()); 
    } catch (Exception e) { // should never happen 
            e.printStackTrace(); 
    } 
} 

I hope this helps you.

phpmailer error "Could not instantiate mail function"

Check if sendmail is enabled, mostly if your server is provided by another company.

System.Security.SecurityException when writing to Event Log

My app gets installed on client web servers. Rather than fiddling with Network Service permissions and the registry, I opted to check SourceExists and run CreateEventSource in my installer.

I also added a try/catch around log.source = "xx" in the app to set it to a known source if my event source wasn't created (This would only come up if I hot swapped a .dll instead of re-installing).

What good technology podcasts are out there?

The Connected Show covers new Microsoft Technologies and other interesting topics for the developer community.

Shell - Write variable contents to a file

All of the above work, but also have to work around a problem (escapes and special characters) that doesn't need to occur in the first place: Special characters when the variable is expanded by the shell. Just don't do that (variable expansion) in the first place. Use the variable directly, without expansion.

Also, if your variable contains a secret and you want to copy that secret into a file, you might want to not have expansion in the command line as tracing/command echo of the shell commands might reveal the secret. Means, all answers which use $var in the command line may have a potential security risk by exposing the variable contents to tracing and logging of the shell.

Use this:

printenv var >file

That means, in case of the OP question:

printenv var >"$destfile"

Note: variable names are case sensitive.

How to rename a component in Angular CLI?

While the OP asks for a CLI command, some of the answers focus on the IDEs. In this answer I just confirm, that the current WebStorm/IntelliJ does allow renaming the component. All that needs to be done is attempting to rename the class in the .ts file. You will be presented with:

enter image description here

and the rename will be performed in all relevant places.

Django set field value after a form is initialized

in widget use 'value' attr. Example:

username = forms.CharField(
    required=False,
    widget=forms.TextInput(attrs={'readonly': True, 'value': 'CONSTANT_VALUE'}),
)

mysqli_connect(): (HY000/2002): No connection could be made because the target machine actively refused it

In most of cases it is data log problem. Follow the steps.

i) Go to data folder of mysql. For xampp go to C:\xampp\mysql\data.

ii) Look for log file name like ib_logfile0 and ib_logfile1.

iii) Create backup and delete those files.

iv) Restart apache and mysql.

How to resolve git status "Unmerged paths:"?

All you should need to do is:

# if the file in the right place isn't already committed:
git add <path to desired file>

# remove the "both deleted" file from the index:
git rm --cached ../public/images/originals/dog.ai

# commit the merge:
git commit

How can I access a hover state in reactjs?

For having hover effect you can simply try this code

import React from "react";
  import "./styles.css";

    export default function App() {

      function MouseOver(event) {
        event.target.style.background = 'red';
      }
      function MouseOut(event){
        event.target.style.background="";
      }
      return (
        <div className="App">
          <button onMouseOver={MouseOver} onMouseOut={MouseOut}>Hover over me!</button>
        </div>
      );
    }

Or if you want to handle this situation using useState() hook then you can try this piece of code

import React from "react";
import "./styles.css";


export default function App() {
   let [over,setOver]=React.useState(false);

   let buttonstyle={
    backgroundColor:''
  }

  if(over){
    buttonstyle.backgroundColor="green";
  }
  else{
    buttonstyle.backgroundColor='';
  }

  return (
    <div className="App">
      <button style={buttonstyle}
      onMouseOver={()=>setOver(true)} 
      onMouseOut={()=>setOver(false)}
      >Hover over me!</button>
    </div>
  );
}

Both of the above code will work for hover effect but first procedure is easier to write and understand

Compiling Java 7 code via Maven

try using a newer version of the maven compiler plugin:

    <plugin>
        <artifactId>maven-compiler-plugin</artifactId>
        <version>3.2</version>
        <configuration>
            <source>1.7</source>
            <target>1.7</target>
        </configuration>
    </plugin>

also, specifying source file encoding in maven is better done globally:

<properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>

EDIT: As this answer is still getting attention i'd just like to point out that the latest values (as of latest edit) are 3.2 for maven compiler plugin and 1.8 for java, as questions about compiling java 8 code via maven are bound to appear soon :-)

how to make a html iframe 100% width and height?

Answering this just in case if someone else like me stumbles upon this post among many that advise use of JavaScripts for changing iframe height to 100%.

I strongly recommend that you see and try this option specified at How do you give iframe 100% height before resorting to a JavaScript based option. The referenced solution works perfectly for me in all of the testing I have done so far. Hope this helps someone.

How do I disable form fields using CSS?

You can fake the disabled effect using CSS.

pointer-events:none;

You might also want to change colors etc.

How to use .htaccess in WAMP Server?

Open the httpd.conf file and search for

"rewrite"

, then remove

"#"

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

LoadModule rewrite_module modules/mod_rewrite.so

then restart the wamp.

How to send json data in POST request using C#

You can do it with HttpWebRequest:

var httpWebRequest = (HttpWebRequest)WebRequest.Create("http://yourUrl");
httpWebRequest.ContentType = "application/json";
httpWebRequest.Method = "POST";
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls;

using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
{
    string json = new JavaScriptSerializer().Serialize(new
            {
                Username = "myusername",
                Password = "pass"
            });
    streamWriter.Write(json);
    streamWriter.Flush();
    streamWriter.Close();
}

var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
    var result = streamReader.ReadToEnd();
}

Javascript AES encryption

Here's a demonstration page that uses slowAES.

slowAES was easy to use. Logically designed. Reasonable OO packaging. Supports knobs and levers like IV and Encryption mode. Good compatibility with .NET/C#. The name is tongue-in-cheek; it's called "slow AES" because it's not implemented in C++. But in my tests it was not impractically slow.

It lacks an ECB mode. Also lacks a CTR mode, although you could build one pretty easily given an ECB mode, I guess.

It is solely focused on encryption. A nice complementary class that does RFC2898-compliant password-based key derivation, in Javascript, is available from Anandam. This pair of libraries works well with the analogous .NET classes. Good interop. Though, in contrast to SlowAES, the Javascript PBKDF2 is noticeably slower than the Rfc2898DeriveBytes class when generating keys.

It's not surprising that technically there is good interop, but the key point for me was the model adopted by SlowAES is familiar and easy to use. I found some of the other Javascript libraries for AES to be hard to understand and use. For example, in some of them I couldn't find the place to set the IV, or the mode (CBC, ECB, etc). Things were not where I expected them to be. SlowAES was not like that. The properties were right where I expected them to be. It was easy for me to pick up, having been familiar with the Java and .NET crypto programming models.

Anandam's PBKDF2 was not quite on that level. It supported only a single call to DeriveBytes function, so if you need to derive both a key and an IV from a password, this library won't work, unchanged. Some slight modification, and it is working just fine for that purpose.

EDIT: I put together an example of packaging SlowAES and a modified version of Anandam's PBKDF2 into Windows Script Components. Using this AES with a password-derived key shows good interop with the .NET RijndaelManaged class.

EDIT2: the demo page shows how to use this AES encryption from a web page. Using the same inputs (iv, key, mode, etc) supported in .NET gives you good interop with the .NET Rijndael class. You can do a "view source" to get the javascript for that page.

EDIT3
a late addition: Javascript Cryptography considered harmful. Worth the read.

How to convert from Hex to ASCII in JavaScript?

_x000D_
_x000D_
console.log(_x000D_
_x000D_
"68656c6c6f20776f726c6421".match(/.{1,2}/g).reduce((acc,char)=>acc+String.fromCharCode(parseInt(char, 16)),"")_x000D_
_x000D_
)
_x000D_
_x000D_
_x000D_

Refer to a cell in another worksheet by referencing the current worksheet's name?

Unless you want to go the VBA route to work out the Tab name, the Excel formula is fairly ugly based upon Mid functions, etc. But both these methods can be found here if you want to go that way.

Rather, the way I would do it is:

1) Make one cell on your sheet named, for example, Reference_Sheet and put in that cell the value "Jan Item" for example.

2) Now, use the Indirect function like:

=INDIRECT(Reference_Sheet&"!J3") 

3) Now, for each month's sheet, you just have to change that one Reference_Sheet cell.

Hope this gives you what you're looking for!

Ruby: How to turn a hash into HTTP parameters?

Steal from Merb:

# File merb/core_ext/hash.rb, line 87
def to_params
  params = ''
  stack = []

  each do |k, v|
    if v.is_a?(Hash)
      stack << [k,v]
    else
      params << "#{k}=#{v}&"
    end
  end

  stack.each do |parent, hash|
    hash.each do |k, v|
      if v.is_a?(Hash)
        stack << ["#{parent}[#{k}]", v]
      else
        params << "#{parent}[#{k}]=#{v}&"
      end
    end
  end

  params.chop! # trailing &
  params
end

See http://noobkit.com/show/ruby/gems/development/merb/hash/to_params.html

string to string array conversion in java

I guess there is simply no need for it, as it won't get more simple than

String[] array = {"name"};

Of course if you insist, you could write:

static String[] convert(String... array) {
   return array;
}

String[] array = convert("name","age","hobby"); 

[Edit] If you want single-letter Strings, you can use:

String[] s = "name".split("");

Unfortunately s[0] will be empty, but after this the letters n,a,m,e will follow. If this is a problem, you can use e.g. System.arrayCopy in order to get rid of the first array entry.

Is there a way to get a list of column names in sqlite?

You can get a list of column names by running:

SELECT name FROM PRAGMA_TABLE_INFO('your_table');
name      
tbl_name  
rootpage  
sql

You can check if a certain column exists by running:

SELECT 1 FROM PRAGMA_TABLE_INFO('your_table') WHERE name='sql';
1

Reference:

https://www.sqlite.org/pragma.html#pragfunc

Restore LogCat window within Android Studio

In Android Studio 3.4, In the case in which Logcat does not appear in View->ToolWindows->Logcat (in that case Alt+6 or CMD+6 will also not work), the way to get the logact window is:

  1. File->Profile or debug APK (choose an APK)
  2. Select new window or use current window.
  3. Logcat is now available through the menu (View->ToolWindows->Logcat) or through Alt+6 or CMD+6

This issue is an indication that something is not configured correctly with the Android Studio project. The above solution can be useful:

  1. As a temporary solution when there are configuration issues with the Android Studio project, that for some reason are causing Android Studio to hide the logcat window.
  2. When trying to use the Android Studio logcat window for debugging an app without an Android Studio project.

Beginner Python: AttributeError: 'list' object has no attribute

Consider:

class Bike(object):
    def __init__(self, name, weight, cost):
        self.name = name
        self.weight = weight
        self.cost = cost

bikes = {
    # Bike designed for children"
    "Trike": Bike("Trike", 20, 100),      # <--
    # Bike designed for everyone"
    "Kruzer": Bike("Kruzer", 50, 165),    # <--
    }

# Markup of 20% on all sales
margin = .2
# Revenue minus cost after sale
for bike in bikes.values():
    profit = bike.cost * margin
    print(profit)

Output:

33.0
20.0

The difference is that in your bikes dictionary, you're initializing the values as lists [...]. Instead, it looks like the rest of your code wants Bike instances. So create Bike instances: Bike(...).

As for your error

AttributeError: 'list' object has no attribute 'cost'

this will occur when you try to call .cost on a list object. Pretty straightforward, but we can figure out what happened by looking at where you call .cost -- in this line:

profit = bike.cost * margin

This indicates that at least one bike (that is, a member of bikes.values() is a list). If you look at where you defined bikes you can see that the values were, in fact, lists. So this error makes sense.

But since your class has a cost attribute, it looked like you were trying to use Bike instances as values, so I made that little change:

[...] -> Bike(...)

and you're all set.

How to determine an object's class?

checking with isinstance() would not be enough if you want to know in run time. use:

if(someObject.getClass().equals(C.class){
    // do something
}

Add a CSS border on hover without moving the element

You can make the border transparent. In this way it exists, but is invisible, so it doesn't push anything around:

_x000D_
_x000D_
.jobs .item {
   background: #eee;
   border: 1px solid transparent;
}

.jobs .item:hover {
   background: #e1e1e1;
   border: 1px solid #d0d0d0;
}
_x000D_
<div class="jobs">
  <div class="item">Item</div>
</div>
_x000D_
_x000D_
_x000D_

For elements that already have a border, and you don't want them to move, you can use negative margins:

_x000D_
_x000D_
.jobs .item {
    background: #eee;
    border: 1px solid #d0d0d0;
}

.jobs .item:hover {
   background: #e1e1e1;
    border: 3px solid #d0d0d0;
    margin: -2px;
}
_x000D_
<div class="jobs">
  <div class="item">Item</div>
</div>
_x000D_
_x000D_
_x000D_

Another possible trick for adding width to an existing border is to add a box-shadow with the spread attribute of the desired pixel width.

_x000D_
_x000D_
.jobs .item {
    background: #eee;
    border: 1px solid #d0d0d0;
}

.jobs .item:hover {
    background: #e1e1e1;
    box-shadow: 0 0 0 2px #d0d0d0;
}
_x000D_
<div class="jobs">
  <div class="item">Item</div>
</div>
_x000D_
_x000D_
_x000D_

Difference between thread's context class loader and normal classloader

There is an article on javaworld.com that explains the difference => Which ClassLoader should you use

(1)

Thread context classloaders provide a back door around the classloading delegation scheme.

Take JNDI for instance: its guts are implemented by bootstrap classes in rt.jar (starting with J2SE 1.3), but these core JNDI classes may load JNDI providers implemented by independent vendors and potentially deployed in the application's -classpath. This scenario calls for a parent classloader (the primordial one in this case) to load a class visible to one of its child classloaders (the system one, for example). Normal J2SE delegation does not work, and the workaround is to make the core JNDI classes use thread context loaders, thus effectively "tunneling" through the classloader hierarchy in the direction opposite to the proper delegation.

(2) from the same source:

This confusion will probably stay with Java for some time. Take any J2SE API with dynamic resource loading of any kind and try to guess which loading strategy it uses. Here is a sampling:

  • JNDI uses context classloaders
  • Class.getResource() and Class.forName() use the current classloader
  • JAXP uses context classloaders (as of J2SE 1.4)
  • java.util.ResourceBundle uses the caller's current classloader
  • URL protocol handlers specified via java.protocol.handler.pkgs system property are looked up in the bootstrap and system classloaders only
  • Java Serialization API uses the caller's current classloader by default

Android, How to read QR code in my application?

I've created a simple example tutorial. You can read this and use in your application.

http://ribinsandroidhelper.blogspot.in/2013/03/qr-code-reading-on-your-application.html

Through this link you can download the qrcode library project and import into your workspace and add library to your project

and copy this code to your activity

 Intent intent = new Intent("com.google.zxing.client.android.SCAN");
 startActivityForResult(intent, 0);

 public void onActivityResult(int requestCode, int resultCode, Intent intent) {
     if (requestCode == 0) {
         if (resultCode == RESULT_OK) {
             String contents = intent.getStringExtra("SCAN_RESULT");
             String format = intent.getStringExtra("SCAN_RESULT_FORMAT");
             Toast.makeText(this, contents,Toast.LENGTH_LONG).show();
             // Handle successful scan
         } else if (resultCode == RESULT_CANCELED) {
             //Handle cancel
         }
     }
}

Difference between dates in JavaScript

If you are looking for a difference expressed as a combination of years, months, and days, I would suggest this function:

_x000D_
_x000D_
function interval(date1, date2) {_x000D_
    if (date1 > date2) { // swap_x000D_
        var result = interval(date2, date1);_x000D_
        result.years  = -result.years;_x000D_
        result.months = -result.months;_x000D_
        result.days   = -result.days;_x000D_
        result.hours  = -result.hours;_x000D_
        return result;_x000D_
    }_x000D_
    result = {_x000D_
        years:  date2.getYear()  - date1.getYear(),_x000D_
        months: date2.getMonth() - date1.getMonth(),_x000D_
        days:   date2.getDate()  - date1.getDate(),_x000D_
        hours:  date2.getHours() - date1.getHours()_x000D_
    };_x000D_
    if (result.hours < 0) {_x000D_
        result.days--;_x000D_
        result.hours += 24;_x000D_
    }_x000D_
    if (result.days < 0) {_x000D_
        result.months--;_x000D_
        // days = days left in date1's month, _x000D_
        //   plus days that have passed in date2's month_x000D_
        var copy1 = new Date(date1.getTime());_x000D_
        copy1.setDate(32);_x000D_
        result.days = 32-date1.getDate()-copy1.getDate()+date2.getDate();_x000D_
    }_x000D_
    if (result.months < 0) {_x000D_
        result.years--;_x000D_
        result.months+=12;_x000D_
    }_x000D_
    return result;_x000D_
}_x000D_
_x000D_
// Be aware that the month argument is zero-based (January = 0)_x000D_
var date1 = new Date(2015, 4-1, 6);_x000D_
var date2 = new Date(2015, 5-1, 9);_x000D_
_x000D_
document.write(JSON.stringify(interval(date1, date2)));
_x000D_
_x000D_
_x000D_

This solution will treat leap years (29 February) and month length differences in a way we would naturally do (I think).

So for example, the interval between 28 February 2015 and 28 March 2015 will be considered exactly one month, not 28 days. If both those days are in 2016, the difference will still be exactly one month, not 29 days.

Dates with exactly the same month and day, but different year, will always have a difference of an exact number of years. So the difference between 2015-03-01 and 2016-03-01 will be exactly 1 year, not 1 year and 1 day (because of counting 365 days as 1 year).

Invalid length for a Base-64 char array

I'm not Reputable enough to upvote or comment yet, but LukeH's answer was spot on for me.

As AES encryption is the standard to use now, it produces a base64 string (at least all the encrypt/decrypt implementations I've seen). This string has a length in multiples of 4 (string.length % 4 = 0)

The strings I was getting contained + and = on the beginning or end, and when you just concatenate that into a URL's querystring, it will look right (for instance, in an email you generate), but when the the link is followed and the .NET page recieves it and puts it into this.Page.Request.QueryString, those special characters will be gone and your string length will not be in a multiple of 4.

As the are special characters at the FRONT of the string (ex: +), as well as = at the end, you can't just add some = to make up the difference as you are altering the cypher text in a way that doesn't match what was actually in the original querystring.

So, wrapping the cypher text with HttpUtility.URLEncode (not HtmlEncode) transforms the non-alphanumeric characters in a way that ensures .NET parses them back into their original state when it is intepreted into the querystring collection.

The good thing is, we only need to do the URLEncode when generating the querystring for the URL. On the incoming side, it's automatically translated back into the original string value.

Here's some example code

string cryptostring = MyAESEncrypt(MySecretString);
string URL = WebFunctions.ToAbsoluteUrl("~/ResetPassword.aspx?RPC=" + HttpUtility.UrlEncode(cryptostring));

Browser detection in JavaScript?

var browser = navigator.appName;
var version = navigator.appVersion;

Note, however, that both will not necessarily reflect the truth. Many browsers can be set to mask as other browsers. So, for example, you can't always be sure if a user is actually surfing with IE6 or with Opera that pretends to be IE6.

Android Room - simple select query - Cannot access database on the main thread

You can use Future and Callable. So you would not be required to write a long asynctask and can perform your queries without adding allowMainThreadQueries().

My dao query:-

@Query("SELECT * from user_data_table where SNO = 1")
UserData getDefaultData();

My repository method:-

public UserData getDefaultData() throws ExecutionException, InterruptedException {

    Callable<UserData> callable = new Callable<UserData>() {
        @Override
        public UserData call() throws Exception {
            return userDao.getDefaultData();
        }
    };

    Future<UserData> future = Executors.newSingleThreadExecutor().submit(callable);

    return future.get();
}

How to save .xlsx data to file as a blob

This works as of: v0.14.0 of https://github.com/SheetJS/js-xlsx

/* generate array buffer */
var wbout = XLSX.write(wb, {type:"array", bookType:'xlsx'});
/* create data URL */
var url = URL.createObjectURL(new Blob([wbout], {type: 'application/octet-stream'}));
/* trigger download with chrome API */
chrome.downloads.download({ url: url, filename: "testsheet.xlsx", saveAs: true });

intellij incorrectly saying no beans of type found for autowired repository

simple you have to do 2 steps

  1. add hibernate-core dependency
  2. change @Autowired to @Resource.
==>> change @Autowired to  @Resource

taking input of a string word by word

Put the line in a stringstream and extract word by word back:

#include <iostream>
#include <sstream>
using namespace std;

int main()
{
    string t;
    getline(cin,t);

    istringstream iss(t);
    string word;
    while(iss >> word) {
        /* do stuff with word */
    }
}

Of course, you can just skip the getline part and read word by word from cin directly.

And here you can read why is using namespace std considered bad practice.

How to force a web browser NOT to cache images

From my point of view, disable images caching is a bad idea. At all.

The root problem here is - how to force browser to update image, when it has been updated on a server side.

Again, from my personal point of view, the best solution is to disable direct access to images. Instead access images via server-side filter/servlet/other similar tools/services.

In my case it's a rest service, that returns image and attaches ETag in response. The service keeps hash of all files, if file is changed, hash is updated. It works perfectly in all modern browsers. Yes, it takes time to implement it, but it is worth it.

The only exception - are favicons. For some reasons, it does not work. I could not force browser to update its cache from server side. ETags, Cache Control, Expires, Pragma headers, nothing helped.

In this case, adding some random/version parameter into url, it seems, is the only solution.

Can I make a phone call from HTML on Android?

I have just written an app which can make a call from a web page - I don't know if this is any use to you, but I include anyway:

in your onCreate you'll need to use a webview and assign a WebViewClient, as below:

browser = (WebView) findViewById(R.id.webkit);
browser.setWebViewClient(new InternalWebViewClient());

then handle the click on a phone number like this:

private class InternalWebViewClient extends WebViewClient {

    @Override
    public boolean shouldOverrideUrlLoading(WebView view, String url) {
         if (url.indexOf("tel:") > -1) {
            startActivity(new Intent(Intent.ACTION_DIAL, Uri.parse(url)));
            return true;
        } else {
            return false;
        }
    }
}

Let me know if you need more pointers.

Laravel 5 - How to access image uploaded in storage within View?

If you are on windows you can run this command on cmd:

mklink /j /path/to/laravel/public/avatars /path/to/laravel/storage/avatars 

from: http://www.sevenforums.com/tutorials/278262-mklink-create-use-links-windows.html

How to center form in bootstrap 3

<div class="col-md-4 offset-md-4"> 
put your form here
</div>

What does "publicPath" in Webpack do?

When executed in the browser, webpack needs to know where you'll host the generated bundle. Thus it is able to request additional chunks (when using code splitting) or referenced files loaded via the file-loader or url-loader respectively.

For example: If you configure your http server to host the generated bundle under /assets/ you should write: publicPath: "/assets/"

Open Facebook page from Android app?

For Facebook page:

try {
    intent = new Intent(Intent.ACTION_VIEW, Uri.parse("fb://page/" + pageId));
} catch (Exception e) {
    intent =  new Intent(Intent.ACTION_VIEW, Uri.parse("https://www.facebook.com/" + pageId));
}

For Facebook profile:

try {
    intent = new Intent(Intent.ACTION_VIEW, Uri.parse("fb://profile/" + profileId));
} catch (Exception e) {
    intent =  new Intent(Intent.ACTION_VIEW, Uri.parse("https://www.facebook.com/" + profileId));
}

...because none of the answers points out the difference

Both tested with Facebook v.27.0.0.24.15 and Android 5.0.1 on Nexus 4

Bash loop ping successful

You don't need to use echo or grep. You could do this:

ping -oc 100000 8.8.8.8 > /dev/null && say "up" || say "down"

How can I display the users profile pic using the facebook graph api?

Knowing the user id the URL for their profile picture is:-

http://graph.facebook.com/[UID]/picture

where in place of [UID] you place your $uid variable, and that URL can be passed to flash

Lumen: get URL parameter in a Blade view

This works well:

{{ app('request')->input('a') }}

Where a is the url parameter.

See more here: http://blog.netgloo.com/2015/07/17/lumen-getting-current-url-parameter-within-a-blade-view/

Append an object to a list in R in amortized constant time, O(1)?

If you pass in the list variable as a quoted string, you can reach it from within the function like:

push <- function(l, x) {
  assign(l, append(eval(as.name(l)), x), envir=parent.frame())
}

so:

> a <- list(1,2)
> a
[[1]]
[1] 1

[[2]]
[1] 2

> push("a", 3)
> a
[[1]]
[1] 1

[[2]]
[1] 2

[[3]]
[1] 3

> 

or for extra credit:

> v <- vector()
> push("v", 1)
> v
[1] 1
> push("v", 2)
> v
[1] 1 2
> 

Eclipse: How to install a plugin manually?

You can try this

click Help>Install New Software on the menu bar

enter image description here

enter image description here

enter image description here

enter image description here

How to get first record in each group using Linq

    var res = from element in list
              group element by element.F1
                  into groups
                  select groups.OrderBy(p => p.F2).First();

What datatype to use when storing latitude and longitude data in SQL databases?

Well, you asked how to store Latitude/Longitude and my answer is: Don't, you might consider using the WGS 84 ( in Europe ETRS 89 ) as it is the standard for Geo references.

But that detail aside I used a User Defined Type in the days before SQL 2008 finally include geo support.

Convert interface{} to int

maybe you need

func TransToString(data interface{}) (res string) {
    switch v := data.(type) {
    case float64:
        res = strconv.FormatFloat(data.(float64), 'f', 6, 64)
    case float32:
        res = strconv.FormatFloat(float64(data.(float32)), 'f', 6, 32)
    case int:
        res = strconv.FormatInt(int64(data.(int)), 10)
    case int64:
        res = strconv.FormatInt(data.(int64), 10)
    case uint:
        res = strconv.FormatUint(uint64(data.(uint)), 10)
    case uint64:
        res = strconv.FormatUint(data.(uint64), 10)
    case uint32:
        res = strconv.FormatUint(uint64(data.(uint32)), 10)
    case json.Number:
        res = data.(json.Number).String()
    case string:
        res = data.(string)
    case []byte:
        res = string(v)
    default:
        res = ""
    }
    return
}

How to call a method in another class of the same package?

If you define the method as static you can use it without instantiating the class first, but then you also dont have the object variables available for use.

public class Foo {
   public static String Bar() {
      return "bla";
   }
}

In that case you could call it with Foo.Bar().

Neither BindingResult nor plain target object for bean name available as request attr

Make sure you declare the bean associated with the form in GET method of the associated controller and also add it in the model model.addAttribute("uploadItem", uploadItem); which contains @RequestMapping(method = RequestMethod.GET) annotation.

For example UploadItem.java is associated with myform.jsp and controller is SecureAreaController.java

myform.jsp contains

<form:form action="/securedArea" commandName="uploadItem" enctype="multipart/form-data"></form:form>

MyFormController.java

@RequestMapping("/securedArea")
@Controller
public class SecureAreaController {

@RequestMapping(method = RequestMethod.GET)
public String showForm(Model model) {
            UploadItem uploadItem = new UploadItem(); // declareing

            model.addAttribute("uploadItem", uploadItem); // adding in model
    return "securedArea/upload";
}

}

As you can see I am declaring UploadItem.java in controller GET method.

Compare every item to every other item in ArrayList

for (int i = 0; i < list.size(); i++) {
  for (int j = i+1; j < list.size(); j++) {
    // compare list.get(i) and list.get(j)
  }
}

Slice indices must be integers or None or have __index__ method

Your debut and fin values are floating point values, not integers, because taille is a float.

Make those values integers instead:

item = plateau[int(debut):int(fin)]

Alternatively, make taille an integer:

taille = int(sqrt(len(plateau)))

Netbeans - Error: Could not find or load main class

Had the same problem here. Usually Clean and Build solves much of the problem. It happened to be caused by a wrongly installed plugin.

How to add app icon within phonegap projects?

Fortunately there is a little bit in the docs about the splash images, which put me on the road to getting the right location for the icon images as well. So here it goes.

Where the files are placed Once you have built your project using command-line interface "cordova build ios" you should have a complete file structure for your iOS app in the platforms/ios/ folder.

Inside that folder is a folder with the name of your app. Which in turn contains a resources/ directory where you will find the icons/ and splashscreen/ folders.

In the icons folder you will find four icon files (for 57px and 72 px, each in regular and @2x version). These are the Phonegap placeholder icons you've been seeing so far.

What to do

All you have to do is save the icon files in this folder. So that's:

YourPhonegapProject/Platforms/ios/YourAppName/Resources/icons

Same for splashscreen files.

Notes

  1. After placing the files there, rebuild the project using cordova build ios AND use xCode's 'Clean product' menu command. Without this, you'll still be seeing the Phonegap placeholders.

  2. It's wisest to rename your files the iOS/Apple way (i.e. [email protected] etc) instead of editing the names in the info.plist or config.xml. At least that worked for me.

  3. And by the way, ignore the weird path and the weird filename given for the icons in config.xml (i.e. <icon gap:platform="ios" height="114" src="res/icon/ios/icon-57-2x.png" width="114" />). I just left those definitions there, and the icons showed up just fine even though my 114px icon was named [email protected] instead of icon-57-2x.png.

  4. Don't use config.xml to prevent Apple's gloss effect on the icon. Instead, tick the box in xCode (click the project title in the left navigation column, select your app under the Target header, and scroll down to the icons section).

How do I get the month and day with leading 0's in SQL? (e.g. 9 => 09)

Use SQL Server's date styles to pre-format your date values.

SELECT
    CONVERT(varchar(2), GETDATE(), 101) AS monthLeadingZero  -- Date Style 101 = mm/dd/yyyy
    ,CONVERT(varchar(2), GETDATE(), 103) AS dayLeadingZero   -- Date Style 103 = dd/mm/yyyy

typescript: error TS2693: 'Promise' only refers to a type, but is being used as a value here

Solved by changing the target in compilerOptions.

{
"compilerOptions": {
    "module": "es2015",
    "target": "es2015",
    "lib": [
        "es2016",
        "dom"
    ],
    "moduleResolution": "node",
    "noImplicitAny": false,
    "sourceMap": false,
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "outDir": "./public/js/app"
},
"exclude": [
    "node_modules",
    "public/js",
    "assets/app/polyfills.ts"
],
"angularCompilerOptions": {
    "skipMetadataEmit": true
}
}

How can I specify my .keystore file with Spring Boot and Tomcat?

It turns out that there is a way to do this, although I'm not sure I've found the 'proper' way since this required hours of reading source code from multiple projects. In other words, this might be a lot of dumb work (but it works).

First, there is no way to get at the server.xml in the embedded Tomcat, either to augment it or replace it. This must be done programmatically.

Second, the 'require_https' setting doesn't help since you can't set cert info that way. It does set up forwarding from http to https, but it doesn't give you a way to make https work so the forwarding isnt helpful. However, use it with the stuff below, which does make https work.

To begin, you need to provide an EmbeddedServletContainerFactory as explained in the Embedded Servlet Container Support docs. The docs are for Java but the Groovy would look pretty much the same. Note that I haven't been able to get it to recognize the @Value annotation used in their example but its not needed. For groovy, simply put this in a new .groovy file and include that file on the command line when you launch spring boot.

Now, the instructions say that you can customize the TomcatEmbeddedServletContainerFactory class that you created in that code so that you can alter web.xml behavior, and this is true, but for our purposes its important to know that you can also use it to tailor server.xml behavior. Indeed, reading the source for the class and comparing it with the Embedded Tomcat docs, you see that this is the only place to do that. The interesting function is TomcatEmbeddedServletContainerFactory.addConnectorCustomizers(), which may not look like much from the Javadocs but actually gives you the Embedded Tomcat object to customize yourself. Simply pass your own implementation of TomcatConnectorCustomizer and set the things you want on the given Connector in the void customize(Connector con) function. Now, there are about a billion things you can do with the Connector and I couldn't find useful docs for it but the createConnector() function in this this guys personal Spring-embedded-Tomcat project is a very practical guide. My implementation ended up looking like this:

package com.deepdownstudios.server

import org.springframework.boot.context.embedded.tomcat.TomcatConnectorCustomizer
import org.springframework.boot.context.embedded.EmbeddedServletContainerFactory
import org.springframework.boot.context.embedded.tomcat.TomcatEmbeddedServletContainerFactory
import org.apache.catalina.connector.Connector;
import org.apache.coyote.http11.Http11NioProtocol;
import org.springframework.boot.*
import org.springframework.stereotype.*

@Configuration
class MyConfiguration {

@Bean
public EmbeddedServletContainerFactory servletContainer() {
final int port = 8443;
final String keystoreFile = "/path/to/keystore"
final String keystorePass = "keystore-password"
final String keystoreType = "pkcs12"
final String keystoreProvider = "SunJSSE"
final String keystoreAlias = "tomcat"

TomcatEmbeddedServletContainerFactory factory = 
        new TomcatEmbeddedServletContainerFactory(this.port);
factory.addConnectorCustomizers( new TomcatConnectorCustomizer() {
    void    customize(Connector con) {
        Http11NioProtocol proto = (Http11NioProtocol) con.getProtocolHandler();
            proto.setSSLEnabled(true);
        con.setScheme("https");
        con.setSecure(true);
        proto.setKeystoreFile(keystoreFile);
        proto.setKeystorePass(keystorePass);
        proto.setKeystoreType(keystoreType);
        proto.setProperty("keystoreProvider", keystoreProvider);
        proto.setKeyAlias(keystoreAlias);
    }
});
return factory;
}
}

The Autowiring will pick up this implementation an run with it. Once I fixed my busted keystore file (make sure you call keytool with -storetype pkcs12, not -storepass pkcs12 as reported elsewhere), this worked. Also, it would be far better to provide the parameters (port, password, etc) as configuration settings for testing and such... I'm sure its possible if you can get the @Value annotation to work with Groovy.

In jQuery how can I set "top,left" properties of an element with position values relative to the parent and not the document?

To set the position relative to the parent you need to set the position:relative of parent and position:absolute of the element

$("#mydiv").parent().css({position: 'relative'});
$("#mydiv").css({top: 200, left: 200, position:'absolute'});

This works because position: absolute; positions relatively to the closest positioned parent (i.e., the closest parent with any position property other than the default static).

Error when checking model input: expected convolution2d_input_1 to have 4 dimensions, but got array with shape (32, 32, 3)

It is as simple as to Add one dimension, so I was going through the tutorial taught by Siraj Rawal on CNN Code Deployment tutorial, it was working on his terminal, but the same code was not working on my terminal, so I did some research about it and solved, I don't know if that works for you all. Here I have come up with solution;

Unsolved code lines which gives you problem:

if K.image_data_format() == 'channels_first':
    x_train = x_train.reshape(x_train.shape[0], 1, img_rows, img_cols)
    x_test = x_test.reshape(x_test.shape[0], 1, img_rows, img_cols)
    print(x_train.shape)
    input_shape = (1, img_rows, img_cols)
else:
    x_train = x_train.reshape(x_train.shape[0], img_rows, img_cols)
    x_test = x_test.reshape(x_test.shape[0], img_rows, img_cols)
    input_shape = (img_rows, img_cols, 1)

Solved Code:

if K.image_data_format() == 'channels_first':
    x_train = x_train.reshape(x_train.shape[0], 1, img_rows, img_cols)
    x_test = x_test.reshape(x_test.shape[0], 1, img_rows, img_cols)
    print(x_train.shape)
    input_shape = (1, img_rows, img_cols)
else:
    x_train = x_train.reshape(x_train.shape[0], img_rows, img_cols, 1)
    x_test = x_test.reshape(x_test.shape[0], img_rows, img_cols, 1)
    input_shape = (img_rows, img_cols, 1)

Please share the feedback here if that worked for you.

What is the difference between SessionState and ViewState?

Session state is saved on the server, ViewState is saved in the page.

Session state is usually cleared after a period of inactivity from the user (no request happened containing the session id in the request cookies).

The view state is posted on subsequent post back in a hidden field.

MySQL 'Order By' - sorting alphanumeric correctly

If you need to sort an alpha-numeric column that does not have any standard format whatsoever

SELECT * FROM table ORDER BY (name = '0') DESC, (name+0 > 0) DESC, name+0 ASC, name ASC

You can adapt this solution to include support for non-alphanumeric characters if desired using additional logic.

Drop data frame columns by name

Find the index of the columns you want to drop using which. Give these indexes a negative sign (*-1). Then subset on those values, which will remove them from the dataframe. This is an example.

DF <- data.frame(one=c('a','b'), two=c('c', 'd'), three=c('e', 'f'), four=c('g', 'h'))
DF
#  one two three four
#1   a   d     f    i
#2   b   e     g    j

DF[which(names(DF) %in% c('two','three')) *-1]
#  one four
#1   a    g
#2   b    h

C# Debug - cannot start debugging because the debug target is missing

I also get this error quite often.

I solve this by modifying the code (doing a very small change), saving it, then building the solution again.

Difference between DataFrame, Dataset, and RDD in Spark

Apache Spark provide three type of APIs

  1. RDD
  2. DataFrame
  3. Dataset

Comparing RDD, Dataframe and Dataset APIs

Here is the APIs comparison between RDD, Dataframe and Dataset.

RDD

The main abstraction Spark provides is a resilient distributed dataset (RDD), which is a collection of elements partitioned across the nodes of the cluster that can be operated on in parallel.

RDD Features:-

  • Distributed collection:
    RDD uses MapReduce operations which is widely adopted for processing and generating large datasets with a parallel, distributed algorithm on a cluster. It allows users to write parallel computations, using a set of high-level operators, without having to worry about work distribution and fault tolerance.

  • Immutable: RDDs composed of a collection of records which are partitioned. A partition is a basic unit of parallelism in an RDD, and each partition is one logical division of data which is immutable and created through some transformations on existing partitions.Immutability helps to achieve consistency in computations.

  • Fault tolerant: In a case of we lose some partition of RDD , we can replay the transformation on that partition in lineage to achieve the same computation, rather than doing data replication across multiple nodes.This characteristic is the biggest benefit of RDD because it saves a lot of efforts in data management and replication and thus achieves faster computations.

  • Lazy evaluations: All transformations in Spark are lazy, in that they do not compute their results right away. Instead, they just remember the transformations applied to some base dataset . The transformations are only computed when an action requires a result to be returned to the driver program.

  • Functional transformations: RDDs support two types of operations: transformations, which create a new dataset from an existing one, and actions, which return a value to the driver program after running a computation on the dataset.

  • Data processing formats:
    It can easily and efficiently process data which is structured as well as unstructured data.

  • Programming Languages supported:
    RDD API is available in Java, Scala, Python and R.

RDD Limitations:-

  • No inbuilt optimization engine: When working with structured data, RDDs cannot take advantages of Spark’s advanced optimizers including catalyst optimizer and Tungsten execution engine. Developers need to optimize each RDD based on its attributes.

  • Handling structured data: Unlike Dataframe and datasets, RDDs don’t infer the schema of the ingested data and requires the user to specify it.

Dataframes

Spark introduced Dataframes in Spark 1.3 release. Dataframe overcomes the key challenges that RDDs had.

A DataFrame is a distributed collection of data organized into named columns. It is conceptually equivalent to a table in a relational database or a R/Python Dataframe. Along with Dataframe, Spark also introduced catalyst optimizer, which leverages advanced programming features to build an extensible query optimizer.

Dataframe Features:-

  • Distributed collection of Row Object: A DataFrame is a distributed collection of data organized into named columns. It is conceptually equivalent to a table in a relational database, but with richer optimizations under the hood.

  • Data Processing: Processing structured and unstructured data formats (Avro, CSV, elastic search, and Cassandra) and storage systems (HDFS, HIVE tables, MySQL, etc). It can read and write from all these various datasources.

  • Optimization using catalyst optimizer: It powers both SQL queries and the DataFrame API. Dataframe use catalyst tree transformation framework in four phases,

     1.Analyzing a logical plan to resolve references
     2.Logical plan optimization
     3.Physical planning
     4.Code generation to compile parts of the query to Java bytecode.
    
  • Hive Compatibility: Using Spark SQL, you can run unmodified Hive queries on your existing Hive warehouses. It reuses Hive frontend and MetaStore and gives you full compatibility with existing Hive data, queries, and UDFs.

  • Tungsten: Tungsten provides a physical execution backend whichexplicitly manages memory and dynamically generates bytecode for expression evaluation.

  • Programming Languages supported:
    Dataframe API is available in Java, Scala, Python, and R.

Dataframe Limitations:-

  • Compile-time type safety: As discussed, Dataframe API does not support compile time safety which limits you from manipulating data when the structure is not know. The following example works during compile time. However, you will get a Runtime exception when executing this code.

Example:

case class Person(name : String , age : Int) 
val dataframe = sqlContext.read.json("people.json") 
dataframe.filter("salary > 10000").show 
=> throws Exception : cannot resolve 'salary' given input age , name

This is challenging specially when you are working with several transformation and aggregation steps.

  • Cannot operate on domain Object (lost domain object): Once you have transformed a domain object into dataframe, you cannot regenerate it from it. In the following example, once we have create personDF from personRDD, we won’t be recover the original RDD of Person class (RDD[Person]).

Example:

case class Person(name : String , age : Int)
val personRDD = sc.makeRDD(Seq(Person("A",10),Person("B",20)))
val personDF = sqlContext.createDataframe(personRDD)
personDF.rdd // returns RDD[Row] , does not returns RDD[Person]

Datasets API

Dataset API is an extension to DataFrames that provides a type-safe, object-oriented programming interface. It is a strongly-typed, immutable collection of objects that are mapped to a relational schema.

At the core of the Dataset, API is a new concept called an encoder, which is responsible for converting between JVM objects and tabular representation. The tabular representation is stored using Spark internal Tungsten binary format, allowing for operations on serialized data and improved memory utilization. Spark 1.6 comes with support for automatically generating encoders for a wide variety of types, including primitive types (e.g. String, Integer, Long), Scala case classes, and Java Beans.

Dataset Features:-

  • Provides best of both RDD and Dataframe: RDD(functional programming, type safe), DataFrame (relational model, Query optimazation , Tungsten execution, sorting and shuffling)

  • Encoders: With the use of Encoders, it is easy to convert any JVM object into a Dataset, allowing users to work with both structured and unstructured data unlike Dataframe.

  • Programming Languages supported: Datasets API is currently only available in Scala and Java. Python and R are currently not supported in version 1.6. Python support is slated for version 2.0.

  • Type Safety: Datasets API provides compile time safety which was not available in Dataframes. In the example below, we can see how Dataset can operate on domain objects with compile lambda functions.

Example:

case class Person(name : String , age : Int)
val personRDD = sc.makeRDD(Seq(Person("A",10),Person("B",20)))
val personDF = sqlContext.createDataframe(personRDD)
val ds:Dataset[Person] = personDF.as[Person]
ds.filter(p => p.age > 25)
ds.filter(p => p.salary > 25)
 // error : value salary is not a member of person
ds.rdd // returns RDD[Person]
  • Interoperable: Datasets allows you to easily convert your existing RDDs and Dataframes into datasets without boilerplate code.

Datasets API Limitation:-

  • Requires type casting to String: Querying the data from datasets currently requires us to specify the fields in the class as a string. Once we have queried the data, we are forced to cast column to the required data type. On the other hand, if we use map operation on Datasets, it will not use Catalyst optimizer.

Example:

ds.select(col("name").as[String], $"age".as[Int]).collect()

No support for Python and R: As of release 1.6, Datasets only support Scala and Java. Python support will be introduced in Spark 2.0.

The Datasets API brings in several advantages over the existing RDD and Dataframe API with better type safety and functional programming.With the challenge of type casting requirements in the API, you would still not the required type safety and will make your code brittle.

Disable browsers vertical and horizontal scrollbars

So far we have overflow:hidden on the body. However IE doesn't always honor that and you need to put scroll="no" on the body element as well and/or place overflow:hidden on the html element as well.

You can take this further when you need to 'take control' of the view port you can do this:-

<style>
 body {width:100%; height:100%; overflow:hidden; margin:0; }
 html {width:100%; height:100%; overflow:hidden; }
</style>

An element granted height 100% in the body has the full height of the window viewport, and element positioned absolutely using bottom:nnPX will be set nn pixels above the bottom edge of the window, etc.

Running stages in parallel with Jenkins workflow / pipeline

You may not place the deprecated non-block-scoped stage (as in the original question) inside parallel.

As of JENKINS-26107, stage takes a block argument. You may put parallel inside stage or stage inside parallel or stage inside stage etc. However visualizations of the build are not guaranteed to support all nestings; in particular

  • The built-in Pipeline Steps (a “tree table” listing every step run by the build) shows arbitrary stage nesting.
  • The Pipeline Stage View plugin will currently only display a linear list of stages, in the order they started, regardless of nesting structure.
  • Blue Ocean will display top-level stages, plus parallel branches inside a top-level stage, but currently no more.

JENKINS-27394, if implemented, would display arbitrarily nested stages.

How can I convert a dictionary into a list of tuples?

These are the breaking changes from Python 3.x and Python 2.x

For Python3.x use

dictlist = []
for key, value in dict.items():
    temp = [key,value]
    dictlist.append(temp)

For Python 2.7 use

dictlist = []
for key, value in dict.iteritems():
    temp = [key,value]
    dictlist.append(temp)

Trigger a button click with JavaScript on the Enter key in a text box

document.onkeypress = function (e) {
 e = e || window.event;
 var charCode = (typeof e.which == "number") ? e.which : e.keyCode;
 if (charCode == 13) {

        // Do something here
        printResult();
    }
};

Heres my two cents. I am working on an app for Windows 8 and want the button to register a click event when I press the Enter button. I am doing this in JS. I tried a couple of suggestions, but had issues. This works just fine.

How to pass parameters using ui-sref in ui-router to controller

You simply misspelled $stateParam, it should be $stateParams (with an s). That's why you get undefined ;)

Failed to execute 'postMessage' on 'DOMWindow': https://www.youtube.com !== http://localhost:9000

Adding origin=${window.location.host} or "*" is not enough.

Add https:// before it and it will work.

Also, make sure that you are using an URL that can be embedded: take the video ID out and concatenate a string that has the YouTube video prefix and the video ID + embed definition.

Selecting text in an element (akin to highlighting with your mouse)

My particular use-case was selecting a text range inside an editable span element, which, as far as I could see, is not described in any of the answers here.

The main difference is that you have to pass a node of type Text to the Range object, as described in the documentation of Range.setStart():

If the startNode is a Node of type Text, Comment, or CDATASection, then startOffset is the number of characters from the start of startNode. For other Node types, startOffset is the number of child nodes between the start of the startNode.

The Text node is the first child node of a span element, so to get it, access childNodes[0] of the span element. The rest is the same as in most other answers.

Here a code example:

var startIndex = 1;
var endIndex = 5;
var element = document.getElementById("spanId");
var textNode = element.childNodes[0];

var range = document.createRange();
range.setStart(textNode, startIndex);
range.setEnd(textNode, endIndex);

var selection = window.getSelection();
selection.removeAllRanges();
selection.addRange(range);

Other relevant documentation:
Range
Selection
Document.createRange()
Window.getSelection()

How to dynamically change the color of the selected menu item of a web page?

It would probably be easiest to implement this using JavaScript ... Here's a JQuery script to demo ... As the others mentioned ... we have a class named 'active' to indicate the active tab - NOT the pseudo-class ':active.' We could have just as easily named it anything though ... selected, current, etc., etc.

/* CSS */

#nav { width:480px;margin:1em auto;}

#nav ul {margin:1em auto; padding:0; font:1em "Arial Black",sans-serif; }

#nav ul li{display:inline;} 

#nav ul li a{text-decoration:none; margin:0; padding:.25em 25px; background:#666; color:#ffffff;} 

#nav ul li a:hover{background:#ff9900; color:#ffffff;} 

#nav ul li a.active {background:#ff9900; color:#ffffff;} 

/* JQuery Example */

<script type="text/javascript">
$(function (){

    $('#nav ul li a').each(function(){
        var path = window.location.href;
        var current = path.substring(path.lastIndexOf('/')+1);
        var url = $(this).attr('href');

        if(url == current){
            $(this).addClass('active');
        };
    });         
});

</script>

 /* HTML */

<div id="nav" >
    <ul>
        <li><a href='index.php?1'>One</a></li>
        <li><a href='index.php?2'>Two</a></li>
        <li><a href='index.php?3'>Three</a></li>
        <li><a href='index.php?4'>Four</a></li>
    </ul>
</div>

Spring Boot application as a Service

You could also use supervisord which is a very handy daemon, which can be used to easily control services. These services are defined by simple configuration files defining what to execute with which user in which directory and so forth, there are a zillion options. supervisord has a very simple syntax, so it makes a very good alternative to writing SysV init scripts.

Here a simple supervisord configuration file for the program you are trying to run/control. (put this into /etc/supervisor/conf.d/yourapp.conf)

/etc/supervisor/conf.d/yourapp.conf

[program:yourapp]
command=/usr/bin/java -jar /path/to/application.jar
user=usertorun
autostart=true
autorestart=true
startsecs=10
startretries=3
stdout_logfile=/var/log/yourapp-stdout.log
stderr_logfile=/var/log/yourapp-stderr.log

To control the application you would need to execute supervisorctl, which will present you with a prompt where you could start, stop, status yourapp.

CLI

# sudo supervisorctl
yourapp             RUNNING   pid 123123, uptime 1 day, 15:00:00
supervisor> stop yourapp
supervisor> start yourapp

If the supervisord daemon is already running and you've added the configuration for your serivce without restarting the daemon you can simply do a reread and update command in the supervisorctl shell.

This really gives you all the flexibilites you would have using SysV Init scripts, but easy to use and control. Take a look at the documentation.

Sort Go map values by keys

If, like me, you find you want essentially the same sorting code in more than one place, or just want to keep the code complexity down, you can abstract away the sorting itself to a separate function, to which you pass the function that does the actual work you want (which would be different at each call site, of course).

Given a map with key type K and value type V, represented as <K> and <V> below, the common sort function might look something like this Go-code template (which Go version 1 does not support as-is):

/* Go apparently doesn't support/allow 'interface{}' as the value (or
/* key) of a map such that any arbitrary type can be substituted at
/* run time, so several of these nearly-identical functions might be
/* needed for different key/value type combinations. */
func sortedMap<K><T>(m map[<K>]<V>, f func(k <K>, v <V>)) {
    var keys []<K>
    for k, _ := range m {
        keys = append(keys, k)
    }
    sort.Strings(keys)  # or sort.Ints(keys), sort.Sort(...), etc., per <K>
    for _, k := range keys {
        v := m[k]
        f(k, v)
    }
}

Then call it with the input map and a function (taking (k <K>, v <V>) as its input arguments) that is called over the map elements in sorted-key order.

So, a version of the code in the answer posted by Mingu might look like:

package main

import (
    "fmt"
    "sort"
)

func sortedMapIntString(m map[int]string, f func(k int, v string)) {
    var keys []int
    for k, _ := range m {
        keys = append(keys, k)
    }
    sort.Ints(keys)
    for _, k := range keys {
        f(k, m[k])
    }
}

func main() {
    // Create a map for processing
    m := make(map[int]string)
    m[1] = "a"
    m[2] = "c"
    m[0] = "b"

    sortedMapIntString(m,
        func(k int, v string) { fmt.Println("Key:", k, "Value:", v) })
}

The sortedMapIntString() function can be re-used for any map[int]string (assuming the same sort order is desired), keeping each use to just two lines of code.

Downsides include:

  • It's harder to read for people unaccustomed to using functions as first-class
  • It might be slower (I haven't done performance comparisons)

Other languages have various solutions:

  • If the use of <K> and <V> (to denote types for the key and value) looks a bit familiar, that code template is not terribly unlike C++ templates.
  • Clojure and other languages support sorted maps as fundamental data types.
  • While I don't know of any way Go makes range a first-class type such that it could be substituted with a custom ordered-range (in place of range in the original code), I think some other languages provide iterators that are powerful enough to accomplish the same thing.

Changing navigation title programmatically

I prefer using self.navigationItem.title = "Your Title Here" over self.title = "Your Title Here" to provide title in the navigation bar since tab bar also uses self.title to alter its title. You should try the following code once.

Note: calling the super view lifecycle is necessary before you do any stuffs.

class ViewController: UIViewController {
    override func viewDidLoad() {
        super.viewDidLoad()
        setupNavBar()
    }
}

private func setupNavBar() {
    self.navigationItem.title = "Your Title Here"
}

MySQL foreach alternative for procedure

This can be done with MySQL, although it's highly unintuitive:

CREATE PROCEDURE p25 (OUT return_val INT)
BEGIN
  DECLARE a,b INT;
  DECLARE cur_1 CURSOR FOR SELECT s1 FROM t;
  DECLARE CONTINUE HANDLER FOR NOT FOUND
  SET b = 1;
  OPEN cur_1;
  REPEAT
    FETCH cur_1 INTO a;
    UNTIL b = 1
  END REPEAT;
  CLOSE cur_1;
  SET return_val = a;
END;//

Check out this guide: mysql-storedprocedures.pdf

How to get rid of punctuation using NLTK tokenizer?

I just used the following code, which removed all the punctuation:

tokens = nltk.wordpunct_tokenize(raw)

type(tokens)

text = nltk.Text(tokens)

type(text)  

words = [w.lower() for w in text if w.isalpha()]

android: stretch image in imageview to fit screen

if you use android:scaleType="fitXY" then you must specify

android:layout_width="75dp" and android:layout_height="75dp"

if use wrap_content it will not stretch to what you need

<ImageView
android:layout_width="75dp"
android:layout_height="75dp"
android:id="@+id/listItemNoteImage"
android:src="@drawable/MyImage"
android:layout_alignParentTop="true"
android:layout_alignParentStart="true"
android:layout_marginStart="12dp"
android:scaleType="fitXY"/>

git ignore all files of a certain type, except those in a specific subfolder

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

http://schacon.github.com/git/gitignore.html

*.json
!spec/*.json

How can I create a carriage return in my C# string

string myHTML = "some words " + Environment.NewLine + "more words");

How can I close a login form and show the main form without my application closing?

It's simple.

Here is the code.

 private void button1_Click(object sender, EventArgs e)
 {  
        //creating instance of main form
        MainForm mainForm = new MainForm();

        // creating event handler to catch the main form closed event
        // this will fire when mainForm closed
        mainForm.FormClosed += new FormClosedEventHandler(mainForm_FormClosed);
        //showing the main form
        mainForm.Show();
        //hiding the current form
        this.Hide();
  }

  // this is the method block executes when main form is closed
  void mainForm_FormClosed(object sender, FormClosedEventArgs e)
  {
       // here you can do anything

       // we will close the application
       Application.Exit();
  }

Camera access through browser

The Picup app is a way to take pictures from an HTML5 page and upload them to your server. It requires some extra programming on the server, but apart from PhoneGap, I have not found another way.

Cannot read property length of undefined

perhaps, you can first determine if the DOM does really exists,

function walkmydog() {
    //when the user starts entering
    var dom = document.getElementById('WallSearch');
    if(dom == null){
        alert('sorry, WallSearch DOM cannot be found');
        return false;    
    }

    if(dom.value.length == 0){
        alert("nothing");
    }
}

if (document.addEventListener){
    document.addEventListener("DOMContentLoaded", walkmydog, false);
}

How do I share a global variable between c files?

Do same as you did in file1.c In file2.c:

#include <stdio.h> 

extern int i;  /*This declare that i is an int variable which is defined in some other file*/

int main(void)
{
/* your code*/

If you use int i; in file2.c under main() then i will be treated as local auto variable not the same as defined in file1.c

Upper memory limit?

You're reading the entire file into memory (line = u.readlines()) which will fail of course if the file is too large (and you say that some are up to 20 GB), so that's your problem right there.

Better iterate over each line:

for current_line in u:
    do_something_with(current_line)

is the recommended approach.

Later in your script, you're doing some very strange things like first counting all the items in a list, then constructing a for loop over the range of that count. Why not iterate over the list directly? What is the purpose of your script? I have the impression that this could be done much easier.

This is one of the advantages of high-level languages like Python (as opposed to C where you do have to do these housekeeping tasks yourself): Allow Python to handle iteration for you, and only collect in memory what you actually need to have in memory at any given time.

Also, as it seems that you're processing TSV files (tabulator-separated values), you should take a look at the csv module which will handle all the splitting, removing of \ns etc. for you.

Insert line break in wrapped cell via code

Just do Ctrl + Enter inside the text box

How can I check if an argument is defined when starting/calling a batch file?

IF "%1"=="" will fail, all versions of this will fail under certain poison character conditions. Only IF DEFINED or IF NOT DEFINED are safe

Spring Boot: Cannot access REST Controller on localhost (404)

Adding to MattR's answer:

As stated in here, @SpringBootApplication automatically inserts the needed annotations: @Configuration, @EnableAutoConfiguration, and also @ComponentScan; however, the @ComponentScan will only look for the components in the same package as the App, in this case your com.nice.application, whereas your controller resides in com.nice.controller. That's why you get 404 because the App didn't find the controller in the application package.

How can I login to a website with Python?

Typically you'll need cookies to log into a site, which means cookielib, urllib and urllib2. Here's a class which I wrote back when I was playing Facebook web games:

import cookielib
import urllib
import urllib2

# set these to whatever your fb account is
fb_username = "[email protected]"
fb_password = "secretpassword"

class WebGamePlayer(object):

    def __init__(self, login, password):
        """ Start up... """
        self.login = login
        self.password = password

        self.cj = cookielib.CookieJar()
        self.opener = urllib2.build_opener(
            urllib2.HTTPRedirectHandler(),
            urllib2.HTTPHandler(debuglevel=0),
            urllib2.HTTPSHandler(debuglevel=0),
            urllib2.HTTPCookieProcessor(self.cj)
        )
        self.opener.addheaders = [
            ('User-agent', ('Mozilla/4.0 (compatible; MSIE 6.0; '
                           'Windows NT 5.2; .NET CLR 1.1.4322)'))
        ]

        # need this twice - once to set cookies, once to log in...
        self.loginToFacebook()
        self.loginToFacebook()

    def loginToFacebook(self):
        """
        Handle login. This should populate our cookie jar.
        """
        login_data = urllib.urlencode({
            'email' : self.login,
            'pass' : self.password,
        })
        response = self.opener.open("https://login.facebook.com/login.php", login_data)
        return ''.join(response.readlines())

You won't necessarily need the HTTPS or Redirect handlers, but they don't hurt, and it makes the opener much more robust. You also might not need cookies, but it's hard to tell just from the form that you've posted. I suspect that you might, purely from the 'Remember me' input that's been commented out.

Check if all checkboxes are selected

This is how I achieved it in my code:

if($('.citiescheckbox:checked').length == $('.citiescheckbox').length){
    $('.citycontainer').hide();
}else{
    $('.citycontainer').show();
}

Output of git branch in tree like fashion

The answer below uses git log:

I mentioned a similar approach in 2009 with "Unable to show a Git tree in terminal":

git log --graph --pretty=oneline --abbrev-commit

But the full one I have been using is in "How to display the tag name and branch name using git log --graph" (2011):

git config --global alias.lgb "log --graph --pretty=format:'%Cred%h%Creset -%C(yellow)%d%Creset %s %Cgreen(%cr) %C(bold blue)<%an>%Creset%n' --abbrev-commit --date=relative --branches"

git lgb

Original answer (2010)

git show-branch --list comes close of what you are looking for (with the topo order)

--topo-order

By default, the branches and their commits are shown in reverse chronological order.
This option makes them appear in topological order (i.e., descendant commits are shown before their parents).

But the tool git wtf can help too. Example:

$ git wtf
Local branch: master
[ ] NOT in sync with remote (needs push)
    - Add before-search hook, for shortcuts for custom search queries. [4430d1b] (edwardzyang@...; 7 days ago)
Remote branch: origin/master ([email protected]:sup/mainline.git)
[x] in sync with local

Feature branches:
{ } origin/release-0.8.1 is NOT merged in (1 commit ahead)
    - bump to 0.8.1 [dab43fb] (wmorgan-sup@...; 2 days ago)
[ ] labels-before-subj is NOT merged in (1 commit ahead)
    - put labels before subject in thread index view [790b64d] (marka@...; 4 weeks ago)
{x} origin/enclosed-message-display-tweaks merged in
(x) experiment merged in (only locally)

NOTE: working directory contains modified files

git-wtf shows you:

  • How your branch relates to the remote repo, if it's a tracking branch.
  • How your branch relates to non-feature ("version") branches, if it's a feature branch.
  • How your branch relates to the feature branches, if it's a version branch

What are the minimum margins most printers can handle?

The margins vary depending on the printer. In Windows GDI, you call the following functions to get the built-in margins, the "no-print zone":

GetDeviceCaps(hdc, PHYSICALWIDTH);
GetDeviceCaps(hdc, PHYSICALHEIGHT);
GetDeviceCaps(hdc, PHYSICALOFFSETX);
GetDeviceCaps(hdc, PHYSICALOFFSETY);

Printing right to the edge is called a "bleed" in the printing industry. The only laser printer I ever knew to print right to the edge was the Xerox 9700: 120 ppm, $500K in 1980.

Getting the first index of an object

There is no way to get the first element, seeing as "hashes" (objects) in JavaScript have unordered properties. Your best bet is to store the keys in an array:

var keys = ["foo", "bar", "baz"];

Then use that to get the proper value:

object[keys[0]]

What is the Regular Expression For "Not Whitespace and Not a hyphen"

Which programming language are you using? May be you just need to escape the backslash like "[^\\s-]"

Detect & Record Audio in Python

import pyaudio
import wave
from array import array

FORMAT=pyaudio.paInt16
CHANNELS=2
RATE=44100
CHUNK=1024
RECORD_SECONDS=15
FILE_NAME="RECORDING.wav"

audio=pyaudio.PyAudio() #instantiate the pyaudio

#recording prerequisites
stream=audio.open(format=FORMAT,channels=CHANNELS, 
                  rate=RATE,
                  input=True,
                  frames_per_buffer=CHUNK)

#starting recording
frames=[]

for i in range(0,int(RATE/CHUNK*RECORD_SECONDS)):
    data=stream.read(CHUNK)
    data_chunk=array('h',data)
    vol=max(data_chunk)
    if(vol>=500):
        print("something said")
        frames.append(data)
    else:
        print("nothing")
    print("\n")


#end of recording
stream.stop_stream()
stream.close()
audio.terminate()
#writing to file
wavfile=wave.open(FILE_NAME,'wb')
wavfile.setnchannels(CHANNELS)
wavfile.setsampwidth(audio.get_sample_size(FORMAT))
wavfile.setframerate(RATE)
wavfile.writeframes(b''.join(frames))#append frames recorded to file
wavfile.close()

I think this will help.It is a simple script which will check if there is a silence or not.If silence is detected it will not record otherwise it will record.

How to use an environment variable inside a quoted string in Bash

Just a quick note/summary for any who came here via Google looking for the answer to the general question asked in the title (as I was). Any of the following should work for getting access to shell variables inside quotes:

echo "$VARIABLE"
echo "${VARIABLE}"

Use of single quotes is the main issue. According to the Bash Reference Manual:

Enclosing characters in single quotes (') preserves the literal value of each character within the quotes. A single quote may not occur between single quotes, even when preceded by a backslash. [...] Enclosing characters in double quotes (") preserves the literal value of all characters within the quotes, with the exception of $, `, \, and, when history expansion is enabled, !. The characters $ and ` retain their special meaning within double quotes (see Shell Expansions). The backslash retains its special meaning only when followed by one of the following characters: $, `, ", \, or newline. Within double quotes, backslashes that are followed by one of these characters are removed. Backslashes preceding characters without a special meaning are left unmodified. A double quote may be quoted within double quotes by preceding it with a backslash. If enabled, history expansion will be performed unless an ! appearing in double quotes is escaped using a backslash. The backslash preceding the ! is not removed. The special parameters * and @ have special meaning when in double quotes (see Shell Parameter Expansion).

In the specific case asked in the question, $COLUMNS is a special variable which has nonstandard properties (see lhunath's answer above).

Server http:/localhost:8080 requires a user name and a password. The server says: XDB

I was facing the same problem, I just change the jboss7.1 port from 8080 to 9090. and it worked perfectly for me. To change the jboss7.1 port go to jboss-as-7.1.0.Final\standalone\configuration open standalone.xml look for the line <socket-binding name="http" port="8080"/> change 8080 to 9090. save the file and Restart the server. it should work

Error: 10 $digest() iterations reached. Aborting! with dynamic sortby predicate

This happened to me after upgrading from angular 1.6 -> 1.7 when using $sce.trustAsResourceUrl() as the return value of a function called from ng-src. You can see this issue mentioned here.

In my case I had to change the following.

<source ng-src="{{trustSrc(someUrl)}}" type='video/mp4' />
trustSrc = function(url){
    return $sce.trustAsResourceUrl(url);
};

to

<source ng-src='{{trustedUrl}} type='video/mp4' />
trustedUrl = $sce.trustAsResourceUrl(someUrl);

How to change the project in GCP using CLI commands

You can try: gcloud config set project [project_id]

Get first letter of a string from column

Cast the dtype of the col to str and you can perform vectorised slicing calling str:

In [29]:
df['new_col'] = df['First'].astype(str).str[0]
df

Out[29]:
   First  Second new_col
0    123     234       1
1     22    4353       2
2     32     355       3
3    453     453       4
4     45     345       4
5    453     453       4
6     56      56       5

if you need to you can cast the dtype back again calling astype(int) on the column

SELECT COUNT in LINQ to SQL C#

You should be able to do the count on the purch variable:

purch.Count();

e.g.

var purch = from purchase in myBlaContext.purchases
select purchase;

purch.Count();

'System.Net.Http.HttpContent' does not contain a definition for 'ReadAsAsync' and no extension method

Adding a reference to System.Net.Http.Formatting.dll may cause DLL mismatch issues. Right now, System.Net.Http.Formatting.dll appears to reference version 4.5.0.0 of Newtonsoft.Json.DLL, whereas the latest version is 6.0.0.0. That means you'll need to also add a binding redirect to avoid a .NET Assembly exception if you reference the latest Newtonsoft NuGet package or DLL:

<dependentAssembly>
   <assemblyIdentity name="Newtonsoft.Json" publicKeyToken="30ad4fe6b2a6aeed" culture="neutral" />
    <bindingRedirect oldVersion="0.0.0.0-6.0.0.0" newVersion="6.0.0.0" />
 </dependentAssembly> 

So an alternative solution to adding a reference to System.Net.Http.Formatting.dll is to read the response as a string and then desearalize yourself with JsonConvert.DeserializeObject(responseAsString). The full method would be:

public async Task<T> GetHttpResponseContentAsType(string baseUrl, string subUrl)
{
     using (var client = new HttpClient())
     {
         client.BaseAddress = new Uri(baseUrl);
         client.DefaultRequestHeaders.Accept.Clear();
         client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

         HttpResponseMessage response = await client.GetAsync(subUrl);
         response.EnsureSuccessStatusCode();
         var responseAsString = await response.Content.ReadAsStringAsync();
         var responseAsConcreteType = JsonConvert.DeserializeObject<T>(responseAsString);
         return responseAsConcreteType;
      }
}

How to uninstall pip on OSX?

In order to completely remove pip, I believe you have to delete its files from all Python versions on your computer. For me, they are here:

cd /Library/Frameworks/Python.framework/Versions/Current/bin/
cd /Library/Frameworks/Python.framework/Versions/3.3/bin/

You may need to remove the files or the directories located at these file-paths (and more, depending on the number of versions of Python you have installed).

Edit: to find all versions of pip on your machine, use: find / -name pip 2>/dev/null, which starts at its highest level (hence the /) and hides all error messages (that's what 2>/dev/null does). This is my output:

$ find / -name pip 2>/dev/null
/Library/Frameworks/Python.framework/Versions/2.7/bin/pip
/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/pip
/Library/Frameworks/Python.framework/Versions/3.3/bin/pip
/Library/Frameworks/Python.framework/Versions/3.3/lib/python3.3/site-packages/pip
/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/site-packages/pip
/Library/Frameworks/Python.framework/Versions/7.1/bin/pip
/Library/Frameworks/Python.framework/Versions/7.1/lib/python2.7/site-packages/pip-1.4.1-py2.7.egg/pip

PHP check if file is an image

Native way to get the mimetype:

For PHP < 5.3 use mime_content_type()
For PHP >= 5.3 use finfo_open() or mime_content_type()

Alternatives to get the MimeType are exif_imagetype and getimagesize, but these rely on having the appropriate libs installed. In addition, they will likely just return image mimetypes, instead of the whole list given in magic.mime.

While mime_content_type is available from PHP 4.3 and is part of the FileInfo extension (which is enabled by default since PHP 5.3, except for Windows platforms, where it must be enabled manually, for details see here).

If you don't want to bother about what is available on your system, just wrap all four functions into a proxy method that delegates the function call to whatever is available, e.g.

function getMimeType($filename)
{
    $mimetype = false;
    if(function_exists('finfo_open')) {
        // open with FileInfo
    } elseif(function_exists('getimagesize')) {
        // open with GD
    } elseif(function_exists('exif_imagetype')) {
       // open with EXIF
    } elseif(function_exists('mime_content_type')) {
       $mimetype = mime_content_type($filename);
    }
    return $mimetype;
}

jquery clear input default value

$(document).ready(function() {
  //...
//clear on focus
$('.input').focus(function() {
    $('.input').val("");
});
   //clear when submitted
$('.button').click(function() {
    $('.input').val("");
});

});

Zoom in on a point (using scale and translate)

you can use scrollto(x,y) function to handle the position of scrollbar right to the point that you need to be showed after zooming.for finding the position of mouse use event.clientX and event.clientY. this will help you

make sounds (beep) with c++

If you're using Windows OS then there is a function called Beep()

#include <iostream> 
#include <windows.h> // WinApi header 

using namespace std;

int main() 
{ 
    Beep(523,500); // 523 hertz (C5) for 500 milliseconds     
    cin.get(); // wait 
    return 0; 
}

Source: http://www.daniweb.com/forums/thread15252.html

For Linux based OS there is:

echo -e "\007" >/dev/tty10

And if you do not wish to use Beep() in windows you can do:

echo "^G"

Source: http://www.frank-buss.de/beep/index.html

Get current time in milliseconds using C++ and Boost

Try this: import headers as mentioned.. gives seconds and milliseconds only. If you need to explain the code read this link.

#include <windows.h>

#include <stdio.h>

void main()
{

    SYSTEMTIME st;
    SYSTEMTIME lt;

    GetSystemTime(&st);
   // GetLocalTime(&lt);

     printf("The system time is: %02d:%03d\n", st.wSecond, st.wMilliseconds);
   //  printf("The local time is: %02d:%03d\n", lt.wSecond, lt.wMilliseconds);

}

Returning JSON object from an ASP.NET page

If you get code behind, use some like this

        MyCustomObject myObject = new MyCustomObject();
        myObject.name='try';
        //OBJECT -> JSON
        var javaScriptSerializer = new System.Web.Script.Serialization.JavaScriptSerializer();
        string myObjectJson = javaScriptSerializer.Serialize(myObject);
        //return JSON   
        Response.Clear();     
        Response.ContentType = "application/json; charset=utf-8";
        Response.Write(myObjectJson );
        Response.End();

So you return a json object serialized with all attributes of MyCustomObject.

How do you handle multiple submit buttons in ASP.NET MVC Framework?

Based on mkozicki answer I come up with a bit different solution. I still use ActionNameSelectorAttribute But I needed to handle two buttons 'Save' and 'Sync'. They do almost the same so I didn't want to have two actions.

attribute:

public class MultipleButtonActionAttribute : ActionNameSelectorAttribute
{        
    private readonly List<string> AcceptedButtonNames;

    public MultipleButtonActionAttribute(params string[] acceptedButtonNames)
    {
        AcceptedButtonNames = acceptedButtonNames.ToList();
    }

    public override bool IsValidName(ControllerContext controllerContext, string actionName, MethodInfo methodInfo)
    {            
        foreach (var acceptedButtonName in AcceptedButtonNames)
        {
            var button = controllerContext.Controller.ValueProvider.GetValue(acceptedButtonName);
            if (button == null)
            {
                continue;
            }                
            controllerContext.Controller.ControllerContext.RouteData.Values.Add("ButtonName", acceptedButtonName);
            return true;
        }
        return false;
    }
}

view

<input type="submit" value="Save" name="Save" />
<input type="submit" value="Save and Sync" name="Sync" />

controller

 [MultipleButtonAction("Save", "Sync")]
 public ActionResult Sync(OrgSynchronizationEditModel model)
 {
     var btn = this.RouteData.Values["ButtonName"];

I also want to point out that if actions do different things I would probably follow mkozicki post.

Write Base64-encoded image to file

import java.util.Base64;

.... Just making it clear that this answer uses the java.util.Base64 package, without using any third-party libraries.

String crntImage=<a valid base 64 string>

byte[] data = Base64.getDecoder().decode(crntImage);

try( OutputStream stream = new FileOutputStream("d:/temp/abc.pdf") ) 
{
   stream.write(data);
}
catch (Exception e) 
{
   System.err.println("Couldn't write to file...");
}

In Django, how do I check if a user is in a certain group?

User.objects.filter(username='tom', groups__name='admin').exists()

That query will inform you user : "tom" whether belong to group "admin " or not

What is the maximum length of a valid email address?

320

And the segments look like this

{64}@{255}

64 + 1 + 255 = 320

You should also read this if you are validating emails

http://haacked.com/archive/2007/08/21/i-knew-how-to-validate-an-email-address-until-i.aspx

Delete all files of specific type (extension) recursively down a directory using a batch file

I don't have enough reputation to add comment, so I posted this as an answer. But for original issue with this command:

@echo off
FOR %%p IN (C:\Users\vexe\Pictures\sample) DO FOR %%t IN (*.jpg) DO del /s %%p\%%t

The first For is lacking recursive syntax, it should be:

@echo off
FOR /R %%p IN (C:\Users\vexe\Pictures\sample) DO FOR %%t IN (*.jpg) DO del /s %%p\%%t

You can just do:

FOR %%p IN (C:\Users\0300092544\Downloads\Ces_Sce_600) DO @ECHO %%p

to show the actual output.

Extract public/private key from PKCS12 file for later use in SSH-PK-Authentication

The accepted answer is the correct command, I just want to add one additional thing, when extracting the key if you leave the PEM password("Enter PEM pass phrase:") blank then the complete key will not be extracted but only the localKeyID will be extracted. To get the complete key you must specify a PEM password whem running the following command.

Please note that when it comes to Import password, you can specify the actual password for "Enter Import Password:" or can leave this password blank:

openssl pkcs12 -in yourP12File.pfx -nocerts -out privateKey.pem

How to config routeProvider and locationProvider in angularJS?

AngularJS provides a simple and concise way to associate routes with controllers and templates using a $routeProvider object. While recently updating an application to the latest release (1.2 RC1 at the current time) I realized that $routeProvider isn’t available in the standard angular.js script any longer.

After reading through the change log I realized that routing is now a separate module (a great move I think) as well as animation and a few others. As a result, standard module definitions and config code like the following won’t work any longer if you’re moving to the 1.2 (or future) release:

var app = angular.module('customersApp', []);

app.config(function ($routeProvider) {

    $routeProvider.when('/', {
        controller: 'customersController',
        templateUrl: '/app/views/customers.html'
    });

});

How do you fix it?

Simply add angular-route.js in addition to angular.js to your page (grab a version of angular-route.js here – keep in mind it’s currently a release candidate version which will be updated) and change the module definition to look like the following:

var app = angular.module('customersApp', ['ngRoute']);

If you’re using animations you’ll need angular-animation.js and also need to reference the appropriate module:

 var app = angular.module('customersApp', ['ngRoute', 'ngAnimate']);

Your Code can be as follows:

    var app = angular.module('app', ['ngRoute']);   

    app.config(function($routeProvider) {

    $routeProvider
        .when('/controllerone', {
                controller: 'friendDetails',
                templateUrl: 'controller3.html'

            }, {
                controller: 'friendsName',
                templateUrl: 'controller3.html'

            }

    )
        .when('/controllerTwo', {
            controller: 'simpleControoller',
            templateUrl: 'views.html'
        })
        .when('/controllerThree', {
            controller: 'simpleControoller',
            templateUrl: 'view2.html'
        })
        .otherwise({
            redirectTo: '/'
        });

});

Can anyone explain IEnumerable and IEnumerator to me?

The IEnumerable and IEnumerator Interfaces

To begin examining the process of implementing existing .NET interfaces, let’s first look at the role of IEnumerable and IEnumerator. Recall that C# supports a keyword named foreach that allows you to iterate over the contents of any array type:

// Iterate over an array of items.
int[] myArrayOfInts = {10, 20, 30, 40};
foreach(int i in myArrayOfInts)
{
   Console.WriteLine(i);
}

While it might seem that only array types can make use of this construct, the truth of the matter is any type supporting a method named GetEnumerator() can be evaluated by the foreach construct.To illustrate, follow me!

Suppose we have a Garage class:

// Garage contains a set of Car objects.
public class Garage
{
   private Car[] carArray = new Car[4];
   // Fill with some Car objects upon startup.
   public Garage()
   {
      carArray[0] = new Car("Rusty", 30);
      carArray[1] = new Car("Clunker", 55);
      carArray[2] = new Car("Zippy", 30);
      carArray[3] = new Car("Fred", 30);
   }
}

Ideally, it would be convenient to iterate over the Garage object’s subitems using the foreach construct, just like an array of data values:

// This seems reasonable ...
public class Program
{
   static void Main(string[] args)
   {
      Console.WriteLine("***** Fun with IEnumerable / IEnumerator *****\n");
      Garage carLot = new Garage();
      // Hand over each car in the collection?
      foreach (Car c in carLot)
      {
         Console.WriteLine("{0} is going {1} MPH",
         c.PetName, c.CurrentSpeed);
      }
      Console.ReadLine();
   }
}

Sadly, the compiler informs you that the Garage class does not implement a method named GetEnumerator(). This method is formalized by the IEnumerable interface, which is found lurking within the System.Collections namespace. Classes or structures that support this behavior advertise that they are able to expose contained subitems to the caller (in this example, the foreach keyword itself). Here is the definition of this standard .NET interface:

// This interface informs the caller
// that the object's subitems can be enumerated.
public interface IEnumerable
{
   IEnumerator GetEnumerator();
}

As you can see, the GetEnumerator() method returns a reference to yet another interface named System.Collections.IEnumerator. This interface provides the infrastructure to allow the caller to traverse the internal objects contained by the IEnumerable-compatible container:

// This interface allows the caller to
// obtain a container's subitems.
public interface IEnumerator
{
   bool MoveNext (); // Advance the internal position of the cursor.
   object Current { get;} // Get the current item (read-only property).
   void Reset (); // Reset the cursor before the first member.
}

If you want to update the Garage type to support these interfaces, you could take the long road and implement each method manually. While you are certainly free to provide customized versions of GetEnumerator(), MoveNext(), Current, and Reset(), there is a simpler way. As the System.Array type (as well as many other collection classes) already implements IEnumerable and IEnumerator, you can simply delegate the request to the System.Array as follows:

using System.Collections;
...
public class Garage : IEnumerable
{
   // System.Array already implements IEnumerator!
   private Car[] carArray = new Car[4];
   public Garage()
   {
      carArray[0] = new Car("FeeFee", 200);
      carArray[1] = new Car("Clunker", 90);
      carArray[2] = new Car("Zippy", 30);
      carArray[3] = new Car("Fred", 30);
   }
   public IEnumerator GetEnumerator()
   {
      // Return the array object's IEnumerator.
      return carArray.GetEnumerator();
   }
}

After you have updated your Garage type, you can safely use the type within the C# foreach construct. Furthermore, given that the GetEnumerator() method has been defined publicly, the object user could also interact with the IEnumerator type:

// Manually work with IEnumerator.
IEnumerator i = carLot.GetEnumerator();
i.MoveNext();
Car myCar = (Car)i.Current;
Console.WriteLine("{0} is going {1} MPH", myCar.PetName, myCar.CurrentSpeed);

However, if you prefer to hide the functionality of IEnumerable from the object level, simply make use of explicit interface implementation:

IEnumerator IEnumerable.GetEnumerator()
{
  // Return the array object's IEnumerator.
  return carArray.GetEnumerator();
}

By doing so, the casual object user will not find the Garage’s GetEnumerator() method, while the foreach construct will obtain the interface in the background when necessary.

Adapted from the Pro C# 5.0 and the .NET 4.5 Framework

How to set a Javascript object values dynamically?

You could also create something that would be similar to a value object (vo);

SomeModelClassNameVO.js;

function SomeModelClassNameVO(name,id) {
    this.name = name;
    this.id = id;
}

Than you can just do;

   var someModelClassNameVO = new someModelClassNameVO('name',1);
   console.log(someModelClassNameVO.name);

Repeating a function every few seconds

Use a timer. Keep in mind that .NET comes with a number of different timers. This article covers the differences.

Upload File With Ajax XmlHttpRequest

  1. There is no such thing as xhr.file = file;; the file object is not supposed to be attached this way.
  2. xhr.send(file) doesn't send the file. You have to use the FormData object to wrap the file into a multipart/form-data post data object:

    var formData = new FormData();
    formData.append("thefile", file);
    xhr.send(formData);
    

After that, the file can be access in $_FILES['thefile'] (if you are using PHP).

Remember, MDC and Mozilla Hack demos are your best friends.

EDIT: The (2) above was incorrect. It does send the file, but it would send it as raw post data. That means you would have to parse it yourself on the server (and it's often not possible, depend on server configuration). Read how to get raw post data in PHP here.

Sorting table rows according to table header column using javascript or jquery

You can use jQuery DataTables plugin for applying column sorting in desired way.

Column Sorting using DataTable

Counting repeated elements in an integer array

If you have values in a short set of possible values then you can use something like Counting Sort

If not you have to use another data structure like a Dictionary, in java a Map

int[] array
Map<Integer, Integer> 

where Key = array value for example array[i] and value = a counter

Example:

int[] array = new int [50];
Map<Integer,Integer> counterMap = new HashMap<>();

//fill the array

    for(int i=0;i<array.length;i++){
         if(counterMap.containsKey(array[i])){
          counterMap.put(array[i], counterMap.get(array[i])+1 );
         }else{
          counterMap.put(array[i], 1);
         }
    }

Change one value based on another value in pandas

The original question addresses a specific narrow use case. For those who need more generic answers here are some examples:

Creating a new column using data from other columns

Given the dataframe below:

import pandas as pd
import numpy as np

df = pd.DataFrame([['dog', 'hound', 5],
                   ['cat', 'ragdoll', 1]],
                  columns=['animal', 'type', 'age'])

In[1]:
Out[1]:
  animal     type  age
----------------------
0    dog    hound    5
1    cat  ragdoll    1

Below we are adding a new description column as a concatenation of other columns by using the + operation which is overridden for series. Fancy string formatting, f-strings etc won't work here since the + applies to scalars and not 'primitive' values:

df['description'] = 'A ' + df.age.astype(str) + ' years old ' \
                    + df.type + ' ' + df.animal

In [2]: df
Out[2]:
  animal     type  age                description
-------------------------------------------------
0    dog    hound    5    A 5 years old hound dog
1    cat  ragdoll    1  A 1 years old ragdoll cat

We get 1 years for the cat (instead of 1 year) which we will be fixing below using conditionals.

Modifying an existing column with conditionals

Here we are replacing the original animal column with values from other columns, and using np.where to set a conditional substring based on the value of age:

# append 's' to 'age' if it's greater than 1
df.animal = df.animal + ", " + df.type + ", " + \
    df.age.astype(str) + " year" + np.where(df.age > 1, 's', '')

In [3]: df
Out[3]:
                 animal     type  age
-------------------------------------
0   dog, hound, 5 years    hound    5
1  cat, ragdoll, 1 year  ragdoll    1

Modifying multiple columns with conditionals

A more flexible approach is to call .apply() on an entire dataframe rather than on a single column:

def transform_row(r):
    r.animal = 'wild ' + r.type
    r.type = r.animal + ' creature'
    r.age = "{} year{}".format(r.age, r.age > 1 and 's' or '')
    return r

df.apply(transform_row, axis=1)

In[4]:
Out[4]:
         animal            type      age
----------------------------------------
0    wild hound    dog creature  5 years
1  wild ragdoll    cat creature   1 year

In the code above the transform_row(r) function takes a Series object representing a given row (indicated by axis=1, the default value of axis=0 will provide a Series object for each column). This simplifies processing since we can access the actual 'primitive' values in the row using the column names and have visibility of other cells in the given row/column.

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

something like this:

List<string> test1 = new List<string> { "@bob.com", "@tom.com" };
List<string> test2 = new List<string> { "[email protected]", "[email protected]" };

var res = test2.Where(f => test1.Count(z => f.Contains(z)) == 0)

Live example: here

Convert array of JSON object strings to array of JS objects

var json = jQuery.parseJSON(s); //If you have jQuery.

Since the comment looks cluttered, please use the parse function after enclosing those square brackets inside the quotes.

var s=['{"Select":"11","PhotoCount":"12"}','{"Select":"21","PhotoCount":"22"}'];

Change the above code to

var s='[{"Select":"11","PhotoCount":"12"},{"Select":"21","PhotoCount":"22"}]';

Eg:

$(document).ready(function() {
    var s= '[{"Select":"11","PhotoCount":"12"},{"Select":"21","PhotoCount":"22"}]';

    s = jQuery.parseJSON(s);

    alert( s[0]["Select"] );
});

And then use the parse function. It'll surely work.

EDIT :Extremely sorry that I gave the wrong function name. it's jQuery.parseJSON

Jquery

The json api

Edit (30 April 2020):

Editing since I got an upvote for this answer. There's a browser native function available instead of JQuery (for nonJQuery users), JSON.parse("<json string here>")

twitter-bootstrap: how to get rid of underlined button text when hovering over a btn-group within an <a>-tag?

Bootstrap 4+

This is now easy to do in Bootstrap 4+

<a href="#" class="text-decoration-none">
    <!-- That is all -->
</a>

Save a file in json format using Notepad++

In Notepad++ on the Language menu you will find the menu item - 'J' and under this menu item chose the language - JSON.

Once you select the JSON language then you won't have to worry about how to save it. When you save it it will by default save it as .JSON file, you have to just select the location of the file.

Thanks, -Sam

Please look at the pic, it will give you a better idea..

keyword not supported data source

I was getting the same problem.
but this code works good try it.

<add name="MyCon" connectionString="Server=****;initial catalog=PortalDb;user id=**;password=**;MultipleActiveResultSets=True;" providerName="System.Data.SqlClient" />

How can I download a specific Maven artifact in one command line?

Regarding how to get the artifact binary, Pascal Thivent's answer is it, but to also get the artifact sources jar, we can use:

mvn dependency:get -Dartifact=groupId:artifactId:version:jar:sources

e.g.

mvn dependency:get -Dartifact=junit:junit:4.12:jar:sources

This works because the artifact parameter actually consists of groupId:artifactId:version[:packaging][:classifier]. Just the packaging and classifier are optional.

With jar as packaging and sources as classifier, the maven dependency plugin understands we're asking for the sources jar, not the artifact jar.

Unfortunately for now sources jar files cannot be downloaded transitively, which does make sense, but ideally I do believe it can also respect the option downloadSources just like the maven eclipse plugin does.

Should we @Override an interface's method implementation?

The problem with including the @Override is that it makes you think that you forgot to call the super.theOverridenMethod() method, which is very confusing. This should be crystal-clear. Perhaps Java should offer an @Interface to be used here. Oh well, yet another half-assed Java peculiarity...

How to make the script wait/sleep in a simple way in unity

With .Net 4.x you can use Task-based Asynchronous Pattern (TAP) to achieve this:

// .NET 4.x async-await
using UnityEngine;
using System.Threading.Tasks;
public class AsyncAwaitExample : MonoBehaviour
{
     private async void Start()
     {
        Debug.Log("Wait.");
        await WaitOneSecondAsync();
        DoMoreStuff(); // Will not execute until WaitOneSecond has completed
     }
    private async Task WaitOneSecondAsync()
    {
        await Task.Delay(TimeSpan.FromSeconds(1));
        Debug.Log("Finished waiting.");
    }
}

this is a feature to use .Net 4.x with Unity please see this link for description about it

and this link for sample project and compare it with coroutine

But becareful as documentation says that This is not fully replacement with coroutine

Redirect on select option in select box

For someone who doesn't want to use inline JS.

<select data-select-name>
    <option value="">Select...</option>
    <option value="http://google.com">Google</option>
    <option value="http://yahoo.com">Yahoo</option>
</select>
<script type="text/javascript">
    document.addEventListener('DOMContentLoaded',function() {
        document.querySelector('select[data-select-name]').onchange=changeEventHandler;
    },false);

    function changeEventHandler(event) {
        window.location.href = this.options[this.selectedIndex].value;
    }
</script>

eslint: error Parsing error: The keyword 'const' is reserved

you also can add this inline instead of config, just add it to the same file before you add your own disable stuff

/* eslint-env es6 */
/* eslint-disable no-console */

my case was disable a file and eslint-disable were not working for me alone

/* eslint-env es6 */
/* eslint-disable */

Magento - How to add/remove links on my account navigation?

Open navigation.phtml

app/design/frontend/yourtheme/default/template/customer/account/navigation.phtml

replace

<?php $_links = $this->getLinks(); ?>

with unset link which you want to remove

<?php 
$_count = count($_links);
unset($_links['account']); // Account Information     
unset($_links['account_edit']); // Account Information  
unset($_links['address_book']); // Address Book
unset($_links['orders']); // My Orders
unset($_links['billing_agreements']); // Billing Agreements
unset($_links['recurring_profiles']); // Recurring Profiles
unset($_links['reviews']);  // My Product Reviews
unset($_links['wishlist']); // My Wishlist
unset($_links['OAuth Customer Tokens']); // My Applications
unset($_links['newsletter']); // Newsletter Subscriptions
unset($_links['downloadable_products']); // My Downloadable Products
unset($_links['tags']); // My Tags
unset($_links['invitations']); // My Invitations
unset($_links['enterprise_customerbalance']); // Store Credit
unset($_links['enterprise_reward']); // Reward Points
unset($_links['giftregistry']); // Gift Registry
unset($_links['enterprise_giftcardaccount']); // Gift Card Link
?>

Git: Remove committed file after push

If you want to remove the file from the remote repo, first remove it from your project with --cache option and then push it:

git rm --cache /path/to/file
git commit -am "Remove file"
git push

(This works even if the file was added to the remote repo some commits ago) Remember to add to .gitignore the file extensions that you don't want to push.

How to wrap text around an image using HTML/CSS

you have to float your image container as follows:

HTML

<div id="container">
    <div id="floated">...some other random text</div>
    ...
    some random text
    ...
</div>

CSS

#container{
    width: 400px;
    background: yellow;
}
#floated{
    float: left;
    width: 150px;
    background: red;
}

FIDDLE

http://jsfiddle.net/kYDgL/

How Do I 'git fetch' and 'git merge' from a Remote Tracking Branch (like 'git pull')

You don't fetch a branch, you fetch an entire remote:

git fetch origin
git merge origin/an-other-branch

Oracle query to identify columns having special characters

I figured out the answer to above problem. Below query will return rows which have even a signle occurrence of characters besides alphabets, numbers, square brackets, curly brackets,s pace and dot. Please note that position of closing bracket ']' in matching pattern is important.

Right ']' has the special meaning of ending a character set definition. It wouldn't make any sense to end the set before you specified any members, so the way to indicate a literal right ']' inside square brackets is to put it immediately after the left '[' that starts the set definition

SELECT * FROM test WHERE REGEXP_LIKE(sampletext,  '[^]^A-Z^a-z^0-9^[^.^{^}^ ]' );

How to call base.base.method()?

This is a bad programming practice, and not allowed in C#. It's a bad programming practice because

  • The details of the grandbase are implementation details of the base; you shouldn't be relying on them. The base class is providing an abstraction overtop of the grandbase; you should be using that abstraction, not building a bypass to avoid it.

  • To illustrate a specific example of the previous point: if allowed, this pattern would be yet another way of making code susceptible to brittle-base-class failures. Suppose C derives from B which derives from A. Code in C uses base.base to call a method of A. Then the author of B realizes that they have put too much gear in class B, and a better approach is to make intermediate class B2 that derives from A, and B derives from B2. After that change, code in C is calling a method in B2, not in A, because C's author made an assumption that the implementation details of B, namely, that its direct base class is A, would never change. Many design decisions in C# are to mitigate the likelihood of various kinds of brittle base failures; the decision to make base.base illegal entirely prevents this particular flavour of that failure pattern.

  • You derived from your base because you like what it does and want to reuse and extend it. If you don't like what it does and want to work around it rather than work with it, then why did you derive from it in the first place? Derive from the grandbase yourself if that's the functionality you want to use and extend.

  • The base might require certain invariants for security or semantic consistency purposes that are maintained by the details of how the base uses the methods of the grandbase. Allowing a derived class of the base to skip the code that maintains those invariants could put the base into an inconsistent, corrupted state.

How do I install Eclipse Marketplace in Eclipse Classic?

Go to Help=>install new software=>workwith choice kEPLER and

search in the below "type filter text" --------------market,

  1. Select and expand general purpose tools and find MPC Marketplace Client
  2. Restart After installed..

Javascript + Regex = Nothing to repeat error?

You need to double the backslashes used to escape the regular expression special characters. However, as @Bohemian points out, most of those backslashes aren't needed. Unfortunately, his answer suffers from the same problem as yours. What you actually want is:

The backslash is being interpreted by the code that reads the string, rather than passed to the regular expression parser. You want:

"[\\[\\]?*+|{}\\\\()@.\n\r]"

Note the quadrupled backslash. That is definitely needed. The string passed to the regular expression compiler is then identical to @Bohemian's string, and works correctly.

how can I enable PHP Extension intl?

I was having same kind of problem with ldap, intl, curl php extensions. I've solved those issues by the following ways:

At first you've to check whether these extensions have been enabled in the php.ini file by removing semicolon (;) in front of the following lines:

;extension=php_intl.dll
;extension=php_ldap.dll
;extension=php_curl.dll

Secondly, libeay32.dll, ibssh2.dll and ssleay32.dll files have to be loaded by php properly to function those extensions properly. These dll files are required by several php extensions (ie curl, ldap, intl etc). These files generally reside in the php installation directory [for my case it is C:\php directory]. Additionally, for intl extension to be enabled you're gonna need some other dll files to be loaded by php properly. The name of these files begin with icu (ie icudt57.dll icuin57.dll etc for php version 5.6). You'll also find these files in the php main installation directory.

There is a alternate way you can load these files from your httpd.conf (apache configuratio file) file instead of copying them to the apache's bin directory. This can be done by using the following technique:

Please note that my php version is 5.5.

LoadFile  "C:/php/icudt51.dll"
LoadFile  "C:/php/icuin51.dll"
LoadFile  "C:/php/icuio51.dll"
LoadFile  "C:/php/icule51.dll"
LoadFile  "C:/php/iculx51.dll"
LoadFile  "C:/php/icutest51.dll"
LoadFile  "C:/php/icutu51.dll"
LoadFile  "C:/php/icuuc51.dll"

LoadFile  "C:/php/libeay32.dll"
LoadFile  "C:/php/libssh2.dll"
LoadFile  "C:/php/ssleay32.dll"

 That's it.

How to send an email with Gmail as provider using Python?

Seems like problem of the old smtplib. In python2.7 everything works fine.

Update: Yep, server.ehlo() also could help.

Deleting Row in SQLite in Android

The only way that worked for me was this

fun removeCart(mCart: Cart) {
    val db = dbHelper.writableDatabase
    val deleteLineWithThisValue = mCart.f
    db.delete(cons.tableNames[3], Cart.KEY_f + "  LIKE  '%" + deleteLineWithThisValue + "%' ", null)
}


class Cart {
    var a: String? = null
    var b: String? = null
    var c: String? = null
    var d: String? = null
    var e: Int? = null
    var f: String? = null

companion object {
    // Labels Table Columns names
    const val rowIdKey = "_id"
    const val idKey = "id"
    const val KEY_a = "a"
    const val KEY_b = "b"
    const val KEY_c = "c"
    const val KEY_d = "d"
    const val KEY_e = "e"
    const val KEY_f = "f"
   }
}

object cons {
    val tableNames = arrayOf(
            /*0*/ "shoes",
            /*1*/ "hats",
            /*2*/ "shirt",
            /*3*/ "car"
         )
 }

Run command on the Ansible host

you can try this way

Why does sed not replace all occurrences?

You should add the g modifier so that sed performs a global substitution of the contents of the pattern buffer:

echo dog dog dos | sed -e 's:dog:log:g'

For a fantastic documentation on sed, check http://www.grymoire.com/Unix/Sed.html. This global flag is explained here: http://www.grymoire.com/Unix/Sed.html#uh-6

The official documentation for GNU sed is available at http://www.gnu.org/software/sed/manual/

Class is inaccessible due to its protection level

It may also be the case that the library containing the class in question is not properly signed with a strong name.

Calling JavaScript Function From CodeBehind

You may try this :

Page.ClientScript.RegisterStartupScript(this.GetType(),"CallMyFunction","MyFunction()",true);

User Authentication in ASP.NET Web API

If you want to authenticate against a user name and password and without an authorization cookie, the MVC4 Authorize attribute won't work out of the box. However, you can add the following helper method to your controller to accept basic authentication headers. Call it from the beginning of your controller's methods.

void EnsureAuthenticated(string role)
{
    string[] parts = UTF8Encoding.UTF8.GetString(Convert.FromBase64String(Request.Headers.Authorization.Parameter)).Split(':');
    if (parts.Length != 2 || !Membership.ValidateUser(parts[0], parts[1]))
        throw new HttpResponseException(Request.CreateErrorResponse(HttpStatusCode.Unauthorized, "No account with that username and password"));
    if (role != null && !Roles.IsUserInRole(parts[0], role))
        throw new HttpResponseException(Request.CreateErrorResponse(HttpStatusCode.Unauthorized, "An administrator account is required"));
}

From the client side, this helper creates a HttpClient with the authentication header in place:

static HttpClient CreateBasicAuthenticationHttpClient(string userName, string password)
{
    var client = new HttpClient();
    client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", Convert.ToBase64String(UTF8Encoding.UTF8.GetBytes(userName + ':' + password)));
    return client;
}

How do I use a regular expression to match any string, but at least 3 characters?

This is python regex, but it probably works in other languages that implement it, too.

I guess it depends on what you consider a character to be. If it's letters, numbers, and underscores:

\w{3,}

if just letters and digits:

[a-zA-Z0-9]{3,}

Python also has a regex method to return all matches from a string.

>>> import re
>>> re.findall(r'\w{3,}', 'This is a long string, yes it is.')
['This', 'long', 'string', 'yes']

Is it possible to format an HTML tooltip (title attribute)?

In bootstrap tooltip just use data-html="true"

How to override maven property in command line?

See Introduction to the POM

finalName is created as:

<build>
    <finalName>${project.artifactId}-${project.version}</finalName>
</build>

One of the solutions is to add own property:

<properties>
    <finalName>${project.artifactId}-${project.version}</finalName>
</properties>
<build>
    <finalName>${finalName}</finalName>
 </build>

And now try:

mvn -DfinalName=build clean package

Using Colormaps to set color of line in matplotlib

A combination of line styles, markers, and qualitative colors from matplotlib:

import itertools
import matplotlib as mpl
import matplotlib.pyplot as plt
N = 8*4+10
l_styles = ['-','--','-.',':']
m_styles = ['','.','o','^','*']
colormap = mpl.cm.Dark2.colors   # Qualitative colormap
for i,(marker,linestyle,color) in zip(range(N),itertools.product(m_styles,l_styles, colormap)):
    plt.plot([0,1,2],[0,2*i,2*i], color=color, linestyle=linestyle,marker=marker,label=i)
plt.legend(bbox_to_anchor=(1.05, 1), loc=2, borderaxespad=0.,ncol=4);

enter image description here

UPDATE: Supporting not only ListedColormap, but also LinearSegmentedColormap

import itertools
import matplotlib.pyplot as plt
Ncolors = 8
#colormap = plt.cm.Dark2# ListedColormap
colormap = plt.cm.viridis# LinearSegmentedColormap
Ncolors = min(colormap.N,Ncolors)
mapcolors = [colormap(int(x*colormap.N/Ncolors)) for x in range(Ncolors)]
N = Ncolors*4+10
l_styles = ['-','--','-.',':']
m_styles = ['','.','o','^','*']
fig,ax = plt.subplots(gridspec_kw=dict(right=0.6))
for i,(marker,linestyle,color) in zip(range(N),itertools.product(m_styles,l_styles, mapcolors)):
    ax.plot([0,1,2],[0,2*i,2*i], color=color, linestyle=linestyle,marker=marker,label=i)
ax.legend(bbox_to_anchor=(1.05, 1), loc=2, borderaxespad=0.,ncol=3,prop={'size': 8})

enter image description here

Visual Studio debugger error: Unable to start program Specified file cannot be found

I think that what you have to check is:

  1. if the target EXE is correctly configured in the project settings ("command", in the debugging tab). Since all individual projects run when you start debugging it's well possible that only the debugging target for the "ALL" solution is missing, check which project is currently active (you can also select the debugger target by changing the active project).

  2. dependencies (DLLs) are also located at the target debugee directory or can be loaded (you can use the "depends.exe" tool for checking dependencies of an executable or DLL).

Prevent flex items from overflowing a container

Instead of flex: 1 0 auto just use flex: 1

_x000D_
_x000D_
main, aside, article {_x000D_
  margin: 10px;_x000D_
  border: solid 1px #000;_x000D_
  border-bottom: 0;_x000D_
  height: 50px;_x000D_
}_x000D_
main {_x000D_
  display: flex;_x000D_
}_x000D_
aside {_x000D_
  flex: 0 0 200px;_x000D_
}_x000D_
article {_x000D_
  flex: 1;_x000D_
}
_x000D_
<main>_x000D_
  <aside>x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x </aside>_x000D_
  <article>don't let flex item overflow container.... y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y </article>_x000D_
</main>
_x000D_
_x000D_
_x000D_

Parse error: syntax error, unexpected T_ECHO in

Missing ; after var_dump($row)

Java way to check if a string is palindrome

You can try something like this :

    String variable = ""; #write a string name

    StringBuffer rev = new StringBuffer(variable).reverse(); 

    String strRev = rev.toString(); 

    if(variable.equalsIgnoreCase(strRev)) # Check the condition

Java: random long number in 0 <= x < n range

From Java 8 API

It could be easier to take actual implementation from API doc https://docs.oracle.com/javase/8/docs/api/java/util/Random.html#longs-long-long-long- they are using it to generate longs stream. And your origin can be "0" like in the question.

long nextLong(long origin, long bound) {
  long r = nextLong();
  long n = bound - origin, m = n - 1;
  if ((n & m) == 0L)  // power of two
    r = (r & m) + origin;
  else if (n > 0L) {  // reject over-represented candidates
    for (long u = r >>> 1;            // ensure nonnegative
         u + m - (r = u % n) < 0L;    // rejection check
         u = nextLong() >>> 1) // retry
        ;
    r += origin;
  }
  else {              // range not representable as long
    while (r < origin || r >= bound)
      r = nextLong();
  }
  return r;
}

C++ string to double conversion

You can convert char to int and viceversa easily because for the machine an int and a char are the same, 8 bits, the only difference comes when they have to be shown in screen, if the number is 65 and is saved as a char, then it will show 'A', if it's saved as a int it will show 65.

With other types things change, because they are stored differently in memory. There's standard function in C that allows you to convert from string to double easily, it's atof. (You need to include stdlib.h)

#include <stdlib.h>

int main()
{
    string word;  
    openfile >> word;
    double lol = atof(word.c_str()); /*c_str is needed to convert string to const char*
                                     previously (the function requires it)*/
    return 0;
}

Connect to Active Directory via LDAP

ldapConnection is the server adres: ldap.example.com Ldap.Connection.Path is the path inside the ADS that you like to use insert in LDAP format.

OU=Your_OU,OU=other_ou,dc=example,dc=com

You start at the deepest OU working back to the root of the AD, then add dc=X for every domain section until you have everything including the top level domain

Now i miss a parameter to authenticate, this works the same as the path for the username

CN=username,OU=users,DC=example,DC=com

Introduction to LDAP

How to get Bitmap from an Uri?

(KOTLIN) So, as of April 7th, 2020 none of the above mentioned options worked, but here's what worked for me:

  1. If you want to store the bitmap in a val and set an imageView with it, use this:

    val bitmap = BitmapFactory.decodeFile(currentPhotoPath).also { bitmap -> imageView.setImageBitmap(bitmap) }

  2. If you just want to set the bitmap to and imageView, use this:

    BitmapFactory.decodeFile(currentPhotoPath).also { bitmap -> imageView.setImageBitmap(bitmap) }

What's the console.log() of java?

console.log() in java is System.out.println(); to put text on the next line

And System.out.print(); puts text on the same line.

how to make div click-able?

If this div is a function I suggest use cursor:pointer in your style like style="cursor:pointer" and can use onclick function.

like this

<div onclick="myfunction()" style="cursor:pointer"></div>

but I suggest you use a JS framework like jquery or extjs

phpexcel to download

Use this call

$objWriter->save('php://output');

To output the XLS sheet to the page you are on, just make sure that the page you are on has no other echo's,print's, outputs.

Why do I get the error "Unsafe code may only appear if compiling with /unsafe"?

Probably because you're using unsafe code.

Are you doing something with pointers or unmanaged assemblies somewhere?

Float to String format specifier

Firstly, as Etienne says, float in C# is Single. It is just the C# keyword for that data type.

So you can definitely do this:

float f = 13.5f;
string s = f.ToString("R");

Secondly, you have referred a couple of times to the number's "format"; numbers don't have formats, they only have values. Strings have formats. Which makes me wonder: what is this thing you have that has a format but is not a string? The closest thing I can think of would be decimal, which does maintain its own precision; however, calling simply decimal.ToString should have the effect you want in that case.

How about including some example code so we can see exactly what you're doing, and why it isn't achieving what you want?

"R cannot be resolved to a variable"?

This error is because of deleting R.java file from project /gen folder. If you have backup of your project, please go to the project directory and paste R.java file which you copy from your backup section.

Corrupt R.java file can also be caused by an error in XML. Often these kinds of errors don't show up in eclipse, so I'd suggest taking a look at your XML files. After that you can also try to Clean your project by going to Project -> Clean... in the menu bar.

How to copy JavaScript object to new variable NOT by reference?

I've found that the following works if you're not using jQuery and only interested in cloning simple objects (see comments).

JSON.parse(JSON.stringify(json_original));

Documentation

Avoid trailing zeroes in printf()

This can't be done with the normal printf format specifiers. The closest you could get would be:

printf("%.6g", 359.013); // 359.013
printf("%.6g", 359.01);  // 359.01

but the ".6" is the total numeric width so

printf("%.6g", 3.01357); // 3.01357

breaks it.

What you can do is to sprintf("%.20g") the number to a string buffer then manipulate the string to only have N characters past the decimal point.

Assuming your number is in the variable num, the following function will remove all but the first N decimals, then strip off the trailing zeros (and decimal point if they were all zeros).

char str[50];
sprintf (str,"%.20g",num);  // Make the number.
morphNumericString (str, 3);
:    :
void morphNumericString (char *s, int n) {
    char *p;
    int count;

    p = strchr (s,'.');         // Find decimal point, if any.
    if (p != NULL) {
        count = n;              // Adjust for more or less decimals.
        while (count >= 0) {    // Maximum decimals allowed.
             count--;
             if (*p == '\0')    // If there's less than desired.
                 break;
             p++;               // Next character.
        }

        *p-- = '\0';            // Truncate string.
        while (*p == '0')       // Remove trailing zeros.
            *p-- = '\0';

        if (*p == '.') {        // If all decimals were zeros, remove ".".
            *p = '\0';
        }
    }
}

If you're not happy with the truncation aspect (which would turn 0.12399 into 0.123 rather than rounding it to 0.124), you can actually use the rounding facilities already provided by printf. You just need to analyse the number before-hand to dynamically create the widths, then use those to turn the number into a string:

#include <stdio.h>

void nDecimals (char *s, double d, int n) {
    int sz; double d2;

    // Allow for negative.

    d2 = (d >= 0) ? d : -d;
    sz = (d >= 0) ? 0 : 1;

    // Add one for each whole digit (0.xx special case).

    if (d2 < 1) sz++;
    while (d2 >= 1) { d2 /= 10.0; sz++; }

    // Adjust for decimal point and fractionals.

    sz += 1 + n;

    // Create format string then use it.

    sprintf (s, "%*.*f", sz, n, d);
}

int main (void) {
    char str[50];
    double num[] = { 40, 359.01335, -359.00999,
        359.01, 3.01357, 0.111111111, 1.1223344 };
    for (int i = 0; i < sizeof(num)/sizeof(*num); i++) {
        nDecimals (str, num[i], 3);
        printf ("%30.20f -> %s\n", num[i], str);
    }
    return 0;
}

The whole point of nDecimals() in this case is to correctly work out the field widths, then format the number using a format string based on that. The test harness main() shows this in action:

  40.00000000000000000000 -> 40.000
 359.01335000000000263753 -> 359.013
-359.00999000000001615263 -> -359.010
 359.00999999999999090505 -> 359.010
   3.01357000000000008200 -> 3.014
   0.11111111099999999852 -> 0.111
   1.12233439999999995429 -> 1.122

Once you have the correctly rounded value, you can once again pass that to morphNumericString() to remove trailing zeros by simply changing:

nDecimals (str, num[i], 3);

into:

nDecimals (str, num[i], 3);
morphNumericString (str, 3);

(or calling morphNumericString at the end of nDecimals but, in that case, I'd probably just combine the two into one function), and you end up with:

  40.00000000000000000000 -> 40
 359.01335000000000263753 -> 359.013
-359.00999000000001615263 -> -359.01
 359.00999999999999090505 -> 359.01
   3.01357000000000008200 -> 3.014
   0.11111111099999999852 -> 0.111
   1.12233439999999995429 -> 1.122

How to format font style and color in echo

Are you trying to echo out a style or an inline style? An inline style would be like

echo "<p style=\"font-color: #ff0000;\">text here</p>";

UnicodeDecodeError, invalid continuation byte

Well this type of error comes when u are taking input a particular file or data in pandas such as :-

data=pd.read_csv('/kaggle/input/fertilizers-by-product-fao/FertilizersProduct.csv)

Then the error is displaying like this :- UnicodeDecodeError: 'utf-8' codec can't decode byte 0xf4 in position 1: invalid continuation byte

So to avoid this type of error can be removed by adding an argument

data=pd.read_csv('/kaggle/input/fertilizers-by-product-fao/FertilizersProduct.csv', encoding='ISO-8859-1')

How do I erase an element from std::vector<> by index?

I suggest to read this since I believe that is what are you looking for.https://en.wikipedia.org/wiki/Erase%E2%80%93remove_idiom

If you use for example

 vec.erase(vec.begin() + 1, vec.begin() + 3);

you will erase n -th element of vector but when you erase second element, all other elements of vector will be shifted and vector sized will be -1. This can be problem if you loop through vector since vector size() is decreasing. If you have problem like this provided link suggested to use existing algorithm in standard C++ library. and "remove" or "remove_if".

Hope that this helped

python JSON object must be str, bytes or bytearray, not 'dict

You are passing a dictionary to a function that expects a string.

This syntax:

{"('Hello',)": 6, "('Hi',)": 5}

is both a valid Python dictionary literal and a valid JSON object literal. But loads doesn't take a dictionary; it takes a string, which it then interprets as JSON and returns the result as a dictionary (or string or array or number, depending on the JSON, but usually a dictionary).

If you pass this string to loads:

'''{"('Hello',)": 6, "('Hi',)": 5}'''

then it will return a dictionary that looks a lot like the one you are trying to pass to it.

You could also exploit the similarity of JSON object literals to Python dictionary literals by doing this:

json.loads(str({"('Hello',)": 6, "('Hi',)": 5}))

But in either case you would just get back the dictionary that you're passing in, so I'm not sure what it would accomplish. What's your goal?

Pointer to 2D arrays in C

int *pointer[280]; //Creates 280 pointers of type int.

In 32 bit os, 4 bytes for each pointer. so 4 * 280 = 1120 bytes.

int (*pointer)[100][280]; // Creates only one pointer which is used to point an array of [100][280] ints.

Here only 4 bytes.

Coming to your question, int (*pointer)[280]; and int (*pointer)[100][280]; are different though it points to same 2D array of [100][280].

Because if int (*pointer)[280]; is incremented, then it will points to next 1D array, but where as int (*pointer)[100][280]; crosses the whole 2D array and points to next byte. Accessing that byte may cause problem if that memory doen't belongs to your process.

Invariant Violation: Objects are not valid as a React child

Just create a valid JSX element. In my case I assigned a component to an object.

const AwesomeButtonComponent = () => <button>AwesomeButton</button>
const next = {
  link: "http://awesomeLink.com",
  text: "Awesome text",
  comp: AwesomeButtonComponent
}

Somewhere else in my Code I wanted to dynamically assign that button.

return (
  <div>
    {next.comp ? next.comp : <DefaultAwesomeButtonComp/>}
  </div>
)

I solve this by declaring a JSX comp which I initialized via the props comp.

const AwesomeBtnFromProps = next.comp
return (
  <div>
    {next.comp ? <AwesomeBtnFromProps/> : <DefaultAwesomeButtonComp/>}
  </div>
)

How to calculate a logistic sigmoid function in Python?

Here's how you would implement the logistic sigmoid in a numerically stable way (as described here):

def sigmoid(x):
    "Numerically-stable sigmoid function."
    if x >= 0:
        z = exp(-x)
        return 1 / (1 + z)
    else:
        z = exp(x)
        return z / (1 + z)

Or perhaps this is more accurate:

import numpy as np

def sigmoid(x):  
    return np.exp(-np.logaddexp(0, -x))

Internally, it implements the same condition as above, but then uses log1p.

In general, the multinomial logistic sigmoid is:

def nat_to_exp(q):
    max_q = max(0.0, np.max(q))
    rebased_q = q - max_q
    return np.exp(rebased_q - np.logaddexp(-max_q, np.logaddexp.reduce(rebased_q)))

(However, logaddexp.reduce could be more accurate.)

How to detect lowercase letters in Python?

To check if a character is lower case, use the islower method of str. This simple imperative program prints all the lowercase letters in your string:

for c in s:
    if c.islower():
         print c

Note that in Python 3 you should use print(c) instead of print c.


Possibly ending up with assigning those letters to a different variable.

To do this I would suggest using a list comprehension, though you may not have covered this yet in your course:

>>> s = 'abCd'
>>> lowercase_letters = [c for c in s if c.islower()]
>>> print lowercase_letters
['a', 'b', 'd']

Or to get a string you can use ''.join with a generator:

>>> lowercase_letters = ''.join(c for c in s if c.islower())
>>> print lowercase_letters
'abd'

Dump a NumPy array into a csv file

tofile is a convenient function to do this:

import numpy as np
a = np.asarray([ [1,2,3], [4,5,6], [7,8,9] ])
a.tofile('foo.csv',sep=',',format='%10.5f')

The man page has some useful notes:

This is a convenience function for quick storage of array data. Information on endianness and precision is lost, so this method is not a good choice for files intended to archive data or transport data between machines with different endianness. Some of these problems can be overcome by outputting the data as text files, at the expense of speed and file size.

Note. This function does not produce multi-line csv files, it saves everything to one line.

How to obtain the location of cacerts of the default java installation?

Under Linux, to find the location of $JAVA_HOME:

readlink -f /usr/bin/java | sed "s:bin/java::"

the cacerts are under lib/security/cacerts:

$(readlink -f /usr/bin/java | sed "s:bin/java::")lib/security/cacerts

Under mac OS X , to find $JAVA_HOME run:

/usr/libexec/java_home

the cacerts are under Home/lib/security/cacerts:

$(/usr/libexec/java_home)/lib/security/cacerts

UPDATE (OS X with JDK)

above code was tested on computer without JDK installed. With JDK installed, as pR0Ps said, it's at

$(/usr/libexec/java_home)/jre/lib/security/cacerts

How can I ping a server port with PHP?

I think the answer to this question pretty much sums up the problem with your question.

If what you want to do is find out whether a given host will accept TCP connections on port 80, you can do this:

$host = '193.33.186.70'; 
$port = 80; 
$waitTimeoutInSeconds = 1; 
if($fp = fsockopen($host,$port,$errCode,$errStr,$waitTimeoutInSeconds)){   
   // It worked 
} else {
   // It didn't work 
} 
fclose($fp);

For anything other than TCP it will be more difficult (although since you specify 80, I guess you are looking for an active HTTP server, so TCP is what you want). TCP is sequenced and acknowledged, so you will implicitly receive a returned packet when a connection is successfully made. Most other transport protocols (commonly UDP, but others as well) do not behave in this manner, and datagrams will not be acknowledged unless the overlayed Application Layer protocol implements it.

The fact that you are asking this question in this manner tells me you have a fundamental gap in your knowledge on Transport Layer protocols. You should read up on ICMP and TCP, as well as the OSI Model.

Also, here's a slightly cleaner version to ping to hosts.

// Function to check response time
function pingDomain($domain){
    $starttime = microtime(true);
    $file      = fsockopen ($domain, 80, $errno, $errstr, 10);
    $stoptime  = microtime(true);
    $status    = 0;

    if (!$file) $status = -1;  // Site is down
    else {
        fclose($file);
        $status = ($stoptime - $starttime) * 1000;
        $status = floor($status);
    }
    return $status;
}

Refused to load the script because it violates the following Content Security Policy directive

It was solved with:

script-src 'self' http://xxxx 'unsafe-inline' 'unsafe-eval';

What is the maximum possible length of a .NET string?

Based on my highly scientific and accurate experiment, it tops out on my machine well before 1,000,000,000 characters. (I'm still running the code below to get a better pinpoint).

UPDATE: After a few hours, I've given up. Final results: Can go a lot bigger than 100,000,000 characters, instantly given System.OutOfMemoryException at 1,000,000,000 characters.

using System;
using System.Collections.Generic;

public class MyClass
{
    public static void Main()
    {
        int i = 100000000;
        try
        {
            for (i = i; i <= int.MaxValue; i += 5000)
            {
                string value = new string('x', i);
                //WL(i);
            }
        }
        catch (Exception exc)
        {
            WL(i);
            WL(exc);
        }
        WL(i);
        RL();
    }

    #region Helper methods

    private static void WL(object text, params object[] args)
    {
        Console.WriteLine(text.ToString(), args);   
    }

    private static void RL()
    {
        Console.ReadLine(); 
    }

    private static void Break() 
    {
        System.Diagnostics.Debugger.Break();
    }

    #endregion
}

How to use ConcurrentLinkedQueue?

Use poll to get the first element, and add to add a new last element. That's it, no synchronization or anything else.

Refused to execute script, strict MIME type checking is enabled?

My problem was that I have been putting the CSS files in the scripts definition area just above the end of the Try to check the files spots within your pages

How can I make an svg scale with its parent container?

To specify the coordinates within the SVG image independently of the scaled size of the image, use the viewBox attribute on the SVG element to define what the bounding box of the image is in the coordinate system of the image, and use the width and height attributes to define what the width or height are with respect to the containing page.

For instance, if you have the following:

<svg>
    <polygon fill=red stroke-width=0 
             points="0,10 20,10 10,0" />
</svg>

It will render as a 10px by 20px triangle:

10x20 triangle

Now, if you set only the width and height, that will change the size of the SVG element, but not scale the triangle:

<svg width=100 height=50>
    <polygon fill=red stroke-width=0 
             points="0,10 20,10 10,0" />
</svg>

10x20 triangle

If you set the view box, that causes it to transform the image such that the given box (in the coordinate system of the image) is scaled up to fit within the given width and height (in the coordinate system of the page). For instance, to scale up the triangle to be 100px by 50px:

<svg width=100 height=50 viewBox="0 0 20 10">
    <polygon fill=red stroke-width=0 
             points="0,10 20,10 10,0" />
</svg>

100x50 triangle

If you want to scale it up to the width of the HTML viewport:

<svg width="100%" viewBox="0 0 20 10">
    <polygon fill=red stroke-width=0 
             points="0,10 20,10 10,0" />
</svg>

300x150 triangle

Note that by default, the aspect ratio is preserved. So if you specify that the element should have a width of 100%, but a height of 50px, it will actually only scale up to the height of 50px (unless you have a very narrow window):

<svg width="100%" height="50px" viewBox="0 0 20 10">
    <polygon fill=red stroke-width=0 
             points="0,10 20,10 10,0" />
</svg>

100x50 triangle

If you actually want it to stretch horizontally, disable aspect ratio preservation with preserveAspectRatio=none:

<svg width="100%" height="50px" viewBox="0 0 20 10" preserveAspectRatio="none">
    <polygon fill=red stroke-width=0 
             points="0,10 20,10 10,0" />
</svg>

300x50 triangle

(note that while in my examples I use syntax that works for HTML embedding, to include the examples as an image in StackOverflow I am instead embedding within another SVG, so I need to use valid XML syntax)

XML Schema minOccurs / maxOccurs default values

example:

XML

<?xml version="1.0" encoding="UTF-8"?> 
<?xml-stylesheet type="text/xsl" href="country.xsl"?>
<country xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="country.xsd">
    <countryName>Australia</countryName>
    <capital>Canberra</capital>
    <nationalLanguage>English</nationalLanguage>
    <population>21000000</population>
    <currency>Australian Dollar</currency>
    <nationalIdentities>
        <nationalAnthem>Advance Australia Fair</nationalAnthem>
        <nationalDay>Australia Day (26 January)</nationalDay>
        <nationalColour>Green and Gold</nationalColour>
        <nationalGemstone>Opal</nationalGemstone>
        <nationalFlower>Wattle (Acacia pycnantha)</nationalFlower>
    </nationalIdentities>
    <publicHolidays>
        <newYearDay>1 January</newYearDay>
        <australiaDay>26 January</australiaDay>
        <anzacDay>25 April</anzacDay>
        <christmasDay>25 December</christmasDay>
        <boxingDay>26 December</boxingDay>
        <laborDay>Variable Date</laborDay>
        <easter>Variable Date</easter>
        <queenBirthDay>21 April (Variable Date)</queenBirthDay>
    </publicHolidays>
    <states>
        <stateName><Name>NSW -  New South Wales</Name></stateName>
        <stateName><Name>VIC -  Victoria</Name></stateName>
        <stateName><Name>QLD -  Queensland</Name></stateName>
        <stateName><Name>SA -  South Australia</Name></stateName>
        <stateName><Name>WA -  Western Australia</Name></stateName>
        <stateName><Name>TAS -  Tasmania</Name></stateName>
    </states>
    <territories>
        <territoryName>ACT -  Australian Capital Territory</territoryName>
        <territoryName>NT -  Northern Territory</territoryName>
    </territories>
</country>

XSD:

<?xml version="1.0" encoding="UTF-8"?> 
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
    <xs:element name="country">
        <xs:complexType>
            <xs:sequence>
                <xs:element name="countryName" type="xs:string"/>
                <xs:element name="capital" type="xs:string"/>
                <xs:element name="nationalLanguage" type="xs:string"/>
                <xs:element name="population" type="xs:double"/>
                <xs:element name="currency" type="xs:string"/>
                <xs:element name="nationalIdentities">
                <xs:complexType>
                    <xs:sequence>
                        <xs:element name="nationalAnthem" type="xs:string"/>
                        <xs:element name="nationalDay" type="xs:string"/>
                        <xs:element name="nationalColour" type="xs:string"/>
                        <xs:element name="nationalGemstone" type="xs:string"/>
                        <xs:element name="nationalFlower" type="xs:string"/>
                    </xs:sequence>
                </xs:complexType>
                </xs:element>
                <xs:element name="publicHolidays">
                    <xs:complexType>
                        <xs:sequence>
                            <xs:element name="newYearDay" maxOccurs="1" type="xs:string"/>
                            <xs:element name="australiaDay" maxOccurs="1" type="xs:string"/>
                            <xs:element name="anzacDay" maxOccurs="1" type="xs:string"/>
                            <xs:element name="christmasDay" maxOccurs="1" type="xs:string"/>
                            <xs:element name="boxingDay" maxOccurs="1" type="xs:string"/>
                            <xs:element name="laborDay" maxOccurs="1" type="xs:string"/>
                            <xs:element name="easter" maxOccurs="1" type="xs:string"/>
                            <xs:element name="queenBirthDay" maxOccurs="1" type="xs:string"/>
                        </xs:sequence>
                    </xs:complexType>
                </xs:element>
                <xs:element name="states">
                    <xs:complexType>
                        <xs:sequence>
                            <xs:element name="stateName" minOccurs="1" maxOccurs="unbounded">
                                <xs:complexType>
                                    <xs:sequence>
                                        <xs:element name="Name" type="xs:string"/>
                                    </xs:sequence>
                                </xs:complexType>
                            </xs:element>
                        </xs:sequence>
                    </xs:complexType>
                </xs:element>
                <xs:element name="territories">
                    <xs:complexType>
                        <xs:sequence>
                            <xs:element name="territoryName" maxOccurs="unbounded"/>
                        </xs:sequence>
                    </xs:complexType>
                </xs:element>
            </xs:sequence>
        </xs:complexType>
    </xs:element>
</xs:schema>

XSL:

<?xml version="1.0"?> 
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
    <xsl:output method="html" indent="yes" version="4.0"/>
    <xsl:template match="/">
        <html>
            <body>          
                <xsl:for-each select="country">         
                    <xsl:value-of select="countryName"/><br/>
                    <xsl:value-of select="capital"/><br/>
                    <xsl:value-of select="nationalLanguage"/><br/>
                    <xsl:value-of select="population"/><br/>
                    <xsl:value-of select="currency"/><br/>              
                    <xsl:for-each select="nationalIdentities">
                        <xsl:value-of select="nationalAnthem"/><br/>
                        <xsl:value-of select="nationalDay"/><br/>
                        <xsl:value-of select="nationalColour"/><br/>
                        <xsl:value-of select="nationalGemstone"/><br/>
                        <xsl:value-of select="nationalFlower"/><br/>
                    </xsl:for-each>
                    <xsl:for-each select="publicHolidays">
                        <xsl:value-of select="newYearDay"/><br/>
                        <xsl:value-of select="australiaDay"/><br/>
                        <xsl:value-of select="anzacDay"/><br/>
                        <xsl:value-of select="christmasDay"/><br/>
                        <xsl:value-of select="boxingDay"/><br/>
                        <xsl:value-of select="laborDay"/><br/>
                        <xsl:value-of select="easter"/><br/>
                        <xsl:value-of select="queenBirthDay"/><br/>
                    </xsl:for-each>
                    <xsl:for-each select="states/stateName">
                        <xsl:value-of select="Name"/><br/>
                    </xsl:for-each>
                </xsl:for-each>
            </body>
        </html>
    </xsl:template>
</xsl:stylesheet>

Result:

Australia
Canberra
English
21000000
Australian Dollar
Advance Australia Fair
Australia Day (26 January)
Green and Gold
Opal
Wattle (Acacia pycnantha)
1 January
26 January
25 April
25 December
26 December
Variable Date
Variable Date
21 April (Variable Date)
NSW - New South Wales
VIC - Victoria
QLD - Queensland
SA - South Australia
WA - Western Australia
TAS - Tasmania

SoapFault exception: Could not connect to host

In my case, disabled SELINUX allow PHP to call my WebService. I run PHP in FPM with Apache2

SELinux status :

# sestatus

Disable SELinux :

setenforce 0

Enable SELinux :

# setenforce 1

Permanent disable :

edit this file /etc/selinux/config

In Java what is the syntax for commenting out multiple lines?

/* 
Lines to be commented
*/

NB: multiline comments like this DO NOT NEST. This can be the source of errors. It is generally better to just comment every line with //. Most IDEs allow you to do this quite simply.

How to solve "Fatal error: Class 'MySQLi' not found"?

on ubuntu:

sudo apt-get install php-mysql
sudo service apache2 restart

how does Array.prototype.slice.call() work?

It uses the slice method arrays have and calls it with its this being the arguments object. This means it calls it as if you did arguments.slice() assuming arguments had such a method.

Creating a slice without any arguments will simply take all elements - so it simply copies the elements from arguments to an array.

Using member variable in lambda capture list inside a member function

Summary of the alternatives:

capture this:

auto lambda = [this](){};

use a local reference to the member:

auto& tmp = grid;
auto lambda = [ tmp](){}; // capture grid by (a single) copy
auto lambda = [&tmp](){}; // capture grid by ref

C++14:

auto lambda = [ grid = grid](){}; // capture grid by copy
auto lambda = [&grid = grid](){}; // capture grid by ref

example: https://godbolt.org/g/dEKVGD

Can you split/explode a field in a MySQL query?

Search in a column containing comma-separated values

MySQL has a dedicated function FIND_IN_SET() that returns field index if the value is found in a string containing comma-separated values.

For example, the following statement returns one-based index of value C in string A,B,C,D.

SELECT FIND_IN_SET('C', 'A,B,C,D') AS result;
+--------+
| result |
+--------+
|      3 |
+--------+

If the given value is not found, FIND_IN_SET() function returns 0.

SELECT FIND_IN_SET('Z', 'A,B,C,D') AS result;
+--------+
| result |
+--------+
|      0 |
+--------+

indexOf method in an object array?

Or prototype it :

Array.prototype.indexOfObject = function arrayObjectIndexOf(property, value) {
    for (var i = 0, len = this.length; i < len; i++) {
        if (this[i][property] === value) return i;
    }
    return -1;
}

myArr.indexOfObject("name", "stevie");

UL list style not applying

and you can also give a left-margin if the reset.css you are using make all margin null : that means :

li {
list-style: disc outside none;
display: list-item;
margin-left: 1em;
}

Assuming you apply this css after the reset, it should work !

Matthieu Ricaud

Passing an Object from an Activity to a Fragment

If the data should survive throughout the application lifecycle and shared among multiple fragments or activities, a Model class might come into consideration, which has got less serialization overhead.

Check this design example

Add legend to ggplot2 line plot

Since @Etienne asked how to do this without melting the data (which in general is the preferred method, but I recognize there may be some cases where that is not possible), I present the following alternative.

Start with a subset of the original data:

datos <-
structure(list(fecha = structure(c(1317452400, 1317538800, 1317625200, 
1317711600, 1317798000, 1317884400, 1317970800, 1318057200, 1318143600, 
1318230000, 1318316400, 1318402800, 1318489200, 1318575600, 1318662000, 
1318748400, 1318834800, 1318921200, 1319007600, 1319094000), class = c("POSIXct", 
"POSIXt"), tzone = ""), TempMax = c(26.58, 27.78, 27.9, 27.44, 
30.9, 30.44, 27.57, 25.71, 25.98, 26.84, 33.58, 30.7, 31.3, 27.18, 
26.58, 26.18, 25.19, 24.19, 27.65, 23.92), TempMedia = c(22.88, 
22.87, 22.41, 21.63, 22.43, 22.29, 21.89, 20.52, 19.71, 20.73, 
23.51, 23.13, 22.95, 21.95, 21.91, 20.72, 20.45, 19.42, 19.97, 
19.61), TempMin = c(19.34, 19.14, 18.34, 17.49, 16.75, 16.75, 
16.88, 16.82, 14.82, 16.01, 16.88, 17.55, 16.75, 17.22, 19.01, 
16.95, 17.55, 15.21, 14.22, 16.42)), .Names = c("fecha", "TempMax", 
"TempMedia", "TempMin"), row.names = c(NA, 20L), class = "data.frame")

You can get the desired effect by (and this also cleans up the original plotting code):

ggplot(data = datos, aes(x = fecha)) +
  geom_line(aes(y = TempMax, colour = "TempMax")) +
  geom_line(aes(y = TempMedia, colour = "TempMedia")) +
  geom_line(aes(y = TempMin, colour = "TempMin")) +
  scale_colour_manual("", 
                      breaks = c("TempMax", "TempMedia", "TempMin"),
                      values = c("red", "green", "blue")) +
  xlab(" ") +
  scale_y_continuous("Temperatura (C)", limits = c(-10,40)) + 
  labs(title="TITULO")

The idea is that each line is given a color by mapping the colour aesthetic to a constant string. Choosing the string which is what you want to appear in the legend is the easiest. The fact that in this case it is the same as the name of the y variable being plotted is not significant; it could be any set of strings. It is very important that this is inside the aes call; you are creating a mapping to this "variable".

scale_colour_manual can now map these strings to the appropriate colors. The result is enter image description here

In some cases, the mapping between the levels and colors needs to be made explicit by naming the values in the manual scale (thanks to @DaveRGP for pointing this out):

ggplot(data = datos, aes(x = fecha)) +
  geom_line(aes(y = TempMax, colour = "TempMax")) +
  geom_line(aes(y = TempMedia, colour = "TempMedia")) +
  geom_line(aes(y = TempMin, colour = "TempMin")) +
  scale_colour_manual("", 
                      values = c("TempMedia"="green", "TempMax"="red", 
                                 "TempMin"="blue")) +
  xlab(" ") +
  scale_y_continuous("Temperatura (C)", limits = c(-10,40)) + 
  labs(title="TITULO")

(giving the same figure as before). With named values, the breaks can be used to set the order in the legend and any order can be used in the values.

ggplot(data = datos, aes(x = fecha)) +
  geom_line(aes(y = TempMax, colour = "TempMax")) +
  geom_line(aes(y = TempMedia, colour = "TempMedia")) +
  geom_line(aes(y = TempMin, colour = "TempMin")) +
  scale_colour_manual("", 
                      breaks = c("TempMedia", "TempMax", "TempMin"),
                      values = c("TempMedia"="green", "TempMax"="red", 
                                 "TempMin"="blue")) +
  xlab(" ") +
  scale_y_continuous("Temperatura (C)", limits = c(-10,40)) + 
  labs(title="TITULO")

Python dictionary: Get list of values for list of keys

A little speed comparison:

Python 2.7.11 |Anaconda 2.4.1 (64-bit)| (default, Dec  7 2015, 14:10:42) [MSC v.1500 64 bit (AMD64)] on win32
In[1]: l = [0,1,2,3,2,3,1,2,0]
In[2]: m = {0:10, 1:11, 2:12, 3:13}
In[3]: %timeit [m[_] for _ in l]  # list comprehension
1000000 loops, best of 3: 762 ns per loop
In[4]: %timeit map(lambda _: m[_], l)  # using 'map'
1000000 loops, best of 3: 1.66 µs per loop
In[5]: %timeit list(m[_] for _ in l)  # a generator expression passed to a list constructor.
1000000 loops, best of 3: 1.65 µs per loop
In[6]: %timeit map(m.__getitem__, l)
The slowest run took 4.01 times longer than the fastest. This could mean that an intermediate result is being cached 
1000000 loops, best of 3: 853 ns per loop
In[7]: %timeit map(m.get, l)
1000000 loops, best of 3: 908 ns per loop
In[33]: from operator import itemgetter
In[34]: %timeit list(itemgetter(*l)(m))
The slowest run took 9.26 times longer than the fastest. This could mean that an intermediate result is being cached 
1000000 loops, best of 3: 739 ns per loop

So list comprehension and itemgetter are the fastest ways to do this.

UPDATE: For large random lists and maps I had a bit different results:

Python 2.7.11 |Anaconda 2.4.1 (64-bit)| (default, Dec  7 2015, 14:10:42) [MSC v.1500 64 bit (AMD64)] on win32
In[2]: import numpy.random as nprnd
l = nprnd.randint(1000, size=10000)
m = dict([(_, nprnd.rand()) for _ in range(1000)])
from operator import itemgetter
import operator
f = operator.itemgetter(*l)
%timeit f(m)
%timeit list(itemgetter(*l)(m))
%timeit [m[_] for _ in l]  # list comprehension
%timeit map(m.__getitem__, l)
%timeit list(m[_] for _ in l)  # a generator expression passed to a list constructor.
%timeit map(m.get, l)
%timeit map(lambda _: m[_], l)
1000 loops, best of 3: 1.14 ms per loop
1000 loops, best of 3: 1.68 ms per loop
100 loops, best of 3: 2 ms per loop
100 loops, best of 3: 2.05 ms per loop
100 loops, best of 3: 2.19 ms per loop
100 loops, best of 3: 2.53 ms per loop
100 loops, best of 3: 2.9 ms per loop

So in this case the clear winner is f = operator.itemgetter(*l); f(m), and clear outsider: map(lambda _: m[_], l).

UPDATE for Python 3.6.4:

import numpy.random as nprnd
l = nprnd.randint(1000, size=10000)
m = dict([(_, nprnd.rand()) for _ in range(1000)])
from operator import itemgetter
import operator
f = operator.itemgetter(*l)
%timeit f(m)
%timeit list(itemgetter(*l)(m))
%timeit [m[_] for _ in l]  # list comprehension
%timeit list(map(m.__getitem__, l))
%timeit list(m[_] for _ in l)  # a generator expression passed to a list constructor.
%timeit list(map(m.get, l))
%timeit list(map(lambda _: m[_], l)
1.66 ms ± 74.2 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)
2.1 ms ± 93.2 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
2.58 ms ± 88.8 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
2.36 ms ± 60.7 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
2.98 ms ± 142 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
2.7 ms ± 284 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
3.14 ms ± 62.6 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)

So, results for Python 3.6.4 is almost the same.

What is the purpose of Looper and how to use it?

What is Looper?

Looper is a class which is used to execute the Messages(Runnables) in a queue. Normal threads have no such queue, e.g. simple thread does not have any queue. It executes once and after method execution finishes, the thread will not run another Message(Runnable).

Where we can use Looper class?

If someone wants to execute multiple messages(Runnables) then he should use the Looper class which is responsible for creating a queue in the thread. For example, while writing an application that downloads files from the internet, we can use Looper class to put files to be downloaded in the queue.

How it works?

There is prepare() method to prepare the Looper. Then you can use loop() method to create a message loop in the current thread and now your Looper is ready to execute the requests in the queue until you quit the loop.

Here is the code by which you can prepare the Looper.

class LooperThread extends Thread {
      public Handler mHandler;

      @Override
      public void run() {
          Looper.prepare();

          mHandler = new Handler() {
              @Override
              public void handleMessage(Message msg) {
                  // process incoming messages here
              }
          };

          Looper.loop();
      }
  }

How to create unit tests easily in eclipse

Any unit test you could create by just pressing a button would not be worth anything. How is the tool to know what parameters to pass your method and what to expect back? Unless I'm misunderstanding your expectations.

Close to that is something like FitNesse, where you can set up tests, then separately you set up a wiki page with your test data, and it runs the tests with that data, publishing the results as red/greens.

If you would be happy to make test writing much faster, I would suggest Mockito, a mocking framework that lets you very easily mock the classes around the one you're testing, so there's less setup/teardown, and you know you're really testing that one class instead of a dependent of it.

Python - Check If Word Is In A String

What is wrong with:

if word in mystring: 
   print 'success'

Convert js Array() to JSon object for use with JQuery .ajax

When using the data on the server, your characters can reach with the addition of slashes eg if string = {"hello"} comes as string = {\ "hello \"} to solve the following function can be used later to use json decode.

<?php
function stripslashes_deep($value)
{
    $value = is_array($value) ?
                array_map('stripslashes_deep', $value) :
                stripslashes($value);

    return $value;
}

$array = $_POST['jObject'];
$array = stripslashes_deep($array);

$data = json_decode($array, true);
print_r($data);
?>

What database does Google use?

As others have mentioned, Google uses a homegrown solution called BigTable and they've released a few papers describing it out into the real world.

The Apache folks have an implementation of the ideas presented in these papers called HBase. HBase is part of the larger Hadoop project which according to their site "is a software platform that lets one easily write and run applications that process vast amounts of data." Some of the benchmarks are quite impressive. Their site is at http://hadoop.apache.org.