Programs & Examples On #Bitnami

Bitnami is a library of popular server applications and development environments that can be installed with one click, either in your laptop, in a virtual machine or hosted in the cloud.

XAMPP permissions on Mac OS X?

Go to htdocs folder, right click, get info, click to unlock the padlock icon, type your password, under sharing permission change the priviledge for everyone to read & write, on the cog wheel button next to the + and - icons, click and select apply to all enclosed items, click to accept security request, close get info. Now xampp can write and read your root folder.

Note:

  1. If you copy a new folder into the htdocs after this, you need to repeat the process for that folder to have write permission.

  2. When you move your files to the live server, you need to also chmod the appropriate files & folders on the server as well.

Enum to String C++

You could throw the enum value and string into an STL map. Then you could use it like so.

   return myStringMap[Enum::Apple];

Using Lato fonts in my css (@font-face)

Well, you're missing the letter 'd' in url("~/fonts/Lato-Bol.ttf"); - but assuming that's not it, I would open up your page with developer tools in Chrome and make sure there's no errors loading any of the files (you would probably see an issue in the JavaScript console, or you can check the Network tab and see if anything is red).

(I don't see anything obviously wrong with the code you have posted above)

Other things to check: 1) Are you including your CSS file in your html above the lines where you are trying to use the font-family style? 2) What do you see in the CSS panel in the developer tools for that div? Is font-family: lato crossed out?

How to use UIPanGestureRecognizer to move object? iPhone/iPad

-(IBAction)Method
{
      UIPanGestureRecognizer *panRecognizer = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(handlePan:)];
      [panRecognizer setMinimumNumberOfTouches:1];
      [panRecognizer setMaximumNumberOfTouches:1];
      [ViewMain addGestureRecognizer:panRecognizer];
      [panRecognizer release];
}
- (Void)handlePan:(UIPanGestureRecognizer *)recognizer
{

     CGPoint translation = [recognizer translationInView:self.view];
     recognizer.view.center = CGPointMake(recognizer.view.center.x + translation.x, 
                                     recognizer.view.center.y + translation.y);
     [recognizer setTranslation:CGPointMake(0, 0) inView:self.view];

     if (recognizer.state == UIGestureRecognizerStateEnded) {

         CGPoint velocity = [recognizer velocityInView:self.view];
         CGFloat magnitude = sqrtf((velocity.x * velocity.x) + (velocity.y * velocity.y));
         CGFloat slideMult = magnitude / 200;
         NSLog(@"magnitude: %f, slideMult: %f", magnitude, slideMult);

         float slideFactor = 0.1 * slideMult; // Increase for more of a slide
         CGPoint finalPoint = CGPointMake(recognizer.view.center.x + (velocity.x * slideFactor), 
                                     recognizer.view.center.y + (velocity.y * slideFactor));
         finalPoint.x = MIN(MAX(finalPoint.x, 0), self.view.bounds.size.width);
         finalPoint.y = MIN(MAX(finalPoint.y, 0), self.view.bounds.size.height);

         [UIView animateWithDuration:slideFactor*2 delay:0 options:UIViewAnimationOptionCurveEaseOut animations:^{
             recognizer.view.center = finalPoint;
         } completion:nil];

    }

}

how to convert String into Date time format in JAVA?

Using this,

        String s = "03/24/2013 21:54";
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("MM/dd/yyyy HH:mm");
        try
        {
            Date date = simpleDateFormat.parse(s);

            System.out.println("date : "+simpleDateFormat.format(date));
        }
        catch (ParseException ex)
        {
            System.out.println("Exception "+ex);
        }

Use YAML with variables

Rails / ruby frameworks are able to do some templating ... it's frequently used to load env variables ...

# fooz.yml
  foo:
    bar: <%= $ENV[:some_var] %>

No idea if this works for javascript frameworks as I think that YML format is superset of json and it depends on what reads the yml file for you.

If you can use the template like that or the << >> or the {{ }} styles depending on your reader, after that you just ...

In another yml file ...

# boo.yml

development:
  fooz: foo

Which allows you to basically insert a variable as your reference that original file each time which is dynamically set. When reading I was also seeing you can create or open YML files as objects on the fly for several languages which allows you to create a file & chain write a series of YML files or just have them all statically pointing to the dynamically created one.

What is the format for the PostgreSQL connection string / URL?

If you use Libpq binding for respective language, according to its documentation URI is formed as follows:

postgresql://[user[:password]@][netloc][:port][/dbname][?param1=value1&...]

Here are examples from same document

postgresql://
postgresql://localhost
postgresql://localhost:5432
postgresql://localhost/mydb
postgresql://user@localhost
postgresql://user:secret@localhost
postgresql://other@localhost/otherdb?connect_timeout=10&application_name=myapp
postgresql://localhost/mydb?user=other&password=secret

No matching client found for package name (Google Analytics) - multiple productFlavors & buildTypes

Check for applicationIdSuffix in your app's build.gradle file. See if it is concatenating any text to your applicationId. If so, remove it.

How to fill DataTable with SQL Table

The SqlDataReader is a valid data source for the DataTable. As such, all you need to do its this:

public DataTable GetData()
{
    SqlConnection conn = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["BarManConnectionString"].ConnectionString);
    conn.Open();
    string query = "SELECT * FROM [EventOne]";
    SqlCommand cmd = new SqlCommand(query, conn);

    DataTable dt = new DataTable();
    dt.Load(cmd.ExecuteReader());
    conn.Close();
    return dt;
}

Authenticated HTTP proxy with Java

But, setting only that parameters, the authentication don't works.

Are necessary to add to that code the following:

final String authUser = "myuser";
final String authPassword = "secret";

System.setProperty("http.proxyHost", "hostAddress");
System.setProperty("http.proxyPort", "portNumber");
System.setProperty("http.proxyUser", authUser);
System.setProperty("http.proxyPassword", authPassword);

Authenticator.setDefault(
  new Authenticator() {
    public PasswordAuthentication getPasswordAuthentication() {
      return new PasswordAuthentication(authUser, authPassword.toCharArray());
    }
  }
);

Change project name on Android Studio

  • Changing the name in res>values>strings.xml will change the app name that is shown in the apps menu after installation

  • Renaming the android studio project folder (when android studio is closed) will likely satisfy many developers

How to change Rails 3 server default port in develoment?

One more idea for you. Create a rake task that calls rails server with the -p.

task "start" => :environment do
  system 'rails server -p 3001'
end

then call rake start instead of rails server

SQLite add Primary Key

You can't modify SQLite tables in any significant way after they have been created. The accepted suggested solution is to create a new table with the correct requirements and copy your data into it, then drop the old table.

here is the official documentation about this: http://sqlite.org/faq.html#q11

How to download PDF automatically using js?

Use the download attribute.

var link = document.createElement('a');
link.href = url;
link.download = 'file.pdf';
link.dispatchEvent(new MouseEvent('click'));

javax vs java package

Some packages like javax.swing were not included in java standard library at first. Sun company decided to consider them official and included them into the early versions of java as standard libraries or standard extensions.

By convention, all the standard extensions start with an X while they can get promoted to first-class over time like what happened for javax.swing.

What does it mean if a Python object is "subscriptable" or not?

It basically means that the object implements the __getitem__() method. In other words, it describes objects that are "containers", meaning they contain other objects. This includes strings, lists, tuples, and dictionaries.

How can I create a war file of my project in NetBeans?

Right click your project, hit "Clean and Build". Netbeans does the rest.

under the dist directory of your app, you should find a pretty looking .war all ready for deployment.

Use Mockito to mock some methods but not others

Partial mocking using Mockito's spy method could be the solution to your problem, as already stated in the answers above. To some degree I agree that, for your concrete use case, it may be more appropriate to mock the DB lookup. From my experience this is not always possible - at least not without other workarounds - that I would consider as being very cumbersome or at least fragile. Note, that partial mocking does not work with ally versions of Mockito. You have use at least 1.8.0.

I would have just written a simple comment for the original question instead of posting this answer, but StackOverflow does not allow this.

Just one more thing: I really cannot understand that many times a question is being asked here gets comment with "Why you want to do this" without at least trying to understand the problem. Escpecially when it comes to then need for partial mocking there are really a lot of use cases that I could imagine where it would be useful. That's why the guys from Mockito provided that functionality. This feature should of course not be overused. But when we talk about test case setups that otherwise could not be established in a very complicated way, spying should be used.

Benefits of EBS vs. instance-store (and vice-versa)

99% of our AWS setup is recyclable. So for me it doesn't really matter if I terminate an instance -- nothing is lost ever. E.g. my application is automatically deployed on an instance from SVN, our logs are written to a central syslog server.

The only benefit of instance storage that I see are cost-savings. Otherwise EBS-backed instances win. Eric mentioned all the advantages.


[2012-07-16] I would phrase this answer a lot different today.

I haven't had any good experience with EBS-backed instances in the past year or so. The last downtimes on AWS pretty much wrecked EBS as well.

I am guessing that a service like RDS uses some kind of EBS as well and that seems to work for the most part. On the instances we manage ourselves, we have got rid off EBS where possible.

Getting rid to an extend where we moved a database cluster back to iron (= real hardware). The only remaining piece in our infrastructure is a DB server where we stripe multiple EBS volumes into a software RAID and backup twice a day. Whatever would be lost in between backups, we can live with.

EBS is a somewhat flakey technology since it's essentially a network volume: a volume attached to your server from remote. I am not negating the work done with it – it is an amazing product since essentially unlimited persistent storage is just an API call away. But it's hardly fit for scenarios where I/O performance is key.

And in addition to how network storage behaves, all network is shared on EC2 instances. The smaller an instance (e.g. t1.micro, m1.small) the worse it gets because your network interfaces on the actual host system are shared among multiple VMs (= your EC2 instance) which run on top of it.

The larger instance you get, the better it gets of course. Better here means within reason.

When persistence is required, I would always advice people to use something like S3 to centralize between instances. S3 is a very stable service. Then automate your instance setup to a point where you can boot a new server and it gets ready by itself. Then there is no need to have network storage which lives longer than the instance.

So all in all, I see no benefit to EBS-backed instances what so ever. I rather add a minute to bootstrap, then run with a potential SPOF.

Is there a naming convention for git repositories?

The problem with camel case is that there are often different interpretations of words - for example, checkinService vs checkInService. Going along with Aaron's answer, it is difficult with auto-completion if you have many similarly named repos to have to constantly check if the person who created the repo you care about used a certain breakdown of the upper and lower cases. avoid upper case.

His point about dashes is also well-advised.

  1. use lower case.
  2. use dashes.
  3. be specific. you may find you have to differentiate between similar ideas later - ie use purchase-rest-service instead of service or rest-service.
  4. be consistent. consider usage from the various GIT vendors - how do you want your repositories to be sorted/grouped?

How can I make a program wait for a variable change in javascript?

No you would have to create your own solution. Like using the Observer design pattern or something.

If you have no control over the variable or who is using it, I'm afraid you're doomed. EDIT: Or use Skilldrick's solution!

Mike

How do I make a transparent canvas in html5?

Can't comment the last answer but the fix is relatively easy. Just set the background color of your opaque canvas:

#canvas1 { background-color: black; } //opaque canvas
#canvas2 { ... } //transparent canvas

I'm not sure but it looks like that the background-color is inherited as transparent from the body.

SQL Server Management Studio missing

If you have a copy of backup of SQL Server setup then you could add features (Management Tools Basic/Complete) as you requested.

Please use the below steps in Windows machine:

  1. Go to Control Panel -> Programs -> Program and Features -> Select your current version of Microsoft SQL Server
  2. Right Click, select Change/Uninstall
  3. Click Add features
  4. Select the backup copy folder
  5. Do the steps what you done for SQL Server installation until features selection
  6. Now select the features Management Tools Basic/Complete or both
  7. And go ahead with process for complete installation.
  8. Now you should get, SQL Server Management Studio and you can browse your databases.

How to set Java SDK path in AndroidStudio?

This problem arises due to incompatible JDK version. Download and install latest JDK(currently its 8) from java official site in case you are using previous versions. Then in Android Studio go to File->Project Structure->SDK location -> JDK location and set it to 'C:\Program Files\Java\jdk1.8.0_121' (Default location of JDK). Gradle sync your project and you are all set...

How can I use JSON data to populate the options of a select box?

Why not just make the server return the names?

["Woodland Hills", "none", "Los Angeles", "Laguna Hills"]

Then create the <option> elements using JavaScript.

$.ajax({
    url:'suggest.html',
    type:'POST',
    data: 'q=' + str,
    dataType: 'json',
    success: function( json ) {
        $.each(json, function(i, value) {
            $('#myselect').append($('<option>').text(value).attr('value', value));
        });
    }
});

Sort an ArrayList based on an object field

You can use the Bean Comparator to sort on any property in your custom class.

Increase heap size in Java

This only works with 64 bit version of Java. Go to Control Panel and click on the Java icon. On the small window of Java Control Panel, click on the Java menu bar and then click on view button.

If you have two Java platforms, disable the previous version of Java, then click on Runtime parameters text field and write -Xmx1024m or less than RAM size. Don't increase heap size equal to RAM otherwise your system will crash.

How to convert from java.sql.Timestamp to java.util.Date?

Class java.sql.TimeStamp extends from java.util.Date.

You can directly assign a TimeStamp object to Date reference:

TimeStamp timeStamp = //whatever value you have;
Date startDate = timestampValue;

How can I define an interface for an array of objects with Typescript?

You don't need to use an indexer (since it a bit less typesafe). You have two options :

interface EnumServiceItem {
    id: number; label: string; key: any
}

interface EnumServiceItems extends Array<EnumServiceItem>{}


// Option A 
var result: EnumServiceItem[] = [
    { id: 0, label: 'CId', key: 'contentId' },
    { id: 1, label: 'Modified By', key: 'modifiedBy' },
    { id: 2, label: 'Modified Date', key: 'modified' },
    { id: 3, label: 'Status', key: 'contentStatusId' },
    { id: 4, label: 'Status > Type', key: ['contentStatusId', 'contentTypeId'] },
    { id: 5, label: 'Title', key: 'title' },
    { id: 6, label: 'Type', key: 'contentTypeId' },
    { id: 7, label: 'Type > Status', key: ['contentTypeId', 'contentStatusId'] }
];

// Option B
var result: EnumServiceItems = [
    { id: 0, label: 'CId', key: 'contentId' },
    { id: 1, label: 'Modified By', key: 'modifiedBy' },
    { id: 2, label: 'Modified Date', key: 'modified' },
    { id: 3, label: 'Status', key: 'contentStatusId' },
    { id: 4, label: 'Status > Type', key: ['contentStatusId', 'contentTypeId'] },
    { id: 5, label: 'Title', key: 'title' },
    { id: 6, label: 'Type', key: 'contentTypeId' },
    { id: 7, label: 'Type > Status', key: ['contentTypeId', 'contentStatusId'] }
]

Personally I recommend Option A (simpler migration when you are using classes not interfaces).

C99 stdint.h header and MS Visual Studio

Another portable solution:

POSH: The Portable Open Source Harness

"POSH is a simple, portable, easy-to-use, easy-to-integrate, flexible, open source "harness" designed to make writing cross-platform libraries and applications significantly less tedious to create and port."

http://poshlib.hookatooka.com/poshlib/trac.cgi

as described and used in the book: Write portable code: an introduction to developing software for multiple platforms By Brian Hook http://books.google.ca/books?id=4VOKcEAPPO0C

-Jason

Using File.listFiles with FileNameExtensionFilter

Duh.... listFiles requires java.io.FileFilter. FileNameExtensionFilter extends javax.swing.filechooser.FileFilter. I solved my problem by implementing an instance of java.io.FileFilter

Edit: I did use something similar to @cFreiner's answer. I was trying to use a Java API method instead of writing my own implementation which is why I was trying to use FileNameExtensionFilter. I have many FileChoosers in my application and have used FileNameExtensionFilters for that and I mistakenly assumed that it was also extending java.io.FileFilter.

Cutting the videos based on start and end time using ffmpeg

You probably do not have a keyframe at the 3 second mark. Because non-keyframes encode differences from other frames, they require all of the data starting with the previous keyframe.

With the mp4 container it is possible to cut at a non-keyframe without re-encoding using an edit list. In other words, if the closest keyframe before 3s is at 0s then it will copy the video starting at 0s and use an edit list to tell the player to start playing 3 seconds in.

If you are using the latest ffmpeg from git master it will do this using an edit list when invoked using the command that you provided. If this is not working for you then you are probably either using an older version of ffmpeg, or your player does not support edit lists. Some players will ignore the edit list and always play all of the media in the file from beginning to end.

If you want to cut precisely starting at a non-keyframe and want it to play starting at the desired point on a player that does not support edit lists, or want to ensure that the cut portion is not actually in the output file (for example if it contains confidential information), then you can do that by re-encoding so that there will be a keyframe precisely at the desired start time. Re-encoding is the default if you do not specify copy. For example:

ffmpeg -i movie.mp4 -ss 00:00:03 -t 00:00:08 -async 1 cut.mp4

When re-encoding you may also wish to include additional quality-related options or a particular AAC encoder. For details, see ffmpeg's x264 Encoding Guide for video and AAC Encoding Guide for audio.

Also, the -t option specifies a duration, not an end time. The above command will encode 8s of video starting at 3s. To start at 3s and end at 8s use -t 5. If you are using a current version of ffmpeg you can also replace -t with -to in the above command to end at the specified time.

How can I save multiple documents concurrently in Mongoose/Node.js?

I know this is an old question, but it worries me that there are no properly correct answers here. Most answers just talk about iterating through all the documents and saving each of them individually, which is a BAD idea if you have more than a few documents, and the process gets repeated for even one in many requests.

MongoDB specifically has a batchInsert() call for inserting multiple documents, and this should be used from the native mongodb driver. Mongoose is built on this driver, and it doesn't have support for batch inserts. It probably makes sense as it is supposed to be a Object document modelling tool for MongoDB.

Solution: Mongoose comes with the native MongoDB driver. You can use that driver by requiring it require('mongoose/node_modules/mongodb') (not too sure about this, but you can always install the mongodb npm again if it doesn't work, but I think it should) and then do a proper batchInsert

How do you extract classes' source code from a dll file?

You can use Reflector and also use Add-In FileGenerator to extract source code into a project.

JQuery Number Formatting

I would recommend looking at this article on how to use javascript to handle basic formatting:

function addCommas(nStr)
{
    nStr += '';
    x = nStr.split('.');
    x1 = x[0];
    x2 = x.length > 1 ? '.' + x[1] : '';
    var rgx = /(\d+)(\d{3})/;
    while (rgx.test(x1)) {
        x1 = x1.replace(rgx, '$1' + ',' + '$2');
    }
    return x1 + x2;
}

source: http://www.mredkj.com/javascript/numberFormat.html

While jQuery can make your life easier in a million different ways I would say it's overkill for this. Keep in mind that jQuery can be fairly large and your user's browser needs to download it when you use it on a page.

When ever using jQuery you should step back and ask if it contributes enough to justify the extra overhead of downloading the library.

If you need some sort of advanced formatting (like the localization stuff in the plugin you linked), or you are already including jQuery it might be worth looking at a jQuery plugin.

Side note - check this out if you want to get a chuckle about the over use of jQuery.

OpenMP set_num_threads() is not working

Try setting your num_threads inside your omp parallel code, it worked for me. This will give output as 4

#pragma omp parallel
{
   omp_set_num_threads(4);
   int id = omp_get_num_threads();
   #pragma omp for
   for (i = 0:n){foo(A);}
}

printf("Number of threads: %d", id);

How do I check if a Socket is currently connected in Java?

  • socket.isConnected() returns always true once the client connects (and even after the disconnect) weird !!
  • socket.getInputStream().read()
    • makes the thread wait for input as long as the client is connected and therefore makes your program not do anything - except if you get some input
    • returns -1 if the client disconnected
  • socket.getInetAddress().isReachable(int timeout): From isReachable(int timeout)

    Test whether that address is reachable. Best effort is made by the implementation to try to reach the host, but firewalls and server configuration may block requests resulting in a unreachable status while some specific ports may be accessible. A typical implementation will use ICMP ECHO REQUESTs if the privilege can be obtained, otherwise it will try to establish a TCP connection on port 7 (Echo) of the destination host.

How do I get Flask to run on port 80?

For externally visible server, where you don't use apache or other web server you just type

flask run --host=0.0.0.0 --port=80

Clearing NSUserDefaults

Did you try using -removeObjectForKey?

 [[NSUserDefaults standardUserDefaults] removeObjectForKey:@"defunctPreference"];

SQL Server Express CREATE DATABASE permission denied in database 'master'

After I performed the following instructions in SSMS, everything works fine:

create login [IIS APPPOOL\MyWebAPP] from windows;

exec sp_addsrvrolemember N'IIS APPPOOL\MyWebAPP', sysadmin

How to add "class" to host element?

for multiple classes situation, as @jbojcic mentioned above, you can use:

host: {class: 'A B C'}

Download multiple files as a zip-file using php

You can use the ZipArchive class to create a ZIP file and stream it to the client. Something like:

$files = array('readme.txt', 'test.html', 'image.gif');
$zipname = 'file.zip';
$zip = new ZipArchive;
$zip->open($zipname, ZipArchive::CREATE);
foreach ($files as $file) {
  $zip->addFile($file);
}
$zip->close();

and to stream it:

header('Content-Type: application/zip');
header('Content-disposition: attachment; filename='.$zipname);
header('Content-Length: ' . filesize($zipname));
readfile($zipname);

The second line forces the browser to present a download box to the user and prompts the name filename.zip. The third line is optional but certain (mainly older) browsers have issues in certain cases without the content size being specified.

Random float number generation

drand48(3) is the POSIX standard way. GLibC also provides a reentrant version, drand48_r(3).

The function was declared obsolete in SVID 3 but no adequate alternative was provided so IEEE Std 1003.1-2013 still includes it and has no notes that it's going anywhere anytime soon.

In Windows, the standard way is CryptGenRandom().

How to squash all git commits into one?

As of git 1.6.2, you can use git rebase --root -i.

For each commit except the first, change pick to squash.

Extract parameter value from url using regular expressions

I know the question is Old and already answered but this can also be a solution

\b[\w-]+$

and I checked these two URLs

http://www.youtube.com/watch?v=Ahg6qcgoay4
https://www.youtube.com/watch?v=22hUHCr-Tos

DEMO

What is the cleanest way to ssh and run multiple commands in Bash?

Edit your script locally, then pipe it into ssh, e.g.

cat commands-to-execute-remotely.sh | ssh blah_server

where commands-to-execute-remotely.sh looks like your list above:

ls some_folder
./someaction.sh
pwd;

How to change the href for a hyperlink using jQuery

href in an attribute, so you can change it using pure JavaScript, but if you already have jQuery injected in your page, don't worry, I will show it both ways:

Imagine you have this href below:

<a id="ali" alt="Ali" href="http://dezfoolian.com.au">Alireza Dezfoolian</a>

And you like to change it the link...

Using pure JavaScript without any library you can do:

document.getElementById("ali").setAttribute("href", "https://stackoverflow.com");

But also in jQuery you can do:

$("#ali").attr("href", "https://stackoverflow.com");

or

$("#ali").prop("href", "https://stackoverflow.com");

In this case, if you already have jQuery injected, probably jQuery one look shorter and more cross-browser...but other than that I go with the JS one...

How to POST using HTTPclient content type = application/x-www-form-urlencoded

The best solution for me is:

// Add key/value
var dict = new Dictionary<string, string>();
dict.Add("Content-Type", "application/x-www-form-urlencoded");

// Execute post method
using (var response = httpClient.PostAsync(path, new FormUrlEncodedContent(dict))){}

How to loop an object in React?

You can use it in a more compact way as:

var tifs = {1: 'Joe', 2: 'Jane'};
...

return (
   <select id="tif" name="tif" onChange={this.handleChange}>  
      { Object.entries(tifs).map((t,k) => <option key={k} value={t[0]}>{t[1]}</option>) }          
   </select>
)

And another slightly different flavour:

 Object.entries(tifs).map(([key,value],i) => <option key={i} value={key}>{value}</option>)  

Align an element to bottom with flexbox

When setting your display to flex, you could simply use the flex property to mark which content can grow and which content cannot.

Flex property

_x000D_
_x000D_
div.content {_x000D_
 height: 300px;_x000D_
 display: flex;_x000D_
 flex-direction: column;_x000D_
}_x000D_
_x000D_
div.up {_x000D_
  flex: 1;_x000D_
}_x000D_
_x000D_
div.down {_x000D_
  flex: none;_x000D_
}
_x000D_
<div class="content">_x000D_
  <div class="up">_x000D_
    <h1>heading 1</h1>_x000D_
    <h2>heading 2</h2>_x000D_
    <p>Some more or less text</p>_x000D_
  </div>_x000D_
_x000D_
  <div class="down">_x000D_
    <a href="/" class="button">Click me</a>_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

PHP Fatal error: Call to undefined function mssql_connect()

I am using IIS and mysql (directly downloaded, without wamp or xampp) My php was installed in c:\php I was getting the error of "call to undefined function mysql_connect()" For me the change of extension_dir worked. This is what I did. In the php.ini, Originally, I had this line

; On windows: extension_dir = "ext"

I changed it to:

; On windows: extension_dir = "C:\php\ext"

And it worked. Of course, I did the other things also like uncommenting the dll extensions etc, as explained in others remarks.

Printing PDFs from Windows Command Line

The error message is telling you.

Try just

"C:\Program Files (x86)\Adobe\Reader 10.0\Reader\AcroRd32.exe" /t "$pdf"

When you enclose the string in single-quotes, this makes everything inside a valid string, including the " chars. By removing the single-quotes, the shell will process the dbl-quotes as string "wrappers".

I would also wrap the filename variable in dbl-quotes so you can easily process files with spaces in their names, i.e.

"C:\Program Files (x86)\Adobe\Reader 10.0\Reader\AcroRd32.exe" /t "$pdf"

IHTH

Why am I getting this error: No mapping specified for the following EntitySet/AssociationSet - Entity1?

For those who are using Database First approach all you have to do after inserting a new entity is to Generate Database From Model again by right click on your .edmx file and select Generate Database From Model...

CSS - How to Style a Selected Radio Buttons Label?

You can add a span to your html and css .

Here's an example from my code ...

HTML ( JSX ):

<input type="radio" name="AMPM" id="radiostyle1" value="AM" checked={this.state.AMPM==="AM"} onChange={this.handleChange}/>  
<label for="radiostyle1"><span></span> am  </label>

<input type="radio" name="AMPM" id="radiostyle2" value="PM" checked={this.state.AMPM==="PM"} onChange={this.handleChange}/>
<label for="radiostyle2"><span></span> pm  </label>

CSS to make standard radio button vanish on screen and superimpose custom button image:

input[type="radio"] {  
    opacity:0;                                      
}

input[type="radio"] + label {
    font-size:1em;
    text-transform: uppercase;
    color: white ;  
    cursor: pointer;
    margin:auto 15px auto auto;                    
}

input[type="radio"] + label span {
    display:inline-block;
    width:30px;
    height:10px;
    margin:1px 0px 0 -30px;                       
    cursor:pointer;
    border-radius: 20%;
}


input[type="radio"] + label span {
    background-color: #FFFFFF 
}


input[type="radio"]:checked + label span{
     background-color: #660006;  
}

Returning a value from callback function in Node.js

Its undefined because, console.log(response) runs before doCall(urlToCall); is finished. You have to pass in a callback function aswell, that runs when your request is done.

First, your function. Pass it a callback:

function doCall(urlToCall, callback) {
    urllib.request(urlToCall, { wd: 'nodejs' }, function (err, data, response) {                              
        var statusCode = response.statusCode;
        finalData = getResponseJson(statusCode, data.toString());
        return callback(finalData);
    });
}

Now:

var urlToCall = "http://myUrlToCall";
doCall(urlToCall, function(response){
    // Here you have access to your variable
    console.log(response);
})

@Rodrigo, posted a good resource in the comments. Read about callbacks in node and how they work. Remember, it is asynchronous code.

Git keeps asking me for my ssh key passphrase

It sounds like you may be having trouble with SSH-Agent itself. I would try troubleshooting that.

1) Did you do ssh-add to add your key to SSH?

2) Are you closing the terminal window between uses, because if you close the window you will have to enter the password again when you reopen it.

Remove ALL white spaces from text

Now you can use "replaceAll":

console.log(' a b    c d e   f g   '.replaceAll(' ',''));

will print:

abcdefg

But not working in every possible browser:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replaceAll

How to add a new schema to sql server 2008?

Best way to add schema to your existing table: Right click on the specific table-->Design --> Under the management studio Right sight see the Properties window and select the schema and click it, see the drop down list and select your schema. After the change the schema save it. Then will see it will chage your schema.

How to predict input image using trained model in Keras?

If someone is still struggling to make predictions on images, here is the optimized code to load the saved model and make predictions:

# Modify 'test1.jpg' and 'test2.jpg' to the images you want to predict on

from keras.models import load_model
from keras.preprocessing import image
import numpy as np

# dimensions of our images
img_width, img_height = 320, 240

# load the model we saved
model = load_model('model.h5')
model.compile(loss='binary_crossentropy',
              optimizer='rmsprop',
              metrics=['accuracy'])

# predicting images
img = image.load_img('test1.jpg', target_size=(img_width, img_height))
x = image.img_to_array(img)
x = np.expand_dims(x, axis=0)

images = np.vstack([x])
classes = model.predict_classes(images, batch_size=10)
print classes

# predicting multiple images at once
img = image.load_img('test2.jpg', target_size=(img_width, img_height))
y = image.img_to_array(img)
y = np.expand_dims(y, axis=0)

# pass the list of multiple images np.vstack()
images = np.vstack([x, y])
classes = model.predict_classes(images, batch_size=10)

# print the classes, the images belong to
print classes
print classes[0]
print classes[0][0]

java.math.BigInteger cannot be cast to java.lang.Integer

You can use:

Integer grandChildCount = ((BigInteger) result[1]).intValue();

Or perhaps cast to Number to cover both Integer and BigInteger values.

Java null check why use == instead of .equals()

Object.equals is null safe, however be aware that if two objects are null, object.equals will return true so be sure to check that the objects you are comparing aren't null (or hold null values) before using object.equals for comparison.

String firstname = null;
String lastname = null;

if(Objects.equals(firstname, lastname)){
    System.out.println("equal!");
} else {
    System.out.println("not equal!");
}

Example snippet above will return equal!

How to Correctly Use Lists in R?

One reason lists work as they do (ordered) is to address the need for an ordered container that can contain any type at any node, which vectors do not do. Lists are re-used for a variety of purposes in R, including forming the base of a data.frame, which is a list of vectors of arbitrary type (but the same length).

Why do these two expressions not return the same result?

x = list(1, 2, 3, 4); x2 = list(1:4)

To add to @Shane's answer, if you wanted to get the same result, try:

x3 = as.list(1:4)

Which coerces the vector 1:4 into a list.

Using Excel OleDb to get sheet names IN SHEET ORDER

I like the idea of @deathApril to name the sheets as 1_Germany, 2_UK, 3_IRELAND. I also got your issue to do this rename for hundreds of sheets. If you don't have a problem to rename the sheet name then you can use this macro to do it for you. It will take less than seconds to rename all sheet names. unfortunately ODBC, OLEDB return the sheet name order by asc. There is no replacement for that. You have to either use COM or rename your name to be in the order.

Sub Macro1()
'
' Macro1 Macro
'

'
Dim i As Integer
For i = 1 To Sheets.Count
 Dim prefix As String
 prefix = i
 If Len(prefix) < 4 Then
  prefix = "000"
 ElseIf Len(prefix) < 3 Then
  prefix = "00"
 ElseIf Len(prefix) < 2 Then
  prefix = "0"
 End If
 Dim sheetName As String
 sheetName = Sheets(i).Name
 Dim names
 names = Split(sheetName, "-")
 If (UBound(names) > 0) And IsNumeric(names(0)) Then
  'do nothing
 Else
  Sheets(i).Name = prefix & i & "-" & Sheets(i).Name
 End If
Next

End Sub

UPDATE: After reading @SidHoland comment regarding BIFF an idea flashed. The following steps can be done through code. Don't know if you really want to do that to get the sheet names in the same order. Let me know if you need help to do this through code.

1. Consider XLSX as a zip file. Rename *.xlsx into *.zip
2. Unzip
3. Go to unzipped folder root and open /docprops/app.xml
4. This xml contains the sheet name in the same order of what you see.
5. Parse the xml and get the sheet names

UPDATE: Another solution - NPOI might be helpful here http://npoi.codeplex.com/

 FileStream file = new FileStream(@"yourexcelfilename", FileMode.Open, FileAccess.Read);

      HSSFWorkbook  hssfworkbook = new HSSFWorkbook(file);
        for (int i = 0; i < hssfworkbook.NumberOfSheets; i++)
        {
            Console.WriteLine(hssfworkbook.GetSheetName(i));
        }
        file.Close();

This solution works for xls. I didn't try xlsx.

Thanks,

Esen

Getting value from table cell in JavaScript...not jQuery

function GetCellValues() {
    var table = document.getElementById('mytable');
    for (var r = 0, n = table.rows.length; r < n; r++) {
        for (var c = 0, m = table.rows[r].cells.length; c < m; c++) {
            alert(table.rows[r].cells[c].innerHTML);
        }
    }
}

Errors in pom.xml with dependencies (Missing artifact...)

This is a very late answer,but this might help.I went to this link and searched for ojdbc8(I was trying to add jdbc oracle driver) When clicked on the result , a note was displayed like this:

enter image description here

I clicked the link in the note and the correct dependency was mentioned like below enter image description here

How to add and remove classes in Javascript without jQuery

To add class without JQuery just append yourClassName to your element className

document.documentElement.className += " yourClassName";

To remove class you can use replace() function

document.documentElement.className.replace(/(?:^|\s)yourClassName(?!\S)/,'');

Also as @DavidThomas mentioned you'd need to use the new RegExp() constructor if you want to pass class names dynamically to the replace function.

How to close activity and go back to previous activity in android

it may be possible you are calling finish(); in the click button event so the main activity is closed just after you clicking the button and when you are coming back from next activity the application is exit because main activity is already closed and there is no active activity.

Filtering Table rows using Jquery

Adding one more approach :

value = $(this).val().toLowerCase();
$("#product-search-result tr").filter(function () {
$(this).toggle($(this).text().toLowerCase().indexOf(value) > -1)
});

How to select a specific node with LINQ-to-XML

Assuming the ID is unique:

var result = xmldoc.Element("Customers")
                   .Elements("Customer")
                   .Single(x => (int?)x.Attribute("ID") == 2);

You could also use First, FirstOrDefault, SingleOrDefault or Where, instead of Single for different circumstances.

How can I pause setInterval() functions?

You could use a flag to keep track of the status:

_x000D_
_x000D_
var output = $('h1');_x000D_
var isPaused = false;_x000D_
var time = 0;_x000D_
var t = window.setInterval(function() {_x000D_
  if(!isPaused) {_x000D_
    time++;_x000D_
    output.text("Seconds: " + time);_x000D_
  }_x000D_
}, 1000);_x000D_
_x000D_
//with jquery_x000D_
$('.pause').on('click', function(e) {_x000D_
  e.preventDefault();_x000D_
  isPaused = true;_x000D_
});_x000D_
_x000D_
$('.play').on('click', function(e) {_x000D_
  e.preventDefault();_x000D_
  isPaused = false;_x000D_
});
_x000D_
h1 {_x000D_
    font-family: Helvetica, Verdana, sans-serif;_x000D_
    font-size: 12px;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<h1>Seconds: 0</h1>_x000D_
<button class="play">Play</button>_x000D_
<button class="pause">Pause</button>
_x000D_
_x000D_
_x000D_

This is just what I would do, I'm not sure if you can actually pause the setInterval.

Note: This system is easy and works pretty well for applications that don't require a high level of precision, but it won't consider the time elapsed in between ticks: if you click pause after half a second and later click play your time will be off by half a second.

Django Cookies, how can I set them?

You could manually set the cookie, but depending on your use case (and if you might want to add more types of persistent/session data in future) it might make more sense to use Django's sessions feature. This will let you get and set variables tied internally to the user's session cookie. Cool thing about this is that if you want to store a lot of data tied to a user's session, storing it all in cookies will add a lot of weight to HTTP requests and responses. With sessions the session cookie is all that is sent back and forth (though there is the overhead on Django's end of storing the session data to keep in mind).

Android ImageView setImageResource in code

This is how to set an image into ImageView using the setImageResource() method:

ImageView myImageView = (ImageView)v.findViewById(R.id.img_play);
// supossing to have an image called ic_play inside my drawables.
myImageView.setImageResource(R.drawable.ic_play);

Getting activity from context in android

Never ever use getApplicationContext() with views.

It should always be activity's context, as the view is attached to activity. Also, you may have a custom theme set, and when using application's context, all theming will be lost. Read more about different versions of contexts here.

How to convert an int array to String with toString method in Java

You can use java.util.Arrays:

String res = Arrays.toString(array);
System.out.println(res);

Output:

[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

How to write to Console.Out during execution of an MSTest test

The Console output is not appearing is because the backend code is not running in the context of the test.

You're probably better off using Trace.WriteLine (In System.Diagnostics) and then adding a trace listener which writes to a file.

This topic from MSDN shows a way of doing this.


According to Marty Neal's and Dave Anderson's comments:

using System;
using System.Diagnostics;

...

Trace.Listeners.Add(new TextWriterTraceListener(Console.Out));
// or Trace.Listeners.Add(new ConsoleTraceListener());
Trace.WriteLine("Hello World");

Can I exclude some concrete urls from <url-pattern> inside <filter-mapping>?

I also Had to filter based on the URL pattern(/{servicename}/api/stats/)in java code .

if (path.startsWith("/{servicename}/api/statistics/")) {
validatingAuthToken(((HttpServletRequest) request).getHeader("auth_token"));
filterChain.doFilter(request, response);            
}

But its bizarre, that servlet doesn't support url pattern other than (/*), This should be a very common case for servlet API's !

PostgreSQL: How to change PostgreSQL user password?

In general, just use pg admin UI for doing db related activity.

If instead you are focusin more in automating database setup for your local development, or CI etc...

For example, you can use a simple combo like this.

(a) Create a dummy super user via jenkins with a command similar to this:

docker exec -t postgres11-instance1 createuser --username=postgres --superuser experiment001

this will create a super user called experiment001 in you postgres db.

(b) Give this user some password by running a NON-Interactive SQL command.

docker exec -t postgres11-instance1 psql -U experiment001 -d postgres -c "ALTER USER experiment001 WITH PASSWORD 'experiment001' "

Postgres is probably the best database out there for command line (non-interactive) tooling. Creating users, running SQL, making backup of database etc... In general it is all quite basic with postgres and it is overall quite trivial to integrate this into your development setup scripts or into automated CI configuration.

How to create a DataTable in C# and how to add rows?

To add a row:

DataRow row = dt.NewRow();
row["Name"] = "Ravi";
row["Marks"] = 500;
dt.Rows.Add(row);

To see the structure:

Table.Columns

jQuery call function after load

In regards to the question in your comment:

Assuming that you've previously bound your function to the click event of the radio button, add this to your $(document).ready function:

$('#[radioButtonOptionID]').click()

Without a parameter, that simulates the click event.

How to perform a sum of an int[] array

Here is an efficient way to solve this question using For loops in Java

 public static void main(String[] args) {

    int [] numbers = { 1, 2, 3, 4 };
    int size = numbers.length;

    int sum = 0;
    for (int i = 0; i < size; i++) {
        sum += numbers[i];
    }

    System.out.println(sum);
}

Formatting text in a TextBlock

Check out this example from Charles Petzolds Bool Application = Code + markup

//----------------------------------------------
// FormatTheText.cs (c) 2006 by Charles Petzold
//----------------------------------------------
using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Documents;

namespace Petzold.FormatTheText
{
    class FormatTheText : Window
    {
        [STAThread]
        public static void Main()
        {
            Application app = new Application();
            app.Run(new FormatTheText());
        }
        public FormatTheText()
        {
            Title = "Format the Text";

            TextBlock txt = new TextBlock();
            txt.FontSize = 32; // 24 points
            txt.Inlines.Add("This is some ");
            txt.Inlines.Add(new Italic(new Run("italic")));
            txt.Inlines.Add(" text, and this is some ");
            txt.Inlines.Add(new Bold(new Run("bold")));
            txt.Inlines.Add(" text, and let's cap it off with some ");
            txt.Inlines.Add(new Bold(new Italic (new Run("bold italic"))));
            txt.Inlines.Add(" text.");
            txt.TextWrapping = TextWrapping.Wrap;

            Content = txt;
        }
    }
}

"Warning: iPhone apps should include an armv6 architecture" even with build config set

In addition to Nick's answer about Xcode 4.2, you may also need to review your info.plist file. It seems as if new projects started in Xcode 4.2 by default specify 'armv7' in the 'Required Device Capabilities'. You'll need to remove this if wanting to support devices that run armv6 (e.g. the iPhone 3G).

enter image description here

Delete armv7 from the 'Required device capabilities' in yourProjectName-Info.plist

How do I convert 2018-04-10T04:00:00.000Z string to DateTime?

Using Date pattern yyyy-MM-dd'T'HH:mm:ss.SSS'Z' and Java 8 you could do

String string = "2018-04-10T04:00:00.000Z";
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'", Locale.ENGLISH);
LocalDate date = LocalDate.parse(string, formatter);
System.out.println(date);

Update: For pre 26 use Joda time

String string = "2018-04-10T04:00:00.000Z";
DateTimeFormatter formatter = DateTimeFormat.forPattern("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
LocalDate date = org.joda.time.LocalDate.parse(string, formatter);

In app/build.gradle file, add like this-

dependencies {    
    compile 'joda-time:joda-time:2.9.4'
}

Meaning of numbers in "col-md-4"," col-xs-1", "col-lg-2" in Bootstrap

From Twitter Bootstrap documentation:

  • small grid (= 768px) = .col-sm-*,
  • medium grid (= 992px) = .col-md-*,
  • large grid (= 1200px) = .col-lg-*.

to Read More...

Make div 100% Width of Browser Window

.myDiv {
    background-color: red;
    width: 100%;
    min-height: 100vh;
    max-height: 100%;
    position: absolute;
    top: 0;
    left: 0;
    margin: 0 auto;
}

Basically, we're fixing the div's position regardless of it's parent, and then position it using margin: 0 auto; and settings its position at the top left corner.

open failed: EACCES (Permission denied)

Add these both permission of read and write, to solve this issue

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

Add this below line in Application tag

android:requestLegacyExternalStorage="true"

matching query does not exist Error in Django

try:
    user = UniversityDetails.objects.get(email=email)
except UniversityDetails.DoesNotExist:
    user = None

I also see you're storing your passwords in plaintext (a big security no-no!). Consider using the built-in auth system instead.

How to add additional fields to form before submit?

Yes.You can try with some hidden params.

  $("#form").submit( function(eventObj) {
      $("<input />").attr("type", "hidden")
          .attr("name", "something")
          .attr("value", "something")
          .appendTo("#form");
      return true;
  });

taking input of a string word by word

getline is storing the entire line at once, which is not what you want. A simple fix is to have three variables and use cin to get them all. C++ will parse automatically at the spaces.

#include <iostream>
using namespace std;

int main() {
    string a, b, c;
    cin >> a >> b >> c;
    //now you have your three words
    return 0;
}

I don't know what particular "operation" you're talking about, so I can't help you there, but if it's changing characters, read up on string and indices. The C++ documentation is great. As for using namespace std; versus std:: and other libraries, there's already been a lot said. Try these questions on StackOverflow to start.

PLS-00428: an INTO clause is expected in this SELECT statement

In PLSQL block, columns of select statements must be assigned to variables, which is not the case in SQL statements.

The second BEGIN's SQL statement doesn't have INTO clause and that caused the error.

DECLARE
   PROD_ROW_ID   VARCHAR (10) := NULL;
   VIS_ROW_ID    NUMBER;
   DSC           VARCHAR (512);
BEGIN
   SELECT ROW_ID
     INTO VIS_ROW_ID
     FROM SIEBEL.S_PROD_INT
    WHERE PART_NUM = 'S0146404';

   BEGIN
      SELECT    RTRIM (VIS.SERIAL_NUM)
             || ','
             || RTRIM (PLANID.DESC_TEXT)
             || ','
             || CASE
                   WHEN PLANID.HIGH = 'TEST123'
                   THEN
                      CASE
                         WHEN TO_DATE (PROD.START_DATE) + 30 > SYSDATE
                         THEN
                            'Y'
                         ELSE
                            'N'
                      END
                   ELSE
                      'N'
                END
             || ','
             || 'GB'
             || ','
             || RTRIM (TO_CHAR (PROD.START_DATE, 'YYYY-MM-DD'))
        INTO DSC
        FROM SIEBEL.S_LST_OF_VAL PLANID
             INNER JOIN SIEBEL.S_PROD_INT PROD
                ON PROD.PART_NUM = PLANID.VAL
             INNER JOIN SIEBEL.S_ASSET NETFLIX
                ON PROD.PROD_ID = PROD.ROW_ID
             INNER JOIN SIEBEL.S_ASSET VIS
                ON VIS.PROM_INTEG_ID = PROD.PROM_INTEG_ID
             INNER JOIN SIEBEL.S_PROD_INT VISPROD
                ON VIS.PROD_ID = VISPROD.ROW_ID
       WHERE     PLANID.TYPE = 'Test Plan'
             AND PLANID.ACTIVE_FLG = 'Y'
             AND VISPROD.PART_NUM = VIS_ROW_ID
             AND PROD.STATUS_CD = 'Active'
             AND VIS.SERIAL_NUM IS NOT NULL;
   END;
END;
/

References

http://docs.oracle.com/cd/E11882_01/appdev.112/e25519/static.htm#LNPLS00601 http://docs.oracle.com/cd/B19306_01/appdev.102/b14261/selectinto_statement.htm#CJAJAAIG http://pls-00428.ora-code.com/

Styling HTML email for Gmail

As others have said, some email programs will not read the css styles. If you already have a web email written up you can use the following tool from zurb to inline all of your styles:

http://zurb.com/ink/inliner.php

This comes in extremely handy when using templates like those mentioned above from mailchimp, campaign monitor, etc. as they, as you have found, will not work in some email programs. This tool leaves your style section for the mail programs that will read it and puts all the styles inline to get more universal readability in the format that you wanted.

Looping from 1 to infinity in Python

Simplest and best:

i = 0
while not there_is_reason_to_break(i):
    # some code here
    i += 1

It may be tempting to choose the closest analogy to the C code possible in Python:

from itertools import count

for i in count():
    if thereIsAReasonToBreak(i):
        break

But beware, modifying i will not affect the flow of the loop as it would in C. Therefore, using a while loop is actually a more appropriate choice for porting that C code to Python.

docker unauthorized: authentication required - upon push with successful login

You can mv the xxx/.docker/config.json file somewhere for handle it. Then try to login again for create new config.json file.

#mv xx/.docker/config.json xx/.docker/config_old.json
#docker login https://index.docker.io/v1/
Login with your Docker ID to push and pull images from Docker Hub. If you don't have a Docker ID, head over to https://hub.docker.com to create one.
Username: YOUR USERNAME
Password: YOUR PASSWORD
WARNING! Your password will be stored unencrypted in /xxx/.docker/config.json.
Configure a credential helper to remove this warning. See https://docs.docker.com/engine/reference/commandline/login/#credentials-store

Login Succeeded

Format cell color based on value in another sheet and cell

You can also do this with named ranges so you don't have to copy the cells from Sheet1 to Sheet2:

  1. Define a named range, say Sheet1Vals for the column that has the values on which you want to base your condition. You can define a new named range by using the Insert\Name\Define... menu item. Type in your name, then use the cell browser in the Refers to box to select the cells you want in the range. If the range will change over time (add or remove rows) you can use this formula instead of selecting the cells explicitly:

    =OFFSET('SheetName'!$COL$ROW,0,0,COUNTA('SheetName'!$COL:$COL)).

    Add a -1 before the last ) if the column has a header row.

  2. Define a named range, say Sheet2Vals for the column that has the values you want to conditionally format.

  3. Use the Conditional Formatting dialog to create your conditions. Specify Formula Is in the dropdown, then put this for the formula:

    =INDEX(Sheet1Vals, MATCH([FirstCellInRange],Sheet2Vals))=[Condition]

    where [FirstCellInRange] is the address of the cell you want to format and [Condition] is the value your checking.

For example, if my conditions in Sheet1 have the values of 1, 2 and 3 and the column I'm formatting is column B in Sheet2 then my conditional formats would be something like:

=INDEX(Sheet1Vals, MATCH(B1,Sheet2Vals))=1
=INDEX(Sheet1Vals, MATCH(B1,Sheet2Vals))=2
=INDEX(Sheet1Vals, MATCH(B1,Sheet2Vals))=3

You can then use the format painter to copy these formats to the rest of the cells.

jquery select option click handler

One possible solution is to add a class to every option

<select name="export_type" id="export_type">
    <option class="export_option" value="pdf">PDF</option>
    <option class="export_option" value="xlsx">Excel</option>
    <option class="export_option" value="docx">DocX</option>
</select>

and then use the click handler for this class

$(document).ready(function () {

    $(".export_option").click(function (e) {
        //alert('click');
    });

});

UPDATE: it looks like the code works in FF, IE and Opera but not in Chrome. Looking at the specs http://www.w3.org/TR/html401/interact/forms.html#h-17.6 I would say it's a bug in Chrome.

Tainted canvases may not be exported

In my case I was drawing onto a canvas tag from a video. To address the tainted canvas error I had to do two things:

<video id="video_source" crossorigin="anonymous">
    <source src="http://crossdomain.example.com/myfile.mp4">
</video>
  • Ensure Access-Control-Allow-Origin header is set in the video source response (proper setup of crossdomain.example.com)
  • Set the video tag to have crossorigin="anonymous"

Curl command line for consuming webServices?

Posting a string:

curl -d "String to post" "http://www.example.com/target"

Posting the contents of a file:

curl -d @soap.xml "http://www.example.com/target"

Replace one substring for another string in shell script

For Dash all previous posts aren't working

The POSIX sh compatible solution is:

result=$(echo "$firstString" | sed "s/Suzi/$secondString/")

This will replace the first occurrence on each line of input. Add a /g flag to replace all occurrences:

result=$(echo "$firstString" | sed "s/Suzi/$secondString/g")

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.

C# windows application Event: CLR20r3 on application start

I've seen this same problem when my application depended on a referenced assembly that was not present on the deployment machine. I'm not sure what you mean by "referencing DotNetBar out of the install directory" - make sure it's set to CopyLocal=true in your project, or exists at the same full path on both your development and production machine.

Check whether a path is valid in Python without creating a file at the path's target

if os.path.exists(filePath):
    #the file is there
elif os.access(os.path.dirname(filePath), os.W_OK):
    #the file does not exists but write privileges are given
else:
    #can not write there

Note that path.exists can fail for more reasons than just the file is not there so you might have to do finer tests like testing if the containing directory exists and so on.


After my discussion with the OP it turned out, that the main problem seems to be, that the file name might contain characters that are not allowed by the filesystem. Of course they need to be removed but the OP wants to maintain as much human readablitiy as the filesystem allows.

Sadly I do not know of any good solution for this. However Cecil Curry's answer takes a closer look at detecting the problem.

pyplot scatter plot marker size

Because other answers here claim that s denotes the area of the marker, I'm adding this answer to clearify that this is not necessarily the case.

Size in points^2

The argument s in plt.scatter denotes the markersize**2. As the documentation says

s : scalar or array_like, shape (n, ), optional
size in points^2. Default is rcParams['lines.markersize'] ** 2.

This can be taken literally. In order to obtain a marker which is x points large, you need to square that number and give it to the s argument.

So the relationship between the markersize of a line plot and the scatter size argument is the square. In order to produce a scatter marker of the same size as a plot marker of size 10 points you would hence call scatter( .., s=100).

enter image description here

import matplotlib.pyplot as plt

fig,ax = plt.subplots()

ax.plot([0],[0], marker="o",  markersize=10)
ax.plot([0.07,0.93],[0,0],    linewidth=10)
ax.scatter([1],[0],           s=100)

ax.plot([0],[1], marker="o",  markersize=22)
ax.plot([0.14,0.86],[1,1],    linewidth=22)
ax.scatter([1],[1],           s=22**2)

plt.show()

Connection to "area"

So why do other answers and even the documentation speak about "area" when it comes to the s parameter?

Of course the units of points**2 are area units.

  • For the special case of a square marker, marker="s", the area of the marker is indeed directly the value of the s parameter.
  • For a circle, the area of the circle is area = pi/4*s.
  • For other markers there may not even be any obvious relation to the area of the marker.

enter image description here

In all cases however the area of the marker is proportional to the s parameter. This is the motivation to call it "area" even though in most cases it isn't really.

Specifying the size of the scatter markers in terms of some quantity which is proportional to the area of the marker makes in thus far sense as it is the area of the marker that is perceived when comparing different patches rather than its side length or diameter. I.e. doubling the underlying quantity should double the area of the marker.

enter image description here

What are points?

So far the answer to what the size of a scatter marker means is given in units of points. Points are often used in typography, where fonts are specified in points. Also linewidths is often specified in points. The standard size of points in matplotlib is 72 points per inch (ppi) - 1 point is hence 1/72 inches.

It might be useful to be able to specify sizes in pixels instead of points. If the figure dpi is 72 as well, one point is one pixel. If the figure dpi is different (matplotlib default is fig.dpi=100),

1 point == fig.dpi/72. pixels

While the scatter marker's size in points would hence look different for different figure dpi, one could produce a 10 by 10 pixels^2 marker, which would always have the same number of pixels covered:

enter image description here enter image description here enter image description here

import matplotlib.pyplot as plt

for dpi in [72,100,144]:

    fig,ax = plt.subplots(figsize=(1.5,2), dpi=dpi)
    ax.set_title("fig.dpi={}".format(dpi))

    ax.set_ylim(-3,3)
    ax.set_xlim(-2,2)

    ax.scatter([0],[1], s=10**2, 
               marker="s", linewidth=0, label="100 points^2")
    ax.scatter([1],[1], s=(10*72./fig.dpi)**2, 
               marker="s", linewidth=0, label="100 pixels^2")

    ax.legend(loc=8,framealpha=1, fontsize=8)

    fig.savefig("fig{}.png".format(dpi), bbox_inches="tight")

plt.show() 

If you are interested in a scatter in data units, check this answer.

JavaScript sleep/wait before continuing

JS does not have a sleep function, it has setTimeout() or setInterval() functions.

If you can move the code that you need to run after the pause into the setTimeout() callback, you can do something like this:

//code before the pause
setTimeout(function(){
    //do what you need here
}, 2000);

see example here : http://jsfiddle.net/9LZQp/

This won't halt the execution of your script, but due to the fact that setTimeout() is an asynchronous function, this code

console.log("HELLO");
setTimeout(function(){
    console.log("THIS IS");
}, 2000);
console.log("DOG");

will print this in the console:

HELLO
DOG
THIS IS

(note that DOG is printed before THIS IS)


You can use the following code to simulate a sleep for short periods of time:

function sleep(milliseconds) {
  var start = new Date().getTime();
  for (var i = 0; i < 1e7; i++) {
    if ((new Date().getTime() - start) > milliseconds){
      break;
    }
  }
}

now, if you want to sleep for 1 second, just use:

sleep(1000);

example: http://jsfiddle.net/HrJku/1/

please note that this code will keep your script busy for n milliseconds. This will not only stop execution of Javascript on your page, but depending on the browser implementation, may possibly make the page completely unresponsive, and possibly make the entire browser unresponsive. In other words this is almost always the wrong thing to do.

Test process.env with Jest

In test file:

const APP_PORT = process.env.APP_PORT || 8080;

In the test script of ./package.json:

"scripts": {
   "test": "jest --setupFiles dotenv/config",
 }

In ./env:

APP_PORT=8080

Pygame Drawing a Rectangle

import pygame, sys
from pygame.locals import *

def main():
    pygame.init()

    DISPLAY=pygame.display.set_mode((500,400),0,32)

    WHITE=(255,255,255)
    BLUE=(0,0,255)

    DISPLAY.fill(WHITE)

    pygame.draw.rect(DISPLAY,BLUE,(200,150,100,50))

    while True:
        for event in pygame.event.get():
            if event.type==QUIT:
                pygame.quit()
                sys.exit()
        pygame.display.update()

main()

This creates a simple window 500 pixels by 400 pixels that is white. Within the window will be a blue rectangle. You need to use the pygame.draw.rect to go about this, and you add the DISPLAY constant to add it to the screen, the variable blue to make it blue (blue is a tuple that values which equate to blue in the RGB values and it's coordinates.

Look up pygame.org for more info

Scale iFrame css width 100% like an image

Big difference between an image and an iframe is the fact that an image keeps its aspect-ratio. You could combine an image and an iframe with will result in a responsive iframe. Hope this answerers your question.

Check this link for example : http://jsfiddle.net/Masau/7WRHM/

HTML:

<div class="wrapper">
    <div class="h_iframe">
        <!-- a transparent image is preferable -->
        <img class="ratio" src="http://placehold.it/16x9"/>
        <iframe src="http://www.youtube.com/embed/WsFWhL4Y84Y" frameborder="0" allowfullscreen></iframe>
    </div>
    <p>Please scale the "result" window to notice the effect.</p>
</div>

CSS:

html,body        {height:100%;}
.wrapper         {width:80%;height:100%;margin:0 auto;background:#CCC}
.h_iframe        {position:relative;}
.h_iframe .ratio {display:block;width:100%;height:auto;}
.h_iframe iframe {position:absolute;top:0;left:0;width:100%; height:100%;}

note: This only works with a fixed aspect-ratio.

Press Keyboard keys using a batch file

Just to be clear, you are wanting to launch a program from a batch file and then have the batch file press keys (in your example, the arrow keys) within that launched program?

If that is the case, you aren't going to be able to do that with simply a ".bat" file as the launched would stop the batch file from continuing until it terminated--

My first recommendation would be to use something like AutoHotkey or AutoIt if possible, simply because they both have active forums where you'd find countless examples of people launching applications and sending key presses not to mention tools to simply "record" what you want to do. However you said this is a work computer and you may not be able to load a 3rd party program.. but you aren't without options.

You can use Windows Scripting Host from something like a .vbs file to launch a program and send keys to that process. If you're running a version of Windows that includes PowerShell 2.0 (Windows XP with Service Pack 3, Windows Vista with Service Pack 1, Windows 7, etc.) you can use Windows Scripting Host as a COM object from your PS script or use VB's Intereact class.

The specifics of how to do it are outside the scope of this answer but you can find numerous examples using the methods I just described by searching on SO or Google.

edit: Just to help you get started you can look here:

  1. Automate tasks with Windows Script Host's SendKeys method
  2. A useful thread about SendKeys

How do I filter an array with TypeScript in Angular 2?

You need to put your code into ngOnInit and use the this keyword:

ngOnInit() {
  this.booksByStoreID = this.books.filter(
          book => book.store_id === this.store.id);
}

You need ngOnInit because the input store wouldn't be set into the constructor:

ngOnInit is called right after the directive's data-bound properties have been checked for the first time, and before any of its children have been checked. It is invoked only once when the directive is instantiated.

(https://angular.io/docs/ts/latest/api/core/index/OnInit-interface.html)

In your code, the books filtering is directly defined into the class content...

Select last N rows from MySQL

You can do it with a sub-query:

SELECT * FROM (
    SELECT * FROM table ORDER BY id DESC LIMIT 50
) sub
ORDER BY id ASC

This will select the last 50 rows from table, and then order them in ascending order.

React PropTypes : Allow different types of PropTypes for one prop

For documentation purpose, it's better to list the string values that are legal:

size: PropTypes.oneOfType([
    PropTypes.number,
    PropTypes.oneOf([ 'SMALL', 'LARGE' ]),
]),

Exclude subpackages from Spring autowiring?

You can also use @SpringBootApplication, which according to Spring documentation does the same functionality as the following three annotations: @Configuration, @EnableAutoConfiguration @ComponentScan in one annotation.

@SpringBootApplication(exclude= {Foo.class})
public class MySpringConfiguration {}

failed to find target with hash string android-23

This poblem is solved for me after Run as administrator the Andorid Studio

Add regression line equation and R^2 on graph

Inspired by the equation style provided in this answer, a more generic approach (more than one predictor + latex output as option) can be:

print_equation= function(model, latex= FALSE, ...){
    dots <- list(...)
    cc= model$coefficients
    var_sign= as.character(sign(cc[-1]))%>%gsub("1","",.)%>%gsub("-"," - ",.)
    var_sign[var_sign==""]= ' + '

    f_args_abs= f_args= dots
    f_args$x= cc
    f_args_abs$x= abs(cc)
    cc_= do.call(format, args= f_args)
    cc_abs= do.call(format, args= f_args_abs)
    pred_vars=
        cc_abs%>%
        paste(., x_vars, sep= star)%>%
        paste(var_sign,.)%>%paste(., collapse= "")

    if(latex){
        star= " \\cdot "
        y_var= strsplit(as.character(model$call$formula), "~")[[2]]%>%
            paste0("\\hat{",.,"_{i}}")
        x_vars= names(cc_)[-1]%>%paste0(.,"_{i}")
    }else{
        star= " * "
        y_var= strsplit(as.character(model$call$formula), "~")[[2]]        
        x_vars= names(cc_)[-1]
    }

    equ= paste(y_var,"=",cc_[1],pred_vars)
    if(latex){
        equ= paste0(equ," + \\hat{\\varepsilon_{i}} \\quad where \\quad \\varepsilon \\sim \\mathcal{N}(0,",
                    summary(MetamodelKdifEryth)$sigma,")")%>%paste0("$",.,"$")
    }
    cat(equ)
}

The model argument expects an lm object, the latex argument is a boolean to ask for a simple character or a latex-formated equation, and the ... argument pass its values to the format function.

I also added an option to output it as latex so you can use this function in a rmarkdown like this:


```{r echo=FALSE, results='asis'}
print_equation(model = lm_mod, latex = TRUE)
```

Now using it:

df <- data.frame(x = c(1:100))
df$y <- 2 + 3 * df$x + rnorm(100, sd = 40)
df$z <- 8 + 3 * df$x + rnorm(100, sd = 40)
lm_mod= lm(y~x+z, data = df)

print_equation(model = lm_mod, latex = FALSE)

This code yields: y = 11.3382963933174 + 2.5893419 * x + 0.1002227 * z

And if we ask for a latex equation, rounding the parameters to 3 digits:

print_equation(model = lm_mod, latex = TRUE, digits= 3)

This yields: latex equation

MySQL high CPU usage

As this is the top post if you google for MySQL high CPU usage or load, I'll add an additional answer:

On the 1st of July 2012, a leap second was added to the current UTC-time to compensate for the slowing rotation of the earth due to the tides. When running ntp (or ntpd) this second was added to your computer's/server's clock. MySQLd does not seem to like this extra second on some OS'es, and yields a high CPU load. The quick fix is (as root):

$ /etc/init.d/ntpd stop
$ date -s "`date`"
$ /etc/init.d/ntpd start

How to access the GET parameters after "?" in Express?

const express = require('express')
const bodyParser = require('body-parser')
const { usersNdJobs, userByJob, addUser , addUserToCompany } = require ('./db/db.js')

const app = express()
app.set('view engine', 'pug')
app.use(express.static('public'))
app.use(bodyParser.urlencoded({ extended: false }))
app.use(bodyParser.json())

app.get('/', (req, res) => {
  usersNdJobs()
    .then((users) => {
      res.render('users', { users })
    })
    .catch(console.error)
})

app.get('/api/company/users', (req, res) => {
  const companyname = req.query.companyName
  console.log(companyname)
  userByJob(companyname)
    .then((users) => {
      res.render('job', { users })
    }).catch(console.error)
})

app.post('/api/users/add', (req, res) => {
  const userName = req.body.userName
  const jobName = req.body.jobName
  console.log("user name = "+userName+", job name : "+jobName)
  addUser(userName, jobName)
    .then((result) => {
      res.status(200).json(result)
    })
    .catch((error) => {
      res.status(404).json({ 'message': error.toString() })
    })
})
app.post('/users/add', (request, response) => {
  const { userName, job } = request.body
  addTeam(userName, job)
  .then((user) => {
    response.status(200).json({
      "userName": user.name,
      "city": user.job
    })
  .catch((err) => {
    request.status(400).json({"message": err})
  })
})

app.post('/api/user/company/add', (req, res) => {
  const userName = req.body.userName
  const companyName = req.body.companyName
  console.log(userName, companyName)
  addUserToCompany(userName, companyName)
  .then((result) => {
    res.json(result)
  })
  .catch(console.error)
})

app.get('/api/company/user', (req, res) => {
 const companyname = req.query.companyName
 console.log(companyname)
 userByJob(companyname)
 .then((users) => {
   res.render('jobs', { users })
 })
})

app.listen(3000, () =>
  console.log('Example app listening on port 3000!')
)

Is it possible to add dynamically named properties to JavaScript object?

in addition to all the previous answers, and in case you're wondering how we're going to write dynamic property names in the Future using Computed Property Names ( ECMAScript 6 ), here's how:

var person = "John Doe";
var personId = "person_" + new Date().getTime();
var personIndex = {
    [ personId ]: person
//  ^ computed property name
};

personIndex[ personId ]; // "John Doe"

reference: Understanding ECMAScript 6 - Nickolas Zakas

How to install Visual Studio 2015 on a different drive

Uninstall the plugins first. And then try this. This uninstaller worked like a charm (I didn't even uninstall 2015 myself, it did everything on its own)!

How to get a subset of a javascript object's properties

You can use Lodash also.

var subset = _.pick(elmo ,'color', 'height');

Complementing, let's say you have an array of "elmo"s :

elmos = [{ 
      color: 'red',
      annoying: true,
      height: 'unknown',
      meta: { one: '1', two: '2'}
    },{ 
      color: 'blue',
      annoying: true,
      height: 'known',
      meta: { one: '1', two: '2'}
    },{ 
      color: 'yellow',
      annoying: false,
      height: 'unknown',
      meta: { one: '1', two: '2'}
    }
];

If you want the same behavior, using lodash, you would just:

var subsets = _.map(elmos, function(elm) { return _.pick(elm, 'color', 'height'); });

Get CPU Usage from Windows Command Prompt

typeperf gives me issues when it randomly doesn't work on some computers (Error: No valid counters.) or if the account has insufficient rights. Otherwise, here is a way to extract just the value from its output. It still needs rounding though:

@for /f "delims=, tokens=2" %p in ('typeperf "\Processor(_Total)\% Processor Time" -sc 3 ^| find ":"') do @echo %~p%

Powershell has two cmdlets to get the percent utilization for all CPUs: Get-Counter (preferred) or Get-WmiObject:

Powershell "Get-Counter '\Processor(*)\% Processor Time' | Select -Expand Countersamples | Select InstanceName, CookedValue"

Or,

Powershell "Get-WmiObject Win32_PerfFormattedData_PerfOS_Processor | Select Name, PercentProcessorTime"


To get the overall CPU load with formatted output exactly like the question:

Powershell "[string][int](Get-Counter '\Processor(*)\% Processor Time').Countersamples[0].CookedValue + '%'"

Or,

 Powershell "gwmi Win32_PerfFormattedData_PerfOS_Processor | Select -First 1 | %{'{0}%' -f $_.PercentProcessorTime}"

What does 'killed' mean when a processing of a huge CSV with Python, which suddenly stops?

I doubt anything is killing the process just because it takes a long time. Killed generically means something from the outside terminated the process, but probably not in this case hitting Ctrl-C since that would cause Python to exit on a KeyboardInterrupt exception. Also, in Python you would get MemoryError exception if that was the problem. What might be happening is you're hitting a bug in Python or standard library code that causes a crash of the process.

How do I configure Maven for offline development?

You can run maven in offline mode mvn -o install. Of course any artifacts not available in your local repository will fail. Maven is not predicated on distributed repositories, but they certainly make things more seamless. Its for this reason that many shops use internal mirrors that are incrementally synced with the central repos.

In addition, the mvn dependency:go-offline can be used to ensure you have all of your dependencies installed locally before you begin to work offline.

How to modify the nodejs request default timeout time?

I'm assuming you're using express, given the logs you have in your question. The key is to set the timeout property on server (the following sets the timeout to one second, use whatever value you want):

var server = app.listen(app.get('port'), function() {
  debug('Express server listening on port ' + server.address().port);
});
server.timeout = 1000;

If you're not using express and are only working with vanilla node, the principle is the same. The following will not return data:

var http = require('http');
var server = http.createServer(function (req, res) {
  setTimeout(function() {
    res.writeHead(200, {'Content-Type': 'text/plain'});
    res.end('Hello World\n');
  }, 200);
}).listen(1337, '127.0.0.1');

server.timeout = 20;
console.log('Server running at http://127.0.0.1:1337/');

How do I find out which process is locking a file using .NET?

I had issues with stefan's solution. Below is a modified version which seems to work well.

using System;
using System.Collections;
using System.Diagnostics;
using System.Management;
using System.IO;

static class Module1
{
    static internal ArrayList myProcessArray = new ArrayList();
    private static Process myProcess;

    public static void Main()
    {
        string strFile = "c:\\windows\\system32\\msi.dll";
        ArrayList a = getFileProcesses(strFile);
        foreach (Process p in a)
        {
            Debug.Print(p.ProcessName);
        }
    }

    private static ArrayList getFileProcesses(string strFile)
    {
        myProcessArray.Clear();
        Process[] processes = Process.GetProcesses();
        int i = 0;
        for (i = 0; i <= processes.GetUpperBound(0) - 1; i++)
        {
            myProcess = processes[i];
            //if (!myProcess.HasExited) //This will cause an "Access is denied" error
            if (myProcess.Threads.Count > 0)
            {
                try
                {
                    ProcessModuleCollection modules = myProcess.Modules;
                    int j = 0;
                    for (j = 0; j <= modules.Count - 1; j++)
                    {
                        if ((modules[j].FileName.ToLower().CompareTo(strFile.ToLower()) == 0))
                        {
                            myProcessArray.Add(myProcess);
                            break;
                            // TODO: might not be correct. Was : Exit For
                        }
                    }
                }
                catch (Exception exception)
                {
                    //MsgBox(("Error : " & exception.Message)) 
                }
            }
        }

        return myProcessArray;
    }
}

UPDATE

If you just want to know which process(es) are locking a particular DLL, you can execute and parse the output of tasklist /m YourDllName.dll. Works on Windows XP and later. See

What does this do? tasklist /m "mscor*"

I just discovered why all ASP.Net websites are slow, and I am trying to work out what to do about it

Marking a controller's session state as readonly or disabled will solve the problem.

You can decorate a controller with the following attribute to mark it read-only:

[SessionState(System.Web.SessionState.SessionStateBehavior.ReadOnly)]

the System.Web.SessionState.SessionStateBehavior enum has the following values:

  • Default
  • Disabled
  • ReadOnly
  • Required

Base64 encoding and decoding in oracle

Solution with utl_encode.base64_encode and utl_encode.base64_decode have one limitation, they work only with strings up to 32,767 characters/bytes.

In case you have to convert bigger strings you will face several obstacles.

  • For BASE64_ENCODE the function has to read 3 Bytes and transform them. In case of Multi-Byte characters (e.g. öäüè€ stored at UTF-8, aka AL32UTF8) 3 Character are not necessarily also 3 Bytes. In order to read always 3 Bytes you have to convert your CLOB into BLOB first.
  • The same problem applies for BASE64_DECODE. The function has to read 4 Bytes and transform them into 3 Bytes. Those 3 Bytes are not necessarily also 3 Characters
  • Typically a BASE64-String has NEW_LINE (CR and/or LF) character each 64 characters. Such new-line characters have to be ignored while decoding.

Taking all this into consideration the full featured solution could be this one:

CREATE OR REPLACE FUNCTION DecodeBASE64(InBase64Char IN OUT NOCOPY CLOB) RETURN CLOB IS

    blob_loc BLOB;
    clob_trim CLOB;
    res CLOB;

    lang_context INTEGER := DBMS_LOB.DEFAULT_LANG_CTX;
    dest_offset INTEGER := 1;
    src_offset INTEGER := 1;
    read_offset INTEGER := 1;
    warning INTEGER;
    ClobLen INTEGER := DBMS_LOB.GETLENGTH(InBase64Char);

    amount INTEGER := 1440; -- must be a whole multiple of 4
    buffer RAW(1440);
    stringBuffer VARCHAR2(1440);
    -- BASE64 characters are always simple ASCII. Thus you get never any Mulit-Byte character and having the same size as 'amount' is sufficient

BEGIN

    IF InBase64Char IS NULL OR NVL(ClobLen, 0) = 0 THEN 
        RETURN NULL;
    ELSIF ClobLen<= 32000 THEN
        RETURN UTL_RAW.CAST_TO_VARCHAR2(UTL_ENCODE.BASE64_DECODE(UTL_RAW.CAST_TO_RAW(InBase64Char)));
    END IF;        
    -- UTL_ENCODE.BASE64_DECODE is limited to 32k, process in chunks if bigger    

    -- Remove all NEW_LINE from base64 string
    ClobLen := DBMS_LOB.GETLENGTH(InBase64Char);
    DBMS_LOB.CREATETEMPORARY(clob_trim, TRUE);
    LOOP
        EXIT WHEN read_offset > ClobLen;
        stringBuffer := REPLACE(REPLACE(DBMS_LOB.SUBSTR(InBase64Char, amount, read_offset), CHR(13), NULL), CHR(10), NULL);
        DBMS_LOB.WRITEAPPEND(clob_trim, LENGTH(stringBuffer), stringBuffer);
        read_offset := read_offset + amount;
    END LOOP;

    read_offset := 1;
    ClobLen := DBMS_LOB.GETLENGTH(clob_trim);
    DBMS_LOB.CREATETEMPORARY(blob_loc, TRUE);
    LOOP
        EXIT WHEN read_offset > ClobLen;
        buffer := UTL_ENCODE.BASE64_DECODE(UTL_RAW.CAST_TO_RAW(DBMS_LOB.SUBSTR(clob_trim, amount, read_offset)));
        DBMS_LOB.WRITEAPPEND(blob_loc, DBMS_LOB.GETLENGTH(buffer), buffer);
        read_offset := read_offset + amount;
    END LOOP;

    DBMS_LOB.CREATETEMPORARY(res, TRUE);
    DBMS_LOB.CONVERTTOCLOB(res, blob_loc, DBMS_LOB.LOBMAXSIZE, dest_offset, src_offset,  DBMS_LOB.DEFAULT_CSID, lang_context, warning);

    DBMS_LOB.FREETEMPORARY(blob_loc);
    DBMS_LOB.FREETEMPORARY(clob_trim);
    RETURN res;    

END DecodeBASE64;




CREATE OR REPLACE FUNCTION EncodeBASE64(InClearChar IN OUT NOCOPY CLOB) RETURN CLOB IS

    dest_lob BLOB;  
    lang_context INTEGER := DBMS_LOB.DEFAULT_LANG_CTX;
    dest_offset INTEGER := 1;
    src_offset INTEGER := 1;
    read_offset INTEGER := 1;
    warning INTEGER;
    ClobLen INTEGER := DBMS_LOB.GETLENGTH(InClearChar);

    amount INTEGER := 1440; -- must be a whole multiple of 3
    -- size of a whole multiple of 48 is beneficial to get NEW_LINE after each 64 characters 
    buffer RAW(1440);
    res CLOB := EMPTY_CLOB();

BEGIN

    IF InClearChar IS NULL OR NVL(ClobLen, 0) = 0 THEN 
        RETURN NULL;
    ELSIF ClobLen <= 24000 THEN
        RETURN UTL_RAW.CAST_TO_VARCHAR2(UTL_ENCODE.BASE64_ENCODE(UTL_RAW.CAST_TO_RAW(InClearChar)));
    END IF;
    -- UTL_ENCODE.BASE64_ENCODE is limited to 32k/(3/4), process in chunks if bigger    

    DBMS_LOB.CREATETEMPORARY(dest_lob, TRUE);
    DBMS_LOB.CONVERTTOBLOB(dest_lob, InClearChar, DBMS_LOB.LOBMAXSIZE, dest_offset, src_offset, DBMS_LOB.DEFAULT_CSID, lang_context, warning);
    LOOP
        EXIT WHEN read_offset >= dest_offset;
        DBMS_LOB.READ(dest_lob, amount, read_offset, buffer);
        res := res || UTL_RAW.CAST_TO_VARCHAR2(UTL_ENCODE.BASE64_ENCODE(buffer));       
        read_offset := read_offset + amount;
    END LOOP;
    DBMS_LOB.FREETEMPORARY(dest_lob);
    RETURN res;

END EncodeBASE64;

What is the equivalent of "none" in django templates?

{% if profile.user.first_name %} works (assuming you also don't want to accept '').

if in Python in general treats None, False, '', [], {}, ... all as false.

Usage of the backtick character (`) in JavaScript

Backticks (`) are used to define template literals. Template literals are a new feature in ECMAScript 6 to make working with strings easier.

Features:

  • we can interpolate any kind of expression in the template literals.
  • They can be multi-line.

Note: we can easily use single quotes (') and double quotes (") inside the backticks (`).

Example:

var nameStr = `I'm "Rohit" Jindal`;

To interpolate the variables or expression we can use the ${expression} notation for that.

var name = 'Rohit Jindal';
var text = `My name is ${name}`;
console.log(text); // My name is Rohit Jindal

Multi-line strings means that you no longer have to use \n for new lines anymore.

Example:

const name = 'Rohit';
console.log(`Hello ${name}!
How are you?`);

Output:

Hello Rohit!
How are you?

Run a script in Dockerfile

Try to create script with ADD command and specification of working directory Like this("script" is the name of script and /root/script.sh is where you want it in the container, it can be different path:

ADD script.sh /root/script.sh

In this case ADD has to come before CMD, if you have one BTW it's cool way to import scripts to any location in container from host machine

In CMD place [./script]

It should automatically execute your script

You can also specify WORKDIR as /root, then you'l be automatically placed in root, upon starting a container

Jquery Ajax Loading image

Description

You should do this using jQuery.ajaxStart and jQuery.ajaxStop.

  1. Create a div with your image
  2. Make it visible in jQuery.ajaxStart
  3. Hide it in jQuery.ajaxStop

Sample

<div id="loading" style="display:none">Your Image</div>

<script src="../../Scripts/jquery-1.5.1.min.js" type="text/javascript"></script>
<script>
    $(function () {
        var loading = $("#loading");
        $(document).ajaxStart(function () {
            loading.show();
        });

        $(document).ajaxStop(function () {
            loading.hide();
        });

        $("#startAjaxRequest").click(function () {
            $.ajax({
                url: "http://www.google.com",
                // ... 
            });
        });
    });
</script>

<button id="startAjaxRequest">Start</button>

More Information

How to remove empty lines with or without whitespace in Python

Same as what @NullUserException said, this is how I write it:

removedWhitespce = re.sub(r'^\s*$', '', line)

How do I create a constant in Python?

In addition to the two top answers (just use variables with UPPERCASE names, or use properties to make the values read-only), I want to mention that it's possible to use metaclasses in order to implement named constants. I provide a very simple solution using metaclasses at GitHub which may be helpful if you want the values to be more informative about their type/name:

>>> from named_constants import Constants
>>> class Colors(Constants):
...     black = 0
...     red = 1
...     white = 15
...
>>> c = Colors.black
>>> c == 0
True
>>> c
Colors.black
>>> c.name()
'black'
>>> Colors(0) is c
True

This is slightly more advanced Python, but still very easy to use and handy. (The module has some more features, including constants being read-only, see its README.)

There are similar solutions floating around in various repositories, but to the best of my knowledge they either lack one of the fundamental features that I would expect from constants (like being constant, or being of arbitrary type), or they have esoteric features added that make them less generally applicable. But YMMV, I would be grateful for feedback. :-)

Disable/Enable button in Excel/VBA

too good !!! it's working and resolved my one day old problem easily

Dim b1 As Button

Set b1 = ActiveSheet.Buttons("Button 1")


b1.Enabled = False

Python 2.7: %d, %s, and float()

See String Formatting Operations:

%d is the format code for an integer. %f is the format code for a float.

%s prints the str() of an object (What you see when you print(object)).

%r prints the repr() of an object (What you see when you print(repr(object)).

For a float %s, %r and %f all display the same value, but that isn't the case for all objects. The other fields of a format specifier work differently as well:

>>> print('%10.2s' % 1.123) # print as string, truncate to 2 characters in a 10-place field.
        1.
>>> print('%10.2f' % 1.123) # print as float, round to 2 decimal places in a 10-place field.
      1.12

Angularjs dynamic ng-pattern validation

This is an interesting problem, complex Angular validation. The following fiddle implements what you want:

http://jsfiddle.net/2G8gA/1/

Details

I created a new directive, rpattern, that is a mix of Angular's ng-required and the ng-pattern code from input[type=text]. What it does is watch the required attribute of the field and take that into account when validating with regexp, i.e. if not required mark field as valid-pattern.

Notes

  • Most of the code is from Angular, tailored to the needs of this.
  • When the checkbox is checked, the field is required.
  • The field is not hidden when the required checkbox is false.
  • The regular expression is simplified for the demo (valid is 3 digits).

A dirty (but smaller) solution, if you do not want a new directive, would be something like:

$scope.phoneNumberPattern = (function() {
    var regexp = /^\(?(\d{3})\)?[ .-]?(\d{3})[ .-]?(\d{4})$/;
    return {
        test: function(value) {
            if( $scope.requireTel === false ) {
                return true;
            }
            return regexp.test(value);
        }
    };
})();

And in HTML no changes would be required:

<input type="text" ng-model="..." ng-required="requireTel"
    ng-pattern="phoneNumberPattern" />

This actually tricks angular into calling our test() method, instead of RegExp.test(), that takes the required into account.

Hive ParseException - cannot recognize input near 'end' 'string'

You can always escape the reserved keyword if you still want to make your query work!!

Just replace end with `end`

Here is the list of reserved keywords https://cwiki.apache.org/confluence/display/Hive/LanguageManual+DDL

CREATE EXTERNAL TABLE moveProjects (cid string, `end` string, category string)
STORED BY 'org.apache.hadoop.hive.dynamodb.DynamoDBStorageHandler'
TBLPROPERTIES ("dynamodb.table.name" = "Projects",
    "dynamodb.column.mapping" = "cid:cid,end:end,category:category");

Where is body in a nodejs http.get response?

A portion of Coffee here:

# My little helper
read_buffer = (buffer, callback) ->
  data = ''
  buffer.on 'readable', -> data += buffer.read().toString()
  buffer.on 'end', -> callback data

# So request looks like
http.get 'http://i.want.some/stuff', (res) ->
  read_buffer res, (response) ->
    # Do some things with your response
    # but don't do that exactly :D
    eval(CoffeeScript.compile response, bare: true)

And compiled

var read_buffer;

read_buffer = function(buffer, callback) {
  var data;
  data = '';
  buffer.on('readable', function() {
    return data += buffer.read().toString();
  });
  return buffer.on('end', function() {
    return callback(data);
  });
};

http.get('http://i.want.some/stuff', function(res) {
  return read_buffer(res, function(response) {
    return eval(CoffeeScript.compile(response, {
      bare: true
    }));
  });
});

Using Excel VBA to export data to MS Access table

is it possible to export without looping through all records

For a range in Excel with a large number of rows you may see some performance improvement if you create an Access.Application object in Excel and then use it to import the Excel data into Access. The code below is in a VBA module in the same Excel document that contains the following test data

SampleData.png

Option Explicit

Sub AccImport()
    Dim acc As New Access.Application
    acc.OpenCurrentDatabase "C:\Users\Public\Database1.accdb"
    acc.DoCmd.TransferSpreadsheet _
            TransferType:=acImport, _
            SpreadSheetType:=acSpreadsheetTypeExcel12Xml, _
            TableName:="tblExcelImport", _
            Filename:=Application.ActiveWorkbook.FullName, _
            HasFieldNames:=True, _
            Range:="Folio_Data_original$A1:B10"
    acc.CloseCurrentDatabase
    acc.Quit
    Set acc = Nothing
End Sub

How to remove items from a list while iterating?

You might want to use filter() available as the built-in.

For more details check here

How do I set cell value to Date and apply default Excel date format?

This example is for working with .xlsx file types. This example comes from a .jsp page used to create a .xslx spreadsheet.

import org.apache.poi.xssf.usermodel.*; //import needed

XSSFWorkbook  wb = new XSSFWorkbook ();  // Create workbook
XSSFSheet sheet = wb.createSheet();      // Create spreadsheet in workbook
XSSFRow row = sheet.createRow(rowIndex); // Create the row in the spreadsheet


//1. Create the date cell style
XSSFCreationHelper createHelper = wb.getCreationHelper();
XSSFCellStyle cellStyle         = wb.createCellStyle();
cellStyle.setDataFormat(
createHelper.createDataFormat().getFormat("MMMM dd, yyyy")); 

//2. Apply the Date cell style to a cell

//This example sets the first cell in the row using the date cell style
cell = row.createCell(0);
cell.setCellValue(new Date());
cell.setCellStyle(cellStyle);

Converting byte array to String (Java)

The byte array contains characters in a special encoding (that you should know). The way to convert it to a String is:

String decoded = new String(bytes, "UTF-8");  // example for one encoding type

By The Way - the raw bytes appear may appear as negative decimals just because the java datatype byte is signed, it covers the range from -128 to 127.


-109 = 0x93: Control Code "Set Transmit State"

The value (-109) is a non-printable control character in UNICODE. So UTF-8 is not the correct encoding for that character stream.

0x93 in "Windows-1252" is the "smart quote" that you're looking for, so the Java name of that encoding is "Cp1252". The next line provides a test code:

System.out.println(new String(new byte[]{-109}, "Cp1252")); 

Inserting values into a SQL Server database using ado.net via C#

As I said in comments - you should always use parameters in your query - NEVER EVER concatenate together your SQL statements yourself.

Also: I would recommend to separate the click event handler from the actual code to insert the data.

So I would rewrite your code to be something like

In your web page's code-behind file (yourpage.aspx.cs)

private void button1_Click(object sender, EventArgs e)
{
      string connectionString = "Data Source=DELL-PC;initial catalog=AdventureWorks2008R2 ; User ID=sa;Password=sqlpass;Integrated Security=SSPI;";

      InsertData(connectionString,
                 textBox1.Text.Trim(),  -- first name
                 textBox2.Text.Trim(),  -- last name
                 textBox3.Text.Trim(),  -- user name
                 textBox4.Text.Trim(),  -- password
                 Convert.ToInt32(comboBox1.Text),  -- age
                 comboBox2.Text.Trim(), -- gender
                 textBox7.Text.Trim() );  -- contact
}

In some other code (e.g. a databaselayer.cs):

private void InsertData(string connectionString, string firstName, string lastname, string username, string password
                        int Age, string gender, string contact)
{
    // define INSERT query with parameters
    string query = "INSERT INTO dbo.regist (FirstName, Lastname, Username, Password, Age, Gender,Contact) " + 
                   "VALUES (@FirstName, @Lastname, @Username, @Password, @Age, @Gender, @Contact) ";

    // create connection and command
    using(SqlConnection cn = new SqlConnection(connectionString))
    using(SqlCommand cmd = new SqlCommand(query, cn))
    {
        // define parameters and their values
        cmd.Parameters.Add("@FirstName", SqlDbType.VarChar, 50).Value = firstName;
        cmd.Parameters.Add("@Lastname", SqlDbType.VarChar, 50).Value = lastName;
        cmd.Parameters.Add("@Username", SqlDbType.VarChar, 50).Value = userName;
        cmd.Parameters.Add("@Password", SqlDbType.VarChar, 50).Value = password;
        cmd.Parameters.Add("@Age", SqlDbType.Int).Value = age;
        cmd.Parameters.Add("@Gender", SqlDbType.VarChar, 50).Value = gender;
        cmd.Parameters.Add("@Contact", SqlDbType.VarChar, 50).Value = contact;

        // open connection, execute INSERT, close connection
        cn.Open();
        cmd.ExecuteNonQuery();
        cn.Close();
    }
}

Code like this:

  • is not vulnerable to SQL injection attacks
  • performs much better on SQL Server (since the query is parsed once into an execution plan, then cached and reused later on)
  • separates the event handler (code-behind file) from your actual database code (putting things where they belong - helping to avoid "overweight" code-behinds with tons of spaghetti code, doing everything from handling UI events to database access - NOT a good design!)

Visual Studio - How to change a project's folder name and solution name without breaking the solution

I found that these instructions were not enough. I also had to search through the code files for models, controllers, and views as well as the AppStart files to change the namespace.

Since I was copying my project not just renaming it, I also had to go into the applicationhost.config for IIS express and recreate the bindings using different port numbers and change the physical directory as well.

Why use Gradle instead of Ant or Maven?

I agree partly with Ed Staub. Gradle definitely is more powerful compared to maven and provides more flexibility long term.

After performing an evaluation to move from maven to gradle, we decided to stick to maven itself for two issues we encountered with gradle ( speed is slower than maven, proxy was not working ) .

How to format code in Xcode?

Select first the text you want to format and then press Ctrl+I.

Use Cmd+A first if you wish to format all text in the selected file.

Note: this procedure only re-indents the lines, it does not do any advanced formatting.


In XCode 12 beta:

The new key binding to re-indent is control+I.

How to call a function, PostgreSQL

you declare your function as returning boolean, but it never returns anything.

how to reset <input type = "file">

I faced the issue with ng2-file-upload for angular. if you are looking for the solution in angular refer below code

HTML:

<input type="file" name="myfile" #activeFrameinputFile ng2FileSelect [uploader]="frameUploader" (change)="frameUploader.uploadAll()" />

component

import { Component, OnInit, ElementRef, ViewChild } from '@angular/core';

@ViewChild('activeFrameinputFile')InputFrameVariable: ElementRef;

this.frameUploader.onSuccessItem = (item, response, status, headers) => {

`this.`**InputFrameVariable**`.nativeElement.value = '';`

};

How do I convert a float to an int in Objective C?

In support of unwind, remember that Objective-C is a superset of C, rather than a completely new language.

Anything you can do in regular old ANSI C can be done in Objective-C.

Trigger a Travis-CI rebuild without pushing a commit?

Travis now offers a way to trigger a "custom" build from their web UI. Look for the "More Options" menu button on the right side near the top of your project's page.

More Options ? Trigger Build

You'll then be presented with a dialog box in which you can choose the branch and customize the configuration:

Custom Build Dialog Box

At the time I'm writing this it is in beta, and appears to be slightly buggy (but I expect they'll get the problems ironed out soon).

Access Control Origin Header error using Axios in React Web throwing error in Chrome

If your backend support CORS, you probably need to add to your request this header:

headers: {"Access-Control-Allow-Origin": "*"}

[Update] Access-Control-Allow-Origin is a response header - so in order to enable CORS - you need to add this header to the response from your server.

But for the most cases better solution would be configuring the reverse proxy, so that your server would be able to redirect requests from the frontend to backend, without enabling CORS.

You can find documentation about CORS mechanism here: https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS

Removing duplicate objects with Underscore for Javascript

.uniq/.unique accepts a callback

var list = [{a:1,b:5},{a:1,c:5},{a:2},{a:3},{a:4},{a:3},{a:2}];

var uniqueList = _.uniq(list, function(item, key, a) { 
    return item.a;
});

// uniqueList = [Object {a=1, b=5}, Object {a=2}, Object {a=3}, Object {a=4}]

Notes:

  1. Callback return value used for comparison
  2. First comparison object with unique return value used as unique
  3. underscorejs.org demonstrates no callback usage
  4. lodash.com shows usage

Another example : using the callback to extract car makes, colors from a list

File Upload ASP.NET MVC 3.0

I have to upload file in 100 kb chunks of file and last of the upload file store in database using command. I hope, it will helpfull to you.

    public HttpResponseMessage Post(AttachmentUploadForm form)
    {
        var response = new WebApiResultResponse
        {
            IsSuccess = true,
            RedirectRequired = false
        };

        var tempFilesFolder = Sanelib.Common.SystemSettings.Globals.CreateOrGetCustomPath("Temp\\" + form.FileId);

        File.WriteAllText(tempFilesFolder + "\\" + form.ChunkNumber + ".temp", form.ChunkData);

        if (form.ChunkNumber < Math.Ceiling((double)form.Size / 102400)) return Content(response);

        var folderInfo = new DirectoryInfo(tempFilesFolder);
        var totalFiles = folderInfo.GetFiles().Length;

        var sb = new StringBuilder();

        for (var i = 1; i <= totalFiles; i++)
        {
            sb.Append(File.ReadAllText(tempFilesFolder + "\\" + i + ".temp"));
        }

        var base64 = sb.ToString();
        base64 = base64.Substring(base64.IndexOf(',') + 1);
        var fileBytes = Convert.FromBase64String(base64);
        var fileStream = new FileStream(tempFilesFolder + "\\" + form.Name, FileMode.OpenOrCreate, FileAccess.ReadWrite);
        fileStream.Seek(fileStream.Length, SeekOrigin.Begin);
        fileStream.Write(fileBytes, 0, fileBytes.Length);
        fileStream.Close();

        Directory.Delete(tempFilesFolder, true);

        var md5 = MD5.Create();

        var command = Mapper.Map<AttachmentUploadForm, AddAttachment>(form);
        command.FileData = fileBytes;
        command.FileHashCode = BitConverter.ToString(md5.ComputeHash(fileBytes)).Replace("-", "");

        return ExecuteCommand(command);
    }

Javascript (Knockout Js)

define(['util', 'ajax'], function (util, ajax) {
"use strict";

var exports = {},
     ViewModel, Attachment, FileObject;

//File Upload
FileObject = function (file, parent) {
    var self = this;
    self.fileId = util.guid();
    self.name = ko.observable(file.name);
    self.type = ko.observable(file.type);
    self.size = ko.observable();
    self.fileData = null;
    self.fileSize = ko.observable(file.size / 1024 / 1024);
    self.chunks = 0;
    self.currentChunk = ko.observable();

    var reader = new FileReader();

    // Closure to capture the file information.
    reader.onload = (function (e) {
        self.fileData = e.target.result;
        self.size(self.fileData.length);
        self.chunks = Math.ceil(self.size() / 102400);
        self.sendChunk(1);
    });

    reader.readAsDataURL(file);

    self.percentComplete = ko.computed(function () {
        return self.currentChunk() * 100 / self.chunks;
    }, self);

    self.cancel = function (record) {
        parent.uploads.remove(record);
    };

    self.sendChunk = function (number) {
        var start = (number - 1) * 102400;
        var end = number * 102400;
        self.currentChunk(number);
        var form = {
            fileId: self.fileId,
            name: self.name(),
            fileType: self.type(),
            Size: self.size(),
            FileSize: self.fileSize(),
            chunkNumber: number,
            chunkData: self.fileData.slice(start, end),
            entityTypeValue: parent.entityTypeValue,
            ReferenceId: parent.detail.id,
            ReferenceName: parent.detail.name
        };

        ajax.post('Attachment', JSON.stringify(form)).done(function (response) {
            if (number < self.chunks)
                self.sendChunk(number + 1);
            if (response.id != null) {
                parent.attachments.push(new Attachment(response));
                self.cancel(response);
            }
        });
    };
};

Attachment = function (data) {
    var self = this;
    self.id = ko.observable(data.id);
    self.name = ko.observable(data.name);
    self.fileType = ko.observable(data.fileType);
    self.fileSize = ko.observable(data.fileSize);
    self.fileData = ko.observable(data.fileData);
    self.typeName = ko.observable(data.typeName);
    self.description = ko.observable(data.description).revertable();
    self.tags = ko.observable(data.tags).revertable();
    self.operationTime = ko.observable(moment(data.createdOn).format('MM-DD-YYYY HH:mm:ss'));

    self.description.subscribe(function () {
        var form = {
            Id: self.id(),
            Description: self.description(),
            Tags: self.tags()
        };

        ajax.put('attachment', JSON.stringify(form)).done(function (response) {
            self.description.commit();
            return;
        }).fail(function () {
            self.description.revert();
        });
    });

    self.tags.subscribe(function () {
        var form = {
            Id: self.id(),
            Description: self.description(),
            Tags: self.tags()
        };

        ajax.put('attachment', JSON.stringify(form)).done(function (response) {
            self.tags.commit();
            return;
        }).fail(function () {
            self.tags.revert();
        });
    });
};

ViewModel = function (data) {
    var self = this;

    // for attachment
    self.attachments = ko.observableArray([]);
    $.each(data.attachments, function (row, val) {
        self.attachments.push(new Attachment(val));
    });

    self.deleteAttachmentRecord = function (record) {
        if (!confirm("Are you sure you want to delete this record?")) return;
        ajax.del('attachment', record.id(), { async: false }).done(function () {
            self.attachments.remove(record);
            return;
        });
    };


exports.exec = function (model) {
    console.log(model);
    var viewModel = new ViewModel(model);
    ko.applyBindings(viewModel, document.getElementById('ShowAuditDiv'));
};

return exports;
});

HTML Code:

<div class="row-fluid spacer-bottom fileDragHolder">
    <div class="spacer-bottom"></div>
    <div class="legend">
        Attachments<div class="pull-right">@Html.AttachmentPicker("AC")</div>
    </div>
    <div>
        <div class="row-fluid spacer-bottom">
            <div style="overflow: auto">
                <table class="table table-bordered table-hover table-condensed" data-bind="visible: uploads().length > 0 || attachments().length > 0">
                    <thead>
                        <tr>
                            <th class=" btn btn-primary col-md-2" style="text-align: center">
                                Name
                            </th>
                            <th class="btn btn-primary col-md-1" style="text-align: center">Type</th>
                            <th class="btn btn-primary col-md-1" style="text-align: center">Size (MB)</th>
                            <th class="btn btn-primary col-md-1" style="text-align: center">Upload Time</th>
                            <th class="btn btn-primary col-md-1" style="text-align: center">Tags</th>
                            <th class="btn btn-primary col-md-6" style="text-align: center">Description</th>
                            <th class="btn btn-primary col-md-1" style="text-align: center">Delete</th>
                        </tr>
                    </thead>
                    <tbody>
                        <!-- ko foreach: attachments -->
                        <tr>
                            <td style="text-align: center" class="col-xs-2"><a href="#" data-bind="text: name,attr:{'href':'/attachment/index?id=' + id()}"></a></td>
                            <td style="text-align: center" class="col-xs-1"><span data-bind="text: fileType"></span></td>
                            <td style="text-align: center" class="col-xs-1"><span data-bind="text: fileSize"></span></td>
                            <td style="text-align: center" class="col-xs-2"><span data-bind="text: operationTime"></span></td>
                            <td style="text-align: center" class="col-xs-3"><div contenteditable="true" data-bind="editableText: tags"></div></td>
                            <td style="text-align: center" class="col-xs-4"><div contenteditable="true" data-bind="editableText: description"></div></td>
                            <td style="text-align: center" class="col-xs-1"><button class="btn btn-primary" data-bind="click:$root.deleteAttachmentRecord"><i class="icon-trash"></i></button></td>
                        </tr>
                        <!-- /ko -->
                    </tbody>
                    <tfoot data-bind="visible: uploads().length > 0">
                        <tr>
                            <th colspan="6">Files upload status</th>
                        </tr>
                        <tr>
                            <th>Name</th>
                            <th>Type</th>
                            <th>Size (MB)</th>
                            <th colspan="2">Status</th>
                            <th></th>
                        </tr>
                        <!-- ko foreach: uploads -->
                        <tr>
                            <td><span data-bind="text: name"></span></td>
                            <td><span data-bind="text: type"></span></td>
                            <td><span data-bind="text: fileSize"></span></td>
                            <td colspan="2">
                                <div class="progress">
                                    <div class="progress-bar" data-bind="style: { width: percentComplete() + '%' }"></div>
                                </div>
                            </td>
                            <td style="text-align: center"><button class="btn btn-primary" data-bind="click:cancel"><i class="icon-trash"></i></button></td>
                        </tr>
                        <!-- /ko -->
                    </tfoot>
                </table>
            </div>
            <div data-bind="visible: attachments().length == 0" class="span12" style="margin-left:0">
                <span>No Records found.</span>
            </div>
        </div>

How to negate specific word in regex?

You could either use a negative look-ahead or look-behind:

^(?!.*?bar).*
^(.(?<!bar))*?$

Or use just basics:

^(?:[^b]+|b(?:$|[^a]|a(?:$|[^r])))*$

These all match anything that does not contain bar.

How do I close an Android alertdialog

AlertDialog.Builder builder = new AlertDialog.Builder(this); 
AlertDialog alert = builder.create(); 
alert.show();

The above code works but make sure you make alert a global variable so you can reach it from within the onClick method.

How to Export-CSV of Active Directory Objects?

csvde -f test.csv

This command will perform a CSV dump of every entry in your Active Directory server. You should be able to see the full DN's of users and groups.

You will have to go through that output file and get rid off the unnecessary content.

Difference between "managed" and "unmanaged"

Managed Code

Managed code is what Visual Basic .NET and C# compilers create. It runs on the CLR (Common Language Runtime), which, among other things, offers services like garbage collection, run-time type checking, and reference checking. So, think of it as, "My code is managed by the CLR."

Visual Basic and C# can only produce managed code, so, if you're writing an application in one of those languages you are writing an application managed by the CLR. If you are writing an application in Visual C++ .NET you can produce managed code if you like, but it's optional.

Unmanaged Code

Unmanaged code compiles straight to machine code. So, by that definition all code compiled by traditional C/C++ compilers is 'unmanaged code'. Also, since it compiles to machine code and not an intermediate language it is non-portable.

No free memory management or anything else the CLR provides.

Since you cannot create unmanaged code with Visual Basic or C#, in Visual Studio all unmanaged code is written in C/C++.

Mixing the two

Since Visual C++ can be compiled to either managed or unmanaged code it is possible to mix the two in the same application. This blurs the line between the two and complicates the definition, but it's worth mentioning just so you know that you can still have memory leaks if, for example, you're using a third party library with some badly written unmanaged code.

Here's an example I found by googling:

#using <mscorlib.dll>
using namespace System;

#include "stdio.h"

void ManagedFunction()
{
    printf("Hello, I'm managed in this section\n");
}

#pragma unmanaged
UnmanagedFunction()
{
    printf("Hello, I am unmanaged through the wonder of IJW!\n");
    ManagedFunction();
}

#pragma managed
int main()
{
    UnmanagedFunction();
    return 0;
}

Center a popup window on screen?

Due to the complexity of determining the center of the current screen in a multi-monitor setup, an easier option is to center the pop-up over the parent window. Simply pass the parent window as another parameter:

function popupWindow(url, windowName, win, w, h) {
    const y = win.top.outerHeight / 2 + win.top.screenY - ( h / 2);
    const x = win.top.outerWidth / 2 + win.top.screenX - ( w / 2);
    return win.open(url, windowName, `toolbar=no, location=no, directories=no, status=no, menubar=no, scrollbars=no, resizable=no, copyhistory=no, width=${w}, height=${h}, top=${y}, left=${x}`);
}

Implementation:

popupWindow('google.com', 'test', window, 200, 100);

Spring jUnit Testing properties file

I faced the same issue, spent too much calories searching for the right fix until I decided to settle down with file reading:

Properties configProps = new Properties();
InputStream iStream = new ClassPathResource("myapp-test.properties").getInputStream();
InputStream iStream = getConfigFile();
configProps.load(iStream);

Getting Date or Time only from a DateTime Object

Sometimes you want to have your GridView as simple as:

  <asp:GridView ID="grid" runat="server" />

You don't want to specify any BoundField, you just want to bind your grid to DataReader. The following code helped me to format DateTime in this situation.

protected void Page_Load(object sender, EventArgs e)
{
  grid.RowDataBound += grid_RowDataBound;
  // Your DB access code here...
  // grid.DataSource = cmd.ExecuteReader(CommandBehavior.CloseConnection);
  // grid.DataBind();
}

void grid_RowDataBound(object sender, GridViewRowEventArgs e)
{
  if (e.Row.RowType != DataControlRowType.DataRow)
    return;
  var dt = (e.Row.DataItem as DbDataRecord).GetDateTime(4);
  e.Row.Cells[4].Text = dt.ToString("dd.MM.yyyy");
}

The results shown here. DateTime Formatting

Compilation fails with "relocation R_X86_64_32 against `.rodata.str1.8' can not be used when making a shared object"

Do what the compiler tells you to do, i.e. recompile with -fPIC. To learn what does this flag do and why you need it in this case, see Code Generation Options of the GCC manual.

In brief, the term position independent code (PIC) refers to the generated machine code which is memory address agnostic, i.e. does not make any assumptions about where it was loaded into RAM. Only position independent code is supposed to be included into shared objects (SO) as they should have an ability to dynamically change their location in RAM.

Finally, you can read about it on Wikipedia too.

HTML5 LocalStorage: Checking if a key exists

The MDN documentation shows how the getItem method is implementated:

Object.defineProperty(oStorage, "getItem", {
      value: function (sKey) { return sKey ? this[sKey] : null; },
      writable: false,
      configurable: false,
      enumerable: false
    });

If the value isn't set, it returns null. You are testing to see if it is undefined. Check to see if it is null instead.

if(localStorage.getItem("username") === null){

Select max value of each group

SELECT DISTINCT (t1.ProdId), t1.Quantity FROM Dummy t1 INNER JOIN
       (SELECT ProdId, MAX(Quantity) as MaxQuantity FROM Dummy GROUP BY ProdId) t2
    ON t1.ProdId = t2.ProdId
   AND t1.Quantity = t2.MaxQuantity
 ORDER BY t1.ProdId

this will give you the idea.

Function passed as template argument

Edit: Passing the operator as a reference doesnt work. For simplicity, understand it as a function pointer. You just send the pointer, not a reference. I think you are trying to write something like this.

struct Square
{
    double operator()(double number) { return number * number; }
};

template <class Function>
double integrate(Function f, double a, double b, unsigned int intervals)
{
    double delta = (b - a) / intervals, sum = 0.0;

    while(a < b)
    {
        sum += f(a) * delta;
        a += delta;
    }

    return sum;
}

. .

std::cout << "interval : " << i << tab << tab << "intgeration = "
 << integrate(Square(), 0.0, 1.0, 10) << std::endl;

Remove a marker from a GoogleMap

If you use Kotlin language you just add this code:

Create global variables of GoogleMap and Marker types.

I use variable marker to make variable marker value can change directly

private lateinit var map: GoogleMap
private lateinit var marker: Marker

And I use this function/method to add the marker on my map:

private fun placeMarkerOnMap(location: LatLng) {
    val markerOptions = MarkerOptions().position(location)
    val titleStr = getAddress(location)
    markerOptions.title(titleStr)
    marker = map.addMarker(markerOptions)
}

After I create the function I place this code on the onMapReady() to remove the marker and create a new one:

map.setOnMapClickListener { location ->
        map.clear()
        marker.remove()
        placeMarkerOnMap(location)
    }

It's bonus if you want to display the address location when you click the marker add this code to hide and show the marker address but you need a method to get the address location. I got the code from this post: How to get complete address from latitude and longitude?

map.setOnMarkerClickListener {marker ->
        if (marker.isInfoWindowShown){
            marker.hideInfoWindow()
        }else{
            marker.showInfoWindow()
        }
        true
    }

How do I create a timer in WPF?

Adding to the above. You use the Dispatch timer if you want the tick events marshalled back to the UI thread. Otherwise I would use System.Timers.Timer.

How to simplify a null-safe compareTo() implementation?

If you want a simple Hack:

arrlist.sort((o1, o2) -> {
    if (o1.getName() == null) o1.setName("");
    if (o2.getName() == null) o2.setName("");

    return o1.getName().compareTo(o2.getName());
})

if you want put nulls to end of the list just change this in above metod

return o2.getName().compareTo(o1.getName());

Regex select all text between tags

preg_match_all(/<pre>([^>]*?)<\/pre>/,$content,$matches) this regex will select everyting between tag. no matter is it in new line(work with multiline.

convert base64 to image in javascript/jquery

Html

<img id="imgElem"></img>

Js

string baseStr64="/9j/4AAQSkZJRgABAQE...";
imgElem.setAttribute('src', "data:image/jpg;base64," + baseStr64);

How can I enable the Windows Server Task Scheduler History recording?

Here is where I found it on a Windows 2008R2 server. Elevated Task Scheduler Click on "Task Scheduler Library" It appears as an option on the right hand "Actions" panel.

enter image description here

How to run Visual Studio post-build events for debug build only

In Visual Studio 2012 you have to use (I think in Visual Studio 2010, too)

if $(Configuration) == Debug xcopy

$(ConfigurationName) was listed as a macro, but it wasn't assigned.

Enter image description here

Compare: Macros for Build Commands and Properties

What's the C# equivalent to the With statement in VB?

Aside from object initializers (usable only in constructor calls), the best you can get is:

var it = Stuff.Elements.Foo;
it.Name = "Bob Dylan";
it.Age = 68;
...

Maximum length of HTTP GET request

Technically, I have seen HTTP GET will have issues if the URL length goes beyond 2000 characters. In that case, it's better to use HTTP POST or split the URL.

HTML checkbox onclick called in Javascript

Label without an onclick will behave as you would expect. It changes the input. What you relly want is to execute selectAll() when you click on a label, right? Then only add select all to the label onclick. Or wrap the input into the the label and assign onclick only for the label

<label for="check_all_1" onclick="selectAll(document.wizard_form, this);">
  <input type="checkbox" id="check_all_1" name="check_all_1" title="Select All">
  Select All
</label>

JS how to cache a variable

Use localStorage for that. It's persistent over sessions.

Writing :

localStorage['myKey'] = 'somestring'; // only strings

Reading :

var myVar = localStorage['myKey'] || 'defaultValue';

If you need to store complex structures, you might serialize them in JSON. For example :

Reading :

var stored = localStorage['myKey'];
if (stored) myVar = JSON.parse(stored);
else myVar = {a:'test', b: [1, 2, 3]};

Writing :

localStorage['myKey'] = JSON.stringify(myVar);

Note that you may use more than one key. They'll all be retrieved by all pages on the same domain.

Unless you want to be compatible with IE7, you have no reason to use the obsolete and small cookies.

Play infinitely looping video on-load in HTML5

As of April 2018, Chrome (along with several other major browsers) now require the muted attribute too.

Therefore, you should use

<video width="320" height="240" autoplay loop muted>
  <source src="movie.mp4" type="video/mp4" />
</video>

UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position 23: ordinal not in range(128)

You are encoding to UTF-8, then re-encoding to UTF-8. Python can only do this if it first decodes again to Unicode, but it has to use the default ASCII codec:

>>> u'ñ'
u'\xf1'
>>> u'ñ'.encode('utf8')
'\xc3\xb1'
>>> u'ñ'.encode('utf8').encode('utf8')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position 0: ordinal not in range(128)

Don't keep encoding; leave encoding to UTF-8 to the last possible moment instead. Concatenate Unicode values instead.

You can use str.join() (or, rather, unicode.join()) here to concatenate the three values with dashes in between:

nombre = u'-'.join(fabrica, sector, unidad)
return nombre.encode('utf-8')

but even encoding here might be too early.

Rule of thumb: decode the moment you receive the value (if not Unicode values supplied by an API already), encode only when you have to (if the destination API does not handle Unicode values directly).

Redirecting a page using Javascript, like PHP's Header->Location

The PHP code is executed on the server, so your redirect is executed before the browser even sees the JavaScript.

You need to do the redirect in JavaScript too

$('.entry a:first').click(function()
{
    window.location.replace("http://www.google.com");
});

Formatting MM/DD/YYYY dates in textbox in VBA

I never suggest using Textboxes or Inputboxes to accept dates. So many things can go wrong. I cannot even suggest using the Calendar Control or the Date Picker as for that you need to register the mscal.ocx or mscomct2.ocx and that is very painful as they are not freely distributable files.

Here is what I recommend. You can use this custom made calendar to accept dates from the user

PROS:

  1. You don't have to worry about user inputting wrong info
  2. You don't have to worry user pasting in the textbox
  3. You don't have to worry about writing any major code
  4. Attractive GUI
  5. Can be easily incorporated in your application
  6. Doesn't use any controls for which you need to reference any libraries like mscal.ocx or mscomct2.ocx

CONS:

Ummm...Ummm... Can't think of any...

HOW TO USE IT (File missing from my dropbox. Please refer to the bottom of the post for an upgraded version of the calendar)

  1. Download the Userform1.frm and Userform1.frx from here.
  2. In your VBA, simply import Userform1.frm as shown in the image below.

Importing the form

enter image description here

RUNNING IT

You can call it in any procedure. For example

Sub Sample()
    UserForm1.Show
End Sub

SCREEN SHOTS IN ACTION

enter image description here

NOTE: You may also want to see Taking Calendar to new level

How to upload images into MySQL database using PHP code

Just few more details:

  • Add mysql field

`image` blob

  • Get data from image

$image = addslashes(file_get_contents($_FILES['image']['tmp_name']));

  • Insert image data into db

$sql = "INSERT INTO `product_images` (`id`, `image`) VALUES ('1', '{$image}')";

  • Show image to the web

<img src="data:image/png;base64,'.base64_encode($row['image']).'">

  • End

Set equal width of columns in table layout in Android

Change android:stretchColumns value to *.

Value 0 means stretch the first column. Value 1 means stretch the second column and so on.

Value * means stretch all the columns.

Each for object?

for(var key in object) {
   console.log(object[key]);
}

What is the (best) way to manage permissions for Docker shared volumes?

UPDATE 2016-03-02: As of Docker 1.9.0, Docker has named volumes which replace data-only containers. The answer below, as well as my linked blog post, still has value in the sense of how to think about data inside docker but consider using named volumes to implement the pattern described below rather than data containers.


I believe the canonical way to solve this is by using data-only containers. With this approach, all access to the volume data is via containers that use -volumes-from the data container, so the host uid/gid doesn't matter.

For example, one use case given in the documentation is backing up a data volume. To do this another container is used to do the backup via tar, and it too uses -volumes-from in order to mount the volume. So I think the key point to grok is: rather than thinking about how to get access to the data on the host with the proper permissions, think about how to do whatever you need -- backups, browsing, etc. -- via another container. The containers themselves need to use consistent uid/gids, but they don't need to map to anything on the host, thereby remaining portable.

This is relatively new for me as well but if you have a particular use case feel free to comment and I'll try to expand on the answer.

UPDATE: For the given use case in the comments, you might have an image some/graphite to run graphite, and an image some/graphitedata as the data container. So, ignoring ports and such, the Dockerfile of image some/graphitedata is something like:

FROM debian:jessie
# add our user and group first to make sure their IDs get assigned consistently, regardless of other deps added later
RUN groupadd -r graphite \
  && useradd -r -g graphite graphite
RUN mkdir -p /data/graphite \
  && chown -R graphite:graphite /data/graphite
VOLUME /data/graphite
USER graphite
CMD ["echo", "Data container for graphite"]

Build and create the data container:

docker build -t some/graphitedata Dockerfile
docker run --name graphitedata some/graphitedata

The some/graphite Dockerfile should also get the same uid/gids, therefore it might look something like this:

FROM debian:jessie
# add our user and group first to make sure their IDs get assigned consistently, regardless of other deps added later
RUN groupadd -r graphite \
  && useradd -r -g graphite graphite
# ... graphite installation ...
VOLUME /data/graphite
USER graphite
CMD ["/bin/graphite"]

And it would be run as follows:

docker run --volumes-from=graphitedata some/graphite

Ok, now that gives us our graphite container and associated data-only container with the correct user/group (note you could re-use the some/graphite container for the data container as well, overriding the entrypoing/cmd when running it, but having them as separate images IMO is clearer).

Now, lets say you want to edit something in the data folder. So rather than bind mounting the volume to the host and editing it there, create a new container to do that job. Lets call it some/graphitetools. Lets also create the appropriate user/group, just like the some/graphite image.

FROM debian:jessie
# add our user and group first to make sure their IDs get assigned consistently, regardless of other deps added later
RUN groupadd -r graphite \
  && useradd -r -g graphite graphite
VOLUME /data/graphite
USER graphite
CMD ["/bin/bash"]

You could make this DRY by inheriting from some/graphite or some/graphitedata in the Dockerfile, or instead of creating a new image just re-use one of the existing ones (overriding entrypoint/cmd as necessary).

Now, you simply run:

docker run -ti --rm --volumes-from=graphitedata some/graphitetools

and then vi /data/graphite/whatever.txt. This works perfectly because all the containers have the same graphite user with matching uid/gid.

Since you never mount /data/graphite from the host, you don't care how the host uid/gid maps to the uid/gid defined inside the graphite and graphitetools containers. Those containers can now be deployed to any host, and they will continue to work perfectly.

The neat thing about this is that graphitetools could have all sorts of useful utilities and scripts, that you can now also deploy in a portable manner.

UPDATE 2: After writing this answer, I decided to write a more complete blog post about this approach. I hope it helps.

UPDATE 3: I corrected this answer and added more specifics. It previously contained some incorrect assumptions about ownership and perms -- the ownership is usually assigned at volume creation time i.e. in the data container, because that is when the volume is created. See this blog. This is not a requirement though -- you can just use the data container as a "reference/handle" and set the ownership/perms in another container via chown in an entrypoint, which ends with gosu to run the command as the correct user. If anyone is interested in this approach, please comment and I can provide links to a sample using this approach.

What is the difference between json.dump() and json.dumps() in python?

In memory usage and speed.

When you call jsonstr = json.dumps(mydata) it first creates a full copy of your data in memory and only then you file.write(jsonstr) it to disk. So this is a faster method but can be a problem if you have a big piece of data to save.

When you call json.dump(mydata, file) -- without 's', new memory is not used, as the data is dumped by chunks. But the whole process is about 2 times slower.

Source: I checked the source code of json.dump() and json.dumps() and also tested both the variants measuring the time with time.time() and watching the memory usage in htop.

How to get the current working directory using python 3?

It seems that IDLE changes its current working dir to location of the script that is executed, while when running the script using cmd doesn't do that and it leaves CWD as it is.

To change current working dir to the one containing your script you can use:

import os
os.chdir(os.path.dirname(__file__))
print(os.getcwd())

The __file__ variable is available only if you execute script from file, and it contains path to the file. More on it here: Python __file__ attribute absolute or relative?

How to get PID of process I've just started within java program?

Using JNA, supporting old and new JVM to get process id

public static long getProcessId(Process p){
    long pid = -1;
    try {
      pid = p.pid();
    } catch (NoSuchMethodError e) {
        try
        {
            //for windows
            if (p.getClass().getName().equals("java.lang.Win32Process") || p.getClass().getName().equals("java.lang.ProcessImpl")) {
                Field f = p.getClass().getDeclaredField("handle");
                f.setAccessible(true);              
                long handl = f.getLong(p);
                Kernel32 kernel = Kernel32.INSTANCE;
                WinNT.HANDLE hand = new WinNT.HANDLE();
                hand.setPointer(Pointer.createConstant(handl));
                pid = kernel.GetProcessId(hand);
                f.setAccessible(false);
            }
            //for unix based operating systems
            else if (p.getClass().getName().equals("java.lang.UNIXProcess")) 
            {
                Field f = p.getClass().getDeclaredField("pid");
                f.setAccessible(true);
                pid = f.getLong(p);
                f.setAccessible(false);
            }
        }
        catch(Exception ex)
        {
            pid = -1;
        }
    }        
    return pid;
}

how to use "AND", "OR" for RewriteCond on Apache?

This is an interesting question and since it isn't explained very explicitly in the documentation I'll answer this by going through the sourcecode of mod_rewrite; demonstrating a big benefit of open-source.

In the top section you'll quickly spot the defines used to name these flags:

#define CONDFLAG_NONE               1<<0
#define CONDFLAG_NOCASE             1<<1
#define CONDFLAG_NOTMATCH           1<<2
#define CONDFLAG_ORNEXT             1<<3
#define CONDFLAG_NOVARY             1<<4

and searching for CONDFLAG_ORNEXT confirms that it is used based on the existence of the [OR] flag:

else if (   strcasecmp(key, "ornext") == 0
         || strcasecmp(key, "OR") == 0    ) {
    cfg->flags |= CONDFLAG_ORNEXT;
}

The next occurrence of the flag is the actual implementation where you'll find the loop that goes through all the RewriteConditions a RewriteRule has, and what it basically does is (stripped, comments added for clarity):

# loop through all Conditions that precede this Rule
for (i = 0; i < rewriteconds->nelts; ++i) {
    rewritecond_entry *c = &conds[i];

    # execute the current Condition, see if it matches
    rc = apply_rewrite_cond(c, ctx);

    # does this Condition have an 'OR' flag?
    if (c->flags & CONDFLAG_ORNEXT) {
        if (!rc) {
            /* One condition is false, but another can be still true. */
            continue;
        }
        else {
            /* skip the rest of the chained OR conditions */
            while (   i < rewriteconds->nelts
                   && c->flags & CONDFLAG_ORNEXT) {
                c = &conds[++i];
            }
        }
    }
    else if (!rc) {
        return 0;
    }
}

You should be able to interpret this; it means that OR has a higher precedence, and your example indeed leads to if ( (A OR B) AND (C OR D) ). If you would, for example, have these Conditions:

RewriteCond A [or]
RewriteCond B [or]
RewriteCond C
RewriteCond D

it would be interpreted as if ( (A OR B OR C) and D ).

Vibrate and Sound defaults on notification

// set notification audio

builder.setDefaults(Notification.DEFAULT_VIBRATE);
//OR 
builder.setDefaults(Notification.DEFAULT_SOUND);

SwiftUI - How do I change the background color of a View?

Would this solution work?:

add following line to SceneDelegate: window.rootViewController?.view.backgroundColor = .black

func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
        if let windowScene = scene as? UIWindowScene {

                window.rootViewController?.view.backgroundColor = .black
}

what is .subscribe in angular?

subscribe() -Invokes an execution of an Observable and registers Observer handlers for notifications it will emit. -Observable- representation of any set of values over any amount of time.

How to find controls in a repeater header or footer

As noted in the comments, this only works AFTER you've DataBound your repeater.

To find a control in the header:

lblControl = repeater1.Controls[0].Controls[0].FindControl("lblControl");

To find a control in the footer:

lblControl = repeater1.Controls[repeater1.Controls.Count - 1].Controls[0].FindControl("lblControl");

With extension methods

public static class RepeaterExtensionMethods
{
    public static Control FindControlInHeader(this Repeater repeater, string controlName)
    {
        return repeater.Controls[0].Controls[0].FindControl(controlName);
    }

    public static Control FindControlInFooter(this Repeater repeater, string controlName)
    {
        return repeater.Controls[repeater.Controls.Count - 1].Controls[0].FindControl(controlName);
    }
}

COUNT(*) vs. COUNT(1) vs. COUNT(pk): which is better?

Bottom Line

Use either COUNT(field) or COUNT(*), and stick with it consistently, and if your database allows COUNT(tableHere) or COUNT(tableHere.*), use that.

In short, don't use COUNT(1) for anything. It's a one-trick pony, which rarely does what you want, and in those rare cases is equivalent to count(*)

Use count(*) for counting

Use * for all your queries that need to count everything, even for joins, use *

SELECT boss.boss_id, COUNT(subordinate.*)
FROM boss
LEFT JOIN subordinate on subordinate.boss_id = boss.boss_id
GROUP BY boss.id

But don't use COUNT(*) for LEFT joins, as that will return 1 even if the subordinate table doesn't match anything from parent table

SELECT boss.boss_id, COUNT(*)
FROM boss
LEFT JOIN subordinate on subordinate.boss_id = boss.boss_id
GROUP BY boss.id

Don't be fooled by those advising that when using * in COUNT, it fetches entire row from your table, saying that * is slow. The * on SELECT COUNT(*) and SELECT * has no bearing to each other, they are entirely different thing, they just share a common token, i.e. *.

An alternate syntax

In fact, if it is not permitted to name a field as same as its table name, RDBMS language designer could give COUNT(tableNameHere) the same semantics as COUNT(*). Example:

For counting rows we could have this:

SELECT COUNT(emp) FROM emp

And they could make it simpler:

SELECT COUNT() FROM emp

And for LEFT JOINs, we could have this:

SELECT boss.boss_id, COUNT(subordinate)
FROM boss
LEFT JOIN subordinate on subordinate.boss_id = boss.boss_id
GROUP BY boss.id

But they cannot do that (COUNT(tableNameHere)) since SQL standard permits naming a field with the same name as its table name:

CREATE TABLE fruit -- ORM-friendly name
(
fruit_id int NOT NULL,
fruit varchar(50), /* same name as table name, 
                and let's say, someone forgot to put NOT NULL */
shape varchar(50) NOT NULL,
color varchar(50) NOT NULL
)

Counting with null

And also, it is not a good practice to make a field nullable if its name matches the table name. Say you have values 'Banana', 'Apple', NULL, 'Pears' on fruit field. This will not count all rows, it will only yield 3, not 4

SELECT count(fruit) FROM fruit

Though some RDBMS do that sort of principle (for counting the table's rows, it accepts table name as COUNT's parameter), this will work in Postgresql (if there is no subordinate field in any of the two tables below, i.e. as long as there is no name conflict between field name and table name):

SELECT boss.boss_id, COUNT(subordinate)
FROM boss
LEFT JOIN subordinate on subordinate.boss_id = boss.boss_id
GROUP BY boss.id

But that could cause confusion later if we will add a subordinate field in the table, as it will count the field(which could be nullable), not the table rows.

So to be on the safe side, use:

SELECT boss.boss_id, COUNT(subordinate.*)
FROM boss
LEFT JOIN subordinate on subordinate.boss_id = boss.boss_id
GROUP BY boss.id

count(1): The one-trick pony

In particular to COUNT(1), it is a one-trick pony, it works well only on one table query:

SELECT COUNT(1) FROM tbl

But when you use joins, that trick won't work on multi-table queries without its semantics being confused, and in particular you cannot write:

-- count the subordinates that belongs to boss
SELECT boss.boss_id, COUNT(subordinate.1)
FROM boss
LEFT JOIN subordinate on subordinate.boss_id = boss.boss_id
GROUP BY boss.id

So what's the meaning of COUNT(1) here?

SELECT boss.boss_id, COUNT(1)
FROM boss
LEFT JOIN subordinate on subordinate.boss_id = boss.boss_id
GROUP BY boss.id

Is it this...?

-- counting all the subordinates only
SELECT boss.boss_id, COUNT(subordinate.boss_id)
FROM boss
LEFT JOIN subordinate on subordinate.boss_id = boss.boss_id
GROUP BY boss.id

Or this...?

-- or is that COUNT(1) will also count 1 for boss regardless if boss has a subordinate
SELECT boss.boss_id, COUNT(*)
FROM boss
LEFT JOIN subordinate on subordinate.boss_id = boss.boss_id
GROUP BY boss.id

By careful thought, you can infer that COUNT(1) is the same as COUNT(*), regardless of type of join. But for LEFT JOINs result, we cannot mold COUNT(1) to work as: COUNT(subordinate.boss_id), COUNT(subordinate.*)

So just use either of the following:

-- count the subordinates that belongs to boss
SELECT boss.boss_id, COUNT(subordinate.boss_id)
FROM boss
LEFT JOIN subordinate on subordinate.boss_id = boss.boss_id
GROUP BY boss.id

Works on Postgresql, it's clear that you want to count the cardinality of the set

-- count the subordinates that belongs to boss
SELECT boss.boss_id, COUNT(subordinate.*)
FROM boss
LEFT JOIN subordinate on subordinate.boss_id = boss.boss_id
GROUP BY boss.id

Another way to count the cardinality of the set, very English-like (just don't make a column with a name same as its table name) : http://www.sqlfiddle.com/#!1/98515/7

select boss.boss_name, count(subordinate)
from boss
left join subordinate on subordinate.boss_code = boss.boss_code
group by boss.boss_name

You cannot do this: http://www.sqlfiddle.com/#!1/98515/8

select boss.boss_name, count(subordinate.1)
from boss
left join subordinate on subordinate.boss_code = boss.boss_code
group by boss.boss_name

You can do this, but this produces wrong result: http://www.sqlfiddle.com/#!1/98515/9

select boss.boss_name, count(1)
from boss
left join subordinate on subordinate.boss_code = boss.boss_code
group by boss.boss_name

Java: How to check if object is null?

DIY

private boolean isNull(Object obj) {
    return obj == null;
}

Drawable drawable = Common.getDrawableFromUrl(this, product.getMapPath());
if (isNull(drawable)) {
    drawable = getRandomDrawable();
}

The matching wildcard is strict, but no declaration can be found for element 'tx:annotation-driven'

FWIW I had this same issue. Turned out my xsi:schemaLocation entries were incorrect, so I went to the official docs and pasted theirs into mine:

http://docs.spring.io/spring/docs/current/spring-framework-reference/html/transaction.html section 16.5.6

I had to add a couple more but that was ok. Next up is to find out why this fixed the problem...

React-Router: No Not Found Route?

DefaultRoute and NotFoundRoute were removed in react-router 1.0.0.

I'd like to emphasize that the default route with the asterisk has to be last in the current hierarchy level to work. Otherwise it will override all other routes that appear after it in the tree because it's first and matches every path.

For react-router 1, 2 and 3

If you want to display a 404 and keep the path (Same functionality as NotFoundRoute)

<Route path='*' exact={true} component={My404Component} />

If you want to display a 404 page but change the url (Same functionality as DefaultRoute)

<Route path='/404' component={My404Component} />
<Redirect from='*' to='/404' />

Example with multiple levels:

<Route path='/' component={Layout} />
    <IndexRoute component={MyComponent} />
    <Route path='/users' component={MyComponent}>
        <Route path='user/:id' component={MyComponent} />
        <Route path='*' component={UsersNotFound} />
    </Route>
    <Route path='/settings' component={MyComponent} />
    <Route path='*' exact={true} component={GenericNotFound} />
</Route>

For react-router 4 and 5

Keep the path

<Switch>
    <Route exact path="/users" component={MyComponent} />
    <Route component={GenericNotFound} />
</Switch>

Redirect to another route (change url)

<Switch>
    <Route path="/users" component={MyComponent} />
    <Route path="/404" component={GenericNotFound} />
    <Redirect to="/404" />
</Switch>

The order matters!

I need to learn Web Services in Java. What are the different types in it?

The SOAP WS supports both remote procedure call (i.e. RPC) and message oriented middle-ware (MOM) integration styles. The Restful Web Service supports only RPC integration style.

The SOAP WS is transport protocol neutral. Supports multiple protocols like HTTP(S), Messaging, TCP, UDP SMTP, etc. The REST is transport protocol specific. Supports only HTTP or HTTPS protocols.

The SOAP WS permits only XML data format.You define operations, which tunnels through the POST. The focus is on accessing the named operations and exposing the application logic as a service. The REST permits multiple data formats like XML, JSON data, text, HTML, etc. Any browser can be used because the REST approach uses the standard GET, PUT, POST, and DELETE Web operations. The focus is on accessing the named resources and exposing the data as a service. REST has AJAX support. It can use the XMLHttpRequest object. Good for stateless CRUD (Create, Read, Update, and Delete) operations. GET - represent() POST - acceptRepresention() PUT - storeRepresention() DELETE - removeRepresention()

SOAP based reads cannot be cached. REST based reads can be cached. Performs and scales better. SOAP WS supports both SSL security and WS-security, which adds some enterprise security features like maintaining security right up to the point where it is needed, maintaining identities through intermediaries and not just point to point SSL only, securing different parts of the message with different security algorithms, etc. The REST supports only point-to-point SSL security. The SSL encrypts the whole message, whether all of it is sensitive or not. The SOAP has comprehensive support for both ACID based transaction management for short-lived transactions and compensation based transaction management for long-running transactions. It also supports two-phase commit across distributed resources. The REST supports transactions, but it is neither ACID compliant nor can provide two phase commit across distributed transactional resources as it is limited by its HTTP protocol.

The SOAP has success or retry logic built in and provides end-to-end reliability even through SOAP intermediaries. REST does not have a standard messaging system, and expects clients invoking the service to deal with communication failures by retrying.

source http://java-success.blogspot.in/2012/02/java-web-services-interview-questions.html

Calling functions in a DLL from C++

You can either go the LoadLibrary/GetProcAddress route (as Harper mentioned in his answer, here's link to the run-time dynamic linking MSDN sample again) or you can link your console application to the .lib produced from the DLL project and include the hea.h file with the declaration of your function (as described in the load-time dynamic linking MSDN sample)

In both cases, you need to make sure your DLL exports the function you want to call properly. The easiest way to do it is by using __declspec(dllexport) on the function declaration (as shown in the creating a simple dynamic-link library MSDN sample), though you can do it also through the corresponding .def file in your DLL project.

For more information on the topic of DLLs, you should browse through the MSDN About Dynamic-Link Libraries topic.

Convert DateTime to a specified Format

Easy peasy:

var date = DateTime.Parse("14/11/2011"); // may need some Culture help here
Console.Write(date.ToString("yyyy-MM-dd"));

Take a look at DateTime.ToString() method, Custom Date and Time Format Strings and Standard Date and Time Format Strings

string customFormattedDateTimeString = DateTime.Now.ToString("yyyy-MM-dd");