Programs & Examples On #Google ranking

How to check if running in Cygwin, Mac or Linux?

Windows Subsystem for Linux did not exist when this question was asked. It gave these results in my test:

uname -s -> Linux
uname -o -> GNU/Linux
uname -r -> 4.4.0-17763-Microsoft

This means that you need uname -r to distinguish it from native Linux.

Emulate a 403 error page

I understand you have a scenario with ErrorDocument already defined within your apache conf or .htaccess and want to make those pages appear when manually sending a 4xx status code via php.

Unfortunately this is not possible with common methods because php sends header directly to user's browser (not to Apache web server) whereas ErrorDocument is a display handler for http status generated from Apache.

How to sort a Pandas DataFrame by index?

Slightly more compact:

df = pd.DataFrame([1, 2, 3, 4, 5], index=[100, 29, 234, 1, 150], columns=['A'])
df = df.sort_index()
print(df)

Note:

How to convert Windows end of line in Unix end of line (CR/LF to LF)

In order to overcome

Ambiguous output in step `CR-LF..data'

simply solution might be to add -f flag to force conversion.

How do I escape a percentage sign in T-SQL?

In MySQL,

WHERE column_name LIKE '%|%%' ESCAPE '|'

Access IP Camera in Python OpenCV

Getting the correct URL for your camera seems to be the actual challenge! I'm putting my working URL here, it might help someone. The camera is EZVIZ C1C with exact model cs-c1c-d0-1d2wf. The working URL is

rtsp://admin:[email protected]/h264_stream

where SZGBZT is the verification code found at the bottom of the camera. admin is always admin regardless of any settings or users you have.

The final code will be

video_capture = cv2.VideoCapture('rtsp://admin:[email protected]/h264_stream')

Regex for parsing directory and filename

In languages that support regular expressions with non-capturing groups:

((?:[^/]*/)*)(.*)

I'll explain the gnarly regex by exploding it...

(
  (?:
    [^/]*
    /
  )
  *
)
(.*)

What the parts mean:

(  -- capture group 1 starts
  (?:  -- non-capturing group starts
    [^/]*  -- greedily match as many non-directory separators as possible
    /  -- match a single directory-separator character
  )  -- non-capturing group ends
  *  -- repeat the non-capturing group zero-or-more times
)  -- capture group 1 ends
(.*)  -- capture all remaining characters in group 2

Example

To test the regular expression, I used the following Perl script...

#!/usr/bin/perl -w

use strict;
use warnings;

sub test {
  my $str = shift;
  my $testname = shift;

  $str =~ m#((?:[^/]*/)*)(.*)#;

  print "$str -- $testname\n";
  print "  1: $1\n";
  print "  2: $2\n\n";
}

test('/var/log/xyz/10032008.log', 'absolute path');
test('var/log/xyz/10032008.log', 'relative path');
test('10032008.log', 'filename-only');
test('/10032008.log', 'file directly under root');

The output of the script...

/var/log/xyz/10032008.log -- absolute path
  1: /var/log/xyz/
  2: 10032008.log

var/log/xyz/10032008.log -- relative path
  1: var/log/xyz/
  2: 10032008.log

10032008.log -- filename-only
  1:
  2: 10032008.log

/10032008.log -- file directly under root
  1: /
  2: 10032008.log

How do I remove blue "selected" outline on buttons?

This is an issue in the Chrome family and has been there forever.

A bug has been raised https://bugs.chromium.org/p/chromium/issues/detail?id=904208

It can be shown here: https://codepen.io/anon/pen/Jedvwj as soon as you add a border to anything button-like (say role="button" has been added to a tag for example) Chrome messes up and sets the focus state when you click with your mouse. You should see that outline only on keyboard tab-press.

I highly recommend using this fix: https://github.com/wicg/focus-visible.

Just do the following

npm install --save focus-visible

Add the script to your html:

<script src="/node_modules/focus-visible/dist/focus-visible.min.js"></script>

or import into your main entry file if using webpack or something similar:

import 'focus-visible/dist/focus-visible.min';

then put this in your css file:

// hide the focus indicator if element receives focus via mouse, but show on keyboard focus (on tab).
.js-focus-visible :focus:not(.focus-visible) {
  outline: none;
}

// Define a strong focus indicator for keyboard focus.
// If you skip this then the browser's default focus indicator will display instead
// ideally use outline property for those users using windows high contrast mode
.js-focus-visible .focus-visible {
  outline: magenta auto 5px;
}

You can just set:

button:focus {outline:0;}

but if you have a large number of users, you're disadvantaging those who cannot use mice or those who just want to use their keyboard for speed.

jQuery changing style of HTML element

Use this:

$('#navigation ul li').css('display', 'inline-block');

Also, as others have stated, if you want to make multiple css changes at once, that's when you would add the curly braces (for object notation), and it would look something like this (if you wanted to change, say, 'background-color' and 'position' in addition to 'display'):

$('#navigation ul li').css({'display': 'inline-block', 'background-color': '#fff', 'position': 'relative'}); //The specific CSS changes after the first one, are, of course, just examples.

Windows command for file size only

This is not exactly what you were asking about and it can only be used from the command line (and may be useless in a batch file), but one quick way to check file size is just to use dir:

> dir Microsoft.WindowsAzure.Storage.xml

Results in:

Directory of C:\PathToTheFile

08/10/2015  10:57 AM         2,905,897 Microsoft.WindowsAzure.Storage.xml
               1 File(s)      2,905,897 bytes
               0 Dir(s)  759,192,064,000 bytes free

Why use Ruby's attr_accessor, attr_reader and attr_writer?

All of the answers above are correct; attr_reader and attr_writer are more convenient to write than manually typing the methods they are shorthands for. Apart from that they offer much better performance than writing the method definition yourself. For more info see slide 152 onwards from this talk (PDF) by Aaron Patterson.

How to disable spring security for particular url

I have a better way:

http
    .authorizeRequests()
    .antMatchers("/api/v1/signup/**").permitAll()
    .anyRequest().authenticated()

Format / Suppress Scientific Notation from Python Pandas Aggregation Results

Here is another way of doing it, similar to Dan Allan's answer but without the lambda function:

>>> pd.options.display.float_format = '{:.2f}'.format
>>> Series(np.random.randn(3))
0    0.41
1    0.99
2    0.10

or

>>> pd.set_option('display.float_format', '{:.2f}'.format)

Retrieve the maximum length of a VARCHAR column in SQL Server

SELECT MAX(LEN(Desc)) as MaxLen FROM table

Python if-else short-hand

Try this:

x = a > b and 10 or 11

This is a sample of execution:

>>> a,b=5,7
>>> x = a > b and 10 or 11
>>> print x
11

splitting a string into an array in C++ without using vector

Here's a suggestion: use two indices into the string, say start and end. start points to the first character of the next string to extract, end points to the character after the last one belonging to the next string to extract. start starts at zero, end gets the position of the first char after start. Then you take the string between [start..end) and add that to your array. You keep going until you hit the end of the string.

How to disable all div content

Another way, in jQuery, would be to get the inner height, inner width and positioning of the containing DIV, and simply overlay another DIV, transparent, over the top the same size. This will work on all elements inside that container, instead of only the inputs.

Remember though, with JS disabled, you'll still be able to use the DIVs inputs/content. The same goes with the above answers too.

How to resolve 'npm should be run outside of the node repl, in your normal shell'

As mscdex said NPM comes with the nodejs msi installed file. I happened to just install the node js installer (standalone). To separately add NPM I followed following step

  1. Download the latest zip file of NPM from here.
  2. Extract it in the same file as that of node js installer.
  3. If you have added the directory containing to node js installer to PATH env variable then now even npm should be a recognized command.

Delete many rows from a table using id in Mysql

The best way is to use IN statement :

DELETE from tablename WHERE id IN (1,2,3,...,254);

You can also use BETWEEN if you have consecutive IDs :

DELETE from tablename WHERE id BETWEEN 1 AND 254;

You can of course limit for some IDs using other WHERE clause :

DELETE from tablename WHERE id BETWEEN 1 AND 254 AND id<>10;

How to allow users to check for the latest app version from inside the app?

I did using in-app updates. This will only with devices running Android 5.0 (API level 21) or higher,

Could not find or load main class with a Jar File

I know this is an old question, but I had this problem recently and none of the answers helped me. However, Corral's comment on Ryan Atkinson's answer did tip me off to the problem.

I had all my compiled class files in target/classes, which are not packages in my case. I was trying to package it with jar cvfe App.jar target/classes App, from the root directory of my project, as my App class was in the default unnamed package.

This doesn't work, as the newly created App.jar will have the class App.class in the directory target/classes. If you try to run this jar with java -jar App.jar, it will complain that it cannot find the App class. This is because the packages inside App.jar don't match the actual packages in the project.

This could be solved by creating the jar directly from the target/classes directory, using jar cvfe App.jar . App. This is rather cumbersome in my opinion.

The simple solution is to list the folders you want to add with the -C option instead of using the default way of listing folders. So, in my case, the correct command is java cvfe App.jar App -C target/classes .. This will directly add all files in the target/classes directory to the root of App.jar, thus solving the problem.

Styling Google Maps InfoWindow

You could use a css class too.

$('#hook').parent().parent().parent().siblings().addClass("class_name");

Good day!

How to get response as String using retrofit without using GSON or any other library in android

** Update ** A scalars converter has been added to retrofit that allows for a String response with less ceremony than my original answer below.

Example interface --

public interface GitHubService {
    @GET("/users/{user}")
    Call<String> listRepos(@Path("user") String user);
}

Add the ScalarsConverterFactory to your retrofit builder. Note: If using ScalarsConverterFactory and another factory, add the scalars factory first.

Retrofit retrofit = new Retrofit.Builder()
    .baseUrl(BASE_URL)
    .addConverterFactory(ScalarsConverterFactory.create())
    // add other factories here, if needed.
    .build();

You will also need to include the scalars converter in your gradle file --

implementation 'com.squareup.retrofit2:converter-scalars:2.1.0'

--- Original Answer (still works, just more code) ---

I agree with @CommonsWare that it seems a bit odd that you want to intercept the request to process the JSON yourself. Most of the time the POJO has all the data you need, so no need to mess around in JSONObject land. I suspect your specific problem might be better solved using a custom gson TypeAdapter or a retrofit Converter if you need to manipulate the JSON. However, retrofit provides more the just JSON parsing via Gson. It also manages a lot of the other tedious tasks involved in REST requests. Just because you don't want to use one of the features, doesn't mean you have to throw the whole thing out. There are times you just want to get the raw stream, so here is how to do it -

First, if you are using Retrofit 2, you should start using the Call API. Instead of sending an object to convert as the type parameter, use ResponseBody from okhttp --

public interface GitHubService {
    @GET("/users/{user}")
    Call<ResponseBody> listRepos(@Path("user") String user);
}

then you can create and execute your call --

GitHubService service = retrofit.create(GitHubService.class);
Call<ResponseBody> result = service.listRepos(username);
result.enqueue(new Callback<ResponseBody>() {
    @Override
    public void onResponse(Response<ResponseBody> response) {
        try {
            System.out.println(response.body().string());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onFailure(Throwable t) {
        e.printStackTrace();
    }
});

Note The code above calls string() on the response object, which reads the entire response into a String. If you are passing the body off to something that can ingest streams, you can call charStream() instead. See the ResponseBody docs.

How to pass parameters or arguments into a gradle task

I think you probably want to view the minification of each set of css as a separate task

task minifyBrandACss(type: com.eriwen.gradle.css.tasks.MinifyCssTask) {
     source = "src/main/webapp/css/brandA/styles.css"
     dest = "${buildDir}/brandA/styles.css"
}

etc etc

BTW executing your minify tasks in an action of the war task seems odd to me - wouldn't it make more sense to make them a dependency of the war task?

Read Post Data submitted to ASP.Net Form

Read the Request.Form NameValueCollection and process your logic accordingly:

NameValueCollection nvc = Request.Form;
string userName, password;
if (!string.IsNullOrEmpty(nvc["txtUserName"]))
{
  userName = nvc["txtUserName"];
}

if (!string.IsNullOrEmpty(nvc["txtPassword"]))
{
  password = nvc["txtPassword"];
}

//Process login
CheckLogin(userName, password);

... where "txtUserName" and "txtPassword" are the Names of the controls on the posting page.

javac option to compile all java files under a given directory recursively

If your shell supports it, would something like this work ?

javac com/**/*.java 

If your shell does not support **, then maybe

javac com/*/*/*.java

works (for all packages with 3 components - adapt for more or less).

Application.WorksheetFunction.Match method

You are getting this error because the value cannot be found in the range. String or integer doesn't matter. Best thing to do in my experience is to do a check first to see if the value exists.

I used CountIf below, but there is lots of different ways to check existence of a value in a range.

Public Sub test()

Dim rng As Range
Dim aNumber As Long

aNumber = 666

Set rng = Sheet5.Range("B16:B615")

    If Application.WorksheetFunction.CountIf(rng, aNumber) > 0 Then

        rowNum = Application.WorksheetFunction.Match(aNumber, rng, 0)

    Else
        MsgBox aNumber & " does not exist in range " & rng.Address
    End If

End Sub

ALTERNATIVE WAY

Public Sub test()
    Dim rng As Range
    Dim aNumber As Variant
    Dim rowNum As Long

    aNumber = "2gg"

    Set rng = Sheet5.Range("B1:B20")

    If Not IsError(Application.Match(aNumber, rng, 0)) Then
        rowNum = Application.Match(aNumber, rng, 0)
        MsgBox rowNum
    Else
        MsgBox "error"
    End If
End Sub

OR

Public Sub test()
    Dim rng As Range
    Dim aNumber As Variant
    Dim rowNum As Variant

    aNumber = "2gg"

    Set rng = Sheet5.Range("B1:B20")

    rowNum = Application.Match(aNumber, rng, 0)

    If Not IsError(rowNum) Then
        MsgBox rowNum
    Else
        MsgBox "error"
    End If
End Sub

Convert Map<String,Object> to Map<String,String>

There are two ways to do this. One is very simple but unsafe:

Map<String, Object> map = new HashMap<String, Object>();
Map<String, String> newMap = new HashMap<String, String>((Map)map);  // unchecked warning

The other way has no compiler warnings and ensures type safety at runtime, which is more robust. (After all, you can't guarantee the original map contains only String values, otherwise why wouldn't it be Map<String, String> in the first place?)

Map<String, Object> map = new HashMap<String, Object>();
Map<String, String> newMap = new HashMap<String, String>();
@SuppressWarnings("unchecked") Map<String, Object> intermediate =
    (Map)Collections.checkedMap(newMap, String.class, String.class);
intermediate.putAll(map);

Common CSS Media Queries Break Points


@media only screen and (min-width : 320px) and (max-width : 480px) {/*--- Mobile portrait ---*/}
@media only screen and (min-width : 480px) and (max-width : 595px) {/*--- Mobile landscape ---*/}
@media only screen and (min-width : 595px) and (max-width : 690px) {/*--- Small tablet portrait ---*/}
@media only screen and (min-width : 690px) and (max-width : 800px) {/*--- Tablet portrait ---*/}
@media only screen and (min-width : 800px) and (max-width : 1024px) {/*--- Small tablet landscape ---*/}
@media only screen and (min-width : 1024px) and (max-width : 1224px) {/*--- Tablet landscape --- */}

How do you specify a different port number in SQL Management Studio?

You'll need the SQL Server Configuration Manager. Go to Sql Native Client Configuration, Select Client Protocols, Right Click on TCP/IP and set your default port there.

Using % for host when creating a MySQL user

Going to provide a slightly different answer to those provided so far.

If you have a row for an anonymous user from localhost in your users table ''@'localhost' then this will be treated as more specific than your user with wildcard'd host 'user'@'%'. This is why it is necessary to also provide 'user'@'localhost'.

You can see this explained in more detail at the bottom of this page.

how can get index & count in vuejs

In case, your data is in the following structure, you get string as an index

items = {
   am:"Amharic",
   ar:"Arabic",
   az:"Azerbaijani",
   ba:"Bashkir",
   be:"Belarusian"
}

In this case, you can use extra variable to get the index in number:

<ul>
  <li v-for="(item, key, index) in items">
    {{ item }} - {{ key }} - {{ index }}
  </li>
</ul>

Source: https://alligator.io/vuejs/iterating-v-for/

How can I solve a connection pool problem between ASP.NET and SQL Server?

I wasn't thinking this was my issue at first but in running through this list I discovered that it didn't cover what my issues was.

My issue was that I had a bug in which it tried to write the same record numerous times using entity framework. It shouldn't have been doing this; it was my bug. Take a look at the data you are writing. My thoughts are that SQL was busy writing a record, possibly locking and creating the timeout. After I fixed the area of code that was attempting to write the record multiple in sequential attempts, the error went away.

Cocoa Touch: How To Change UIView's Border Color And Thickness?

If you want to add different border on different sides, may be add a subview with the specific style is a way easy to come up with.

Delete item from state array in react

I also had a same requirement to delete an element from array which is in state.

const array= [...this.state.selectedOption]
const found= array.findIndex(x=>x.index===k)
if(found !== -1){
   this.setState({
   selectedOption:array.filter(x => x.index !== k)
    })
 }

First I copied the elements into an array. Then checked whether the element exist in the array or not. Then only I have deleted the element from the state using the filter option.

Multiple -and -or in PowerShell Where-Object statement

You're using curvy-braces when you should be using parentheses.

A where statement is kept inside a scriptblock, which is defined using curvy baces { }. To isolate/wrap you tests, you should use parentheses ().

I would also suggest trying to do the filtering on the remote computer. Try:

Invoke-Command -computername SERVERNAME {
    Get-ChildItem -path E:\dfsroots\datastore2\public |
    Where-Object { ($_.extension -eq "xls" -or $_.extension -eq "xlk") -and $_.creationtime -ge "06/01/2014" }
}

What is %0|%0 and how does it work?

It's a logic bomb, it keeps recreating itself and takes up all your CPU resources. It overloads your computer with too many processes and it forces it to shut down. If you make a batch file with this in it and start it you can end it using taskmgr. You have to do this pretty quickly or your computer will be too slow to do anything.

Unable to resolve dependency for ':app@debug/compileClasspath': Could not resolve

In my case I used google play services...I increase library service it solved

implementation 'com.google.android.gms:play-services-auth:16.0.0'

Google play service must be same in library and app modules

Reference

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

Using rcParams you can show grid very easily as follows

plt.rcParams['axes.facecolor'] = 'white'
plt.rcParams['axes.edgecolor'] = 'white'
plt.rcParams['axes.grid'] = True
plt.rcParams['grid.alpha'] = 1
plt.rcParams['grid.color'] = "#cccccc"

If grid is not showing even after changing these parameters then use

plt.grid(True)

before calling

plt.show()

PreparedStatement IN clause alternatives?

Sormula supports SQL IN operator by allowing you to supply a java.util.Collection object as a parameter. It creates a prepared statement with a ? for each of the elements the collection. See Example 4 (SQL in example is a comment to clarify what is created but is not used by Sormula).

Distribution certificate / private key not installed

Click on Manage Certificates->Apple Distribution->Done

java.net.UnknownHostException: Unable to resolve host "<url>": No address associated with hostname and End of input at character 0 of

I encountered this error when running my Android app on my home WiFi, then trying to run it on different WiFi without closing my simulator.

Simply closing the simulator and re-launching the app worked for me!

Undo a Git merge that hasn't been pushed yet

If you committed the merge:

git reset HEAD~1
# Make sure what you are reverting is in fact the merge files
git add .
git reset --hard

Update R using RStudio

You install a new version of R from the official website.

RStudio should automatically start with the new version when you relaunch it.

In case you need to do it manually, in RStudio, go to :Tools -> options -> General.

Check @micstr's answer for a more detailed walkthrough.

How to connect to SQL Server database from JavaScript in the browser?

This would be really bad to do because sharing your connection string opens up your website to so many vulnerabilities that you can't simply patch up, you have to use a different method if you want it to be secure. Otherwise you are opening up to a huge audience to take advantage of your site.

Strings in C, how to get subString

#include <string.h>
...
char otherString[6]; // note 6, not 5, there's one there for the null terminator
...
strncpy(otherString, someString, 5);
otherString[5] = '\0'; // place the null terminator

Reason: no suitable image found

If you accidentally reset your keychain, this can occur due to missing Apple certificates in the keychain. I followed the answer on this to solve my problem.

I had the same issue and was able to fix by re-downloading the WWDR (Apple Worldwide Developer Relations Certification Authority). Download from here: http://developer.apple.com/certificationauthority/AppleWWDRCA.cer

How do I remove carriage returns with Ruby?

You can use this :

my_string.strip.gsub(/\s+/, ' ')

What's the difference between & and && in MATLAB?

&& and || are short circuit operators operating on scalars. & and | operate on arrays, and use short-circuiting only in the context of if or while loop expressions.

How to change row color in datagridview?

With this code, you only change rows backcolor where columname value is null other rows color still the default one.

       foreach (DataGridViewRow row in dataGridView1.Rows)
                {
                    if (row.Cells["columnname"].Value != null)
                    {
                        dataGridView1.AlternatingRowsDefaultCellStyle.BackColor = Color.MistyRose;
                    }
                 }

How to delete rows in tables that contain foreign keys to other tables

From your question, I think it is safe to assume you have CASCADING DELETES turned on.
All that is needed in that case is

DELETE FROM MainTable
WHERE PrimaryKey = ???

You database engine will take care of deleting the corresponding referencing records.

CodeIgniter removing index.php from url

Note the difference with the added "?" character after ".php", especially when dealing with CodeIgniter:

RewriteRule ^(.*)$ index.php/$1 [L]

vs.

RewriteRule ^(.*)$ index.php?/$1 [L]

It depends on several other things.. if doesn't work, try the other option!

Convert normal date to unix timestamp

You can use Date.parse(), but the input formats that it accepts are implementation-dependent. However, if you can convert the date to ISO format (YYYY-MM-DD), most implementations should understand it.

See Why does Date.parse give incorrect results?.

Anonymous method in Invoke call

I never understood why this makes a difference for the compiler, but this is sufficient.

public static class ControlExtensions
{
    public static void Invoke(this Control control, Action action)
    {
        control.Invoke(action);
    }
}

Bonus: add some error handling, because it is likely that, if you are using Control.Invoke from a background thread you are updating the text / progress / enabled state of a control and don't care if the control is already disposed.

public static class ControlExtensions
{
    public static void Invoke(this Control control, Action action)
    {
        try
        {
            if (!control.IsDisposed) control.Invoke(action);
        }
        catch (ObjectDisposedException) { }
    }
}

printf with std::string?

Use std::printf and c_str() example:

std::printf("Follow this command: %s", myString.c_str());

Check if a variable is between two numbers with Java

Assuming you are programming in Java, this works:

if (90 >= angle  &&  angle <= 180 )  {

(don't you mean 90 is less than angle? If so: 90 <= angle)

How do I insert an image in an activity with android studio?

since you followed the tutorial, I presume you have a screen that says Hello World.

that means you have some code in your layout xml that looks like this

<TextView        
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="@string/hello_world" />

you want to display an image, so instead of TextView you want to have ImageView. and instead of a text attribute you want an src attribute, that links to your drawable resource

<ImageView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:src="@drawable/cool_pic"
/>

Read from a gzip file in python

Try gzipping some data through the gzip libary like this...

import gzip
content = "Lots of content here"
f = gzip.open('Onlyfinnaly.log.gz', 'wb')
f.write(content)
f.close()

... then run your code as posted ...

import gzip
f=gzip.open('Onlyfinnaly.log.gz','rb')
file_content=f.read()
print file_content

This method worked for me as for some reason the gzip library fails to read some files.

How to alter a column's data type in a PostgreSQL table?

If data already exists in the column you should do:

ALTER TABLE tbl_name ALTER COLUMN col_name TYPE integer USING col_name::integer;

As pointed out by @nobu and @jonathan-porter in comments to @derek-kromm's answer.

How to view the list of compile errors in IntelliJ?

A more up to date answer for anyone else who comes across this:

(from https://www.jetbrains.com/help/idea/eclipse.html, §Auto-compilation; click for screenshots)

Compile automatically:

To enable automatic compilation, navigate to Settings/Preferences | Build, Execution, Deployment | Compiler and select the Build project automatically option

Show all errors in one place:

The Problems tool window appears if the Make project automatically option is enabled in the Compiler settings. It shows a list of problems that were detected on project compilation.

Use the Eclipse compiler: This is actually bundled in IntelliJ. It gives much more useful error messages, in my opinion, and, according to this blog, it's much faster since it was designed to run in the background of an IDE and uses incremental compilation.

While Eclipse uses its own compiler, IntelliJ IDEA uses the javac compiler bundled with the project JDK. If you must use the Eclipse compiler, navigate to Settings/Preferences | Build, Execution, Deployment | Compiler | Java Compiler and select it... The biggest difference between the Eclipse and javac compilers is that the Eclipse compiler is more tolerant to errors, and sometimes lets you run code that doesn't compile.

HTML5 Video Stop onClose

To save hours of coding time, use a jquery plug-in already optimized for embedded video iframes.

I spent a couple days trying to integrate Vimeo's moogaloop API with jquery tools unsuccessfully. See this list for a handful of easier options.

How do I make an asynchronous GET request in PHP?

Suggestion: format a FRAMESET HTML page which contains, let´s say, 9 frames inside. Each frame will GET a different "instance" of your myapp.php page. There will be 9 different threads running on the Web server, in parallel.

Java foreach loop: for (Integer i : list) { ... }

Another way, you can use a pass-through object to capture the last value and then do something with it:

List<Integer> list = new ArrayList<Integer>();
Integer lastValue = null;
for (Integer i : list) {
    // do stuff
    lastValue = i;
}
// do stuff with last value

Even though JRE 8 is installed on my MAC -" No Java Runtime present,requesting to install " gets displayed in terminal

I have Mojave 10.14.6 and the only thing that did work for me was:

  • setting JAVA_HOME to the following:
export JAVA_HOME=/Library/Internet\ Plug-Ins/JavaAppletPlugin.plugin/Contents/Home
  • source .bash_profile (or wherever you keep your vars, in my case .zshrc)

Hope it helps! You can now type java --version and it should work

How to close form

There are different methods to open or close winform. Form.Close() is one method in closing a winform.

When 'Form.Close()' execute , all resources created in that form are destroyed. Resources means control and all its child controls (labels , buttons) , forms etc.

Some other methods to close winform

  1. Form.Hide()
  2. Application.Exit()

Some methods to Open/Start a form

  1. Form.Show()
  2. Form.ShowDialog()
  3. Form.TopMost()

All of them act differently , Explore them !

How to make a div with a circular shape?

.circle {
    border-radius: 50%;
    width: 500px;
    height: 500px;
    background: red;
}

<div class="circle"></div>

see this FIDDLE

How do you run JavaScript script through the Terminal?

Technically, Node.js isn't proper JavaScript as we know it, since there isn't a Document Object Model (DOM). For instance, JavaScript scripts that run in the browser will not work. At all. The solution would be to run JavaScript with a headless browser. Fortunately there is a project still active: Mozilla Firefox has a headless mode.

https://developer.mozilla.org/en-US/docs/Mozilla/Firefox/Headless_mode

$ /Applications/Firefox.app/Contents/MacOS/firefox -headless index.html
*** You are running in headless mode.

OpenCV - DLL missing, but it's not?

you can find the opencv_core248 and other dlls in opencv\build\x86\vc12\bin folder. Just copy the dlls you require into system32 folder. And your app should start working in a flash ! Hope it helps.

How do I create an HTML table with a fixed/frozen left column and a scrollable body?

Here is another modification of the most popular answer, but with handling of variable length of text in the first column labels: http://jsfiddle.net/ozx56n41/

Basically, I'm using the second column for creating row height, like was mentioned. But my fiddle actually works unlike most mentioned above.

HTML:

<div id="outerdiv">
    <div id="innerdiv">
        <table>
            <tr>
                <td class="headcol"><div>This is a long label</div></td>
                <td class="hiddenheadcol"><div>This is a long label</div></td>
                <td class="long">QWERTYUIOPASDFGHJKLZXCVBNM</td>
                <td class="long">QWERTYUIOPASDFGHJKLZXCVBNM</td>
            </tr>
            <tr>
                <td class="headcol"><div>Short label</div></td>
                <td class="hiddenheadcol"><div>Short label</div></td>
                <td class="long">QWERTYUIOPASDFGHJKLZXCVBNM</td>
                <td class="long">QWERTYUIOPASDFGHJKLZXCVBNM</td>
            </tr>
        </table>
    </div>
</div>

CSS:

body {
    font: 16px Calibri;
}
#outerdiv {
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    width: 100%;
    border-top: 1px solid grey;
}
#innerdiv {
    overflow-x: scroll;
    margin-left: 100px;
    overflow-y: visible;
    padding-bottom: 1px;
}
table {
    border-collapse:separate;
}
td {
    margin: 0;
    border: 1px solid grey;
    border-top-width: 0;
    border-left-width: 0px;
    padding: 10px;
}
td.headcol {
    /* Frozen 1st column */
    position: absolute;
    left: 0;
    top: auto;
    border-bottom-width: 1px;
    padding: 0;
    border-left-width: 1px;
}
td.hiddenheadcol {
    /* Hidden 2nd column to create height */
    max-width: 0;
    visibility: hidden;
    padding: 0;
}
td.headcol div {
    /* Text container in the 1st column */
    width: 100px;
    max-width: 100px;
    background: lightblue;
    padding: 10px;
    box-sizing: border-box;
}
td.hiddenheadcol div {
    /* Text container in the 2nd column */
    width: 100px;
    max-width: 100px;
    background: red;
    padding: 10px;
}
td.long {
    background:yellow;
    letter-spacing:1em;
}

SQL UPDATE all values in a field with appended string CONCAT not working

Solved it. Turns out the column had a limited set of characters it would accept, changed it, and now the query works fine.

What is the purpose of using -pedantic in GCC/G++ compiler?

Basically, it will make your code a lot easier to compile under other compilers which also implement the ANSI standard, and, if you are careful in which libraries/api calls you use, under other operating systems/platforms.

The first one, turns off SPECIFIC features of GCC. (-ansi) The second one, will complain about ANYTHING at all that does not adhere to the standard (not only specific features of GCC, but your constructs too.) (-pedantic).

Is there a way to style a TextView to uppercase all of its letters?

It seems like there is permission on mobile keypad setting, so the easiest way to do this is:

editText.setFilters(new InputFilter[]{new InputFilter.AllCaps()});

hope this will work

When would you use the Builder Pattern?

Below are some reasons arguing for the use of the pattern and example code in Java, but it is an implementation of the Builder Pattern covered by the Gang of Four in Design Patterns. The reasons you would use it in Java are also applicable to other programming languages as well.

As Joshua Bloch states in Effective Java, 2nd Edition:

The builder pattern is a good choice when designing classes whose constructors or static factories would have more than a handful of parameters.

We've all at some point encountered a class with a list of constructors where each addition adds a new option parameter:

Pizza(int size) { ... }        
Pizza(int size, boolean cheese) { ... }    
Pizza(int size, boolean cheese, boolean pepperoni) { ... }    
Pizza(int size, boolean cheese, boolean pepperoni, boolean bacon) { ... }

This is called the Telescoping Constructor Pattern. The problem with this pattern is that once constructors are 4 or 5 parameters long it becomes difficult to remember the required order of the parameters as well as what particular constructor you might want in a given situation.

One alternative you have to the Telescoping Constructor Pattern is the JavaBean Pattern where you call a constructor with the mandatory parameters and then call any optional setters after:

Pizza pizza = new Pizza(12);
pizza.setCheese(true);
pizza.setPepperoni(true);
pizza.setBacon(true);

The problem here is that because the object is created over several calls it may be in an inconsistent state partway through its construction. This also requires a lot of extra effort to ensure thread safety.

The better alternative is to use the Builder Pattern.

public class Pizza {
  private int size;
  private boolean cheese;
  private boolean pepperoni;
  private boolean bacon;

  public static class Builder {
    //required
    private final int size;

    //optional
    private boolean cheese = false;
    private boolean pepperoni = false;
    private boolean bacon = false;

    public Builder(int size) {
      this.size = size;
    }

    public Builder cheese(boolean value) {
      cheese = value;
      return this;
    }

    public Builder pepperoni(boolean value) {
      pepperoni = value;
      return this;
    }

    public Builder bacon(boolean value) {
      bacon = value;
      return this;
    }

    public Pizza build() {
      return new Pizza(this);
    }
  }

  private Pizza(Builder builder) {
    size = builder.size;
    cheese = builder.cheese;
    pepperoni = builder.pepperoni;
    bacon = builder.bacon;
  }
}

Note that Pizza is immutable and that parameter values are all in a single location. Because the Builder's setter methods return the Builder object they are able to be chained.

Pizza pizza = new Pizza.Builder(12)
                       .cheese(true)
                       .pepperoni(true)
                       .bacon(true)
                       .build();

This results in code that is easy to write and very easy to read and understand. In this example, the build method could be modified to check parameters after they have been copied from the builder to the Pizza object and throw an IllegalStateException if an invalid parameter value has been supplied. This pattern is flexible and it is easy to add more parameters to it in the future. It is really only useful if you are going to have more than 4 or 5 parameters for a constructor. That said, it might be worthwhile in the first place if you suspect you may be adding more parameters in the future.

I have borrowed heavily on this topic from the book Effective Java, 2nd Edition by Joshua Bloch. To learn more about this pattern and other effective Java practices I highly recommend it.

Escaping Strings in JavaScript

Use encodeURI()

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

Escapes pretty much all problematic characters in strings for proper JSON encoding and transit for use in web applications. It's not a perfect validation solution but it catches the low-hanging fruit.

Python Linked List

Linked List Class

class LinkedStack:
# Nested Node Class
class Node:
    def __init__(self, element, next):
        self.__element = element
        self.__next = next

    def get_next(self):
        return self.__next

    def get_element(self):
        return self.__element

def __init__(self):
    self.head = None
    self.size = 0
    self.data = []

def __len__(self):
    return self.size

def __str__(self):
    return str(self.data)

def is_empty(self):
    return self.size == 0

def push(self, e):
    newest = self.Node(e, self.head)
    self.head = newest
    self.size += 1
    self.data.append(newest)

def top(self):
    if self.is_empty():
        raise Empty('Stack is empty')
    return self.head.__element

def pop(self):
    if self.is_empty():
        raise Empty('Stack is empty')
    answer = self.head.element
    self.head = self.head.next
    self.size -= 1
    return answer

Usage

from LinkedStack import LinkedStack

x = LinkedStack()

x.push(10)
x.push(25)
x.push(55)


for i in range(x.size - 1, -1, -1):

    print '|', x.data[i].get_element(), '|' ,
    #next object

    if x.data[i].get_next() == None:
        print '--> None'
    else:
        print  x.data[i].get_next().get_element(), '-|---->  ',

Output

| 55 | 25 -|---->   | 25 | 10 -|---->   | 10 | --> None

How to remove only 0 (Zero) values from column in excel 2010

There is an issue with the Command + F solution. It will replace all 0's if you click replace all. This means if you do not review every zero, zero's contained in important cells will also be removed. For example, if you have phone numbers that have (420) area codes they will all be changed to (40).

SQL Server: how to select records with specific date from datetime column

For Perfect DateTime Match in SQL Server

SELECT ID FROM [Table Name] WHERE (DateLog between '2017-02-16 **00:00:00.000**' and '2017-12-16 **23:59:00.999**') ORDER BY DateLog DESC

How to programmatically set the ForeColor of a label to its default?

The default (when created with the designer) is:

label.ForeColor = SystemColors.ControlText;

This should respect the system color settings (e.g. these "high contrast" schemes for visual impaired).

assign multiple variables to the same value in Javascript

Nothing stops you from doing

moveUp = moveDown = moveLeft = moveRight = mouseDown = touchDown = false;

Check this example

_x000D_
_x000D_
var a, b, c;_x000D_
a = b = c = 10;_x000D_
console.log(a + b + c)
_x000D_
_x000D_
_x000D_

web-api POST body object always null

In my case the problem was the DateTime object I was sending. I created a DateTime with "yyyy-MM-dd", and the DateTime that was required by the object I was mapping to needed "HH-mm-ss" aswell. So appending "00-00" solved the problem (the full item was null because of this).

How to generate .json file with PHP?

Here is a sample code:

<?php 
$sql="select * from Posts limit 20"; 

$response = array();
$posts = array();
$result=mysql_query($sql);
while($row=mysql_fetch_array($result)) { 
  $title=$row['title']; 
  $url=$row['url']; 

  $posts[] = array('title'=> $title, 'url'=> $url);
} 

$response['posts'] = $posts;

$fp = fopen('results.json', 'w');
fwrite($fp, json_encode($response));
fclose($fp);


?> 

Pandas dataframe fillna() only some columns in place

Sometimes this syntax wont work:

df[['col1','col2']] = df[['col1','col2']].fillna()

Use the following instead:

df['col1','col2']

java.lang.RuntimeException: Unable to instantiate org.apache.hadoop.hive.ql.metadata.SessionHiveMetaStoreClient

I solved this problem by removing --deploy-mode cluster from spark-submit code. By default , spark submit takes client mode which has following advantage :

1. It opens up Netty HTTP server and distributes all jars to the worker nodes.
2. Driver program runs on master node , which means dedicated resources to driver process.

While in cluster mode :

 1.  It runs on worker node.
 2. All the jars need to be placed in a common folder of the cluster so that it is accessible to all the worker nodes or in folder of each worker node.

Here it's not able to access hive metastore due to unavailability of hive jar to any of the nodes in cluster. enter image description here

ASP.NET Core form POST results in a HTTP 415 Unsupported Media Type response

In my case, I received the HTTP 415 Unsupported Media Type response, since I specified the content type to be TEXT and NOT JSON, so simply changing the type solved the issue. Please check the solution in more detail in the following blog post: https://www.howtodevelop.net/article/20/unsupported-media-type-415-in-aspnet-core-web-api

How do I check if a type is a subtype OR the type of an object?

typeof(BaseClass).IsAssignableFrom(unknownType);

Double value to round up in Java

Try this: org.apache.commons.math3.util.Precision.round(double x, int scale)

See: http://commons.apache.org/proper/commons-math/apidocs/org/apache/commons/math3/util/Precision.html

Apache Commons Mathematics Library homepage is: http://commons.apache.org/proper/commons-math/index.html

The internal implemetation of this method is:

public static double round(double x, int scale) {
    return round(x, scale, BigDecimal.ROUND_HALF_UP);
}

public static double round(double x, int scale, int roundingMethod) {
    try {
        return (new BigDecimal
               (Double.toString(x))
               .setScale(scale, roundingMethod))
               .doubleValue();
    } catch (NumberFormatException ex) {
        if (Double.isInfinite(x)) {
            return x;
        } else {
            return Double.NaN;
        }
    }
}

VB.NET: Clear DataGridView

I had the same problem: I was programmatically binding my GridView1 to one SQL table [dictonary] or another [meny] BUT when I selected the second table from my RadioButtonList1, I was getting an error (System.Web.HttpException: Field or property with the title [the first column's title from the previously selected table] was not found in the selected data source.) i.e. saying that the columns from my first-selected table couldn't be found. All I needed to do was insert:

GridView1.Columns.Clear()

before adding the table columns. Here goes the full code:

Dim connectionString As String = "your-string-details"
Dim connection As New SqlConnection(connectionString)

Then comes your first Sub:

Private Sub BindOrders()
    connection.Open()

    Dim sqlCommand As String = "SELECT * FROM [dictionary]" 
    Dim dataAdapter As New SqlDataAdapter(sqlCommand, connection)
    Dim dt As New DataTable() 
    dataAdapter.Fill(dt)

    GridView1.Columns.Clear() ' clear columns before adding new ones

    If GridView1.Columns.Count <= 0 Then
        Dim Field As New BoundField()
        Field.DataField = "id"
        Field.HeaderText = "id"
        GridView1.Columns.Add(Field)

        Field = New BoundField()
        Field.DataField = "strArHundreds"
        Field.HeaderText = "strArHundreds"
        GridView1.Columns.Add(Field)

        Field = New BoundField()
        Field.DataField = "strArTens"
        Field.HeaderText = "strArTens"
        GridView1.Columns.Add(Field)

        Field = New BoundField()
        Field.DataField = "strArSingles"
        Field.HeaderText = "strArSingles"
        GridView1.Columns.Add(Field)
    End If

    GridView1.DataSource = dt
    GridView1.DataBind()

    connection.Close()
End Sub

Then comes your second Sub:

Private Sub BindDocuments()
    connection.Open()

    Dim sqlCommand As String = "SELECT * FROM [meny]"
    Dim dataAdapter As New SqlDataAdapter(sqlCommand, connection)
    Dim dt As New DataTable()

    dataAdapter.Fill(dt)

    GridView1.Columns.Clear() ' clear columns before adding new ones

    If GridView1.Columns.Count <= 0 Then
        Dim Field As New BoundField
        Field = New BoundField
        Field.DataField = "id"
        Field.HeaderText = "id"
        GridView1.Columns.Add(Field)

        Field = New BoundField
        Field.DataField = "nazev"
        Field.HeaderText = "nazev"
        GridView1.Columns.Add(Field)
    End If

    GridView1.DataSource = dt
    GridView1.DataBind()

    connection.Close()
End Sub

Finally comes your RadioButton:

Protected Sub RadioButtonList1_SelectedIndexChanged(sender As Object, e As EventArgs) Handles RadioButtonList1.SelectedIndexChanged
    Dim index As Integer
    index = RadioButtonList1.SelectedIndex
    Select Case index
        Case 0
            BindOrders()
            Exit Select
        Case 1
            BindDocuments()
            Exit Select
    End Select
End Sub

For completion, here is the code for the GridView1 and the RadioButtonList1 in the associated aspx.file:

<asp:RadioButtonList ID="RadioButtonList1"
    runat="server"
    AutoPostBack="True"
    OnSelectedIndexChanged="RadioButtonList1_SelectedIndexChanged">
    <asp:ListItem>Obraty</asp:ListItem>
    <asp:ListItem>Dokumenty</asp:ListItem>
</asp:RadioButtonList>

<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False">
</asp:GridView>

This all works well now.

Flutter Countdown Timer

Little late to the party but why don't you guys try animation.No I am not telling you to manage animation controllers and disposing them off and all that stuff.theres a built-in widget for that called TweenAnimationBuilder.You can animate between values of any type,heres an example with a Duration class

TweenAnimationBuilder<Duration>(
              duration: Duration(minutes: 3),
              tween: Tween(begin: Duration(minutes: 3), end: Duration.zero),
              onEnd: () {
                print('Timer ended');
              },
              builder: (BuildContext context, Duration value, Widget child) {
              final minutes = value.inMinutes;
              final seconds = value.inSeconds % 60;
              return Padding(
                     padding: const EdgeInsets.symmetric(vertical: 5),
                     child: Text('$minutes:$seconds',
                            textAlign: TextAlign.center,
                            style: TextStyle(
                            color: Colors.black,
                            fontWeight: FontWeight.bold,
                            fontSize: 30)));
              }),

and You also get onEnd call back which notifies you when the animation completes;

here's the output

How to select all elements with a particular ID in jQuery?

Can you assign a unique CSS class to each distinct timer? That way you could use the selector for the CSS class, which would work fine with multiple div elements.

<hr> tag in Twitter Bootstrap not functioning correctly?

By default, the hr element in Twitter Bootstrap CSS file has a top and bottom margin of 18px. That's what creates a gap. If you want the gap to be smaller you'll need to adjust margin property of the hr element.

In your example, do something like this:

.container hr {
margin: 2px 0;
}

How can I parse a CSV string with JavaScript, which contains comma in data?

I liked FakeRainBrigand's answer, however it contains a few problems: It can not handle whitespace between a quote and a comma, and does not support 2 consecutive commas. I tried editing his answer but my edit got rejected by reviewers that apparently did not understand my code. Here is my version of FakeRainBrigand's code. There is also a fiddle: http://jsfiddle.net/xTezm/46/

String.prototype.splitCSV = function() {
        var matches = this.match(/(\s*"[^"]+"\s*|\s*[^,]+|,)(?=,|$)/g);
        for (var n = 0; n < matches.length; ++n) {
            matches[n] = matches[n].trim();
            if (matches[n] == ',') matches[n] = '';
        }
        if (this[0] == ',') matches.unshift("");
        return matches;
}

var string = ',"string, duppi, du" , 23 ,,, "string, duppi, du",dup,"", , lala';
var parsed = string.splitCSV();
alert(parsed.join('|'));

Is there an API to get bank transaction and bank balance?

Also check out the open financial exchange (ofx) http://www.ofx.net/

This is what apps like quicken, ms money etc use.

Get Value of Row in Datatable c#

for (Int32 i = 1; i < dt_pattern.Rows.Count - 1; i++){ double yATmax = ToDouble(dt_pattern.Rows[i]["Ampl"].ToString()) + AT; }

if you want to get around the + 1 issue

What are some great online database modeling tools?

You may want to look at IBExpert Personal Edition. While not open source, this is a very good tool for designing, building, and administering Firebird and InterBase databases.

The Personal Edition is free, but some of the more advanced features are not available. Still, even without the slick extras, the free version is very powerful.

IsNumeric function in c#

http://msdn.microsoft.com/en-us/library/wkze6zky.aspx

menu: Project-->Add Reference

click: assemblies, framework

Put a checkmark on Microsoft.VisualBasic.

Hit OK.

That link is for Visual Studio 2013, you can use the "Other versions" dropdown for different versions of visual studio.

In all cases you need to add a reference to the .NET assembly "Microsoft.VisualBasic".

At the top of your c# file you neeed:

using Microsoft.VisualBasic;

Then you can look at writing the code.

The code would be something like:

   private void btnOK_Click(object sender, EventArgs e)
   {
      if ( Information.IsNumeric(startingbudget) )
      {
         MessageBox.Show("This is a number.");
      }
   }

How to access accelerometer/gyroscope data from Javascript?

There are currently three distinct events which may or may not be triggered when the client devices moves. Two of them are focused around orientation and the last on motion:

  • ondeviceorientation is known to work on the desktop version of Chrome, and most Apple laptops seems to have the hardware required for this to work. It also works on Mobile Safari on the iPhone 4 with iOS 4.2. In the event handler function, you can access alpha, beta, gamma values on the event data supplied as the only argument to the function.

  • onmozorientation is supported on Firefox 3.6 and newer. Again, this is known to work on most Apple laptops, but might work on Windows or Linux machines with accelerometer as well. In the event handler function, look for x, y, z fields on the event data supplied as first argument.

  • ondevicemotion is known to work on iPhone 3GS + 4 and iPad (both with iOS 4.2), and provides data related to the current acceleration of the client device. The event data passed to the handler function has acceleration and accelerationIncludingGravity, which both have three fields for each axis: x, y, z

The "earthquake detecting" sample website uses a series of if statements to figure out which event to attach to (in a somewhat prioritized order) and passes the data received to a common tilt function:

if (window.DeviceOrientationEvent) {
    window.addEventListener("deviceorientation", function () {
        tilt([event.beta, event.gamma]);
    }, true);
} else if (window.DeviceMotionEvent) {
    window.addEventListener('devicemotion', function () {
        tilt([event.acceleration.x * 2, event.acceleration.y * 2]);
    }, true);
} else {
    window.addEventListener("MozOrientation", function () {
        tilt([orientation.x * 50, orientation.y * 50]);
    }, true);
}

The constant factors 2 and 50 are used to "align" the readings from the two latter events with those from the first, but these are by no means precise representations. For this simple "toy" project it works just fine, but if you need to use the data for something slightly more serious, you will have to get familiar with the units of the values provided in the different events and treat them with respect :)

How to adjust the size of y axis labels only in R?

Don't know what you are doing (helpful to show what you tried that didn't work), but your claim that cex.axis only affects the x-axis is not true:

set.seed(123)
foo <- data.frame(X = rnorm(10), Y = rnorm(10))
plot(Y ~ X, data = foo, cex.axis = 3)

at least for me with:

> sessionInfo()
R version 2.11.1 Patched (2010-08-17 r52767)
Platform: x86_64-unknown-linux-gnu (64-bit)

locale:
 [1] LC_CTYPE=en_GB.UTF-8       LC_NUMERIC=C              
 [3] LC_TIME=en_GB.UTF-8        LC_COLLATE=en_GB.UTF-8    
 [5] LC_MONETARY=C              LC_MESSAGES=en_GB.UTF-8   
 [7] LC_PAPER=en_GB.UTF-8       LC_NAME=C                 
 [9] LC_ADDRESS=C               LC_TELEPHONE=C            
[11] LC_MEASUREMENT=en_GB.UTF-8 LC_IDENTIFICATION=C       

attached base packages:
[1] grid      stats     graphics  grDevices utils     datasets  methods  
[8] base     

other attached packages:
[1] ggplot2_0.8.8 proto_0.3-8   reshape_0.8.3 plyr_1.2.1   

loaded via a namespace (and not attached):
[1] digest_0.4.2 tools_2.11.1

Also, cex.axis affects the labelling of tick marks. cex.lab is used to control what R call the axis labels.

plot(Y ~ X, data = foo, cex.lab = 3)

but even that works for both the x- and y-axis.


Following up Jens' comment about using barplot(). Check out the cex.names argument to barplot(), which allows you to control the bar labels:

dat <- rpois(10, 3) names(dat) <- LETTERS[1:10] barplot(dat, cex.names = 3, cex.axis = 2)

As you mention that cex.axis was only affecting the x-axis I presume you had horiz = TRUE in your barplot() call as well? As the bar labels are not drawn with an axis() call, applying Joris' (otherwise very useful) answer with individual axis() calls won't help in this situation with you using barplot()

HTH

How to add users to Docker container?

Ubuntu

Try the following lines in Dockerfile:

RUN useradd -rm -d /home/ubuntu -s /bin/bash -g root -G sudo -u 1001 ubuntu
USER ubuntu
WORKDIR /home/ubuntu

useradd options (see: man useradd):

  • -r, --system Create a system account. see: Implications creating system accounts
  • -m, --create-home Create the user's home directory.
  • -d, --home-dir HOME_DIR Home directory of the new account.
  • -s, --shell SHELL Login shell of the new account.
  • -g, --gid GROUP Name or ID of the primary group.
  • -G, --groups GROUPS List of supplementary groups.
  • -u, --uid UID Specify user ID. see: Understanding how uid and gid work in Docker containers
  • -p, --password PASSWORD Encrypted password of the new account (e.g. ubuntu).

Setting default user's password

To set the user password, add -p "$(openssl passwd -1 ubuntu)" to useradd command.

Alternatively add the following lines to your Dockerfile:

SHELL ["/bin/bash", "-o", "pipefail", "-c"]
RUN echo 'ubuntu:ubuntu' | chpasswd

The first shell instruction is to make sure that -o pipefail option is enabled before RUN with a pipe in it. Read more: Hadolint: Linting your Dockerfile.

jQuery hasAttr checking to see if there is an attribute on an element

I wrote a hasAttr() plugin for jquery that will do all of this very simply, exactly as the OP has requested. More information here

EDIT: My plugin was deleted in the great plugins.jquery.com database deletion disaster of 2010. You can look here for some info on adding it yourself, and why it hasn't been added.

Pass arguments to Constructor in VBA

Here's a little trick I'm using lately and brings good results. I would like to share with those who have to fight often with VBA.

1.- Implement a public initiation subroutine in each of your custom classes. I call it InitiateProperties throughout all my classes. This method has to accept the arguments you would like to send to the constructor.

2.- Create a module called factory, and create a public function with the word "Create" plus the same name as the class, and the same incoming arguments as the constructor needs. This function has to instantiate your class, and call the initiation subroutine explained in point (1), passing the received arguments. Finally returned the instantiated and initiated method.

Example:

Let's say we have the custom class Employee. As the previous example, is has to be instantiated with name and age.

This is the InitiateProperties method. m_name and m_age are our private properties to be set.

Public Sub InitiateProperties(name as String, age as Integer)

    m_name = name
    m_age = age

End Sub

And now in the factory module:

Public Function CreateEmployee(name as String, age as Integer) as Employee

    Dim employee_obj As Employee
    Set employee_obj = new Employee

    employee_obj.InitiateProperties name:=name, age:=age
    set CreateEmployee = employee_obj

End Function

And finally when you want to instantiate an employee

Dim this_employee as Employee
Set this_employee = factory.CreateEmployee(name:="Johnny", age:=89)

Especially useful when you have several classes. Just place a function for each in the module factory and instantiate just by calling factory.CreateClassA(arguments), factory.CreateClassB(other_arguments), etc.

EDIT

As stenci pointed out, you can do the same thing with a terser syntax by avoiding to create a local variable in the constructor functions. For instance the CreateEmployee function could be written like this:

Public Function CreateEmployee(name as String, age as Integer) as Employee

    Set CreateEmployee = new Employee
    CreateEmployee.InitiateProperties name:=name, age:=age

End Function

Which is nicer.

Regular expression to detect semi-colon terminated C++ for & while loops

You could write a little, very simple routine that does it, without using a regular expression:

  • Set a position counter pos so that is points to just before the opening bracket after your for or while.
  • Set an open brackets counter openBr to 0.
  • Now keep incrementing pos, reading the characters at the respective positions, and increment openBr when you see an opening bracket, and decrement it when you see a closing bracket. That will increment it once at the beginning, for the first opening bracket in "for (", increment and decrement some more for some brackets in between, and set it back to 0 when your for bracket closes.
  • So, stop when openBr is 0 again.

The stopping positon is your closing bracket of for(...). Now you can check if there is a semicolon following or not.

Locate Git installation folder on Mac OS X

If you have fresh installation / update of Xcode, it is possible that your git binary can't be executed (I had mine under /usr/bin/git). To fix this problem just run the Xcode and "Accept" license conditions and try again, it should work.

How to build a Horizontal ListView with RecyclerView?

With the release of RecyclerView library, now you can align a list of images bind with text easily. You can use LinearLayoutManager to specify the direction in which you would like to orient your list, either vertical or horizontal as shown below.

enter image description here

You can download a full working demo from this post

vue.js 2 how to watch store values from vuex

You could also subscribe to the store mutations:

store.subscribe((mutation, state) => {
  console.log(mutation.type)
  console.log(mutation.payload)
})

https://vuex.vuejs.org/api/#subscribe

Setting mime type for excel document

You should always use below MIME type if you want to serve excel file in xlsx format

application/vnd.openxmlformats-officedocument.spreadsheetml.sheet 

What's the yield keyword in JavaScript?

don't forget the very helpful 'x of generator' syntax to loop through the generator. No need to use the next() function at all.

function* square(x){
    for(i=0;i<100;i++){
        x = x * 2;
        yield x;        
    }   
}

var gen = square(2);
for(x of gen){
   console.log(x);
}

Editable text to string

Based on this code (which you provided in response to Alex's answer):

Editable newTxt=(Editable)userName1.getText(); 
String newString = newTxt.toString();

It looks like you're trying to get the text out of a TextView or EditText. If that's the case then this should work:

String newString = userName1.getText().toString(); 

How to force a script reload and re-execute?

Small tweak to Luke's answer,

 function reloadJs(src) {
    src = $('script[src$="' + src + '"]').attr("src");
    $('script[src$="' + src + '"]').remove();
    $('<script/>').attr('src', src).appendTo('head');
}

and call it like,

reloadJs("myFile.js");

This will not have any path related issues.

Removing leading and trailing spaces from a string

string trim(const string & sStr)
{
    int nSize = sStr.size();
    int nSPos = 0, nEPos = 1, i;
    for(i = 0; i< nSize; ++i) {
        if( !isspace( sStr[i] ) ) {
            nSPos = i ;
            break;
        }
    }
    for(i = nSize -1 ; i >= 0 ; --i) {
        if( !isspace( sStr[i] ) ) {
            nEPos = i;
            break;
        }
    }
    return string(sStr, nSPos, nEPos - nSPos + 1);
}

The mysql extension is deprecated and will be removed in the future: use mysqli or PDO instead

  1. Why is this happening?

    The entire ext/mysql PHP extension, which provides all functions named with the prefix mysql_, was officially deprecated in PHP v5.5.0 and removed in PHP v7.

    It was originally introduced in PHP v2.0 (November 1997) for MySQL v3.20, and no new features have been added since 2006. Coupled with the lack of new features are difficulties in maintaining such old code amidst complex security vulnerabilities.

    The manual has contained warnings against its use in new code since June 2011.

  2. How can I fix it?

    As the error message suggests, there are two other MySQL extensions that you can consider: MySQLi and PDO_MySQL, either of which can be used instead of ext/mysql. Both have been in PHP core since v5.0, so if you're using a version that is throwing these deprecation errors then you can almost certainly just start using them right away—i.e. without any installation effort.

    They differ slightly, but offer a number of advantages over the old extension including API support for transactions, stored procedures and prepared statements (thereby providing the best way to defeat SQL injection attacks). PHP developer Ulf Wendel has written a thorough comparison of the features.

    Hashphp.org has an excellent tutorial on migrating from ext/mysql to PDO.

  3. I understand that it's possible to suppress deprecation errors by setting error_reporting in php.ini to exclude E_DEPRECATED:

    error_reporting = E_ALL ^ E_DEPRECATED
    

    What will happen if I do that?

    Yes, it is possible to suppress such error messages and continue using the old ext/mysql extension for the time being. But you really shouldn't do this—this is a final warning from the developers that the extension may not be bundled with future versions of PHP (indeed, as already mentioned, it has been removed from PHP v7). Instead, you should take this opportunity to migrate your application now, before it's too late.

    Note also that this technique will suppress all E_DEPRECATED messages, not just those to do with the ext/mysql extension: therefore you may be unaware of other upcoming changes to PHP that would affect your application code. It is, of course, possible to only suppress errors that arise on the expression at issue by using PHP's error control operator—i.e. prepending the relevant line with @—however this will suppress all errors raised by that expression, not just E_DEPRECATED ones.


What should you do?

  • You are starting a new project.

    There is absolutely no reason to use ext/mysql—choose one of the other, more modern, extensions instead and reap the rewards of the benefits they offer.

  • You have (your own) legacy codebase that currently depends upon ext/mysql.

    It would be wise to perform regression testing: you really shouldn't be changing anything (especially upgrading PHP) until you have identified all of the potential areas of impact, planned around each of them and then thoroughly tested your solution in a staging environment.

    • Following good coding practice, your application was developed in a loosely integrated/modular fashion and the database access methods are all self-contained in one place that can easily be swapped out for one of the new extensions.

      Spend half an hour rewriting this module to use one of the other, more modern, extensions; test thoroughly. You can later introduce further refinements to reap the rewards of the benefits they offer.

    • The database access methods are scattered all over the place and cannot easily be swapped out for one of the new extensions.

      Consider whether you really need to upgrade to PHP v5.5 at this time.

      You should begin planning to replace ext/mysql with one of the other, more modern, extensions in order that you can reap the rewards of the benefits they offer; you might also use it as an opportunity to refactor your database access methods into a more modular structure.

      However, if you have an urgent need to upgrade PHP right away, you might consider suppressing deprecation errors for the time being: but first be sure to identify any other deprecation errors that are also being thrown.

  • You are using a third party project that depends upon ext/mysql.

    Consider whether you really need to upgrade to PHP v5.5 at this time.

    Check whether the developer has released any fixes, workarounds or guidance in relation to this specific issue; or, if not, pressure them to do so by bringing this matter to their attention. If you have an urgent need to upgrade PHP right away, you might consider suppressing deprecation errors for the time being: but first be sure to identify any other deprecation errors that are also being thrown.

    It is absolutely essential to perform regression testing.

Recommended add-ons/plugins for Microsoft Visual Studio

Build Version Increment (GPL) gives you (nearly) everything you need for controlling the version of your assemblies.

Some Features (copied from the site):

  • Different auto increment styles can be set per major, minor, build or revision number.
  • Supports C#, VB.NET and C++.NET projects.
  • Not required to be installed by all project members. Configuration is shared via properties in the solution and project files. Developers who don't have the addin won't feel a thing.
  • Automatically checks out required files if under source control.
  • Can be configured per solution and/or per project.
  • Can be configured to update only on certain configuration builds (debug, release, any or custom)
  • Can update assembly attributes in an external source file instead of the default AssemblyInfo.

C# Switch-case string starting with

This is now possible with C# 7.0's pattern matching. For example:

var myString = "abcDEF";

switch(myString)
{
    case string x when x.StartsWith("abc"):
        //Do something here
        break;
}

JavaScript console.log causes error: "Synchronous XMLHttpRequest on the main thread is deprecated..."

In a MVC application, I got this warning because I was opening a Kendo Window with a method that was returning a View(), instead of a PartialView(). The View() was trying to retrive again all the scripts of the page.

Exporting data In SQL Server as INSERT INTO

If you are running SQL Server 2008 R2 the built in options on to do this in SSMS as marc_s described above changed a bit. Instead of selecting Script data = true as shown in his diagram, there is now a new option called "Types of data to script" just above the "Table/View Options" grouping. Here you can select to script data only, schema and data or schema only. Works like a charm.

ListView item background via custom selector

instead of:

android:drawable="@color/transparent" 

write

android:drawable="@android:color/transparent"

Read lines from a file into a Bash array

The readarray command (also spelled mapfile) was introduced in bash 4.0.

readarray -t a < /path/to/filename

How do I fill arrays in Java?

Arrays.fill(arrayName,value);

in java

int arrnum[] ={5,6,9,2,10};
for(int i=0;i<arrnum.length;i++){
  System.out.println(arrnum[i]+" ");
}
Arrays.fill(arrnum,0);
for(int i=0;i<arrnum.length;i++){
  System.out.println(arrnum[i]+" ");
}

Output

5 6 9 2 10
0 0 0 0 0

How to set a variable to be "Today's" date in Python/Pandas

Easy solution in Python3+:

import time


todaysdate = time.strftime("%d/%m/%Y")

#with '.' isntead of '/'
todaysdate = time.strftime("%d.%m.%Y")

Set line spacing

You cannot set inter-paragraph spacing in CSS using line-height, the spacing between <p> blocks. That instead sets the intra-paragraph line spacing, the space between lines within a <p> block. That is, line-height is the typographer's inter-line leading within the paragraph is controlled by line-height.

I presently do not know of any method in CSS to produce (for example) a 0.15em inter-<p> spacing, whether using em or rem variants on any font property. I suspect it can be done with more complex floats or offsets. A pity this is necessary in CSS.

How can I select records ONLY from yesterday?

If you don't support future dated transactions then something like this might work:

AND oh.tran_date >= trunc(sysdate-1)

How to make nginx to listen to server_name:port

The server_namedocs directive is used to identify virtual hosts, they're not used to set the binding.

netstat tells you that nginx listens on 0.0.0.0:80 which means that it will accept connections from any IP.

If you want to change the IP nginx binds on, you have to change the listendocs rule.
So, if you want to set nginx to bind to localhost, you'd change that to:

listen 127.0.0.1:80;

In this way, requests that are not coming from localhost are discarded (they don't even hit nginx).

Android Fragment handle back button press

I'd rather do something like this:

private final static String TAG_FRAGMENT = "TAG_FRAGMENT";

private void showFragment() {
    final Myfragment fragment = new MyFragment();
    final FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
    transaction.replace(R.id.fragment, fragment, TAG_FRAGMENT);
    transaction.addToBackStack(null);
    transaction.commit();
}

@Override
public void onBackPressed() {
    final Myfragment fragment = (Myfragment) getSupportFragmentManager().findFragmentByTag(TAG_FRAGMENT);

    if (fragment.allowBackPressed()) { // and then you define a method allowBackPressed with the logic to allow back pressed or not
        super.onBackPressed();
    }
}

How to use WinForms progress bar?

Hey there's a useful tutorial on Dot Net pearls: http://www.dotnetperls.com/progressbar

In agreement with Peter, you need to use some amount of threading or the program will just hang, somewhat defeating the purpose.

Example that uses ProgressBar and BackgroundWorker: C#

using System.ComponentModel;
using System.Threading;
using System.Windows.Forms;

namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, System.EventArgs e)
        {
            // Start the BackgroundWorker.
            backgroundWorker1.RunWorkerAsync();
        }

        private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
        {
            for (int i = 1; i <= 100; i++)
            {
                // Wait 100 milliseconds.
                Thread.Sleep(100);
                // Report progress.
                backgroundWorker1.ReportProgress(i);
            }
        }

        private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
        {
            // Change the value of the ProgressBar to the BackgroundWorker progress.
            progressBar1.Value = e.ProgressPercentage;
            // Set the text.
            this.Text = e.ProgressPercentage.ToString();
        }
    }
} //closing here

File Explorer in Android Studio

This works on Android Studio 1.x:

  • Tools --> Android --> Android Device Monitor (this open the ADM)
  • Window --> Show View
  • Search for File Explorer then press the OK Button
  • The File Explorer Tab is now open on the View

Best way to import Observable from rxjs

Update for RxJS 6 (April 2018)

It is now perfectly fine to import directly from rxjs. (As can be seen in Angular 6+). Importing from rxjs/operators is also fine and it is actually no longer possible to import operators globally (one of major reasons for refactoring rxjs 6 and the new approach using pipe). Thanks to this treeshaking can now be used as well.

Sample code from rxjs repo:

import { Observable, Subject, ReplaySubject, from, of, range } from 'rxjs';
import { map, filter, switchMap } from 'rxjs/operators';

range(1, 200)
  .pipe(filter(x => x % 2 === 1), map(x => x + x))
  .subscribe(x => console.log(x));

Backwards compatibility for rxjs < 6?

rxjs team released a compatibility package on npm that is pretty much install & play. With this all your rxjs 5.x code should run without any issues. This is especially useful now when most of the dependencies (i.e. modules for Angular) are not yet updated.

How to print the array?

What you are doing is printing the value in the array at spot [3][3], which is invalid for a 3by3 array, you need to loop over all the spots and print them.

for(int i = 0; i < 3; i++) {
    for(int j = 0; j < 3; j++) {
        printf("%d ", array[i][j]);
    }
    printf("\n");
} 

This will print it in the following format

10 23 42
1 654 0
40652 22 0

if you want more exact formatting you'll have to change how the printf is formatted.

class << self idiom in Ruby

What class << thing does:

class Hi
  self #=> Hi
  class << self #same as 'class << Hi'
    self #=> #<Class:Hi>
    self == Hi.singleton_class #=> true
  end
end

[it makes self == thing.singleton_class in the context of its block].


What is thing.singleton_class?

hi = String.new
def hi.a
end

hi.class.instance_methods.include? :a #=> false
hi.singleton_class.instance_methods.include? :a #=> true

hi object inherits its #methods from its #singleton_class.instance_methods and then from its #class.instance_methods.
Here we gave hi's singleton class instance method :a. It could have been done with class << hi instead.
hi's #singleton_class has all instance methods hi's #class has, and possibly some more (:a here).

[instance methods of thing's #class and #singleton_class can be applied directly to thing. when ruby sees thing.a, it first looks for :a method definition in thing.singleton_class.instance_methods and then in thing.class.instance_methods]


By the way - they call object's singleton class == metaclass == eigenclass.

Open local folder from link

Local Explorer - File Manager on web browser extention can solve for chrome

but still some encoding problems

How to use a class object in C++ as a function parameter

I was asking the same too. Another solution is you could overload your method:

void remove_id(EmployeeClass);
void remove_id(ProductClass);
void remove_id(DepartmentClass);

in the call the argument will fit accordingly the object you pass. but then you will have to repeat yourself

void remove_id(EmployeeClass _obj) {
    int saveId = _obj->id;
    ...
};

void remove_id(ProductClass _obj) {
    int saveId = _obj->id;
    ...
};

void remove_id(DepartmentClass _obj) {
    int saveId = _obj->id;
    ...
};

How to access a RowDataPacket object

Solution

Just do: JSON.stringify(results)

Is there a way to catch the back button event in javascript?

I have created a solution which may be of use to some people. Simply include the code on your page, and you can write your own function that will be called when the back button is clicked.

I have tested in IE, FF, Chrome, and Safari, and are all working. The solution I have works based on iframes without the need for constant polling, in IE and FF, however, due to limitations in other browsers, the location hash is used in Safari.

How to add a response header on nginx when using proxy_pass?

There is a module called HttpHeadersMoreModule that gives you more control over headers. It does not come with Nginx and requires additional installation. With it, you can do something like this:

location ... {
  more_set_headers "Server: my_server";
}

That will "set the Server output header to the custom value for any status code and any content type". It will replace headers that are already set or add them if unset.

How to display a range input slider vertically

You can do this with css transforms, though be careful with container height/width. Also you may need to position it lower:

_x000D_
_x000D_
input[type="range"] {_x000D_
   position: absolute;_x000D_
   top: 40%;_x000D_
   transform: rotate(270deg);_x000D_
}
_x000D_
<input type="range"/>
_x000D_
_x000D_
_x000D_


or the 3d transform equivalent:

input[type="range"] {
   transform: rotateZ(270deg);
}

You can also use this to switch the direction of the slide by setting it to 180deg or 90deg for horizontal or vertical respectively.

WampServer orange icon

Wamp server default disk is "C:\" if you install it to another disk for ex G:\: go to

  1. g:\wamp\bin\apache\apache2.4.9\bin\

2 .call cmd

3 .execute httpd.exe -t

you will see errors

enter image description here

  1. go to g:\wamp\bin\apache\apache2.4.9\conf\extra\httpd-autoindex.conf

  2. change in line 23 to :

Alias /icons/ "g:/Apache24/icons/"

<Directory "g:/Apache24/icons">
    Options Indexes MultiViews
    AllowOverride None
    Require all granted
</Directory>
  1. Restart All services. Done. Resolved

Show pop-ups the most elegant way

See http://adamalbrecht.com/2013/12/12/creating-a-simple-modal-dialog-directive-in-angular-js/ for a simple way of doing modal dialog with Angular and without needing bootstrap

Edit: I've since been using ng-dialog from http://likeastore.github.io/ngDialog which is flexible and doesn't have any dependencies.

What does Python's socket.recv() return for non-blocking sockets if no data is received until a timeout occurs?

When you use recv in connection with select if the socket is ready to be read from but there is no data to read that means the client has closed the connection.

Here is some code that handles this, also note the exception that is thrown when recv is called a second time in the while loop. If there is nothing left to read this exception will be thrown it doesn't mean the client has closed the connection :

def listenToSockets(self):

    while True:

        changed_sockets = self.currentSockets

        ready_to_read, ready_to_write, in_error = select.select(changed_sockets, [], [], 0.1)

        for s in ready_to_read:

            if s == self.serverSocket:
                self.acceptNewConnection(s)
            else:
                self.readDataFromSocket(s)

And the function that receives the data :

def readDataFromSocket(self, socket):

    data = ''
    buffer = ''
    try:

        while True:
            data = socket.recv(4096)

            if not data: 
                break

            buffer += data

    except error, (errorCode,message): 
        # error 10035 is no data available, it is non-fatal
        if errorCode != 10035:
            print 'socket.error - ('+str(errorCode)+') ' + message


    if data:
        print 'received '+ buffer
    else:
        print 'disconnected'

What is the right way to debug in iPython notebook?

After you get an error, in the next cell just run %debug and that's it.

How to get the first column of a pandas DataFrame as a Series?

>>> import pandas as pd
>>> df = pd.DataFrame({'x' : [1, 2, 3, 4], 'y' : [4, 5, 6, 7]})
>>> df
   x  y
0  1  4
1  2  5
2  3  6
3  4  7
>>> s = df.ix[:,0]
>>> type(s)
<class 'pandas.core.series.Series'>
>>>

===========================================================================

UPDATE

If you're reading this after June 2017, ix has been deprecated in pandas 0.20.2, so don't use it. Use loc or iloc instead. See comments and other answers to this question.

Insert line at middle of file with Python?

You can just read the data into a list and insert the new record where you want.

names = []
with open('names.txt', 'r+') as fd:
    for line in fd:
        names.append(line.split(' ')[-1].strip())

    names.insert(2, "Charlie") # element 2 will be 3. in your list
    fd.seek(0)
    fd.truncate()

    for i in xrange(len(names)):
        fd.write("%d. %s\n" %(i + 1, names[i]))

HTTP test server accepting GET/POST requests

There is http://ptsv2.com/

"Here you will find a server which receives any POST you wish to give it and stores the contents for you to review."

Find non-ASCII characters in varchar columns using SQL Server

This script searches for non-ascii characters in one column. It generates a string of all valid characters, here code point 32 to 127. Then it searches for rows that don't match the list:

declare @str varchar(128)
declare @i int
set @str = ''
set @i = 32
while @i <= 127
    begin
    set @str = @str + '|' + char(@i)
    set @i = @i + 1
    end

select  col1
from    YourTable
where   col1 like '%[^' + @str + ']%' escape '|'

jQuery: serialize() form and other parameters

Following Rory McCrossan answer, if you want to send an array of integer (almost for .NET), this is the code:

// ...

url: "MyUrl",       //  For example --> @Url.Action("Method", "Controller")
method: "post",
traditional: true,  
data: 
    $('#myForm').serialize() +
    "&param1="xxx" +
    "&param2="33" +
    "&" + $.param({ paramArray: ["1","2","3"]}, true)
,             

// ...

Android: No Activity found to handle Intent error? How it will resolve

Generally to avoid this kind of exceptions, you will need to surround your code by try and catch like this

try{

// your intent here

} catch (ActivityNotFoundException e) {
// show message to user 
}

Call int() function on every list element?

This is what list comprehensions are for:

numbers = [ int(x) for x in numbers ]

jQuery: how to scroll to certain anchor/div on page load?

I have tried some hours now and the easiest way to stop browsers to jump to the anchor instead of scrolling to it is: Using another anchor (an id you do not use on the site). So instead of linking to "http://#YourActualID" you link to "http://#NoIDonYourSite". Poof, browsers won’t jump anymore.

Then just check if an anchor is set (with the script provided below, that is pulled out of the other thread!). And set your actual id you want to scroll to.

$(document).ready(function(){


  $(window).load(function(){
    // Remove the # from the hash, as different browsers may or may not include it
    var hash = location.hash.replace('#','');

    if(hash != ''){

       // Clear the hash in the URL
       // location.hash = '';   // delete front "//" if you want to change the address bar
        $('html, body').animate({ scrollTop: $('#YourIDtoScrollTo').offset().top}, 1000);

       }
   });
});

See https://lightningsoul.com/media/article/coding/30/YOUTUBE-SOCKREAD-SCRIPT-FOR-MIRC#content for a working example.

How can I view live MySQL queries?

You can run the MySQL command SHOW FULL PROCESSLIST; to see what queries are being processed at any given time, but that probably won't achieve what you're hoping for.

The best method to get a history without having to modify every application using the server is probably through triggers. You could set up triggers so that every query run results in the query being inserted into some sort of history table, and then create a separate page to access this information.

Do be aware that this will probably considerably slow down everything on the server though, with adding an extra INSERT on top of every single query.


Edit: another alternative is the General Query Log, but having it written to a flat file would remove a lot of possibilities for flexibility of displaying, especially in real-time. If you just want a simple, easy-to-implement way to see what's going on though, enabling the GQL and then using running tail -f on the logfile would do the trick.

How to retrieve element value of XML using Java?

There are a number of different ways to do this. You might want to check out XStream or JAXB. There are tutorials and the examples.

Which is faster: Stack allocation or Heap allocation

Stack allocation is much faster since all it really does is move the stack pointer. Using memory pools, you can get comparable performance out of heap allocation, but that comes with a slight added complexity and its own headaches.

Also, stack vs. heap is not only a performance consideration; it also tells you a lot about the expected lifetime of objects.

Empty set literal?

Yes. The same notation that works for non-empty dict/set works for empty ones.

Notice the difference between non-empty dict and set literals:

{1: 'a', 2: 'b', 3: 'c'} -- a number of key-value pairs inside makes a dict
{'aaa', 'bbb', 'ccc'} -- a tuple of values inside makes a set

So:

{} == zero number of key-value pairs == empty dict
{*()} == empty tuple of values == empty set

However the fact, that you can do it, doesn't mean you should. Unless you have some strong reasons, it's better to construct an empty set explicitly, like:

a = set()

Performance:

The literal is ~15% faster than the set-constructor (CPython-3.8, 2019 PC, Intel(R) Core(TM) i7-8550U CPU @ 1.80GHz):

>>> %timeit ({*()} & {*()}) | {*()}
214 ns ± 1.26 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)

>>> %timeit (set() & set()) | set()
252 ns ± 0.566 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)

... and for completeness, Renato Garcia's frozenset proposal on the above expression is some 60% faster!

>>> ? = frozenset()

>>> %timeit (? & ?) | ?
100 ns ± 0.51 ns per loop (mean ± std. dev. of 7 runs, 10000000 loops each)

NB: As ctrueden noticed in comments, {()} is not an empty set. It's a set with 1 element: empty tuple.

No Exception while type casting with a null in java

This language feature is convenient in this situation.

public String getName() {
  return (String) memberHashMap.get("Name");
}

If memberHashMap.get("Name") returns null, you'd still want the method above to return null without throwing an exception. No matter what the class is, null is null.

Converting a float to a string without rounding it

Other answers already pointed out that the representation of floating numbers is a thorny issue, to say the least.

Since you don't give enough context in your question, I cannot know if the decimal module can be useful for your needs:

http://docs.python.org/library/decimal.html

Among other things you can explicitly specify the precision that you wish to obtain (from the docs):

>>> getcontext().prec = 6
>>> Decimal('3.0')
Decimal('3.0')
>>> Decimal('3.1415926535')
Decimal('3.1415926535')
>>> Decimal('3.1415926535') + Decimal('2.7182818285')
Decimal('5.85987')
>>> getcontext().rounding = ROUND_UP
>>> Decimal('3.1415926535') + Decimal('2.7182818285')
Decimal('5.85988')

A simple example from my prompt (python 2.6):

>>> import decimal
>>> a = decimal.Decimal('10.000000001')
>>> a
Decimal('10.000000001')
>>> print a
10.000000001
>>> b = decimal.Decimal('10.00000000000000000000000000900000002')
>>> print b
10.00000000000000000000000000900000002
>>> print str(b)
10.00000000000000000000000000900000002
>>> len(str(b/decimal.Decimal('3.0')))
29

Maybe this can help? decimal is in python stdlib since 2.4, with additions in python 2.6.

Hope this helps, Francesco

How to create a pivot query in sql server without aggregate function

SELECT *
FROM
(
SELECT [Period], [Account], [Value]
FROM TableName
) AS source
PIVOT
(
    MAX([Value])
    FOR [Period] IN ([2000], [2001], [2002])
) as pvt

Another way,

SELECT ACCOUNT,
      MAX(CASE WHEN Period = '2000' THEN Value ELSE NULL END) [2000],
      MAX(CASE WHEN Period = '2001' THEN Value ELSE NULL END) [2001],
      MAX(CASE WHEN Period = '2002' THEN Value ELSE NULL END) [2002]
FROM tableName
GROUP BY Account

MySQL Select last 7 days

The WHERE clause is misplaced, it has to follow the table references and JOIN operations.

Something like this:

 FROM tartikel p1 
 JOIN tartikelpict p2 
   ON p1.kArtikel = p2.kArtikel 
  AND p2.nNr = 1
WHERE p1.dErstellt >= DATE(NOW()) - INTERVAL 7 DAY
ORDER BY p1.kArtikel DESC

EDIT (three plus years later)

The above essentially answers the question "I tried to add a WHERE clause to my query and now the query is returning an error, how do I fix it?"

As to a question about writing a condition that checks a date range of "last 7 days"...

That really depends on interpreting the specification, what the datatype of the column in the table is (DATE or DATETIME) and what data is available... what should be returned.

To summarize: the general approach is to identify a "start" for the date/datetime range, and "end" of that range, and reference those in a query. Let's consider something easier... all rows for "yesterday".

If our column is DATE type. Before we incorporate an expression into a query, we can test it in a simple SELECT

 SELECT DATE(NOW()) + INTERVAL -1 DAY 

and verify the result returned is what we expect. Then we can use that same expression in a WHERE clause, comparing it to a DATE column like this:

 WHERE datecol = DATE(NOW()) + INTERVAL -1 DAY

For a DATETIME or TIMESTAMP column, we can use >= and < inequality comparisons to specify a range

 WHERE datetimecol >= DATE(NOW()) + INTERVAL -1 DAY
   AND datetimecol <  DATE(NOW()) + INTERVAL  0 DAY

For "last 7 days" we need to know if that mean from this point right now, back 7 days ... e.g. the last 7*24 hours , including the time component in the comparison, ...

 WHERE datetimecol >= NOW() + INTERVAL -7 DAY
   AND datetimecol <  NOW() + INTERVAL  0 DAY

the last seven complete days, not including today

 WHERE datetimecol >= DATE(NOW()) + INTERVAL -7 DAY
   AND datetimecol <  DATE(NOW()) + INTERVAL  0 DAY

or past six complete days plus so far today ...

 WHERE datetimecol >= DATE(NOW()) + INTERVAL -6 DAY
   AND datetimecol <  NOW()       + INTERVAL  0 DAY

I recommend testing the expressions on the right side in a SELECT statement, we can use a user-defined variable in place of NOW() for testing, not being tied to what NOW() returns so we can test borders, across week/month/year boundaries, and so on.

SET @clock = '2017-11-17 11:47:47' ;

SELECT DATE(@clock)
     , DATE(@clock) + INTERVAL -7 DAY 
     , @clock + INTERVAL -6 DAY 

Once we have expressions that return values that work for "start" and "end" for our particular use case, what we mean by "last 7 days", we can use those expressions in range comparisons in the WHERE clause.

(Some developers prefer to use the DATE_ADD and DATE_SUB functions in place of the + INTERVAL val DAY/HOUR/MINUTE/MONTH/YEAR syntax.

And MySQL provides some convenient functions for working with DATE, DATETIME and TIMESTAMP datatypes... DATE, LAST_DAY,

Some developers prefer to calculate the start and end in other code, and supply string literals in the SQL query, such that the query submitted to the database is

  WHERE datetimecol >= '2017-11-10 00:00'
    AND datetimecol <  '2017-11-17 00:00'

And that approach works too. (My preference would be to explicitly cast those string literals into DATETIME, either with CAST, CONVERT or just the + INTERVAL trick...

  WHERE datetimecol >= '2017-11-10 00:00' + INTERVAL 0 SECOND
    AND datetimecol <  '2017-11-17 00:00' + INTERVAL 0 SECOND

The above all assumes we are storing "dates" in appropriate DATE, DATETIME and/or TIMESTAMP datatypes, and not storing them as strings in variety of formats e.g. 'dd/mm/yyyy', m/d/yyyy, julian dates, or in sporadically non-canonical formats, or as a number of seconds since the beginning of the epoch, this answer would need to be much longer.

Use dynamic (variable) string as regex pattern in JavaScript

To create the regex from a string, you have to use JavaScript's RegExp object.

If you also want to match/replace more than one time, then you must add the g (global match) flag. Here's an example:

var stringToGoIntoTheRegex = "abc";
var regex = new RegExp("#" + stringToGoIntoTheRegex + "#", "g");
// at this point, the line above is the same as: var regex = /#abc#/g;

var input = "Hello this is #abc# some #abc# stuff.";
var output = input.replace(regex, "!!");
alert(output); // Hello this is !! some !! stuff.

JSFiddle demo here.


In the general case, escape the string before using as regex:

Not every string is a valid regex, though: there are some speciall characters, like ( or [. To work around this issue, simply escape the string before turning it into a regex. A utility function for that goes in the sample below:

function escapeRegExp(stringToGoIntoTheRegex) {
    return stringToGoIntoTheRegex.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&');
}

var stringToGoIntoTheRegex = escapeRegExp("abc"); // this is the only change from above
var regex = new RegExp("#" + stringToGoIntoTheRegex + "#", "g");
// at this point, the line above is the same as: var regex = /#abc#/g;

var input = "Hello this is #abc# some #abc# stuff.";
var output = input.replace(regex, "!!");
alert(output); // Hello this is !! some !! stuff.

JSFiddle demo here.



Note: the regex in the question uses the s modifier, which didn't exist at the time of the question, but does exist -- a s (dotall) flag/modifier in JavaScript -- today.

SQL: How do I SELECT only the rows with a unique value on certain column?

Utilizing the "dynamic table" capability in SQL Server (querying against a parenthesis-surrounded query), you can return 2000, 49 w/ the following. If your platform doesn't offer an equivalent to the "dynamic table" ANSI-extention, you can always utilize a temp table in two-steps/statement by inserting the results within the "dynamic table" to a temp table, and then performing a subsequent select on the temp table.

DECLARE  @T TABLE(
    [contract] INT,
    project INT,
    activity INT
)

INSERT INTO @T VALUES( 1000,    8000,    10 )
INSERT INTO @T VALUES( 1000,    8000,    20 )
INSERT INTO @T VALUES( 1000,    8001,    10 )
INSERT INTO @T VALUES( 2000,    9000,    49 )
INSERT INTO @T VALUES( 2000,    9001,    49 )
INSERT INTO @T VALUES( 3000,    9000,    79 )
INSERT INTO @T VALUES( 3000,    9000,    78 )

SELECT
    [contract],
    [Activity] =  max (activity)
FROM
    (
    SELECT
        [contract],
        [Activity]
    FROM
        @T
    GROUP BY
        [contract],
        [Activity]
    ) t
GROUP BY
    [contract]
HAVING count (*) = 1

What are your favorite extension methods for C#? (codeplex.com/extensionoverflow)

Sql server has a limit of ~2000 parameters, which is a pain if you have 10k Ids and want the records connected with them. I wrote these methods which accept batched lists of ids and are called like this:

List<Order> orders = dataContext.Orders.FetchByIds(
  orderIdChunks,
  list => row => list.Contains(row.OrderId)
);

List<Customer> customers = dataContext.Orders.FetchByIds(
  orderIdChunks,
  list => row => list.Contains(row.OrderId),
  row => row.Customer
);

public static List<ResultType> FetchByIds<RecordType, ResultType>(
    this IQueryable<RecordType> querySource,
    List<List<int>> IdChunks,
    Func<List<int>, Expression<Func<RecordType, bool>>> filterExpressionGenerator,
    Expression<Func<RecordType, ResultType>> projectionExpression
    ) where RecordType : class
{
    List<ResultType> result = new List<ResultType>();
    foreach (List<int> chunk in IdChunks)
    {
        Expression<Func<RecordType, bool>> filterExpression =
            filterExpressionGenerator(chunk);

        IQueryable<ResultType> query = querySource
            .Where(filterExpression)
            .Select(projectionExpression);

        List<ResultType> rows = query.ToList();
        result.AddRange(rows);
    }

    return result;
}

public static List<RecordType> FetchByIds<RecordType>(
    this IQueryable<RecordType> querySource,
    List<List<int>> IdChunks,
    Func<List<int>, Expression<Func<RecordType, bool>>> filterExpressionGenerator
    ) where RecordType : class
{
    Expression<Func<RecordType, RecordType>> identity = r => r;

    return FetchByIds(
        querySource,
        IdChunks,
        filterExpressionGenerator,
        identity
        );
}

Reading values from DataTable

You can do it using the foreach loop

DataTable dr_art_line_2 = ds.Tables["QuantityInIssueUnit"];

  foreach(DataRow row in dr_art_line_2.Rows)
  {
     QuantityInIssueUnit_value = Convert.ToInt32(row["columnname"]);
  }

Best way to get whole number part of a Decimal number

By the way guys, (int)Decimal.MaxValue will overflow. You can't get the "int" part of a decimal because the decimal is too friggen big to put in the int box. Just checked... its even too big for a long (Int64).

If you want the bit of a Decimal value to the LEFT of the dot, you need to do this:

Math.Truncate(number)

and return the value as... A DECIMAL or a DOUBLE.

edit: Truncate is definitely the correct function!

Angular 5, HTML, boolean on checkbox is checked

Work with checkboxes using observables

You could even choose to use a behaviourSubject to utilize the power of observables so you can start a certain chain of reaction starting at the isChecked$ observable.

In your component.ts:

public isChecked$ = new BehaviorSubject(false);
toggleChecked() {
  this.isChecked$.next(!this.isChecked$.value)
}

In your template

<input type="checkbox" [checked]="isChecked$ | async" (change)="toggleChecked()">

Find the 2nd largest element in an array with minimum number of comparisons

Sorry, JS code...

Tested with the two inputs:

a = [55,11,66,77,72];
a = [ 0, 12, 13, 4, 5, 32, 8 ];

var first = Number.MIN_VALUE;
var second = Number.MIN_VALUE;
for (var i = -1, len = a.length; ++i < len;) {
    var dist = a[i];
    // get the largest 2
    if (dist > first) {
        second = first;
        first = dist;
    } else if (dist > second) { // && dist < first) { // this is actually not needed, I believe
        second = dist;
    }
}

console.log('largest, second largest',first,second);
largest, second largest 32 13

This should have a maximum of a.length*2 comparisons and only goes through the list once.

docker container ssl certificates

Mount the certs onto the Docker container using -v:

docker run -v /host/path/to/certs:/container/path/to/certs -d IMAGE_ID "update-ca-certificates"

How to iterate for loop in reverse order in swift?

Swift 4.0

for i in stride(from: 5, to: 0, by: -1) {
    print(i) // 5,4,3,2,1
}

If you want to include the to value:

for i in stride(from: 5, through: 0, by: -1) {
    print(i) // 5,4,3,2,1,0
}

Django: TemplateSyntaxError: Could not parse the remainder

For me it was using {{ }} instead of {% %}:

href="{{ static 'bootstrap.min.css' }}"  # wrong
href="{% static 'bootstrap.min.css' %}"  # right

Split files using tar, gz, zip, or bzip2

If you are splitting from Linux, you can still reassemble in Windows.

copy /b file1 + file2 + file3 + file4 filetogether

How create a new deep copy (clone) of a List<T>?

Since Clone would return an object instance of Book, that object would first need to be cast to a Book before you can call ToList on it. The example above needs to be written as:

List<Book> books_2 = books_1.Select(book => (Book)book.Clone()).ToList();

Invalid shorthand property initializer

Change the = to : to fix the error.

var makeRequest = function(message) {<br>
 var options = {<br>
  host: 'localhost',<br>
  port : 8080,<br>
  path : '/',<br>
  method: 'POST'<br>
 }

Best Practice: Access form elements by HTML id or name attribute?

This is a bit old but I want to add a thing I think is relevant.
(I meant to comment on one or 2 threads above but it seems I need reputation 50 and I have only 21 at the time I'm writing this. :) )
Just want to say that there are times when it's much better to access the elements of a form by name rather than by id. I'm not talking about the form itself. The form, OK, you can give it an id and then access it by it. But if you have a radio button in a form, it's much easier to use it as a single object (getting and setting its value) and you can only do this by name, as far as I know.

Example:

<form id="mainForm" name="mainForm">
    <input type="radio" name="R1" value="V1">choice 1<br/>
    <input type="radio" name="R1" value="V2">choice 2<br/>
    <input type="radio" name="R1" value="V3">choice 3
</form>

You can get/set the checked value of the radio button R1 as a whole by using
document.mainForm.R1.value
or
document.getElementById("mainForm").R1.value
So if you want to have a unitary style, you might want to always use this method, regardless of the type of form element. Me, I'm perfectly comfortable accessing radio buttons by name and text boxes by id.

X11/Xlib.h not found in Ubuntu

Presume he's using the tutorial from http://www.arcsynthesis.org/gltut/ along with premake4.3 :-)

sudo apt-get install libx11-dev ................. for X11/Xlib.h
sudo apt-get install mesa-common-dev........ for GL/glx.h
sudo apt-get install libglu1-mesa-dev ..... for GL/glu.h
sudo apt-get install libxrandr-dev ........... for X11/extensions/Xrandr.h
sudo apt-get install libxi-dev ................... for X11/extensions/XInput.h

After which I could build glsdk_0.4.4 and examples without further issue.

What is limiting the # of simultaneous connections my ASP.NET application can make to a web service?

while doing performance testing, the measure i go by is RPS, that is how many requests per second can the server serve within acceptable latency.

theoretically one server can only run as many requests concurrently as number of cores on it..

It doesn't look like the problem is ASP.net's threading model, since it can potentially serve thousands of rps. It seems like the problem might be your application. Are you using any synchronization primitives ?

also whats the latency on your web services, are they very quick to respond (within microseconds), if not then you might want to consider asynchronous calls, so you dont end up blocking

If this doesnt yeild something, then you might want to profile your code using visual studio or redgate profiler

wildcard * in CSS for classes

What you need is called attribute selector. An example, using your html structure, is the following:

div[class^="tocolor-"], div[class*=" tocolor-"] {
    color:red 
}

In the place of div you can add any element or remove it altogether, and in the place of class you can add any attribute of the specified element.

[class^="tocolor-"] — starts with "tocolor-".
[class*=" tocolor-"] — contains the substring "tocolor-" occurring directly after a space character.

Demo: http://jsfiddle.net/K3693/1/

More information on CSS attribute selectors, you can find here and here. And from MDN Docs MDN Docs

jQuery, simple polling example

This solution:

  1. has timeout
  2. polling works also after error response

Minimum version of jQuery is 1.12

$(document).ready(function () {
  function poll () {
    $.get({
      url: '/api/stream/',
      success: function (data) {
        console.log(data)
      },
      timeout: 10000                    // == 10 seconds timeout
    }).always(function () {
      setTimeout(poll, 30000)           // == 30 seconds polling period
    })
  }

  // start polling
  poll()
})

TypeScript Objects as Dictionary types as in C#

You can also use the Record type in typescript :

export interface nameInterface { 
    propName : Record<string, otherComplexInterface> 
}

How can I pretty-print JSON using Go?

Here is my solution:

import (
    "bytes"
    "encoding/json"
)

const (
    empty = ""
    tab   = "\t"
)

func PrettyJson(data interface{}) (string, error) {
    buffer := new(bytes.Buffer)
    encoder := json.NewEncoder(buffer)
    encoder.SetIndent(empty, tab)

    err := encoder.Encode(data)
    if err != nil {
       return empty, err
    }
    return buffer.String(), nil
}

How do I check if there are duplicates in a flat list?

This is old, but the answers here led me to a slightly different solution. If you are up for abusing comprehensions, you can get short-circuiting this way.

xs = [1, 2, 1]
s = set()
any(x in s or s.add(x) for x in xs)
# You can use a similar approach to actually retrieve the duplicates.
s = set()
duplicates = set(x for x in xs if x in s or s.add(x))

How to push elements in JSON from javascript array

var arr = [ 'a', 'b', 'c'];
arr.push('d'); // insert as last item

CSS Styling for a Button: Using <input type="button> instead of <button>

Do you really want to style the <div>? Or do you want to style the <input type="button">? You should use the correct selector if you want the latter:

input[type=button] {
    color:#08233e;
    font:2.4em Futura, ‘Century Gothic’, AppleGothic, sans-serif;
    font-size:70%;
    /* ... other rules ... */
    cursor:pointer;
}

input[type=button]:hover {
    background-color:rgba(255,204,0,0.8);
}

See also:

sweet-alert display HTML code in text

I was upgrading from old sweetalert and found out how to do it in the new Version (official Docs):

// this is a Node object    
var span = document.createElement("span");
span.innerHTML = "Testno  sporocilo za objekt <b>test</b>";

swal({
    title: "" + txt + "", 
    content: span,
    confirmButtonText: "V redu", 
    allowOutsideClick: "true" 
});

What is the opposite of evt.preventDefault();

I had to delay a form submission in jQuery in order to execute an asynchronous call. Here's the simplified code...

$("$theform").submit(function(e) {
    e.preventDefault();
    var $this = $(this);
    $.ajax('/path/to/script.php',
        {
        type: "POST",
        data: { value: $("#input_control").val() }
    }).done(function(response) {
        $this.unbind('submit').submit();
    });
});

How to identify unused CSS definitions from multiple CSS files in a project

Google Chrome Developer Tools has (a currently experimental) feature called CSS Overview which will allow you to find unused CSS rules.

To enable it follow these steps:

  1. Open up DevTools (Command+Option+I on Mac; Control+Shift+I on Windows)
  2. Head over to DevTool Settings (Function+F1 on Mac; F1 on Windows)
  3. Click open the Experiments section
  4. Enable the CSS Overview option

enter image description here

How to make a simple popup box in Visual C#?

Try this:

string text = "My text that I want to display";
MessageBox.Show(text);

postgresql - add boolean column to table set default

If you want an actual boolean column:

ALTER TABLE users ADD "priv_user" boolean DEFAULT false;

How to find my php-fpm.sock?

When you look up your php-fpm.conf

example location:
cat /usr/src/php/sapi/fpm/php-fpm.conf

you will see, that you need to configure the PHP FastCGI Process Manager to actually use Unix sockets. Per default, the listen directive` is set up to listen on a TCP socket on one port. If there's no Unix socket defined, you won't find a Unix socket file.

; The address on which to accept FastCGI requests.
; Valid syntaxes are:
;   'ip.add.re.ss:port'    - to listen on a TCP socket to a specific IPv4 address on
;                            a specific port;
;   '[ip:6:addr:ess]:port' - to listen on a TCP socket to a specific IPv6 address on
;                            a specific port;
;   'port'                 - to listen on a TCP socket to all IPv4 addresses on a
;                            specific port;
;   '[::]:port'            - to listen on a TCP socket to all addresses
;                            (IPv6 and IPv4-mapped) on a specific port;
;   '/path/to/unix/socket' - to listen on a unix socket.
; Note: This value is mandatory.
listen = 127.0.0.1:9000

Make button width fit to the text

Remove the width and display: block and then add display: inline-block to the button. To have it remain centered you can either add text-align: center; on the body or do the same on a newly created container.

The advantage of this approach (as opossed to centering with auto margins) is that the button will remain centered regardless of how much text it has.

Example: http://cssdeck.com/labs/2u4kf6dv

How to set TextView textStyle such as bold, italic

Best way is to define it in styles.xml

<style name="common_txt_style_heading" parent="android:style/Widget.TextView">
        <item name="android:textSize">@dimen/common_txtsize_heading</item>
        <item name="android:textColor">@color/color_black</item>
        <item name="android:textStyle">bold|italic</item>
</style>

And update it in TextView

  <TextView
     android:id="@+id/txt_userprofile"
     style="@style/common_txt_style_heading"
     android:layout_width="wrap_content"
     android:layout_height="wrap_content"
     android:layout_centerHorizontal="true"
     android:layout_marginTop="@dimen/margin_small"
     android:text="@string/some_heading" />

How to remove item from a JavaScript object

_x000D_
_x000D_
var test = {'red':'#FF0000', 'blue':'#0000FF'};_x000D_
delete test.blue; // or use => delete test['blue'];_x000D_
console.log(test);
_x000D_
_x000D_
_x000D_

this deletes test.blue

Fastest way to remove non-numeric characters from a VARCHAR in SQL Server

replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(string,'a',''),'b',''),'c',''),'d',''),'e',''),'f',''),'g',''),'h',''),'i',''),'j',''),'k',''),'l',''),'m',''),'n',''),'o',''),'p',''),'q',''),'r',''),'s',''),'t',''),'u',''),'v',''),'w',''),'x',''),'y',''),'z',''),'A',''),'B',''),'C',''),'D',''),'E',''),'F',''),'G',''),'H',''),'I',''),'J',''),'K',''),'L',''),'M',''),'N',''),'O',''),'P',''),'Q',''),'R',''),'S',''),'T',''),'U',''),'V',''),'W',''),'X',''),'Y',''),'Z','')*1 AS string,

:)

How to properly create an SVN tag from trunk?

Just use this:

svn  copy  http://svn.example.com/project/trunk  
           http://svn.example.com/project/branches/release-1
           -m  "branch for release 1.0"

(all on one line, of course.) You should always make a branch of the entire trunk folder and contents. It is of course possible to branch sub-parts of the trunk, but this will almost never be a good practice. You want the branch to behave exactly like the trunk does now, and for that to happen you have to branch the entire trunk.

See a better summary of SVN usage at my blog: SVN Essentials, and SVN Essentials 2

How to make blinking/flashing text with CSS 3

It works for me by using class=blink for the respective element(s)

Simple JS Code

// Blink
      setInterval(function()
        {

        setTimeout(function()
        {

        //$(".blink").css("color","rgba(0,0,0,0.1)"); // If you want simply black/white blink of text
        $(".blink").css("visibility","hidden"); // This is for Visibility of the element  


        },900);


        //$(".blink").css("color","rgba(0,0,0,1)");  // If you want simply black/white blink of text
        $(".blink").css("visibility","visible");  // This is for Visibility of the element

        },1000);

split string only on first instance - java

As many other answers suggest the limit approach, This can be another way

You can use the indexOf method on String which will returns the first Occurance of the given character, Using that index you can get the desired output

String target = "apple=fruit table price=5" ;
int x= target.indexOf("=");
System.out.println(target.substring(x+1));

How to embed HTML into IPython output?

First, the code:

from random import choices

def random_name(length=6):
    return "".join(choices("abcdefghijklmnopqrstuvwxyz", k=length))
# ---

from IPython.display import IFrame, display, HTML
import tempfile
from os import unlink

def display_html_to_frame(html, width=600, height=600):
    name = f"temp_{random_name()}.html"
    with open(name, "w") as f:
        print(html, file=f)
    display(IFrame(name, width, height), metadata=dict(isolated=True))
    # unlink(name)
    
def display_html_inline(html):
    display(HTML(html, metadata=dict(isolated=True)))

h="<html><b>Hello</b></html>"    
display_html_to_iframe(h)
display_html_inline(h)

Some quick notes:

  • You can generally just use inline HTML for simple items. If you are rendering a framework, like a large JavaScript visualization framework, you may need to use an IFrame. Its hard enough for Jupyter to run in a browser without random HTML embedded.
  • The strange parameter, metadata=dict(isolated=True) does not isolate the result in an IFrame, as older documentation suggests. It appears to prevent clear-fix from resetting everything. The flag is no longer documented: I just found using it allowed certain display: grid styles to correctly render.
  • This IFrame solution writes to a temporary file. You could use a data uri as described here but it makes debugging your output difficult. The Jupyter IFrame function does not take a data or srcdoc attribute.
  • The tempfile module creations are not sharable to another process, hence the random_name().
  • If you use the HTML class with an IFrame in it, you get a warning. This may be only once per session.
  • You can use HTML('Hello, <b>world</b>') at top level of cell and its return value will render. Within a function, use display(HTML(...)) as is done above. This also allows you to mix display and print calls freely.
  • Oddly, IFrames are indented slightly more than inline HTML.

Getting a Request.Headers value

if ((Request.Headers["XYZComponent"] ?? "") == "true")
{
    // header is present and set to "true"
}

Sequelize OR condition object

Seems there is another format now

where: {
    LastName: "Doe",
    $or: [
        {
            FirstName: 
            {
                $eq: "John"
            }
        }, 
        {
            FirstName: 
            {
                $eq: "Jane"
            }
        }, 
        {
            Age: 
            {
                $gt: 18
            }
        }
    ]
}

Will generate

WHERE LastName='Doe' AND (FirstName = 'John' OR FirstName = 'Jane' OR Age > 18)

See the doc: http://docs.sequelizejs.com/en/latest/docs/querying/#where

Creating a chart in Excel that ignores #N/A or blank cells

I found a way to do it.

you can do an x,y scatterplot. it will ignore null records (i.e. rows)

What's the difference between @Component, @Repository & @Service annotations in Spring?

all these annotations are type of stereo type type of annotation,the difference between these three annotations are

  • If we add the @Component then it tells the role of class is a component class it means it is a class consisting some logic,but it does not tell whether a class containing a specifically business or persistence or controller logic so we don't use directly this @Component annotation
  • If we add @Service annotation then it tells that a role of class consisting business logic
  • If we add @Repository on top of class then it tells that a class consisting persistence logic
  • Here @Component is a base annotation for @Service,@Repository and @Controller annotations

for example

package com.spring.anno;
@Service
public class TestBean
{
    public void m1()
    {
       //business code
    }
}

package com.spring.anno;
@Repository
public class TestBean
{
    public void update()
    {
       //persistence code
    }
}
  • whenever we adds the @Service or @Repositroy or @Controller annotation by default @Component annotation is going to existence on top of the class

Push git commits & tags simultaneously

@since Git 2.4

git push --atomic origin <branch name> <tag>

How do I save a String to a text file using Java?

You could do this:

import java.io.*;
import java.util.*;

class WriteText
{
    public static void main(String[] args)
    {   
        try {
            String text = "Your sample content to save in a text file.";
            BufferedWriter out = new BufferedWriter(new FileWriter("sample.txt"));
            out.write(text);
            out.close();
        }
        catch (IOException e)
        {
            System.out.println("Exception ");       
        }

        return ;
    }
};

What's the difference between ASCII and Unicode?

Understanding why ASCII and Unicode were created in the first place helped me understand the differences between the two.

ASCII, Origins

As stated in the other answers, ASCII uses 7 bits to represent a character. By using 7 bits, we can have a maximum of 2^7 (= 128) distinct combinations*. Which means that we can represent 128 characters maximum.

Wait, 7 bits? But why not 1 byte (8 bits)?

The last bit (8th) is used for avoiding errors as parity bit. This was relevant years ago.

Most ASCII characters are printable characters of the alphabet such as abc, ABC, 123, ?&!, etc. The others are control characters such as carriage return, line feed, tab, etc.

See below the binary representation of a few characters in ASCII:

0100101 -> % (Percent Sign - 37)
1000001 -> A (Capital letter A - 65)
1000010 -> B (Capital letter B - 66)
1000011 -> C (Capital letter C - 67)
0001101 -> Carriage Return (13)

See the full ASCII table over here.

ASCII was meant for English only.

What? Why English only? So many languages out there!

Because the center of the computer industry was in the USA at that time. As a consequence, they didn't need to support accents or other marks such as á, ü, ç, ñ, etc. (aka diacritics).

ASCII Extended

Some clever people started using the 8th bit (the bit used for parity) to encode more characters to support their language (to support "é", in French, for example). Just using one extra bit doubled the size of the original ASCII table to map up to 256 characters (2^8 = 256 characters). And not 2^7 as before (128).

10000010 -> é (e with acute accent - 130)
10100000 -> á (a with acute accent - 160)

The name for this "ASCII extended to 8 bits and not 7 bits as before" could be just referred as "extended ASCII" or "8-bit ASCII".

As @Tom pointed out in his comment below there is no such thing as "extended ASCII" yet this is an easy way to refer to this 8th-bit trick. There are many variations of the 8-bit ASCII table, for example, the ISO 8859-1, also called ISO Latin-1.

Unicode, The Rise

ASCII Extended solves the problem for languages that are based on the Latin alphabet... what about the others needing a completely different alphabet? Greek? Russian? Chinese and the likes?

We would have needed an entirely new character set... that's the rational behind Unicode. Unicode doesn't contain every character from every language, but it sure contains a gigantic amount of characters (see this table).

You cannot save text to your hard drive as "Unicode". Unicode is an abstract representation of the text. You need to "encode" this abstract representation. That's where an encoding comes into play.

Encodings: UTF-8 vs UTF-16 vs UTF-32

This answer does a pretty good job at explaining the basics:

  • UTF-8 and UTF-16 are variable length encodings.
  • In UTF-8, a character may occupy a minimum of 8 bits.
  • In UTF-16, a character length starts with 16 bits.
  • UTF-32 is a fixed length encoding of 32 bits.

UTF-8 uses the ASCII set for the first 128 characters. That's handy because it means ASCII text is also valid in UTF-8.

Mnemonics:

  • UTF-8: minimum 8 bits.
  • UTF-16: minimum 16 bits.
  • UTF-32: minimum and maximum 32 bits.

Note:

Why 2^7?

This is obvious for some, but just in case. We have seven slots available filled with either 0 or 1 (Binary Code). Each can have two combinations. If we have seven spots, we have 2 * 2 * 2 * 2 * 2 * 2 * 2 = 2^7 = 128 combinations. Think about this as a combination lock with seven wheels, each wheel having two numbers only.

Source: Wikipedia, this great blog post and Mocki.co where I initially posted this summary.