Programs & Examples On #Assistive technology

Assistive Technology (AT) is primarily used by people with disabilities to assist or allow them to use various technologies.

What is aria-label and how should I use it?

If you wants to know how aria-label helps you practically .. then follow the steps ... you will get it by your own ..

Create a html page having below code

<!DOCTYPE html>
<html lang="en">
<head>
    <title></title>
</head>
<body>
    <button title="Close"> X </button>
    <br />
    <br />
    <br />
    <br />
    <button aria-label="Back to the page" title="Close" > X </button>
</body>
</html>

Now, you need a virtual screen reader emulator which will run on browser to observe the difference. So, chrome browser users can install chromevox extension and mozilla users can go with fangs screen reader addin

Once done with installation, put headphones in your ears, open the html page and make focus on both button(by pressing tab) one-by-one .. and you can hear .. focusing on first x button .. will tell you only x button .. but in case of second x button .. you will hear back to the page button only..

i hope you got it well now!!

offsetTop vs. jQuery.offset().top

I think you are right by saying that people cannot click half pixels, so personally, I would use rounded jQuery offset...

Plot a horizontal line using matplotlib

A nice and easy way for those people who always forget the command axhline is the following

plt.plot(x, [y]*len(x))

In your case xs = x and y = 40. If len(x) is large, then this becomes inefficient and you should really use axhline.

How to run docker-compose up -d at system start up?

I tried restart: always, it works at some containers(like php-fpm), but i faced the problem that some containers(like nginx) is still not restarting after reboot.

Solved the problem.

crontab -e

@reboot (sleep 30s ; cd directory_has_dockercomposeyml ; /usr/local/bin/docker-compose up -d )&

Best way to work with dates in Android SQLite

"SELECT  "+_ID+" ,  "+_DESCRIPTION +","+_CREATED_DATE +","+_DATE_TIME+" FROM "+TBL_NOTIFICATION+" ORDER BY "+"strftime(%s,"+_DATE_TIME+") DESC";

How should I log while using multiprocessing in Python?

Simplest idea as mentioned:

  • Grab the filename and the process id of the current process.
  • Set up a [WatchedFileHandler][1]. The reasons for this handler are discussed in detail here, but in short there are certain worse race conditions with the other logging handlers. This one has the shortest window for the race condition.
    • Choose a path to save the logs to such as /var/log/...

How to insert current_timestamp into Postgres via python

Date and time input is accepted in almost any reasonable format, including ISO 8601, SQL-compatible, traditional POSTGRES, and others. For some formats, ordering of month, day, and year in date input is ambiguous and there is support for specifying the expected ordering of these fields.

In other words: just write anything and it will work.

Or check this table with all the unambiguous formats.

JQuery: dynamic height() with window resize()

To see the window height while (or after) it is resized, try it:

$(window).resize(function() {
$('body').prepend('<div>' + $(window).height() - 46 + '</div>');
});

Generate GUID in MySQL for existing Data?

select @i:=uuid();
update some_table set guid = (@i:=uuid());

Syntax behind sorted(key=lambda: ...)

lambda is a Python keyword that is used to generate anonymous functions.

>>> (lambda x: x+2)(3)
5

C# DataRow Empty-check

public static bool AreAllCellsEmpty(DataRow row)
{
  if (row == null) throw new ArgumentNullException("row");

  for (int i = row.Table.Columns.Count - 1; i >= 0; i--)
    if (!row.IsNull(i))
      return false;

  return true;
}

What permission do I need to access Internet from an Android application?

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

Loop through files in a directory using PowerShell

To get the content of a directory you can use

$files = Get-ChildItem "C:\Users\gerhardl\Documents\My Received Files\"

Then you can loop over this variable as well:

for ($i=0; $i -lt $files.Count; $i++) {
    $outfile = $files[$i].FullName + "out" 
    Get-Content $files[$i].FullName | Where-Object { ($_ -match 'step4' -or $_ -match 'step9') } | Set-Content $outfile
}

An even easier way to put this is the foreach loop (thanks to @Soapy and @MarkSchultheiss):

foreach ($f in $files){
    $outfile = $f.FullName + "out" 
    Get-Content $f.FullName | Where-Object { ($_ -match 'step4' -or $_ -match 'step9') } | Set-Content $outfile
}

How to POST form data with Spring RestTemplate?

How to POST mixed data: File, String[], String in one request.

You can use only what you need.

private String doPOST(File file, String[] array, String name) {
    RestTemplate restTemplate = new RestTemplate(true);

    //add file
    LinkedMultiValueMap<String, Object> params = new LinkedMultiValueMap<>();
    params.add("file", new FileSystemResource(file));

    //add array
    UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl("https://my_url");
    for (String item : array) {
        builder.queryParam("array", item);
    }

    //add some String
    builder.queryParam("name", name);

    //another staff
    String result = "";
    HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.MULTIPART_FORM_DATA);

    HttpEntity<LinkedMultiValueMap<String, Object>> requestEntity =
            new HttpEntity<>(params, headers);

    ResponseEntity<String> responseEntity = restTemplate.exchange(
            builder.build().encode().toUri(),
            HttpMethod.POST,
            requestEntity,
            String.class);

    HttpStatus statusCode = responseEntity.getStatusCode();
    if (statusCode == HttpStatus.ACCEPTED) {
        result = responseEntity.getBody();
    }
    return result;
}

The POST request will have File in its Body and next structure:

POST https://my_url?array=your_value1&array=your_value2&name=bob 

Windows equivalent of $export

To translate your *nix style command script to windows/command batch style it would go like this:

SET PROJ_HOME=%USERPROFILE%/proj/111
SET PROJECT_BASEDIR=%PROJ_HOME%/exercises/ex1
mkdir "%PROJ_HOME%"

mkdir on windows doens't have a -p parameter : from the MKDIR /? help:

MKDIR creates any intermediate directories in the path, if needed.

which basically is what mkdir -p (or --parents for purists) on *nix does, as taken from the man guide

Invalid hook call. Hooks can only be called inside of the body of a function component

Yesterday, I shortened the code (just added <Provider store={store}>) and still got this invalid hook call problem. This made me suddenly realized what mistake I did: I didn't install the react-redux software in that folder.

I had installed this software in the other project folder, so I didn't realize this one also needed it. After installing it, the error is gone.

What key shortcuts are to comment and uncomment code?

"commentLine" is the name of function you are looking for. This function coment and uncoment with the same keybinding

SQL Server® 2016, 2017 and 2019 Express full download

Download the developer edition. There you can choose Express as license when installing.

enter image description here

Copying files from one directory to another in Java

Inspired by Mohit's answer in this thread. Applicable only for Java 8.

The following can be used to copy everything recursively from one folder to another:

public static void main(String[] args) throws IOException {
    Path source = Paths.get("/path/to/source/dir");
    Path destination = Paths.get("/path/to/dest/dir");

    List<Path> sources = Files.walk(source).collect(toList());
    List<Path> destinations = sources.stream()
            .map(source::relativize)
            .map(destination::resolve)
            .collect(toList());

    for (int i = 0; i < sources.size(); i++) {
        Files.copy(sources.get(i), destinations.get(i));
    }
}

Stream-style FTW.

Upd 2019-06-10: important note - close the stream (e.g. using try-with-resource) acquired by Files.walk call. Thanks to @jannis for the point.

How to make a custom LinkedIn share button

This works for me:

https://www.linkedin.com/shareArticle?mini=true&url=articleUrl&title=YourarticleTitle&summary=YourarticleSummary&source=YourarticleSource

You can use this link by replacing it with your content. It works 100%.

Disabling SSL Certificate Validation in Spring RestTemplate

If you are using rest template, you can use this piece of code

    fun getClientHttpRequestFactory(): ClientHttpRequestFactory {
        val timeout = envTimeout.toInt()
        val config = RequestConfig.custom()
            .setConnectTimeout(timeout)
            .setConnectionRequestTimeout(timeout)
            .setSocketTimeout(timeout)
            .build()

        val acceptingTrustStrategy = TrustStrategy { chain: Array<X509Certificate?>?, authType: String? -> true }

        val sslContext: SSLContext = SSLContexts.custom()
            .loadTrustMaterial(null, acceptingTrustStrategy)
            .build()

        val csf = SSLConnectionSocketFactory(sslContext)

        val client = HttpClientBuilder
            .create()
            .setDefaultRequestConfig(config)
            .setSSLSocketFactory(csf)
            .setSSLHostnameVerifier(NoopHostnameVerifier.INSTANCE)
            .build()
        return HttpComponentsClientHttpRequestFactory(client)
    }

    @Bean
    fun getRestTemplate(): RestTemplate {
        return RestTemplate(getClientHttpRequestFactory())
    }

An implementation of the fast Fourier transform (FFT) in C#

http://www.exocortex.org/dsp/ is an open-source C# mathematics library with FFT algorithms.

How to check if a string in Python is in ASCII?

I think you are not asking the right question--

A string in python has no property corresponding to 'ascii', utf-8, or any other encoding. The source of your string (whether you read it from a file, input from a keyboard, etc.) may have encoded a unicode string in ascii to produce your string, but that's where you need to go for an answer.

Perhaps the question you can ask is: "Is this string the result of encoding a unicode string in ascii?" -- This you can answer by trying:

try:
    mystring.decode('ascii')
except UnicodeDecodeError:
    print "it was not a ascii-encoded unicode string"
else:
    print "It may have been an ascii-encoded unicode string"

What is the command for cut copy paste a file from one directory to other directory

E:>move "blogger code.txt" d:/"blogger code.txt"

    1 file(s) moved.

"blogger code.txt" is a file name

The file move from E: drive to D: drive

How to convert an Instant to a date format?

Instant i = Instant.ofEpochSecond(cal.getTime);

Read more here and here

Can't find keyplane that supports type 4 for keyboard iPhone-Portrait-NumberPad; using 3876877096_Portrait_iPhone-Simple-Pad_Default

I too had this problem after updating to the latest Xcode Beta. The settings on the simulator are refreshed, so the laptop (external) keyboard was being detected. If you simply press:

iOS Simulator -> Hardware -> Keyboard -> Connect Hardware Keyboard

so that the entry is UNchecked then the software keyboard will be displayed once again.

How to remove youtube branding after embedding video in web page?

I tried this, but it is not possible to remove "Watch on YouTube" icon. Following solution of mine does not remove the icon itself but "blocks" the mouse hover so that watch on YouTube is not click-able. I added a div over icon, so no mouseover will be affected for that logo.

 <div class="holder">
     <div class="frame" id="player" style="height 350"></div>
     <div class="bar" id="bottom-layer">.</div>
 </div>

Where frame is my embedded player. include following to your css file

.holder{
position:relative;
width:640px;
height:350px;
}

.frame{
width: 100%;
height:100%;
}

.bar{
position:absolute;
bottom:0;
right:0;
width:100%;
height:40px;
}

This is not full solution but helps you if you are bothered with users' getting full youtube url.

javascript if number greater than number

Do this.

var x=parseInt(document.forms["frmOrder"]["txtTotal"].value);
var y=parseInt(document.forms["frmOrder"]["totalpoints"].value);

What are the safe characters for making URLs?

Always Safe

In theory and by the specification, these are safe basically anywhere, except the domain name. Percent-encode anything not listed, and you're good to go.

    A-Z a-z 0-9 - . _ ~ ( ) ' ! * : @ , ;

Sometimes Safe

Only safe when used within specific URL components; use with care.

    Paths:     + & =
    Queries:   ? /
    Fragments: ? / # + & =
    

Never Safe

According to the URI specification (RFC 3986), all other characters must be percent-encoded. This includes:

    <space> <control-characters> <extended-ascii> <unicode>
    % < > [ ] { } | \ ^
    

If maximum compatibility is a concern, limit the character set to A-Z a-z 0-9 - _ . (with periods only for filename extensions).

Keep Context in Mind

Even if valid per the specification, a URL can still be "unsafe", depending on context. Such as a file:/// URL containing invalid filename characters, or a query component containing "?", "=", and "&" when not used as delimiters. Correct handling of these cases are generally up to your scripts and can be worked around, but it's something to keep in mind.

SQL Server - transactions roll back on error?

Here the code with getting the error message working with MSSQL Server 2016:

BEGIN TRY
    BEGIN TRANSACTION 
        -- Do your stuff that might fail here
    COMMIT
END TRY
BEGIN CATCH
    IF @@TRANCOUNT > 0
        ROLLBACK TRAN

        DECLARE @ErrorMessage NVARCHAR(4000) = ERROR_MESSAGE()
        DECLARE @ErrorSeverity INT = ERROR_SEVERITY()
        DECLARE @ErrorState INT = ERROR_STATE()

    -- Use RAISERROR inside the CATCH block to return error  
    -- information about the original error that caused  
    -- execution to jump to the CATCH block.  
    RAISERROR (@ErrorMessage, @ErrorSeverity, @ErrorState);
END CATCH

Why does my Eclipse keep not responding?

I just restarted the adb (Android Debug Bridge) this way:

  1. adb kill-server
  2. adb start-server

and it works again!

Resize image proportionally with CSS?

You can use object-fit property:

.my-image {
    width: 100px;
    height: 100px;
    object-fit: contain;
}

This will fit image, without changing the proportionally.

Use of contains in Java ArrayList<String>

You are right that it should work; perhaps you forgot to instantiate something. Does your code look something like this?

String rssFeedURL = "http://stackoverflow.com";
this.rssFeedURLS = new ArrayList<String>();
this.rssFeedURLS.add(rssFeedURL);
if(this.rssFeedURLs.contains(rssFeedURL)) {
// this code will execute
}

For reference, note that the following conditional will also execute if you append this code to the above:

String copyURL = new String(rssFeedURL);
if(this.rssFeedURLs.contains(copyURL)) {
// code will still execute because contains() checks equals()
}

Even though (rssFeedURL == copyURL) is false, rssFeedURL.equals(copyURL) is true. The contains method cares about the equals method.

How to delete migration files in Rails 3

I usually:

  1. Perform a rake db:migrate VERSION=XXX on all environments, to the version before the one I want to delete.
  2. Delete the migration file manually.
  3. If there are pending migrations (i.e., the migration I removed was not the last one), I just perform a new rake db:migrate again.

If your application is already on production or staging, it's safer to just write another migration that destroys your table or columns.

Another great reference for migrations is: http://guides.rubyonrails.org/migrations.html

Check if the file exists using VBA

Function FileExists(fullFileName As String) As Boolean
    FileExists = VBA.Len(VBA.Dir(fullFileName)) > 0
End Function

WAMP Server ERROR "Forbidden You don't have permission to access /phpmyadmin/ on this server."

I faced this problem

Forbidden You don't have permission to access /phpmyadmin/ on this server

Some help about this:

First check you installed a fresh wamp or replace the existing one. If it's fresh there is no problem, For done existing installation.

Follow these steps.

  1. Open your wamp\bin\mysql directory
  2. Check if in this folder there is another folder of mysql with different name, if exists delete it.
  3. enter to remain mysql folder and delete files with duplication.
  4. start your wamp server again. Wamp will be working.

Mean Squared Error in Numpy?

Another alternative to the accepted answer that avoids any issues with matrix multiplication:

 def MSE(Y, YH):
     return np.square(Y - YH).mean()

From the documents for np.square: "Return the element-wise square of the input."

How to get response body using HttpURLConnection, when code other than 2xx is returned?

Wrong method was used for errors, here is the working code:

BufferedReader br = null;
if (100 <= conn.getResponseCode() && conn.getResponseCode() <= 399) {
    br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
} else {
    br = new BufferedReader(new InputStreamReader(conn.getErrorStream()));
}

Floating Point Exception C++ Why and what is it?

Since this page is the number 1 result for the google search "c++ floating point exception", I want to add another thing that can cause such a problem: use of undefined variables.

Creating a Menu in Python

It looks like you've just finished step 3. Instead of running a function, you just print out a statement. A function is defined in the following way:

def addstudent():
    print("Student Added.")

then called by writing addstudent().

I would recommend using a while loop for your input. You can define the menu option outside the loop, put the print statement inside the loop, and do while(#valid option is not picked), then put the if statements after the while. Or you can do a while loop and continue the loop if a valid option is not selected.

Additionally, a dictionary is defined in the following way:

my_dict = {key:definition,...}

How can I submit form on button click when using preventDefault()?

Replace this :

$('#subscription_order_form').submit(function(e){
  e.preventDefault();
});

with this:

$('#subscription_order_form').on('keydown', function(e){
    if (e.which===13) e.preventDefault();
});

FIDDLE

That will prevent the form from submitting when Enter key is pressed as it prevents the default action of the key, but the form will submit normally on click.

Getting the name / key of a JToken with JSON.net

JObject obj = JObject.Parse(json);
var attributes = obj["parent"]["child"]...["your desired element"].ToList<JToken>(); 

foreach (JToken attribute in attributes)
{   
    JProperty jProperty = attribute.ToObject<JProperty>();
    string propertyName = jProperty.Name;
}

When would you use the Builder Pattern?

I used builder in home-grown messaging library. The library core was receiving data from the wire, collecting it with Builder instance, then, once Builder decided it've got everything it needed to create a Message instance, Builder.GetMessage() was constructing a message instance using the data collected from the wire.

How to use the ConfigurationManager.AppSettings

\if what you have posted is exactly what you are using then your problem is a bit obvious. Now assuming in your web.config you have you connection string defined like this

 <add name="SiteSqlServer" connectionString="Data Source=(local);Initial Catalog=some_db;User ID=sa;Password=uvx8Pytec" providerName="System.Data.SqlClient" />

In your code you should use the value in the name attribute to refer to the connection string you want (you could actually define several connection strings to different databases), so you would have

 con.ConnectionString = ConfigurationManager.ConnectionStrings["SiteSqlServer"].ConnectionString;

"Exception has been thrown by the target of an invocation" error (mscorlib)

This is may have 2 reasons

1.I found the connection string error in my web.config file i had changed the connection string and its working.

  1. Connection string is proper then check with the control panel>services> SQL Server Browser > start or not

[Ljava.lang.Object; cannot be cast to

In case entire entity is being return, better solution in spring JPA is use @Query(value = "from entity where Id in :ids")

This return entity type rather than object type

Multiple INNER JOIN SQL ACCESS

Thanks HansUp for your answer, it is very helpful and it works!

I found three patterns working in Access, yours is the best, because it works in all cases.

  • INNER JOIN, your variant. I will call it "closed set pattern". It is possible to join more than two tables to the same table with good performance only with this pattern.

    SELECT C_Name, cr.P_FirstName+" "+cr.P_SurName AS ClassRepresentativ, cr2.P_FirstName+" "+cr2.P_SurName AS ClassRepresentativ2nd
    FROM
         ((class
           INNER JOIN person AS cr 
           ON class.C_P_ClassRep=cr.P_Nr
         )
         INNER JOIN person AS cr2
         ON class.C_P_ClassRep2nd=cr2.P_Nr
      )
    

    ;

  • INNER JOIN "chained-set pattern"

    SELECT C_Name, cr.P_FirstName+" "+cr.P_SurName AS ClassRepresentativ, cr2.P_FirstName+" "+cr2.P_SurName AS ClassRepresentativ2nd
    FROM person AS cr
    INNER JOIN ( class 
       INNER JOIN ( person AS cr2
       ) ON class.C_P_ClassRep2nd=cr2.P_Nr
    ) ON class.C_P_ClassRep=cr.P_Nr
    ;
    
  • CROSS JOIN with WHERE

    SELECT C_Name, cr.P_FirstName+" "+cr.P_SurName AS ClassRepresentativ, cr2.P_FirstName+" "+cr2.P_SurName AS ClassRepresentativ2nd
    FROM class, person AS cr, person AS cr2
    WHERE class.C_P_ClassRep=cr.P_Nr AND class.C_P_ClassRep2nd=cr2.P_Nr
    ;
    

How to update record using Entity Framework Core?

Microsoft Docs gives us two approaches.

Recommended HttpPost Edit code: Read and update

This is the same old way we used to do in previous versions of Entity Framework. and this is what Microsoft recommends for us.

Advantages

  • Prevents overposting
  • EFs automatic change tracking sets the Modified flag on the fields that are changed by form input.

Alternative HttpPost Edit code: Create and attach

an alternative is to attach an entity created by the model binder to the EF context and mark it as modified.

As mentioned in the other answer the read-first approach requires an extra database read, and can result in more complex code for handling concurrency conflicts.

How to see the actual Oracle SQL statement that is being executed

I had (have) a similar problem in a Java application. I wrote a JDBC driver wrapper around the Oracle driver so all output is sent to a log file.

WITH CHECK ADD CONSTRAINT followed by CHECK CONSTRAINT vs. ADD CONSTRAINT

The first syntax is redundant - the WITH CHECK is default for new constraints, and the constraint is turned on by default as well.

This syntax is generated by the SQL management studio when generating sql scripts -- I'm assuming it's some sort of extra redundancy, possibly to ensure the constraint is enabled even if the default constraint behavior for a table is changed.

Replace only some groups with Regex

A good idea could be to encapsulate everything inside groups, no matter if need to identify them or not. That way you can use them in your replacement string. For example:

var pattern = @"(-)(\d+)(-)";
var replaced = Regex.Replace(text, pattern, "$1AA$3"); 

or using a MatchEvaluator:

var replaced = Regex.Replace(text, pattern, m => m.Groups[1].Value + "AA" + m.Groups[3].Value);

Another way, slightly messy, could be using a lookbehind/lookahead:

(?<=-)(\d+)(?=-)

In Python, how do I read the exif data for an image?

Here's the one that may be little easier to read. Hope this is helpful.

from PIL import Image
from PIL import ExifTags

exifData = {}
img = Image.open(picture.jpg)
exifDataRaw = img._getexif()
for tag, value in exifDataRaw.items():
    decodedTag = ExifTags.TAGS.get(tag, tag)
    exifData[decodedTag] = value

how to reset <input type = "file">

var fileInput = $('#uploadCaptureInputFile');
fileInput.replaceWith(fileInput.val('').clone(true));

Java and SQLite

The wiki lists some more wrappers:

Get each line from textarea

For a <br> on each line, use

<textarea wrap="physical"></textarea>

You will get \ns in the value of the textarea. Then, use the nl2br() function to create <br>s, or you can explode() it for <br> or \n.

Hope this helps

How to efficiently calculate a running standard deviation?

The answer is to use Welford's algorithm, which is very clearly defined after the "naive methods" in:

It's more numerically stable than either the two-pass or online simple sum of squares collectors suggested in other responses. The stability only really matters when you have lots of values that are close to each other as they lead to what is known as "catastrophic cancellation" in the floating point literature.

You might also want to brush up on the difference between dividing by the number of samples (N) and N-1 in the variance calculation (squared deviation). Dividing by N-1 leads to an unbiased estimate of variance from the sample, whereas dividing by N on average underestimates variance (because it doesn't take into account the variance between the sample mean and the true mean).

I wrote two blog entries on the topic which go into more details, including how to delete previous values online:

You can also take a look at my Java implement; the javadoc, source, and unit tests are all online:

Mongodb: failed to connect to server on first connect

I connected to a VPN and it worked. I was using school's WiFi.

Getting View's coordinates relative to the root layout

Incase someone is still trying to figure this out. This is how you get the center X and Y of the view.

    int pos[] = new int[2];
    view.getLocationOnScreen(pos);
    int centerX = pos[0] + view.getMeasuredWidth() / 2;
    int centerY = pos[1] + view.getMeasuredHeight() / 2;

Why can't I display a pound (£) symbol in HTML?

Educated guess: You have a ISO-8859-1 encoded pound sign in a UTF-8 encoded page.

Make sure your data is in the right encoding and everything will work fine.

Ignore outliers in ggplot2 boxplot

Use geom_boxplot(outlier.shape = NA) to not display the outliers and scale_y_continuous(limits = c(lower, upper)) to change the axis limits.

An example.

n <- 1e4L
dfr <- data.frame(
  y = exp(rlnorm(n)),  #really right-skewed variable
  f = gl(2, n / 2)
)

p <- ggplot(dfr, aes(f, y)) + 
  geom_boxplot()
p   # big outlier causes quartiles to look too slim

p2 <- ggplot(dfr, aes(f, y)) + 
  geom_boxplot(outlier.shape = NA) +
  scale_y_continuous(limits = quantile(dfr$y, c(0.1, 0.9)))
p2  # no outliers plotted, range shifted

Actually, as Ramnath showed in his answer (and Andrie too in the comments), it makes more sense to crop the scales after you calculate the statistic, via coord_cartesian.

coord_cartesian(ylim = quantile(dfr$y, c(0.1, 0.9)))

(You'll probably still need to use scale_y_continuous to fix the axis breaks.)

jQuery won't parse my JSON from AJAX query

You will to have to set header content type in your php like this:

 <?php

 header('Content-type:application/json');

 ?>

Watch these Video for better understanding....

Reference: http://www.youtube.com/watch?v=EvFXWqEqh6o

Is it possible to do a sparse checkout without checking out the whole repository first?

In git 2.27, it looks like git sparse checkout has evolved. Solution in this answer does not work exactly the same way (compared to git 2.25)

git clone <URL> --no-checkout <directory>
cd <directory>
git sparse-checkout init --cone # to fetch only root files
git sparse-checkout set apps/my_app libs/my_lib # etc, to list sub-folders to checkout
# they are checked out immediately after this command, no need to run git pull

These commands worked better:

git clone --sparse <URL> <directory>
cd <directory>
git sparse-checkout init --cone # to fetch only root files
git sparse-checkout add apps/my_app
git sparse-checkout add libs/my_lib

See also : git-clone --sparse and git-sparse-checkout add

Convert Decimal to Varchar

If you are using SQL Server 2012, 2014 or newer, use the Format Function instead:

select Format( decimalColumnName ,'FormatString','en-US' )

Review the Microsoft topic and .NET format syntax for how to define the format string.

An example for this question would be:

select Format( MyDecimalColumn ,'N','en-US' )

How to query between two dates using Laravel and Eloquent?

The following should work:

$now = date('Y-m-d');
$reservations = Reservation::where('reservation_from', '>=', $now)
                           ->where('reservation_from', '<=', $to)
                           ->get();

Rename Excel Sheet with VBA Macro

Suggest you add handling to test if any of the sheets to be renamed already exist:

Sub Test()

Dim ws As Worksheet
Dim ws1 As Worksheet
Dim strErr As String

On Error Resume Next
For Each ws In ActiveWorkbook.Sheets
Set ws1 = Sheets(ws.Name & "_v1")
    If ws1 Is Nothing Then
        ws.Name = ws.Name & "_v1"
    Else
         strErr = strErr & ws.Name & "_v1" & vbNewLine
    End If
Set ws1 = Nothing
Next
On Error GoTo 0

If Len(strErr) > 0 Then MsgBox strErr, vbOKOnly, "these sheets already existed"

End Sub

request exceeds the configured maxQueryStringLength when using [Authorize]

i have this error using datatables.net

i fixed changing the default ajax Get to POST in te properties of the DataTable()

"ajax": {
        "url": "../ControllerName/MethodJson",
        "type": "POST"
    },

How to calculate date difference in JavaScript?

If you are using moment.js then it is pretty simple to find date difference.

var now  = "04/09/2013 15:00:00";
var then = "04/09/2013 14:20:30";

moment.utc(moment(now,"DD/MM/YYYY HH:mm:ss").diff(moment(then,"DD/MM/YYYY HH:mm:ss"))).format("HH:mm:ss")

How to call a parent class function from derived class function?

I'll take the risk of stating the obvious: You call the function, if it's defined in the base class it's automatically available in the derived class (unless it's private).

If there is a function with the same signature in the derived class you can disambiguate it by adding the base class's name followed by two colons base_class::foo(...). You should note that unlike Java and C#, C++ does not have a keyword for "the base class" (super or base) since C++ supports multiple inheritance which may lead to ambiguity.

class left {
public:
    void foo();
};

class right {
public:
    void foo();
};

class bottom : public left, public right {
public:
    void foo()
    {
        //base::foo();// ambiguous
        left::foo();
        right::foo();

        // and when foo() is not called for 'this':
        bottom b;
        b.left::foo();  // calls b.foo() from 'left'
        b.right::foo();  // call b.foo() from 'right'
    }
};

Incidentally, you can't derive directly from the same class twice since there will be no way to refer to one of the base classes over the other.

class bottom : public left, public left { // Illegal
};

How to use Git Revert

git revert makes a new commit

git revert simply creates a new commit that is the opposite of an existing commit.

It leaves the files in the same state as if the commit that has been reverted never existed. For example, consider the following simple example:

$ cd /tmp/example
$ git init
Initialized empty Git repository in /tmp/example/.git/
$ echo "Initial text" > README.md
$ git add README.md
$ git commit -m "initial commit"
[master (root-commit) 3f7522e] initial commit
 1 file changed, 1 insertion(+)
 create mode 100644 README.md
$ echo "bad update" > README.md 
$ git commit -am "bad update"
[master a1b9870] bad update
 1 file changed, 1 insertion(+), 1 deletion(-)

In this example the commit history has two commits and the last one is a mistake. Using git revert:

$ git revert HEAD
[master 1db4eeb] Revert "bad update"
 1 file changed, 1 insertion(+), 1 deletion(-)

There will be 3 commits in the log:

$ git log --oneline
1db4eeb Revert "bad update"
a1b9870 bad update
3f7522e initial commit

So there is a consistent history of what has happened, yet the files are as if the bad update never occured:

cat README.md 
Initial text

It doesn't matter where in the history the commit to be reverted is (in the above example, the last commit is reverted - any commit can be reverted).

Closing questions

do you have to do something else after?

A git revert is just another commit, so e.g. push to the remote so that other users can pull/fetch/merge the changes and you're done.

Do you have to commit the changes revert made or does revert directly commit to the repo?

git revert is a commit - there are no extra steps assuming reverting a single commit is what you wanted to do.

Obviously you'll need to push again and probably announce to the team.

Indeed - if the remote is in an unstable state - communicating to the rest of the team that they need to pull to get the fix (the reverting commit) would be the right thing to do :).

Switching to a TabBar tab view programmatically?

My issue is a little different, I need to switch from one childViewController in 1st tabBar to home viewController of 2nd tabBar. I simply use the solution provided in the upstairs:

tabBarController.selectedIndex = 2

However when it switched to the home page of 2nd tabBar, the content is invisible. And when I debug, viewDidAppear, viewWillAppear, viewDidLoad, none of them is called. My solutions is to add the following code in the UITabBarController:

override var shouldAutomaticallyForwardAppearanceMethods: Bool 
{
    return true
}

How to convert a SVG to a PNG with ImageMagick?

why don't you give a try to inkscape command line, this is my bat file to convert all svg in this dir to png:

FOR %%x IN (*.svg) DO C:\Ink\App\Inkscape\inkscape.exe %%x -z --export-dpi=500 --export-area-drawing --export-png="%%~nx.png"

Make a directory and copy a file

Use the FileSystemObject object, namely, its CreateFolder and CopyFile methods. Basically, this is what your script will look like:

Dim oFSO
Set oFSO = CreateObject("Scripting.FileSystemObject")

' Create a new folder
oFSO.CreateFolder "C:\MyFolder"

' Copy a file into the new folder
' Note that the destination folder path must end with a path separator (\)
oFSO.CopyFile "\\server\folder\file.ext", "C:\MyFolder\"

You may also want to add additional logic, like checking whether the folder you want to create already exists (because CreateFolder raises an error in this case) or specifying whether or not to overwrite the file being copied. So, you can end up with this:

Const strFolder = "C:\MyFolder\", strFile = "\\server\folder\file.ext"
Const Overwrite = True
Dim oFSO

Set oFSO = CreateObject("Scripting.FileSystemObject")

If Not oFSO.FolderExists(strFolder) Then
  oFSO.CreateFolder strFolder
End If

oFSO.CopyFile strFile, strFolder, Overwrite

Is there any sizeof-like method in Java?

The Java Native Access library is typically used for calling native shared libraries from Java. Within this library there exist methods for determining the size of Java objects:

The getNativeSize(Class cls) method and its overloads will provide the size for most classes.

Alternatively, if your classes inherit from JNA's Structure class the calculateSize(boolean force) method will be available.

Show Error on the tip of the Edit Text Android

u can use this :

@Override
        public void afterTextChanged(Editable s) {
            super.afterTextChanged(s);
            if (s.length() == Bank.PAN_MINIMUM_RECOGNIZABLE_LENGTH + 10) {
                Bank bank = BankUtil.findByPan(s.toString());
                if (null != bank && mNewPanEntered && !mNameDefined) {
                    mNewPanEntered = false;
                    suggestCardName(bank);
                }

private void suggestCardName(Bank bank) {
    mLastSuggestTime = System.currentTimeMillis();
    if (!bank.getName().trim().matches(getActivity().getString(R.string.bank_eghtesadnovin))) {
        inputCardNumber.setError(R.string.balance_not_enmb, true);

    }
}

Why does integer division in C# return an integer and not a float?

As a little trick to know what you are obtaining you can use var, so the compiler will tell you the type to expect:

int a = 1;
int b = 2;
var result = a/b;

your compiler will tell you that result would be of type int here.

Polygon Drawing and Getting Coordinates with Google Map API v3

Adding to Gisheri's answer

Following code worked for me

 var drawingManager = new google.maps.drawing.DrawingManager({
    drawingMode: google.maps.drawing.OverlayType.MARKER,
    drawingControl: true,
    drawingControlOptions: {
      position: google.maps.ControlPosition.TOP_CENTER,
      drawingModes: [
        google.maps.drawing.OverlayType.POLYGON
      ]
    },
    markerOptions: {
      icon: 'images/beachflag.png'
    },
    circleOptions: {
      fillColor: '#ffff00',
      fillOpacity: 1,
      strokeWeight: 5,
      clickable: false,
      editable: true,
      zIndex: 1
    }

  });

  google.maps.event.addListener(drawingManager, 'overlaycomplete', function(polygon) {
      //console.log(polygon.overlay.latLngs.j[0].j);return false;
        $.each(polygon.overlay.latLngs.j[0].j, function(key, LatLongsObject){
            var LatLongs    =   LatLongsObject;

            var lat = LatLongs.k;
            var lon = LatLongs.B;
           console.log("Lat is: "+lat+" Long is: "+lon); //do something with the coordinates

        });

Add a tooltip to a div

You can toggle a child div during onmouseover and onmouseout like this:

function Tooltip(el, text) {
  el.onmouseover = function() {
    el.innerHTML += '<div class="tooltip">' + text + '</div>' 
    }
  el.onmouseout = function() {
    el.removeChild(el.querySelector(".tooltip"))
  }
}

//Sample Usage
Tooltip(document.getElementById("mydiv"),"hello im a tip div")

Example in Stack Snippets & jsFiddle

_x000D_
_x000D_
function Tooltip(el, text) {_x000D_
  el.onmouseover = function() {_x000D_
    el.innerHTML += '<div class="tooltip">' + text + '</div>'_x000D_
  }_x000D_
  el.onmouseout = function() {_x000D_
    el.removeChild(el.querySelector(".tooltip"))_x000D_
  }_x000D_
}_x000D_
_x000D_
//Sample Usage_x000D_
Tooltip(document.getElementById("mydiv"), "I'm a tooltip")
_x000D_
#mydiv {_x000D_
  position: relative;_x000D_
  display: flex;_x000D_
  align-items: center;_x000D_
  justify-content: center;_x000D_
  width: 120px;_x000D_
  height: 50px;_x000D_
  padding: 5px 10px;_x000D_
  background-color: #e2f7ff;_x000D_
  box-shadow: 1px 1px 1px 0px #cecece;_x000D_
}_x000D_
_x000D_
.tooltip {_x000D_
  position: absolute;_x000D_
  display: inline-block;_x000D_
  white-space: nowrap;_x000D_
  width: auto;_x000D_
  height: auto;_x000D_
  background-color: #11121b;_x000D_
  color: white;_x000D_
  padding: 4px 6px;_x000D_
  border-radius: 3px;_x000D_
  z-index: 99;_x000D_
  left: 100%;_x000D_
  top: 0;_x000D_
}
_x000D_
<div id="mydiv"> This is just a div </div>
_x000D_
_x000D_
_x000D_

Static way to get 'Context' in Android?

Do this:

In the Android Manifest file, declare the following.

<application android:name="com.xyz.MyApplication">

</application>

Then write the class:

public class MyApplication extends Application {

    private static Context context;

    public void onCreate() {
        super.onCreate();
        MyApplication.context = getApplicationContext();
    }

    public static Context getAppContext() {
        return MyApplication.context;
    }
}

Now everywhere call MyApplication.getAppContext() to get your application context statically.

How to keep the header static, always on top while scrolling?

Use position: fixed on the div that contains your header, with something like

#header {
  position: fixed;
}

#content {
  margin-top: 100px;
}

In this example, when #content starts off 100px below #header, but as the user scrolls, #header stays in place. Of course it goes without saying that you'll want to make sure #header has a background so that its content will actually be visible when the two divs overlap. Have a look at the position property here: http://reference.sitepoint.com/css/position

How do I detect when someone shakes an iPhone?

I came across this post looking for a "shaking" implementation. millenomi's answer worked well for me, although i was looking for something that required a bit more "shaking action" to trigger. I've replaced to Boolean value with an int shakeCount. I also reimplemented the L0AccelerationIsShaking() method in Objective-C. You can tweak the ammount of shaking required by tweaking the ammount added to shakeCount. I'm not sure i've found the optimal values yet, but it seems to be working well so far. Hope this helps someone:

- (void)accelerometer:(UIAccelerometer *)accelerometer didAccelerate:(UIAcceleration *)acceleration {
    if (self.lastAcceleration) {
        if ([self AccelerationIsShakingLast:self.lastAcceleration current:acceleration threshold:0.7] && shakeCount >= 9) {
            //Shaking here, DO stuff.
            shakeCount = 0;
        } else if ([self AccelerationIsShakingLast:self.lastAcceleration current:acceleration threshold:0.7]) {
            shakeCount = shakeCount + 5;
        }else if (![self AccelerationIsShakingLast:self.lastAcceleration current:acceleration threshold:0.2]) {
            if (shakeCount > 0) {
                shakeCount--;
            }
        }
    }
    self.lastAcceleration = acceleration;
}

- (BOOL) AccelerationIsShakingLast:(UIAcceleration *)last current:(UIAcceleration *)current threshold:(double)threshold {
    double
    deltaX = fabs(last.x - current.x),
    deltaY = fabs(last.y - current.y),
    deltaZ = fabs(last.z - current.z);

    return
    (deltaX > threshold && deltaY > threshold) ||
    (deltaX > threshold && deltaZ > threshold) ||
    (deltaY > threshold && deltaZ > threshold);
}

PS: I've set the update interval to 1/15th of a second.

[[UIAccelerometer sharedAccelerometer] setUpdateInterval:(1.0 / 15)];

String.contains in Java

no real explanation is given by Java (in either JavaDoc or much coveted code comments), but looking at the code, it seems that this is magic:

calling stack:

String.indexOf(char[], int, int, char[], int, int, int) line: 1591  
String.indexOf(String, int) line: 1564  
String.indexOf(String) line: 1546   
String.contains(CharSequence) line: 1934    

code:

/**
 * Code shared by String and StringBuffer to do searches. The
 * source is the character array being searched, and the target
 * is the string being searched for.
 *
 * @param   source       the characters being searched.
 * @param   sourceOffset offset of the source string.
 * @param   sourceCount  count of the source string.
 * @param   target       the characters being searched for.
 * @param   targetOffset offset of the target string.
 * @param   targetCount  count of the target string.
 * @param   fromIndex    the index to begin searching from.
 */
static int indexOf(char[] source, int sourceOffset, int sourceCount,
                   char[] target, int targetOffset, int targetCount,
                   int fromIndex) {
  if (fromIndex >= sourceCount) {
        return (targetCount == 0 ? sourceCount : -1);
  }
      if (fromIndex < 0) {
        fromIndex = 0;
      }
  if (targetCount == 0) {//my comment: this is where it returns, the size of the 
    return fromIndex;    // incoming string is 0,  which is passed in as targetCount
  }                      // fromIndex is 0 as well, as the search starts from the 
                         // start of the source string
    ...//the rest of the method 

How to send Basic Auth with axios

The solution given by luschn and pillravi works fine unless you receive a Strict-Transport-Security header in the response.

Adding withCredentials: true will solve that issue.

  axios.post(session_url, {
    withCredentials: true,
    headers: {
      "Accept": "application/json",
      "Content-Type": "application/json"
    }
  },{
    auth: {
      username: "USERNAME",
      password: "PASSWORD"
  }}).then(function(response) {
    console.log('Authenticated');
  }).catch(function(error) {
    console.log('Error on Authentication');
  });

Convert a python dict to a string and back

I think you should consider using the shelve module which provides persistent file-backed dictionary-like objects. It's easy to use in place of a "real" dictionary because it almost transparently provides your program with something that can be used just like a dictionary, without the need to explicitly convert it to a string and then write to a file (or vice-versa).

The main difference is needing to initially open() it before first use and then close() it when you're done (and possibly sync()ing it, depending on the writeback option being used). Any "shelf" file objects create can contain regular dictionaries as values, allowing them to be logically nested.

Here's a trivial example:

import shelve

shelf = shelve.open('mydata')  # open for reading and writing, creating if nec
shelf.update({'one':1, 'two':2, 'three': {'three.1': 3.1, 'three.2': 3.2 }})
shelf.close()

shelf = shelve.open('mydata')
print shelf
shelf.close()

Output:

{'three': {'three.1': 3.1, 'three.2': 3.2}, 'two': 2, 'one': 1}

Android Split string

.split method will work, but it uses regular expressions. In this example it would be (to steal from Cristian):

String[] separated = CurrentString.split("\\:");
separated[0]; // this will contain "Fruit"
separated[1]; // this will contain " they taste good"

Also, this came from: Android split not working correctly

macro for Hide rows in excel 2010

Well, you're on the right path, Benno!

There are some tips regarding VBA programming that might help you out.

  1. Use always explicit references to the sheet you want to interact with. Otherwise, Excel may 'assume' your code applies to the active sheet and eventually you'll see it screws your spreadsheet up.

  2. As lionz mentioned, get in touch with the native methods Excel offers. You might use them on most of your tricks.

  3. Explicitly declare your variables... they'll show the list of methods each object offers in VBA. It might save your time digging on the internet.

Now, let's have a draft code...

Remember this code must be within the Excel Sheet object, as explained by lionz. It only applies to Sheet 2, is up to you to adapt it to both Sheet 2 and Sheet 3 in the way you prefer.

Hope it helps!

Private Sub Worksheet_Change(ByVal Target As Range)

    Dim oSheet As Excel.Worksheet

    'We only want to do something if the changed cell is B6, right?
    If Target.Address = "$B$6" Then

        'Checks if it's a number...
        If IsNumeric(Target.Value) Then

            'Let's avoid values out of your bonds, correct?
            If Target.Value > 0 And Target.Value < 51 Then

                'Let's assign the worksheet we'll show / hide rows to one variable and then
                '   use only the reference to the variable itself instead of the sheet name.
                '   It's safer.

                'You can alternatively replace 'sheet 2' by 2 (without quotes) which will represent
                '   the sheet index within the workbook
                Set oSheet = ActiveWorkbook.Sheets("Sheet 2")

                'We'll unhide before hide, to ensure we hide the correct ones
                oSheet.Range("A7:A56").EntireRow.Hidden = False

                oSheet.Range("A" & Target.Value + 7 & ":A56").EntireRow.Hidden = True

            End If

        End If

    End If

End Sub

Split a vector into chunks

I needed the same function and have read the previous solutions, however i also needed to have the unbalanced chunk to be at the end i.e if i have 10 elements to split them into vectors of 3 each, then my result should have vectors with 3,3,4 elements respectively. So i used the following (i left the code unoptimised for readability, otherwise no need to have many variables):

chunk <- function(x,n){
  numOfVectors <- floor(length(x)/n)
  elementsPerVector <- c(rep(n,numOfVectors-1),n+length(x) %% n)
  elemDistPerVector <- rep(1:numOfVectors,elementsPerVector)
  split(x,factor(elemDistPerVector))
}
set.seed(1)
x <- rnorm(10)
n <- 3
chunk(x,n)
$`1`
[1] -0.6264538  0.1836433 -0.8356286

$`2`
[1]  1.5952808  0.3295078 -0.8204684

$`3`
[1]  0.4874291  0.7383247  0.5757814 -0.3053884

Is there a way I can retrieve sa password in sql server 2005

There is no way to get the old password back. Log into the SQL server management console as a machine or domain admin using integrated authentication, you can then change any password (including sa).

Start the SQL service again and use the new created login (recovery in my example) Go via the security panel to the properties and change the password of the SA account.

enter image description here

Now write down the new SA password.

How to prevent Screen Capture in Android

You can make your app as device/profile owner and call setScreenCaptureDisabled(). From the docs, this api does the following:

public void setScreenCaptureDisabled (ComponentName admin, boolean disabled) Added in API level 21

Called by a device/profile owner to set whether the screen capture is disabled. Disabling screen capture also prevents the content from being shown on display devices that do not have a secure video output. See FLAG_SECURE for more details about secure surfaces and secure displays.

The calling device admin must be a device or profile owner. If it is not, a security exception will be thrown. Parameters admin Which DeviceAdminReceiver this request is associated with. disabled Whether screen capture is disabled or not.

Alternatively you can become an MDM(Mobile Device Management) partner app.OEMs provides additional APIs to their MDM partner apps to control the device.For example samsung provides api to control screen recording on the device to their MDM partners.

Currently this is the only way you can enforce screen capture restrictions.

Setting action for back button in navigation controller

Swift 4 iOS 11.3 Version:

This builds on the answer from kgaidis from https://stackoverflow.com/a/34343418/4316579

I am not sure when the extension stopped working, but at the time of this writing (Swift 4), it appears that the extension will no longer be executed unless you declare UINavigationBarDelegate conformity as described below.

Hope this helps people that are wondering why their extension no longer works.

extension UINavigationController: UINavigationBarDelegate {
    public func navigationBar(_ navigationBar: UINavigationBar, shouldPop item: UINavigationItem) -> Bool {

    }
}

How to get relative path of a file in visual studio?

In Visual Studio please click 'Folder.ico' file in the Solution Explorer pane. Then you will see Properties pane. Change 'Copy to Output Directory' behavior to 'Copy if newer'. This will make Visual Studio copy the file to the output bin directory.

Now to get the file path using relative path just type:

string pathToIcoFile = AppDomain.CurrentDomain.BaseDirectory + "//FolderIcon//Folder.ico";

Hope that helped.

How to change int into int64?

This is probably obvious, but simplest:

i64 := int64(23)

How can I define fieldset border color?

It works for me when I define the complete border property. (JSFiddle here)

.field_set{
 border: 1px #F00 solid;
}?

the reason is the border-style that is set to none by default for fieldsets. You need to override that as well.

Auto-Submit Form using JavaScript

Try using document.getElementById("myForm") instead of document.myForm.

<script>
var auto_refresh = setInterval(function() { submitform(); }, 10000);

function submitform()
{
  alert('test');
  document.getElementById("myForm").submit();
}
</script>

How can I loop through enum values for display in radio buttons?

Two options:

for (let item in MotifIntervention) {
    if (isNaN(Number(item))) {
        console.log(item);
    }
}

Or

Object.keys(MotifIntervention).filter(key => !isNaN(Number(MotifIntervention[key])));

(code in playground)


Edit

String enums look different than regular ones, for example:

enum MyEnum {
    A = "a",
    B = "b",
    C = "c"
}

Compiles into:

var MyEnum;
(function (MyEnum) {
    MyEnum["A"] = "a";
    MyEnum["B"] = "b";
    MyEnum["C"] = "c";
})(MyEnum || (MyEnum = {}));

Which just gives you this object:

{
    A: "a",
    B: "b",
    C: "c"
}

You can get all the keys (["A", "B", "C"]) like this:

Object.keys(MyEnum);

And the values (["a", "b", "c"]):

Object.keys(MyEnum).map(key => MyEnum[key])

Or using Object.values():

Object.values(MyEnum)

How to import and use image in a Vue single file component?

It is heavily suggested to make use of webpack when importing pictures from assets and in general for optimisation and pathing purposes

If you wish to load them by webpack you can simply use :src='require('path/to/file')' Make sure you use : otherwise it won't execute the require statement as Javascript.

In typescript you can do almost the exact same operation: :src="require('@/assets/image.png')"

Why the following is generally considered bad practice:

<template>
  <div id="app">
    <img src="./assets/logo.png">
  </div>
</template>

<script>
export default {
}
</script>

<style lang="scss">
</style> 

When building using the Vue cli, webpack is not able to ensure that the assets file will maintain a structure that follows the relative importing. This is due to webpack trying to optimize and chunk items appearing inside of the assets folder. If you wish to use a relative import you should do so from within the static folder and use: <img src="./static/logo.png">

Launch Pycharm from command line (terminal)

Update

It is now possible to create command line launcher automatically from JetBrains Toolbox. This is how you do it:

  1. Open up the toolbox window;
  2. Go to the gear icon in the upper right (the settings window for toolbox itself);
  3. Turn on Generate shell scripts;
  4. Fill the Shell script location textbox with the location where you want the launchers to reside. You have to do this manually it will not fill automatically at this time!

On Mac the location could be /usr/local/bin. For the novices, you can use any path inside the PATH variable or add a new path to the PATH variable in your bash profile. Use echo $PATH to see which paths are there.

Note! It did not work right away for me, I had to fiddle around a little before the scripts were generated. You can go to the gearbox of the IDEA (PyCharm for example) and see/change the launcher name. So for PyCharm, the default name is pycharm but you can change this to whatever you prefer.

Original answer

If you do not use the toolbox you can still use my original answer.

~~For some reason, the Create Command Line Launcher is not available anymore in 2019.1.~~ Because it is now part of JetBrains Toolbox

This is how you can create the script yourself:

If you already used the charm command before use type -a charm to find the script. Change the pycharm version in the file paths. Note that the numbering in the first variable RUN_PATH is different. You will have to look this up in the dir yourself.

RUN_PATH = u'/Users/boatfolder/Library/Application Support/JetBrains/Toolbox/apps/PyCharm-P/ch-0/191.6183.50/PyCharm.app'
CONFIG_PATH = u'/Users/boatfolder/Library/Preferences/PyCharm2019.1'
SYSTEM_PATH = u'/Users/boatfolder/Library/Caches/PyCharm2019.1'

If you did not use the charm command before, you will have to create it.

Create the charm file somewhere like this: /usr/local/bin/charm

Then add this code (change version number to your version as explained above):

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

import socket
import struct
import sys
import os
import time

# see com.intellij.idea.SocketLock for the server side of this interface

RUN_PATH = u'/Users/boatfolder/Library/Application Support/JetBrains/Toolbox/apps/PyCharm-P/ch-0/191.6183.50/PyCharm.app'
CONFIG_PATH = u'/Users/boatfolder/Library/Preferences/PyCharm2019.1'
SYSTEM_PATH = u'/Users/boatfolder/Library/Caches/PyCharm2019.1'


def print_usage(cmd):
    print(('Usage:\n' +
           '  {0} -h | -? | --help\n' +
           '  {0} [project_dir]\n' +
           '  {0} [-l|--line line] [project_dir|--temp-project] file[:line]\n' +
           '  {0} diff <left> <right>\n' +
           '  {0} merge <local> <remote> [base] <merged>').format(cmd))


def process_args(argv):
    args = []

    skip_next = False
    for i, arg in enumerate(argv[1:]):
        if arg == '-h' or arg == '-?' or arg == '--help':
            print_usage(argv[0])
            exit(0)
        elif i == 0 and (arg == 'diff' or arg == 'merge' or arg == '--temp-project'):
            args.append(arg)
        elif arg == '-l' or arg == '--line':
            args.append(arg)
            skip_next = True
        elif skip_next:
            args.append(arg)
            skip_next = False
        else:
            path = arg
            if ':' in arg:
                file_path, line_number = arg.rsplit(':', 1)
                if line_number.isdigit():
                    args.append('-l')
                    args.append(line_number)
                    path = file_path
            args.append(os.path.abspath(path))

    return args


def try_activate_instance(args):
    port_path = os.path.join(CONFIG_PATH, 'port')
    token_path = os.path.join(SYSTEM_PATH, 'token')
    if not (os.path.exists(port_path) and os.path.exists(token_path)):
        return False

    try:
        with open(port_path) as pf:
            port = int(pf.read())
        with open(token_path) as tf:
            token = tf.read()
    except (ValueError):
        return False

    s = socket.socket()
    s.settimeout(0.3)
    try:
        s.connect(('127.0.0.1', port))
    except (socket.error, IOError):
        return False

    found = False
    while True:
        try:
            path_len = struct.unpack('>h', s.recv(2))[0]
            path = s.recv(path_len).decode('utf-8')
            if os.path.abspath(path) == os.path.abspath(CONFIG_PATH):
                found = True
                break
        except (socket.error, IOError):
            return False

    if found:
        cmd = 'activate ' + token + '\0' + os.getcwd() + '\0' + '\0'.join(args)
        if sys.version_info.major >= 3: cmd = cmd.encode('utf-8')
        encoded = struct.pack('>h', len(cmd)) + cmd
        s.send(encoded)
        time.sleep(0.5)  # don't close the socket immediately
        return True

    return False


def start_new_instance(args):
    if sys.platform == 'darwin':
        if len(args) > 0:
            args.insert(0, '--args')
        os.execvp('/usr/bin/open', ['-a', RUN_PATH] + args)
    else:
        bin_file = os.path.split(RUN_PATH)[1]
        os.execv(RUN_PATH, [bin_file] + args)


ide_args = process_args(sys.argv)
if not try_activate_instance(ide_args):
    start_new_instance(ide_args)

Handling optional parameters in javascript

Er - that would imply that you are invoking your function with arguments which aren't in the proper order... which I would not recommend.

I would recommend instead feeding an object to your function like so:

function getData( props ) {
    props = props || {};
    props.params = props.params || {};
    props.id = props.id || 1;
    props.callback = props.callback || function(){};
    alert( props.callback )
};

getData( {
    id: 3,
    callback: function(){ alert('hi'); }
} );

Benefits:

  • you don't have to account for argument order
  • you don't have to do type checking
  • it's easier to define default values because no type checking is necessary
  • less headaches. imagine if you added a fourth argument, you'd have to update your type checking every single time, and what if the fourth or consecutive are also functions?

Drawbacks:

  • time to refactor code

If you have no choice, you could use a function to detect whether an object is indeed a function ( see last example ).

Note: This is the proper way to detect a function:

function isFunction(obj) {
    return Object.prototype.toString.call(obj) === "[object Function]";
}

isFunction( function(){} )

Return first N key:value pairs from dict

To get the top N elements from your python dictionary one can use the following line of code:

list(dictionaryName.items())[:N]

In your case you can change it to:

list(d.items())[:4]

OSError [Errno 22] invalid argument when use open() in Python

Just replace with "/" for file path :

   open("description_files/program_description.txt","r")

how to get the last character of a string?

You can achieve this using different ways but with different performance,

1. Using bracket notation:

var str = "Test"; var lastLetter = str[str.length - 1];

But it's not recommended to use brackets. Check the reasons here

2. charAt[index]:

var lastLetter = str.charAt(str.length - 1)

This is readable and fastest among others. It is most recommended way.

3. substring:

str.substring(str.length - 1);

4. slice:

str.slice(-1);

It's slightly faster than substring.

You can check the performance here

With ES6:

You can use str.endsWith("t");

But it is not supported in IE. Check more details about endsWith here

fatal: could not read Username for 'https://github.com': No such file or directory

If you want to continue use https instead ssh, and avoid type into your username and password for security reason.

You can also try Github OAuth token, then you can do git config remote.origin.url 'https://{token}@github.com/{username}/{project}.git' or git remote add origin 'https://{token}@github.com/{username}/{project}.git'

This works for me!

Error Message : Cannot find or open the PDB file

If this happens in visual studio then clean your project and run it again.

Build --> Clean Solution

Run (or F5)

Difference between os.getenv and os.environ.get

One difference observed (Python27):

os.environ raises an exception if the environmental variable does not exist. os.getenv does not raise an exception, but returns None

Real time face detection OpenCV, Python

Your line:

img = cv2.rectangle(img,(x,y),(x+w,y+h),(255,0,0),2) 

will draw a rectangle in the image, but the return value will be None, so img changes to None and cannot be drawn.

Try

cv2.rectangle(img,(x,y),(x+w,y+h),(255,0,0),2) 

How to display Toast in Android?

Extending activity using baseadapter used this

Toast.makeText(getActivity(), 
    "Your Message", Toast.LENGTH_LONG).show();

or if you are using activity or mainactivity

Toast.makeText(MainActivity.this, 
    "Your Message", Toast.LENGTH_LONG).show();

How can I wait for 10 second without locking application UI in android

You can use this:

Handler handler = new Handler();
handler.postDelayed(new Runnable() {
    public void run() {
     // Actions to do after 10 seconds
    }
}, 10000);

For Stop the Handler, You can try this: handler.removeCallbacksAndMessages(null);

Android fade in and fade out with ImageView

The best and the easiest way, for me was this..

->Simply create a thread with Handler containing sleep().

private ImageView myImageView;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_shape_count); myImageView= (ImageView)findViewById(R.id.shape1);
    Animation myFadeInAnimation = AnimationUtils.loadAnimation(this, R.anim.fadein);
    myImageView.startAnimation(myFadeInAnimation);

    new Thread(new Runnable() {
        private Handler handler = new Handler(){
            @Override
            public void handleMessage(Message msg) {
                Log.w("hendler", "recived");
                    Animation myFadeOutAnimation = AnimationUtils.loadAnimation(getBaseContext(), R.anim.fadeout);
                    myImageView.startAnimation(myFadeOutAnimation);
                    myImageView.setVisibility(View.INVISIBLE);
            }
        };

        @Override
        public void run() {
            try{
                Thread.sleep(2000); // your fadein duration
            }catch (Exception e){
            }
            handler.sendEmptyMessage(1);

        }
    }).start();
}

Change background color of edittext in android

The color you are using is white "#ffffff" is white so try a different one change in the values if you want until you get your need from this link Color Codes and it should go fine

Create list or arrays in Windows Batch

@echo off
setlocal
set "list=a b c d"
(
 for %%i in (%list%) do (
  echo(%%i
  echo(
 )
)>file.txt

You don't need - actually, can't "declare" variables in batch. Assigning a value to a variable creates it, and assigning an empty string deletes it. Any variable name that doesn't have an assigned value HAS a value of an empty string. ALL variables are strings - WITHOUT exception. There ARE operations that appear to perform (integer) mathematical functions, but they operate by converting back and forth from strings.

Batch is sensitive to spaces in variable names, so your assignment as posted would assign the string "A B C D" - including the quotes, to the variable "list " - NOT including the quotes, but including the space. The syntax set "var=string" is used to assign the value string to var whereas set var=string will do the same thing. Almost. In the first case, any stray trailing spaces after the closing quote are EXCLUDED from the value assigned, in the second, they are INCLUDED. Spaces are a little hard to see when printed.

ECHO echoes strings. Clasically, it is followed by a space - one of the default separators used by batch (the others are TAB, COMMA, SEMICOLON - any of these do just as well BUT TABS often get transformed to a space-squence by text-editors and the others have grown quirks of their own over the years.) Other characters following the O in ECHO have been found to do precisely what the documented SPACE should do. DOT is common. Open-parenthesis ( is probably the most useful since the command

ECHO.%emptyvalue%

will produce a report of the ECHO state (ECHO is on/off) whereas

ECHO(%emptyvalue%

will produce an empty line.

The problem with ECHO( is that the result "looks" unbalanced.

Java count occurrence of each item in an array

List asList = Arrays.asList(array);
Set<String> mySet = new HashSet<String>(asList);

for(String s: mySet){
 System.out.println(s + " " + Collections.frequency(asList,s));
}

How to convert an Object {} to an Array [] of key-value pairs in JavaScript

This is my solution, i have the same issue and its seems like this solution work for me.

yourObj = [].concat(yourObj);

How to serve .html files with Spring

In case you use spring boot, you must not set the properties spring.mvc.view.prefix and spring.mvc.view.suffix in your application.properties file, instead configure the bean ViewResolver from a configuration class.

application.properties

# Configured in @Configuration GuestNav
#spring.mvc.view.prefix=/WEB-INF/views/
#spring.mvc.view.suffix=.jsp
# Live reload
spring.devtools.restart.additional-paths=.
# Better logging
server.tomcat.accesslog.directory=logs
server.tomcat.accesslog.file-date-format=yyyy-MM-dd
server.tomcat.accesslog.prefix=access_log
server.tomcat.accesslog.suffix=.log

Main method

@SpringBootApplication
public class WebApp extends SpringBootServletInitializer {

    @Override
    protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
        return application.sources(WebApp.class);
    }

    public static void main(String[] args) throws Exception {
        SpringApplication.run(WebApp.class, args);
    }

}

Configuration class

@Configuration
@EnableWebMvc
public class DispatcherConfig implements WebMvcConfigurer {

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/views/**").addResourceLocations("/views/");
    }

    @Bean
    public ViewResolver viewResolver() {
        InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
        viewResolver.setViewClass(JstlView.class);
        viewResolver.setPrefix("/WEB-INF/notinuse/");
        viewResolver.setSuffix("");
        return viewResolver;
    }

}

A controller class

@Controller
public class GuestNav {

    @GetMapping("/")
    public String home() {
        return "forward:/views/guest/index.html";
    }
}

You must place your files in the directory /webapp/views/guest/index.html, be careful, the webapp directory is outside of the resources directory.
In this way you may use the url patterns of spring-mvc but serve static context.

Delete the first five characters on any line of a text file in Linux with sed

sed 's/^.....//'

means

replace ("s", substitute) beginning-of-line then 5 characters (".") with nothing.

There are more compact or flexible ways to write this using sed or cut.

Extreme wait-time when taking a SQL Server database offline

In SSMS: right-click on SQL server icon, Activity Monitor. Open Processes. Find the processed connected. Right-click on the process, Kill.

How do I install imagemagick with homebrew?

You could try:

brew update && brew install imagemagick

Accessing elements by type in javascript

In plain-old JavaScript you can do this:

var inputs = document.getElementsByTagName('input');

for(var i = 0; i < inputs.length; i++) {
    if(inputs[i].type.toLowerCase() == 'text') {
        alert(inputs[i].value);
    }
}

In jQuery, you would just do:

// select all inputs of type 'text' on the page
$("input:text")

// hide all text inputs which are descendants of div class="foo"
$("div.foo input:text").hide();

Create an Array of Arraylists

You can create Array of ArrayList

List<Integer>[] outer = new List[number];
for (int i = 0; i < number; i++) {
    outer[i] = new ArrayList<>();
}

This will be helpful in scenarios like this. You know the size of the outer one. But the size of inner ones varies. Here you can create an array of fixed length which contains size-varying Array lists. Hope this will be helpful for you.

In Java 8 and above you can do it in a much better way.

List<Integer>[] outer = new List[number];
Arrays.setAll(outer, element -> new ArrayList<>());

Even better using method reference

List<Integer>[] outer = new List[10];
Arrays.setAll(outer,  ArrayList :: new);

Laravel: Error [PDOException]: Could not Find Driver in PostgreSQL

In Linux(Ubuntu) just install the driver like so:

sudo apt-get install php-pgsql

This will install the driver with using your php current version.

Can CSS detect the number of children an element has?

NOTE: This solution will return the children of sets of certain lengths, not the parent element as you have asked. Hopefully, it's still useful.

Andre Luis came up with a method: http://lea.verou.me/2011/01/styling-children-based-on-their-number-with-css3/ Unfortunately, it only works in IE9 and above.

Essentially, you combine :nth-child() with other pseudo classes that deal with the position of an element. This approach allows you to specify elements from sets of elements with specific lengths.

For instance :nth-child(1):nth-last-child(3) matches the first element in a set while also being the 3rd element from the end of the set. This does two things: guarantees that the set only has three elements and that we have the first of the three. To specify the second element of the three element set, we'd use :nth-child(2):nth-last-child(2).


Example 1 - Select all list elements if set has three elements:

li:nth-child(1):nth-last-child(3),
li:nth-child(2):nth-last-child(2),
li:nth-child(3):nth-last-child(1) {
    width: 33.3333%;
}

Example 1 alternative from Lea Verou:

li:first-child:nth-last-child(3),
li:first-child:nth-last-child(3) ~ li {
    width: 33.3333%;
}


Example 2 - target last element of set with three list elements:

li:nth-child(3):last-child {
    /* I'm the last of three */
}

Example 2 alternative:

li:nth-child(3):nth-last-child(1) {
    /* I'm the last of three */
}


Example 3 - target second element of set with four list elements:

li:nth-child(2):nth-last-child(3) {
    /* I'm the second of four */
}

How to get a certain element in a list, given the position?

If you frequently need to access the Nth element of a sequence, std::list, which is implemented as a doubly linked list, is probably not the right choice. std::vector or std::deque would likely be better.

That said, you can get an iterator to the Nth element using std::advance:

std::list<Object> l;
// add elements to list 'l'...

unsigned N = /* index of the element you want to retrieve */;
if (l.size() > N)
{
    std::list<Object>::iterator it = l.begin();
    std::advance(it, N);
    // 'it' points to the element at index 'N'
}

For a container that doesn't provide random access, like std::list, std::advance calls operator++ on the iterator N times. Alternatively, if your Standard Library implementation provides it, you may call std::next:

if (l.size() > N)
{
    std::list<Object>::iterator it = std::next(l.begin(), N);
}

std::next is effectively wraps a call to std::advance, making it easier to advance an iterator N times with fewer lines of code and fewer mutable variables. std::next was added in C++11.

How to align center the text in html table row?

Selector > child:

_x000D_
_x000D_
.text-center-row>th,_x000D_
.text-center-row>td {_x000D_
  text-align: center;_x000D_
}
_x000D_
<table border="1" width='500px'>_x000D_
  <tr class="text-center-row">_x000D_
    <th>Text</th>_x000D_
    <th>Text</th>_x000D_
    <th>Text</th>_x000D_
    <th>Text</th>_x000D_
  </tr>_x000D_
  <tr>_x000D_
    <td>Text</td>_x000D_
    <td>Text</td>_x000D_
    <td>Text</td>_x000D_
    <td>Text</td>_x000D_
  </tr>_x000D_
  <tr class="text-center-row">_x000D_
    <td>Text</td>_x000D_
    <td>Text</td>_x000D_
    <td>Text</td>_x000D_
    <td>Text</td>_x000D_
  </tr>_x000D_
</table>
_x000D_
_x000D_
_x000D_

htaccess redirect to https://www

If you are on CloudFlare, make sure you use something like this.

# BEGIN SSL Redirect
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteCond %{HTTP:X-Forwarded-Proto} =http
RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
</IfModule>
# END SSL Redirect

This will save you from the redirect loop and will redirect your site to SSL safely.

P.S. It is a good idea to if check the mod_rewrite.c!

How to send email from SQL Server?

sometimes while not found sp_send_dbmail directly. You may use 'msdb.dbo.sp_send_dbmail' to try (Work fine on Windows Server 2008 R2 and is tested)

Express.js Response Timeout

An update if one is using Express 4.2 then the timeout middleware has been removed so need to manually add it with

npm install connect-timeout

and in the code it has to be (Edited as per comment, how to include it in the code)

 var timeout = require('connect-timeout');
 app.use(timeout('100s'));

Convert DataFrame column type from string to datetime, dd/mm/yyyy format

The easiest way is to use to_datetime:

df['col'] = pd.to_datetime(df['col'])

It also offers a dayfirst argument for European times (but beware this isn't strict).

Here it is in action:

In [11]: pd.to_datetime(pd.Series(['05/23/2005']))
Out[11]:
0   2005-05-23 00:00:00
dtype: datetime64[ns]

You can pass a specific format:

In [12]: pd.to_datetime(pd.Series(['05/23/2005']), format="%m/%d/%Y")
Out[12]:
0   2005-05-23
dtype: datetime64[ns]

Why does Java's hashCode() in String use 31 as a multiplier?

By multiplying, bits are shifted to the left. This uses more of the available space of hash codes, reducing collisions.

By not using a power of two, the lower-order, rightmost bits are populated as well, to be mixed with the next piece of data going into the hash.

The expression n * 31 is equivalent to (n << 5) - n.

Node.js version on the command line? (not the REPL)

On an Arm7 (armhf) device running Debian Stretch, I had to issue either of the following:

$ nodejs -v
$ nodejs -h

The following did not work:

$ node -v
$ node -h
$ apm -v

Hope this helps someone else.

Error:Execution failed for task ':app:compileDebugKotlin'. > Compilation error. See log for more details

I Had the same problem and finally reached to the solution.

add "--stacktrace --debug" to your command-line options(File -> Settings -> Compiler) then run it. This will show the problem(unwanted code) in your code.

Is it acceptable and safe to run pip install under sudo?

It looks like your permissions are messed up. Type chown -R markwalker ~ in the Terminal and try pip again? Let me know if you're sorted.

How to make link not change color after visited?

In order to avoid duplicate code, I recommend you to define the color once, for both states:

a, a:visited{
     color: /* some color */;
}

This, indeeed, will mantain your <a> color (whatever this color is) even when the link has been visited.

Notice that, if the color of the element inside of the <a> is being inherited (e.g. the color is set in the body), you could do the following trick:

a, a:visited {
    color: inherit;
}

Turning multiple lines into one comma separated line

Using paste command:

paste -d, -s file

How do I replace whitespaces with underscore?

OP is using python, but in javascript (something to be careful of since the syntaxes are similar.

// only replaces the first instance of ' ' with '_'
"one two three".replace(' ', '_'); 
=> "one_two three"

// replaces all instances of ' ' with '_'
"one two three".replace(/\s/g, '_');
=> "one_two_three"

Including external jar-files in a new jar-file build with Ant

From your ant buildfile, I assume that what you want is to create a single JAR archive that will contain not only your application classes, but also the contents of other JARs required by your application.

However your build-jar file is just putting required JARs inside your own JAR; this will not work as explained here (see note).

Try to modify this:

<jar destfile="${jar.file}" 
    basedir="${build.dir}" 
    manifest="${manifest.file}">
    <fileset dir="${classes.dir}" includes="**/*.class" />
    <fileset dir="${lib.dir}" includes="**/*.jar" />
</jar>

to this:

<jar destfile="${jar.file}" 
    basedir="${build.dir}" 
    manifest="${manifest.file}">
    <fileset dir="${classes.dir}" includes="**/*.class" />
    <zipgroupfileset dir="${lib.dir}" includes="**/*.jar" />
</jar>

More flexible and powerful solutions are the JarJar or One-Jar projects. Have a look into those if the above does not satisfy your requirements.

DeprecationWarning: Buffer() is deprecated due to security and usability issues when I move my script to another server

new Buffer(number)            // Old
Buffer.alloc(number)          // New

new Buffer(string)            // Old
Buffer.from(string)           // New

new Buffer(string, encoding)  // Old
Buffer.from(string, encoding) // New

new Buffer(...arguments)      // Old
Buffer.from(...arguments)     // New

Note that Buffer.alloc() is also faster on the current Node.js versions than new Buffer(size).fill(0), which is what you would otherwise need to ensure zero-filling.

Insert json file into mongodb

This solution is applicable for Windows machine.

  1. MongoDB needs data directory to store data. Default path is C:\data\db. In case you don't have the data directory, create one in your C: drive. (P.S.: data\db means there is a directory named 'db' inside the directory 'data')

  2. Place the json you want to import in this path: C:\data\db\ .

  3. Open the command prompt and type the following command

    mongoimport --db databaseName --collections collectionName --file fileName.json --type json --batchSize 1

Here,

  • databaseName : your database name
  • collectionName: your collection name
  • fileName: name of your json file which is in the path C:\data\db
  • batchSize can be any integer as per your wish

Display TIFF image in all web browser

Tiff images can be displayed directly onto IE and safari only.. no support of tiff images on chrome and firefox. you can encode the image and then display it on browser by decoding the encoded image to some other format. Hope this works for you

Get DataKey values in GridView RowCommand

I managed to get the value of the DataKeys using this code:

In the GridView I added:

DataKeyNames="ID" OnRowCommand="myRowCommand"

Then in my row command function:

protected void myRowCommand(object sender, GridViewCommandEventArgs e) 
{
    LinkButton lnkBtn = (LinkButton)e.CommandSource;    // the button
    GridViewRow myRow = (GridViewRow)lnkBtn.Parent.Parent;  // the row
    GridView myGrid = (GridView)sender; // the gridview
    string ID = myGrid.DataKeys[myRow.RowIndex].Value.ToString(); // value of the datakey 

    switch (e.CommandName)
    {
      case "cmd1":
      // do something using the ID
      break;
      case "cmd2":
      // do something else using the ID
      break;
    }
 }

Pretty-Print JSON in Java

Following the JSON-P 1.0 specs (JSR-353) a more current solution for a given JsonStructure (JsonObject or JsonArray) could look like this:

import java.io.StringWriter;
import java.util.HashMap;
import java.util.Map;

import javax.json.Json;
import javax.json.JsonStructure;
import javax.json.JsonWriter;
import javax.json.JsonWriterFactory;
import javax.json.stream.JsonGenerator;

public class PrettyJson {

    private static JsonWriterFactory FACTORY_INSTANCE;

    public static String toString(final JsonStructure status) {

        final StringWriter stringWriter = new StringWriter();

        final JsonWriter jsonWriter = getPrettyJsonWriterFactory()
                .createWriter(stringWriter);

        jsonWriter.write(status);
        jsonWriter.close();

        return stringWriter.toString();
    }

    private static JsonWriterFactory getPrettyJsonWriterFactory() {
        if (null == FACTORY_INSTANCE) {
            final Map<String, Object> properties = new HashMap<>(1);
            properties.put(JsonGenerator.PRETTY_PRINTING, true);
            FACTORY_INSTANCE = Json.createWriterFactory(properties);
        }
        return FACTORY_INSTANCE;
    }

}

How can I change column types in Spark SQL's DataFrame?

This method will drop the old column and create new columns with same values and new datatype. My original datatypes when the DataFrame was created were:-

root
 |-- id: integer (nullable = true)
 |-- flag1: string (nullable = true)
 |-- flag2: string (nullable = true)
 |-- name: string (nullable = true)
 |-- flag3: string (nullable = true)

After this I ran following code to change the datatype:-

df=df.withColumnRenamed(<old column name>,<dummy column>) // This was done for both flag1 and flag3
df=df.withColumn(<old column name>,df.col(<dummy column>).cast(<datatype>)).drop(<dummy column>)

After this my result came out to be:-

root
 |-- id: integer (nullable = true)
 |-- flag2: string (nullable = true)
 |-- name: string (nullable = true)
 |-- flag1: boolean (nullable = true)
 |-- flag3: boolean (nullable = true)

Nested ifelse statement

With data.table, the solutions is:

DT[, idnat2 := ifelse(idbp %in% "foreign", "foreign", 
        ifelse(idbp %in% c("colony", "overseas"), "overseas", "mainland" ))]

The ifelse is vectorized. The if-else is not. Here, DT is:

    idnat     idbp
1  french mainland
2  french   colony
3  french overseas
4 foreign  foreign

This gives:

   idnat     idbp   idnat2
1:  french mainland mainland
2:  french   colony overseas
3:  french overseas overseas
4: foreign  foreign  foreign

What Regex would capture everything from ' mark to the end of a line?

This will capture everything up to the ' in backreference 1 - and everything after the ' in backreference 2. You may need to escape the apostrophes though depending on language (\')

/^([^']*)'?(.*)$/

Quick modification: if the line doesn't have an ' - backreference 1 should still catch the whole line.

^ - start of string
([^']*) - capture any number of not ' characters
'? - match the ' 0 or 1 time
(.*) - capture any number of characters
$ - end of string

Encoding URL query parameters in Java

It is not necessary to encode a colon as %3B in the query, although doing so is not illegal.

URI         = scheme ":" hier-part [ "?" query ] [ "#" fragment ]
query       = *( pchar / "/" / "?" )
pchar         = unreserved / pct-encoded / sub-delims / ":" / "@"
unreserved    = ALPHA / DIGIT / "-" / "." / "_" / "~"
pct-encoded   = "%" HEXDIG HEXDIG
sub-delims    = "!" / "$" / "&" / "'" / "(" / ")" / "*" / "+" / "," / ";" / "="

It also seems that only percent-encoded spaces are valid, as I doubt that space is an ALPHA or a DIGIT

look to the URI specification for more details.

React navigation goBack() and update parent state

is there a way to pass param from navigate.goback() and parent can listen to the params and update its state?

You can pass a callback function as parameter (as mentioned in other answers).

Here is a more clear example, when you navigate from A to B and you want B to communicate information back to A you can pass a callback (here onSelect):

ViewA.js

import React from "react";
import { Button, Text, View } from "react-native";

class ViewA extends React.Component {
  state = { selected: false };

  onSelect = data => {
    this.setState(data);
  };

  onPress = () => {
    this.props.navigate("ViewB", { onSelect: this.onSelect });
  };

  render() {
    return (
      <View>
        <Text>{this.state.selected ? "Selected" : "Not Selected"}</Text>
        <Button title="Next" onPress={this.onPress} />
      </View>
    );
  }
}

ViewB.js

import React from "react";
import { Button } from "react-native";

class ViewB extends React.Component {
  goBack() {
    const { navigation } = this.props;
    navigation.goBack();
    navigation.state.params.onSelect({ selected: true });
  }

  render() {
    return <Button title="back" onPress={this.goBack} />;
  }
}

Hats off for debrice - Refer to https://github.com/react-navigation/react-navigation/issues/288#issuecomment-315684617


Edit

For React Navigation v5

ViewB.js

import React from "react";
import { Button } from "react-native";

class ViewB extends React.Component {
  goBack() {
    const { navigation, route } = this.props;
    navigation.goBack();
    route.params.onSelect({ selected: true });
  }

  render() {
    return <Button title="back" onPress={this.goBack} />;
  }
}

MySQL error code: 1175 during UPDATE in MySQL Workbench

On WorkBench I resolved it By deactivating the safe update mode:

-Edit -> Preferences -> Sql Editor then uncheck Safe update.

How do I execute a Shell built-in command with a C function?

You can use the excecl command

int execl(const char *path, const char *arg, ...);

Like shown here

#include <stdio.h>
#include <unistd.h>
#include <dirent.h>

int main (void) {

   return execl ("/bin/pwd", "pwd", NULL);

}

The second argument will be the name of the process as it will appear in the process table.

Alternatively, you can use the getcwd() function to get the current working directory:

#include <stdio.h>
#include <unistd.h>
#include <dirent.h>
#define MAX 255

int main (void) {
char wd[MAX];
wd[MAX-1] = '\0';

if(getcwd(wd, MAX-1) == NULL) {
  printf ("Can not get current working directory\n");
}
else {
  printf("%s\n", wd);
}
  return 0;
}

How to avoid soft keyboard pushing up my layout?

In my case, the reason the buttons got pushed up was because the view above them was a ScrollView, and it got collapsed with the buttons pushed up above the keyboard no matter what value of android:windowSoftInputMode I was setting.

I was able to avoid my bottom row of buttons getting pushed up by the soft keyboard by setting

android:isScrollContainer="false" 

on the ScrollView that sits above the buttons.

Disable automatic sorting on the first column when using jQuery DataTables

If any of other solution doesn't fix it, try to override the styles to hide the sort togglers:

.sorting_asc:after, .sorting_desc:after {
  content: "";
}

convert an enum to another type of enum

Here's an extension method version if anyone is interested

public static TEnum ConvertEnum<TEnum >(this Enum source)
    {
        return (TEnum)Enum.Parse(typeof(TEnum), source.ToString(), true);
    }

// Usage
NewEnumType newEnum = oldEnumVar.ConvertEnum<NewEnumType>();

How to delete an SMS from the inbox in Android programmatically?

I think this can not be perfectly done for the time being. There are 2 basic problems:

  1. How can you make sure the sms is already in the inbox when you try to delete it?
    Notice that SMS_RECEIVED is not an ordered broadcast.
    So dmyung's solution is completely trying one's luck; even the delay in Doug's answer is not a guarantee.

  2. The SmsProvider is not thread safe.(refer to http://code.google.com/p/android/issues/detail?id=2916#c0)
    The fact that more than one clients are requesting delete and insert in it at the same time will cause data corruption or even immediate Runtime Exception.

Reverse order of foreach list items

Assuming you just need to reverse an indexed array (not associative or multidimensional) a simple for loop would suffice:

$fruits = ['bananas', 'apples', 'pears'];
for($i = count($fruits)-1; $i >= 0; $i--) {
    echo $fruits[$i] . '<br>';
} 

What is the attribute property="og:title" inside meta tag?

The property in meta tags allows you to specify values to property fields which come from a property library. The property library (RDFa format) is specified in the head tag.

For example, to use that code you would have to have something like this in your <head tag. <head xmlns:og="http://example.org/"> and inside the http://example.org/ there would be a specification for title (og:title).

The tag from your example was almost definitely from the Open Graph Protocol, the purpose is to specify structured information about your website for the use of Facebook (and possibly other search engines).

How do I make a Git commit in the past?

Or just use a fake-git-history to generate it for a specific data range.

With ng-bind-html-unsafe removed, how do I inject HTML?

You indicated that you're using Angular 1.2.0... as one of the other comments indicated, ng-bind-html-unsafe has been deprecated.

Instead, you'll want to do something like this:

<div ng-bind-html="preview_data.preview.embed.htmlSafe"></div>

In your controller, inject the $sce service, and mark the HTML as "trusted":

myApp.controller('myCtrl', ['$scope', '$sce', function($scope, $sce) {
  // ...
  $scope.preview_data.preview.embed.htmlSafe = 
     $sce.trustAsHtml(preview_data.preview.embed.html);
}

Note that you'll want to be using 1.2.0-rc3 or newer. (They fixed a bug in rc3 that prevented "watchers" from working properly on trusted HTML.)

How to parse dates in multiple formats using SimpleDateFormat

I was having multiple date formats into json, and was extracting csv with universal format. I looked multiple places, tried different ways, but at the end I'm able to convert with the following simple code.

private String getDate(String anyDateFormattedString) {
    @SuppressWarnings("deprecation")
    Date date = new Date(anyDateFormattedString);
    SimpleDateFormat dateFormat = new SimpleDateFormat(yourDesiredDateFormat);
        String convertedDate = dateFormat.format(date);
    return convertedDate;
}

"psql: could not connect to server: Connection refused" Error when connecting to remote database

Check the port defined in postgresql.conf. My installation of postgres 9.4 uses port 5433 instead of 5432

Error 1053 the service did not respond to the start or control request in a timely fashion

As nobody has mentioned I will add it (even if it is a stupid mistake). In case you are on Windows 10 you don't usually need to restart, but

-> Make sure to CLOSE any open properties pages of the "services"-window in case you have just installed the service (and still have opened the properties page of the old service).

I'm talking about this window:

Services list

After closing all services windows and re-trying -> it worked. In contrast to the OP I got Error 1053 basically immediately (without windows waiting on anything)

Setting a WebRequest's body data

With HttpWebRequest.GetRequestStream

Code example from http://msdn.microsoft.com/en-us/library/d4cek6cc.aspx

string postData = "firstone=" + inputData;
ASCIIEncoding encoding = new ASCIIEncoding ();
byte[] byte1 = encoding.GetBytes (postData);

// Set the content type of the data being posted.
myHttpWebRequest.ContentType = "application/x-www-form-urlencoded";

// Set the content length of the string being posted.
myHttpWebRequest.ContentLength = byte1.Length;

Stream newStream = myHttpWebRequest.GetRequestStream ();

newStream.Write (byte1, 0, byte1.Length);

From one of my own code:

var request = (HttpWebRequest)WebRequest.Create(uri);
request.Credentials = this.credentials;
request.Method = method;
request.ContentType = "application/atom+xml;type=entry";
using (Stream requestStream = request.GetRequestStream())
using (var xmlWriter = XmlWriter.Create(requestStream, new XmlWriterSettings() { Indent = true, NewLineHandling = NewLineHandling.Entitize, }))
{
    cmisAtomEntry.WriteXml(xmlWriter);
}

try 
{    
    return (HttpWebResponse)request.GetResponse();  
}
catch (WebException wex)
{
    var httpResponse = wex.Response as HttpWebResponse;
    if (httpResponse != null)
    {
        throw new ApplicationException(string.Format(
            "Remote server call {0} {1} resulted in a http error {2} {3}.",
            method,
            uri,
            httpResponse.StatusCode,
            httpResponse.StatusDescription), wex);
    }
    else
    {
        throw new ApplicationException(string.Format(
            "Remote server call {0} {1} resulted in an error.",
            method,
            uri), wex);
    }
}
catch (Exception)
{
    throw;
}

The storage engine for the table doesn't support repair. InnoDB or MyISAM?

You have the wrong table set on the command. You should use the following on your setup:

ALTER TABLE scode_tracker.ap_visits ENGINE=MyISAM;

Determine .NET Framework version for dll

Yet another option via Visual Studio, add a reference to the DLL to any project, then right-clicking on the new reference and click Properties, you can see what you are looking for in Runtime version:

enter image description here

How do I format my oracle queries so the columns don't wrap?

I use a generic query I call "dump" (why? I don't know) that looks like this:

SET NEWPAGE NONE
SET PAGESIZE 0
SET SPACE 0
SET LINESIZE 16000
SET ECHO OFF
SET FEEDBACK OFF
SET VERIFY OFF
SET HEADING OFF
SET TERMOUT OFF
SET TRIMOUT ON
SET TRIMSPOOL ON
SET COLSEP |

spool &1..txt

@@&1

spool off
exit

I then call SQL*Plus passing the actual SQL script I want to run as an argument:

sqlplus -S user/password@database @dump.sql my_real_query.sql

The result is written to a file

my_real_query.sql.txt

.

How to handle ETIMEDOUT error?

This is caused when your request response is not received in given time(by timeout request module option).

Basically to catch that error first, you need to register a handler on error, so the unhandled error won't be thrown anymore: out.on('error', function (err) { /* handle errors here */ }). Some more explanation here.

In the handler you can check if the error is ETIMEDOUT and apply your own logic: if (err.message.code === 'ETIMEDOUT') { /* apply logic */ }.

If you want to request for the file again, I suggest using node-retry or node-backoff modules. It makes things much simpler.

If you want to wait longer, you can set timeout option of request yourself. You can set it to 0 for no timeout.

Setting a log file name to include current date in Log4j

I have created an appender that will do that. http://stauffer.james.googlepages.com/DateFormatFileAppender.java

/*
 * Copyright (C) The Apache Software Foundation. All rights reserved.
 *
 * This software is published under the terms of the Apache Software
 * License version 1.1, a copy of which has been included with this
 * distribution in the LICENSE.txt file.  */

package sps.log.log4j;

import java.io.IOException;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;

import org.apache.log4j.*;
import org.apache.log4j.helpers.LogLog;
import org.apache.log4j.spi.LoggingEvent;

/**
 * DateFormatFileAppender is a log4j Appender and extends 
 * {@link FileAppender} so each log is 
 * named based on a date format defined in the File property.
 *
 * Sample File: 'logs/'yyyy/MM-MMM/dd-EEE/HH-mm-ss-S'.log'
 * Makes a file like: logs/2004/04-Apr/13-Tue/09-45-15-937.log
 * @author James Stauffer
 */
public class DateFormatFileAppender extends FileAppender {

  /**
   * The default constructor does nothing.
   */
  public DateFormatFileAppender() {
  }

  /**
   * Instantiate a <code>DailyRollingFileAppender</code> and open the
   * file designated by <code>filename</code>. The opened filename will
   * become the ouput destination for this appender.
   */
  public DateFormatFileAppender (Layout layout, String filename) throws IOException {
    super(layout, filename, true);
  }

  private String fileBackup;//Saves the file pattern
  private boolean separate = false;

  public void setFile(String file) {
    super.setFile(file);
    this.fileBackup = getFile();
  }

  /**
   * If true each LoggingEvent causes that file to close and open.
   * This is useful when the file is a pattern that would often
   * produce a different filename.
   */
  public void setSeparate(boolean separate) {
    this.separate = separate;
  }

  protected void subAppend(LoggingEvent event) {
    if(separate) {
        try {//First reset the file so each new log gets a new file.
            setFile(getFile(), getAppend(), getBufferedIO(), getBufferSize());
        } catch(IOException e) {
            LogLog.error("Unable to reset fileName.");
        }
    }
    super.subAppend(event);
  }


  public
  synchronized
  void setFile(String fileName, boolean append, boolean bufferedIO, int bufferSize)
                                                            throws IOException {
    SimpleDateFormat sdf = new SimpleDateFormat(fileBackup);
    String actualFileName = sdf.format(new Date());
    makeDirs(actualFileName);
    super.setFile(actualFileName, append, bufferedIO, bufferSize);
  }

  /**
   * Ensures that all of the directories for the given path exist.
   * Anything after the last / or \ is assumed to be a filename.
   */
  private void makeDirs (String path) {
    int indexSlash = path.lastIndexOf("/");
    int indexBackSlash = path.lastIndexOf("\\");
    int index = Math.max(indexSlash, indexBackSlash);
    if(index > 0) {
        String dirs = path.substring(0, index);
//        LogLog.debug("Making " + dirs);
        File dir = new File(dirs);
        if(!dir.exists()) {
            boolean success = dir.mkdirs();
            if(!success) {
                LogLog.error("Unable to create directories for " + dirs);
            }
        }
    }
  }

}

How to split a python string on new line characters

? Splitting line in Python:

Have you tried using str.splitlines() method?:

From the docs:

str.splitlines([keepends])

Return a list of the lines in the string, breaking at line boundaries. Line breaks are not included in the resulting list unless keepends is given and true.

For example:

>>> 'Line 1\n\nLine 3\rLine 4\r\n'.splitlines()
['Line 1', '', 'Line 3', 'Line 4']

>>> 'Line 1\n\nLine 3\rLine 4\r\n'.splitlines(True)
['Line 1\n', '\n', 'Line 3\r', 'Line 4\r\n']

Which delimiters are considered?

This method uses the universal newlines approach to splitting lines.

The main difference between Python 2.X and Python 3.X is that the former uses the universal newlines approach to splitting lines, so "\r", "\n", and "\r\n" are considered line boundaries for 8-bit strings, while the latter uses a superset of it that also includes:

  • \v or \x0b: Line Tabulation (added in Python 3.2).
  • \f or \x0c: Form Feed (added in Python 3.2).
  • \x1c: File Separator.
  • \x1d: Group Separator.
  • \x1e: Record Separator.
  • \x85: Next Line (C1 Control Code).
  • \u2028: Line Separator.
  • \u2029: Paragraph Separator.

splitlines VS split:

Unlike str.split() when a delimiter string sep is given, this method returns an empty list for the empty string, and a terminal line break does not result in an extra line:

>>> ''.splitlines()
[]

>>> 'Line 1\n'.splitlines()
['Line 1']

While str.split('\n') returns:

>>> ''.split('\n')
['']

>>> 'Line 1\n'.split('\n')
['Line 1', '']

?? Removing additional whitespace:

If you also need to remove additional leading or trailing whitespace, like spaces, that are ignored by str.splitlines(), you could use str.splitlines() together with str.strip():

>>> [str.strip() for str in 'Line 1  \n  \nLine 3 \rLine 4 \r\n'.splitlines()]
['Line 1', '', 'Line 3', 'Line 4']

? Removing empty strings (''):

Lastly, if you want to filter out the empty strings from the resulting list, you could use filter():

>>> # Python 2.X:
>>> filter(bool, 'Line 1\n\nLine 3\rLine 4\r\n'.splitlines())
['Line 1', 'Line 3', 'Line 4']

>>> # Python 3.X:
>>> list(filter(bool, 'Line 1\n\nLine 3\rLine 4\r\n'.splitlines()))
['Line 1', 'Line 3', 'Line 4']

Additional comment regarding the original question:

As the error you posted indicates and Burhan suggested, the problem is from the print. There's a related question about that could be useful to you: UnicodeEncodeError: 'charmap' codec can't encode - character maps to <undefined>, print function

Oracle - How to create a materialized view with FAST REFRESH and JOINS

To start with, from the Oracle Database Data Warehousing Guide:

Restrictions on Fast Refresh on Materialized Views with Joins Only

...

  • Rowids of all the tables in the FROM list must appear in the SELECT list of the query.

This means that your statement will need to look something like this:

CREATE MATERIALIZED VIEW MV_Test
  NOLOGGING
  CACHE
  BUILD IMMEDIATE 
  REFRESH FAST ON COMMIT 
  AS
    SELECT V.*, P.*, V.ROWID as V_ROWID, P.ROWID as P_ROWID 
    FROM TPM_PROJECTVERSION V,
         TPM_PROJECT P 
    WHERE P.PROJECTID = V.PROJECTID

Another key aspect to note is that your materialized view logs must be created as with rowid.

Below is a functional test scenario:

CREATE TABLE foo(foo NUMBER, CONSTRAINT foo_pk PRIMARY KEY(foo));

CREATE MATERIALIZED VIEW LOG ON foo WITH ROWID;

CREATE TABLE bar(foo NUMBER, bar NUMBER, CONSTRAINT bar_pk PRIMARY KEY(foo, bar));

CREATE MATERIALIZED VIEW LOG ON bar WITH ROWID;

CREATE MATERIALIZED VIEW foo_bar
  NOLOGGING
  CACHE
  BUILD IMMEDIATE
  REFRESH FAST ON COMMIT  AS SELECT foo.foo, 
                                    bar.bar, 
                                    foo.ROWID AS foo_rowid, 
                                    bar.ROWID AS bar_rowid 
                               FROM foo, bar
                              WHERE foo.foo = bar.foo;

How to find out the location of currently used MySQL configuration file in linux

If you are using terminal just type the following:

locate my.cnf

How do I create a message box with "Yes", "No" choices and a DialogResult?

dynamic MsgResult = this.ShowMessageBox("Do you want to cancel all pending changes ?", "Cancel Changes", MessageBoxOption.YesNo);

if (MsgResult == System.Windows.MessageBoxResult.Yes)
{
    enter code here
}
else 
{
    enter code here
}

Check more detail from here

Configure active profile in SpringBoot via Maven

There are multiple ways to set profiles for your springboot application.

  1. You can add this in your property file:

    spring.profiles.active=dev
    
  2. Programmatic way:

    SpringApplication.setAdditionalProfiles("dev");
    
  3. Tests make it very easy to specify what profiles are active

    @ActiveProfiles("dev")
    
  4. In a Unix environment

    export spring_profiles_active=dev
    
  5. JVM System Parameter

    -Dspring.profiles.active=dev
    

Example: Running a springboot jar file with profile.

java -jar -Dspring.profiles.active=dev application.jar

LINQ: Select where object does not contain items from list

I have not tried this, so I am not guarantueeing anything, however

foreach Bar f in filterBars
{
     search(f)
}
Foo search(Bar b)
{
    fooSelect = (from f in fooBunch
                 where !(from b in f.BarList select b.BarId).Contains(b.ID)
                 select f).ToList();

    return fooSelect;
}

What does Ruby have that Python doesn't, and vice versa?

I like the fundamental differences in the way that Ruby and Python method invocations operate.

Ruby methods are invoked via a form "message passing" and need not be explicitly first-class functions (there are ways to lift methods into "proper" function-objects) -- in this aspect Ruby is similar to Smalltalk.

Python works much more like JavaScript (or even Perl) where methods are functions which are invoked directly (there is also stored context information, but...)

While this might seem like a "minor" detail it is really just the surface of how different the Ruby and Python designs are. (On the other hand, they are also quite the same :-)

One practical difference is the concept of method_missing in Ruby (which, for better or worse, seems to be used in some popular frameworks). In Python, one can (at least partially) emulate the behavior using __getattr__/__getattribute__, albeit non-idiomatically.

Get full path of the files in PowerShell

Really annoying thing in PS 5, where $_ won't be the full path within foreach. These are the string versions of FileInfo and DirectoryInfo objects. For some reason a wildcard in the path fixes it, or use Powershell 6 or 7. You can also pipe to get-item in the middle.

Get-ChildItem -path C:\WINDOWS\System32\*.txt -Recurse | foreach { "$_" }

Get-ChildItem -path C:\WINDOWS\System32 -Recurse | get-item | foreach { "$_" }

This seems to have been an issue with .Net that got resolved in .Net Core (Powershell 7): Stringification behavior of FileInfo / Directory instances has changed since v6.0.2 #7132

How to overwrite files with Copy-Item in PowerShell

How about calling the .NET Framework methods?

You can do ANYTHING with them... :

[System.IO.File]::Copy($src, $dest, $true);

The $true argument makes it overwrite.

What is the LD_PRELOAD trick?

when LD_PRELOAD is used that file will be loaded before any other $export LD_PRELOAD=/path/lib lib to be pre loaded, even this can be used in programs too

JavaScript Editor Plugin for Eclipse

JavaScript that allows for syntax checking

JSHint-Eclipse

and autosuggestions for .js files in Eclipse?

  1. Use JSDoc more as JSDT has nice support for the standard, so you will get more suggestions for your own code.
  2. There is new TernIDE that provide additional hints for .js and AngulatJS .html. Get them together as Anide from http://www.nodeclipse.org/updates/anide/

As Nodeclipse lead, I am always looking for what is available in Eclipse ecosystem. Nodeclipse site has even more links, and I am inviting to collaborate on the JavaScript tools on GitHub

Set adb vendor keys

I tried almost anything but no help...

Everytime was just this

?  ~ adb devices    
List of devices attached
* daemon not running. starting it now on port 5037 *
* daemon started successfully *
aeef5e4e    unauthorized

However I've managed to connect device!

There is tutor, step by step.

  1. Remove existing adb keys on PC:

$ rm -v .android/adbkey* .android/adbkey .android/adbkey.pub

  1. Remove existing authorized adb keys on device, path is /data/misc/adb/adb_keys

  2. Now create new adb keypair

? ~ adb keygen .android/adbkey adb I 47453 711886 adb_auth_host.cpp:220] generate_key '.android/adbkey' adb I 47453 711886 adb_auth_host.cpp:173] Writing public key to '.android/adbkey.pub'

  1. Manually copy from PC .android/adbkey.pub (pubkic key) to Device on path /data/misc/adb/adb_keys

  2. Reboot device and check adb devices :

? ~ adb devices List of devices attached aeef5e4e device

Permissions of /data/misc/adb/adb_keys are (766/-rwxrw-rw-) on my device

How to check if a service is running via batch file and start it, if it is not running?

I also wanted an email sent if the service was started this way so added a bit to @Ic code just thought I would post it in case it helped anyone. I used SendMail but there are other command line options How to send a simple email from a Windows batch file?

set service=MyServiceName

for /F "tokens=3 delims=: " %%H in ('sc query %service% ^| findstr "        STATE"') do (
  if /I "%%H" NEQ "RUNNING" (

    net start %service%

    for /F "tokens=3 delims=: " %%H in ('sc query %service% ^| findstr "        STATE"') do (
      if /I "%%H" EQ "RUNNING" (
        SendMail /smtpserver localhost /to [email protected] /from [email protected] /subject Service Autostart Notification /body Autostart on service %service% succeded.
      ) else (
        SendMail /smtpserver localhost /to [email protected] /from [email protected] /subject Service Autostart Notification /body Autostart on service %service% failed.
      )
    )

  )
)

How do you create a Marker with a custom icon for google maps API v3?

Try

    var marker = new google.maps.Marker({
      position: map.getCenter(),
      icon: 'http://imageshack.us/a/img826/9489/x1my.png',
      map: map
    });

from here

https://developers.google.com/maps/documentation/javascript/examples/marker-symbol-custom

Return char[]/string from a function

Notice you're not dynamically allocating the variable, which pretty much means the data inside str, in your function, will be lost by the end of the function.

You should have:

char * createStr() {

    char char1= 'm';
    char char2= 'y';

    char *str = malloc(3);
    str[0] = char1;
    str[1] = char2;
    str[2] = '\0';

    return str;

}

Then, when you call the function, the type of the variable that will receive the data must match that of the function return. So, you should have:

char *returned_str = createStr();

It worths mentioning that the returned value must be freed to prevent memory leaks.

char *returned_str = createStr();

//doSomething
...

free(returned_str);

How to make a round button?

Round button in Android

You can make a ImageButton with circular background image.

No operator matches the given name and argument type(s). You might need to add explicit type casts. -- Netbeans, Postgresql 8.4 and Glassfish

I had this issue in a very simple DELETE statement, and it is now solved.

My issue was due to using backticks around the column (this column was named "id").

This query DID NOT WORK and resulted in "No operator matches the given name and argument type(s)"

DELETE FROM mytable WHERE `id` = 3      -- DO NOT USE BACKTICKS

Coming from mysql, in dynamic queries, I always `backtick` columns.

The following query DID WORK (with backticks removed):

DELETE FROM mytable WHERE id = 3

Check if a temporary table exists and delete if it exists before creating a temporary table

My code uses a Source table that changes, and a Destination table that must match those changes.

-- 
-- Sample SQL to update only rows in a "Destination" Table
--  based on only rows that have changed in a "Source" table
--


--
-- Drop and Create a Temp Table to use as the "Source" Table
--
IF OBJECT_ID('tempdb..#tSource') IS NOT NULL drop table #tSource
create table #tSource (Col1 int, Col2 int, Col3 int, Col4 int)

--
-- Insert some values into the source
--
Insert #tSource (Col1, Col2, Col3, Col4) Values(1,1,1,1)
Insert #tSource (Col1, Col2, Col3, Col4) Values(2,1,1,2)
Insert #tSource (Col1, Col2, Col3, Col4) Values(3,1,1,3)
Insert #tSource (Col1, Col2, Col3, Col4) Values(4,1,1,4)
Insert #tSource (Col1, Col2, Col3, Col4) Values(5,1,1,5)
Insert #tSource (Col1, Col2, Col3, Col4) Values(6,1,1,6)

--
-- Drop and Create a Temp Table to use as the "Destination" Table
--
IF OBJECT_ID('tempdb..#tDest') IS NOT NULL drop Table #tDest
create table #tDest (Col1 int, Col2 int, Col3 int, Col4 int)

--
-- Add all Rows from the Source to the Destination
--
Insert #tDest
Select Col1, Col2, Col3, Col4 from #tSource


--
-- Look at both tables to see that they are the same
--
select *
from #tSource
Select *
from #tDest

--
-- Make some changes to the Source
--
update #tSource
    Set Col3=19
    Where Col1=1
update #tSource
    Set Col3=29
    Where Col1=2
update #tSource
    Set Col2=38
    Where Col1=3
update #tSource
    Set Col2=48
    Where Col1=4

--
-- Look at the Differences
-- Note: Only 4 rows are different. 2 Rows have remained the same.
--
Select Col1, Col2, Col3, Col4
from #tSource
except
Select Col1, Col2, Col3, Col4
from #tDest

--
-- Update only the rows that have changed
-- Note: I am using Col1 like an ID column
--
Update #tDest
    Set Col2=S.Col2,
        Col3=S.Col3,
        Col4=S.Col4
From    (   Select Col1, Col2, Col3, Col4
            from #tSource
            except
            Select Col1, Col2, Col3, Col4
            from #tDest
        ) S
Where #tDest.Col1=S.Col1 

--
-- Look at the tables again to see that
--  the destination table has changed to match
--  the source table.

select *
from #tSource
Select *
from #tDest

--
-- Clean Up
--
drop table #tSource
drop table #tDest

html5 input for money/currency

Using javascript's Number.prototype.toLocaleString:

_x000D_
_x000D_
var currencyInput = document.querySelector('input[type="currency"]')
var currency = 'GBP' // https://www.currency-iso.org/dam/downloads/lists/list_one.xml

 // format inital value
onBlur({target:currencyInput})

// bind event listeners
currencyInput.addEventListener('focus', onFocus)
currencyInput.addEventListener('blur', onBlur)


function localStringToNumber( s ){
  return Number(String(s).replace(/[^0-9.-]+/g,""))
}

function onFocus(e){
  var value = e.target.value;
  e.target.value = value ? localStringToNumber(value) : ''
}

function onBlur(e){
  var value = e.target.value

  var options = {
      maximumFractionDigits : 2,
      currency              : currency,
      style                 : "currency",
      currencyDisplay       : "symbol"
  }
  
  e.target.value = (value || value === 0) 
    ? localStringToNumber(value).toLocaleString(undefined, options)
    : ''
}
_x000D_
input{
  padding: 10px;
  font: 20px Arial;
  width: 70%;
}
_x000D_
<input type='currency' value="123" placeholder='Type a number & click outside' />
_x000D_
_x000D_
_x000D_

Here's a very simple demo illustrating the above method (HTML-only)


I've made a tiny React component if anyone's interested

Find a file with a certain extension in folder

Look at the System.IO.Directory class and the static method GetFiles. It has an overload that accepts a path and a search pattern. Example:

 string[] files = System.IO.Directory.GetFiles(path, "*.txt");

php date validation

REGEX should be a last resort. PHP has a few functions that will validate for you. In your case, checkdate is the best option. http://php.net/manual/en/function.checkdate.php

How can you check for a #hash in a URL using JavaScript?

Partridge and Gareths comments above are great. They deserve a separate answer. Apparently, hash and search properties are available on any html Link object:

<a id="test" href="foo.html?bar#quz">test</a>
<script type="text/javascript">
   alert(document.getElementById('test').search); //bar
   alert(document.getElementById('test').hash); //quz
</script>

Or

<a href="bar.html?foo" onclick="alert(this.search)">SAY FOO</a>

Should you need this on a regular string variable and happen to have jQuery around, this should work:

var mylink = "foo.html?bar#quz";

if ($('<a href="'+mylink+'">').get(0).search=='bar')) {
    // do stuff
}

(but its maybe a bit overdone .. )

R Plotting confidence bands with ggplot

require(ggplot2)
require(nlme)

set.seed(101)
mp <-data.frame(year=1990:2010)
N <- nrow(mp)

mp <- within(mp,
         {
             wav <- rnorm(N)*cos(2*pi*year)+rnorm(N)*sin(2*pi*year)+5
             wow <- rnorm(N)*wav+rnorm(N)*wav^3
         })

m01 <- gls(wow~poly(wav,3), data=mp, correlation = corARMA(p=1))

Get fitted values (the same as m01$fitted)

fit <- predict(m01)

Normally we could use something like predict(...,se.fit=TRUE) to get the confidence intervals on the prediction, but gls doesn't provide this capability. We use a recipe similar to the one shown at http://glmm.wikidot.com/faq :

V <- vcov(m01)
X <- model.matrix(~poly(wav,3),data=mp)
se.fit <- sqrt(diag(X %*% V %*% t(X)))

Put together a "prediction frame":

predframe <- with(mp,data.frame(year,wav,
                                wow=fit,lwr=fit-1.96*se.fit,upr=fit+1.96*se.fit))

Now plot with geom_ribbon

(p1 <- ggplot(mp, aes(year, wow))+
    geom_point()+
    geom_line(data=predframe)+
    geom_ribbon(data=predframe,aes(ymin=lwr,ymax=upr),alpha=0.3))

year vs wow

It's easier to see that we got the right answer if we plot against wav rather than year:

(p2 <- ggplot(mp, aes(wav, wow))+
    geom_point()+
    geom_line(data=predframe)+
    geom_ribbon(data=predframe,aes(ymin=lwr,ymax=upr),alpha=0.3))

wav vs wow

It would be nice to do the predictions with more resolution, but it's a little tricky to do this with the results of poly() fits -- see ?makepredictcall.

org.hibernate.MappingException: Unknown entity

Use below line of code in the case of Spring Boot Application Add in Spring Boot Main Class @EntityScan(basePackageClasses=YourClassName.class)

How can I revert a single file to a previous version?

Extracted from here: http://git.661346.n2.nabble.com/Revert-a-single-commit-in-a-single-file-td6064050.html

 git revert <commit> 
 git reset 
 git add <path> 
 git commit ... 
 git reset --hard # making sure you didn't have uncommited changes earlier 

It worked very fine to me.

HQL "is null" And "!= null" on an Oracle column

No. You have to use is null and is not null in HQL.

How do I read the file content from the Internal storage - Android App

Read a file as a string full version (handling exceptions, using UTF-8, handling new line):

// Calling:
/* 
    Context context = getApplicationContext();
    String filename = "log.txt";
    String str = read_file(context, filename);
*/  
public String read_file(Context context, String filename) {
        try {
            FileInputStream fis = context.openFileInput(filename);
            InputStreamReader isr = new InputStreamReader(fis, "UTF-8");
            BufferedReader bufferedReader = new BufferedReader(isr);
            StringBuilder sb = new StringBuilder();
            String line;
            while ((line = bufferedReader.readLine()) != null) {
                sb.append(line).append("\n");
            }
            return sb.toString();
        } catch (FileNotFoundException e) {
            return "";
        } catch (UnsupportedEncodingException e) {
            return "";
        } catch (IOException e) {
            return "";
        }
    }

Note: you don't need to bother about file path only with file name.

What is `git push origin master`? Help with git's refs, heads and remotes

Git has two types of branches: local and remote. To use git pull and git push as you'd like, you have to tell your local branch (my_test) which remote branch it's tracking. In typical Git fashion this can be done in both the config file and with commands.

Commands

Make sure you're on your master branch with

1)git checkout master

then create the new branch with

2)git branch --track my_test origin/my_test

and check it out with

3)git checkout my_test.

You can then push and pull without specifying which local and remote.

However if you've already created the branch then you can use the -u switch to tell git's push and pull you'd like to use the specified local and remote branches from now on, like so:

git pull -u my_test origin/my_test
git push -u my_test origin/my_test

Config

The commands to setup remote branch tracking are fairly straight forward but I'm listing the config way as well as I find it easier if I'm setting up a bunch of tracking branches. Using your favourite editor open up your project's .git/config and add the following to the bottom.

[remote "origin"]
    url = [email protected]:username/repo.git
    fetch = +refs/heads/*:refs/remotes/origin/*
[branch "my_test"]
    remote = origin
    merge = refs/heads/my_test

This specifies a remote called origin, in this case a GitHub style one, and then tells the branch my_test to use it as it's remote.

You can find something very similar to this in the config after running the commands above.

Some useful resources:

How to convert TimeStamp to Date in Java?

Just make a new Date object with the stamp's getTime() value as a parameter.

Here's an example (I use an example timestamp of the current time):

Timestamp stamp = new Timestamp(System.currentTimeMillis());
Date date = new Date(stamp.getTime());
System.out.println(date);

Vlookup referring to table data in a different sheet

Copy =VLOOKUP(M3,A$2:Q$47,13,FALSE) to other sheets, then search for ! replace by !$, search for : replace by :$ one time for all sheets

Pip - Fatal error in launcher: Unable to create process using '"'

One more very basic and simple solution. Run the related python version's installation file (setup file) and click repair mode. It hardly takes one-two minutes and everything works perfectly after that :)

Change placeholder text

For JavaScript use:

document.getElementsByClassName('select-holder')[0].placeholder = "This is my new text";

For jQuery use:

$('.select-holder')[0].placeholder = "This is my new text";

How can I access and process nested objects, arrays or JSON?

Preliminaries

JavaScript has only one data type which can contain multiple values: Object. An Array is a special form of object.

(Plain) Objects have the form

{key: value, key: value, ...}

Arrays have the form

[value, value, ...]

Both arrays and objects expose a key -> value structure. Keys in an array must be numeric, whereas any string can be used as key in objects. The key-value pairs are also called the "properties".

Properties can be accessed either using dot notation

const value = obj.someProperty;

or bracket notation, if the property name would not be a valid JavaScript identifier name [spec], or the name is the value of a variable:

// the space is not a valid character in identifier names
const value = obj["some Property"];

// property name as variable
const name = "some Property";
const value = obj[name];

For that reason, array elements can only be accessed using bracket notation:

const value = arr[5]; // arr.5 would be a syntax error

// property name / index as variable
const x = 5;
const value = arr[x];

Wait... what about JSON?

JSON is a textual representation of data, just like XML, YAML, CSV, and others. To work with such data, it first has to be converted to JavaScript data types, i.e. arrays and objects (and how to work with those was just explained). How to parse JSON is explained in the question Parse JSON in JavaScript? .

Further reading material

How to access arrays and objects is fundamental JavaScript knowledge and therefore it is advisable to read the MDN JavaScript Guide, especially the sections



Accessing nested data structures

A nested data structure is an array or object which refers to other arrays or objects, i.e. its values are arrays or objects. Such structures can be accessed by consecutively applying dot or bracket notation.

Here is an example:

const data = {
    code: 42,
    items: [{
        id: 1,
        name: 'foo'
    }, {
        id: 2,
        name: 'bar'
    }]
};

Let's assume we want to access the name of the second item.

Here is how we can do it step-by-step:

As we can see data is an object, hence we can access its properties using dot notation. The items property is accessed as follows:

data.items

The value is an array, to access its second element, we have to use bracket notation:

data.items[1]

This value is an object and we use dot notation again to access the name property. So we eventually get:

const item_name = data.items[1].name;

Alternatively, we could have used bracket notation for any of the properties, especially if the name contained characters that would have made it invalid for dot notation usage:

const item_name = data['items'][1]['name'];

I'm trying to access a property but I get only undefined back?

Most of the time when you are getting undefined, the object/array simply doesn't have a property with that name.

const foo = {bar: {baz: 42}};
console.log(foo.baz); // undefined

Use console.log or console.dir and inspect the structure of object / array. The property you are trying to access might be actually defined on a nested object / array.

console.log(foo.bar.baz); // 42

What if the property names are dynamic and I don't know them beforehand?

If the property names are unknown or we want to access all properties of an object / elements of an array, we can use the for...in [MDN] loop for objects and the for [MDN] loop for arrays to iterate over all properties / elements.

Objects

To iterate over all properties of data, we can iterate over the object like so:

for (const prop in data) {
    // `prop` contains the name of each property, i.e. `'code'` or `'items'`
    // consequently, `data[prop]` refers to the value of each property, i.e.
    // either `42` or the array
}

Depending on where the object comes from (and what you want to do), you might have to test in each iteration whether the property is really a property of the object, or it is an inherited property. You can do this with Object#hasOwnProperty [MDN].

As alternative to for...in with hasOwnProperty, you can use Object.keys [MDN] to get an array of property names:

Object.keys(data).forEach(function(prop) {
  // `prop` is the property name
  // `data[prop]` is the property value
});

Arrays

To iterate over all elements of the data.items array, we use a for loop:

for(let i = 0, l = data.items.length; i < l; i++) {
    // `i` will take on the values `0`, `1`, `2`,..., i.e. in each iteration
    // we can access the next element in the array with `data.items[i]`, example:
    // 
    // var obj = data.items[i];
    // 
    // Since each element is an object (in our example),
    // we can now access the objects properties with `obj.id` and `obj.name`. 
    // We could also use `data.items[i].id`.
}

One could also use for...in to iterate over arrays, but there are reasons why this should be avoided: Why is 'for(var item in list)' with arrays considered bad practice in JavaScript?.

With the increasing browser support of ECMAScript 5, the array method forEach [MDN] becomes an interesting alternative as well:

data.items.forEach(function(value, index, array) {
    // The callback is executed for each element in the array.
    // `value` is the element itself (equivalent to `array[index]`)
    // `index` will be the index of the element in the array
    // `array` is a reference to the array itself (i.e. `data.items` in this case)
}); 

In environments supporting ES2015 (ES6), you can also use the for...of [MDN] loop, which not only works for arrays, but for any iterable:

for (const item of data.items) {
   // `item` is the array element, **not** the index
}

In each iteration, for...of directly gives us the next element of the iterable, there is no "index" to access or use.


What if the "depth" of the data structure is unknown to me?

In addition to unknown keys, the "depth" of the data structure (i.e. how many nested objects) it has, might be unknown as well. How to access deeply nested properties usually depends on the exact data structure.

But if the data structure contains repeating patterns, e.g. the representation of a binary tree, the solution typically includes to recursively [Wikipedia] access each level of the data structure.

Here is an example to get the first leaf node of a binary tree:

function getLeaf(node) {
    if (node.leftChild) {
        return getLeaf(node.leftChild); // <- recursive call
    }
    else if (node.rightChild) {
        return getLeaf(node.rightChild); // <- recursive call
    }
    else { // node must be a leaf node
        return node;
    }
}

const first_leaf = getLeaf(root);

_x000D_
_x000D_
const root = {_x000D_
    leftChild: {_x000D_
        leftChild: {_x000D_
            leftChild: null,_x000D_
            rightChild: null,_x000D_
            data: 42_x000D_
        },_x000D_
        rightChild: {_x000D_
            leftChild: null,_x000D_
            rightChild: null,_x000D_
            data: 5_x000D_
        }_x000D_
    },_x000D_
    rightChild: {_x000D_
        leftChild: {_x000D_
            leftChild: null,_x000D_
            rightChild: null,_x000D_
            data: 6_x000D_
        },_x000D_
        rightChild: {_x000D_
            leftChild: null,_x000D_
            rightChild: null,_x000D_
            data: 7_x000D_
        }_x000D_
    }_x000D_
};_x000D_
function getLeaf(node) {_x000D_
    if (node.leftChild) {_x000D_
        return getLeaf(node.leftChild);_x000D_
    } else if (node.rightChild) {_x000D_
        return getLeaf(node.rightChild);_x000D_
    } else { // node must be a leaf node_x000D_
        return node;_x000D_
    }_x000D_
}_x000D_
_x000D_
console.log(getLeaf(root).data);
_x000D_
_x000D_
_x000D_

A more generic way to access a nested data structure with unknown keys and depth is to test the type of the value and act accordingly.

Here is an example which adds all primitive values inside a nested data structure into an array (assuming it does not contain any functions). If we encounter an object (or array) we simply call toArray again on that value (recursive call).

function toArray(obj) {
    const result = [];
    for (const prop in obj) {
        const value = obj[prop];
        if (typeof value === 'object') {
            result.push(toArray(value)); // <- recursive call
        }
        else {
            result.push(value);
        }
    }
    return result;
}

_x000D_
_x000D_
const data = {_x000D_
  code: 42,_x000D_
  items: [{_x000D_
    id: 1,_x000D_
    name: 'foo'_x000D_
  }, {_x000D_
    id: 2,_x000D_
    name: 'bar'_x000D_
  }]_x000D_
};_x000D_
_x000D_
_x000D_
function toArray(obj) {_x000D_
  const result = [];_x000D_
  for (const prop in obj) {_x000D_
    const value = obj[prop];_x000D_
    if (typeof value === 'object') {_x000D_
      result.push(toArray(value));_x000D_
    } else {_x000D_
      result.push(value);_x000D_
    }_x000D_
  }_x000D_
  return result;_x000D_
}_x000D_
_x000D_
console.log(toArray(data));
_x000D_
_x000D_
_x000D_



Helpers

Since the structure of a complex object or array is not necessarily obvious, we can inspect the value at each step to decide how to move further. console.log [MDN] and console.dir [MDN] help us doing this. For example (output of the Chrome console):

> console.log(data.items)
 [ Object, Object ]

Here we see that that data.items is an array with two elements which are both objects. In Chrome console the objects can even be expanded and inspected immediately.

> console.log(data.items[1])
  Object
     id: 2
     name: "bar"
     __proto__: Object

This tells us that data.items[1] is an object, and after expanding it we see that it has three properties, id, name and __proto__. The latter is an internal property used for the prototype chain of the object. The prototype chain and inheritance is out of scope for this answer, though.

How to remove \n from a list element?

As an alternate method, if you know that there are no spaces in your data, which it seems is the case, you can use split() (with no arguments). This splits on white space and uses a more efficient algorithm than the other version of split. It also strips whitespace from both ends.

line = line.split()

And that's it.

How to loop through key/value object in Javascript?

for (var key in data) {
    alert("User " + data[key] + " is #" + key); // "User john is #234"
}

How is a tag different from a branch in Git? Which should I use, here?

Branches are made of wood and grow from the trunk of the tree. Tags are made of paper (derivative of wood) and hang like Christmas Ornaments from various places in the tree.

Your project is the tree, and your feature that will be added to the project will grow on a branch. The answer is branch.

Communicating between a fragment and an activity - best practices

I made a annotation library that can do the cast for you. check this out. https://github.com/zeroarst/callbackfragment/

@CallbackFragment
public class MyFragment extends Fragment {

    @Callback
    interface FragmentCallback {
       void onClickButton(MyFragment fragment);
    }    
    private FragmentCallback mCallback;

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.bt1
                mCallback.onClickButton(this);
                break;
            case R.id.bt2
                // Because we give mandatory = false so this might be null if not implemented by the host.
                if (mCallbackNotForce != null)
                mCallbackNotForce.onClickButton(this);
                break;
        }
    }
}

It then generates a subclass of your fragment. And just add it to FragmentManager.

public class MainActivity extends AppCompatActivity implements MyFragment.FragmentCallback {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        getSupportFragmentManager().beginTransaction()
            .add(R.id.lo_fragm_container, MyFragmentCallbackable.create(), "MY_FRAGM")
            .commit();
    }

    Toast mToast;

    @Override
    public void onClickButton(MyFragment fragment) {
        if (mToast != null)
            mToast.cancel();
        mToast = Toast.makeText(this, "Callback from " + fragment.getTag(), Toast.LENGTH_SHORT);
        mToast.show();
    }
}

Disable time in bootstrap date time picker

The selector criteria is now an attribute the DIV tag.

examples are ...

data-date-format="dd MM yyyy" 
data-date-format="dd MM yyyy - HH:ii p
data-date-format="hh:ii"

so the bootstrap example for dd mm yyyy is:-

<div class="input-group date form_date col-md-5" data-date="" 
    data-date-format="dd MM yyyy" data-link-field="dtp_input2" data-link-format="yyyy-mm-dd">
..... etc ....
</div>

my Javascript settings are as follows:-

            var picker_settings = {
                language:  'en',
                weekStart: 1,
                todayBtn:  1,
                autoclose: 1,
                todayHighlight: 1,
                startView: 2,
                minView: 2,
                forceParse: 0
            };

        $(datePickerId).datetimepicker(picker_settings);

You can see working examples of these if you download the bootstrap-datetimepicker-master file. There are sample folders each with an index.html.

Changing CSS style from ASP.NET code

If your div is an ASP.NET control with runat="server" then AviewAnew's answer should do it. If it's just an HTML div, then you'd probably want to use JavaScript. Can you add the actual div tag to your question?