Programs & Examples On #Labeled statements

Labeled statements are names bound to blocks of code such as loops and conditional logic which can be referenced to allow flow control which is independent of source order

How to compare data between two table in different databases using Sql Server 2008?

In order to compare two databases, I've written the procedures bellow. If you want to compare two tables you can use procedure 'CompareTables'. Example :

EXEC master.dbo.CompareTables 'DB1', 'dbo', 'table1', 'DB2', 'dbo', 'table2'

If you want to compare two databases, use the procedure 'CompareDatabases'. Example :

EXEC master.dbo.CompareDatabases 'DB1', 'DB2'

Note : - I tried to make the procedures secure, but anyway, those procedures are only for testing and debugging. - If you want a complete solution for comparison use third party like (Visual Studio, ...)

USE [master]
GO

create proc [dbo].[CompareDatabases]
    @FirstDatabaseName nvarchar(50),
    @SecondDatabaseName nvarchar(50)
    as
begin
    -- Check that databases exist
    if not exists(SELECT name FROM sys.databases WHERE name=@FirstDatabaseName)
        return 0
    if not exists(SELECT name FROM sys.databases WHERE name=@SecondDatabaseName)
        return 0

    declare @result table (TABLE_NAME nvarchar(256))
    SET NOCOUNT ON
    insert into @result EXEC('(Select distinct TABLE_NAME from ' + @FirstDatabaseName  + '.INFORMATION_SCHEMA.COLUMNS '
                                    +'Where TABLE_SCHEMA=''dbo'')'
                            + 'intersect'
                            + '(Select distinct TABLE_NAME from ' + @SecondDatabaseName  + '.INFORMATION_SCHEMA.COLUMNS '
                                    +'Where TABLE_SCHEMA=''dbo'')')

    DECLARE @TABLE_NAME nvarchar(256)
    DECLARE curseur CURSOR FOR
        SELECT TABLE_NAME FROM @result
    OPEN curseur
    FETCH curseur INTO @TABLE_NAME
        WHILE @@FETCH_STATUS = 0
            BEGIN
                print 'TABLE : ' + @TABLE_NAME
                EXEC master.dbo.CompareTables @FirstDatabaseName, 'dbo', @TABLE_NAME, @SecondDatabaseName, 'dbo', @TABLE_NAME
                FETCH curseur INTO @TABLE_NAME
            END
        CLOSE curseur
    DEALLOCATE curseur
    SET NOCOUNT OFF
end
GO

.

USE [master]
GO

CREATE PROC [dbo].[CompareTables]
    @FirstTABLE_CATALOG nvarchar(256),
    @FirstTABLE_SCHEMA nvarchar(256),
    @FirstTABLE_NAME nvarchar(256),
    @SecondTABLE_CATALOG nvarchar(256),
    @SecondTABLE_SCHEMA nvarchar(256),
    @SecondTABLE_NAME nvarchar(256)
    AS
BEGIN
    -- Verify if first table exist
    DECLARE @table1 nvarchar(256) = @FirstTABLE_CATALOG + '.' + @FirstTABLE_SCHEMA + '.' + @FirstTABLE_NAME
    DECLARE @return_status int
    EXEC @return_status = master.dbo.TableExist @FirstTABLE_CATALOG, @FirstTABLE_SCHEMA, @FirstTABLE_NAME
    IF @return_status = 0
        BEGIN
            PRINT @table1 + ' : Table Not FOUND'
            RETURN 0
        END



    -- Verify if second table exist
    DECLARE @table2 nvarchar(256) = @SecondTABLE_CATALOG + '.' + @SecondTABLE_SCHEMA + '.' + @SecondTABLE_NAME
    EXEC @return_status = master.dbo.TableExist @SecondTABLE_CATALOG, @SecondTABLE_SCHEMA, @SecondTABLE_NAME
    IF @return_status = 0
        BEGIN
            PRINT @table2 + ' : Table Not FOUND'
            RETURN 0
        END

    -- Compare the two tables
    DECLARE @sql AS NVARCHAR(MAX)
    SELECT @sql = '('
                + '(SELECT ''' + @table1 + ''' as _Table, * FROM ' + @FirstTABLE_CATALOG + '.' + @FirstTABLE_SCHEMA + '.' + @FirstTABLE_NAME + ')'
                + 'EXCEPT'
                + '(SELECT ''' + @table1 + ''' as _Table, * FROM ' + @SecondTABLE_CATALOG + '.' + @SecondTABLE_SCHEMA + '.' + @SecondTABLE_NAME + ')'
                + ')'
                + 'UNION'
                + '('
                + '(SELECT ''' + @table2 + ''' as _Table, * FROM ' + @SecondTABLE_CATALOG + '.' + @SecondTABLE_SCHEMA + '.' + @SecondTABLE_NAME + ')'
                + 'EXCEPT'
                + '(SELECT ''' + @table2 + ''' as _Table, * FROM ' + @FirstTABLE_CATALOG + '.' + @FirstTABLE_SCHEMA + '.' + @FirstTABLE_NAME + ')'
                + ')'
    DECLARE @wrapper AS NVARCHAR(MAX) = 'if exists (' + @sql + ')' + char(10) + '    (' + @sql + ')ORDER BY 2'
    Exec(@wrapper)
END
GO

.

USE [master]
GO

CREATE PROC [dbo].[TableExist]
    @TABLE_CATALOG nvarchar(256),
    @TABLE_SCHEMA nvarchar(256),
    @TABLE_NAME nvarchar(256)
    AS
BEGIN
    IF NOT EXISTS(SELECT name FROM sys.databases WHERE name=@TABLE_CATALOG)
        RETURN 0

    declare @result table (TABLE_SCHEMA nvarchar(256), TABLE_NAME nvarchar(256))
    SET NOCOUNT ON
    insert into @result EXEC('Select TABLE_SCHEMA, TABLE_NAME from ' + @TABLE_CATALOG  + '.INFORMATION_SCHEMA.COLUMNS')
    SET NOCOUNT OFF

    IF EXISTS(SELECT TABLE_SCHEMA, TABLE_NAME FROM @result
                WHERE TABLE_SCHEMA=@TABLE_SCHEMA AND TABLE_NAME=@TABLE_NAME)
        RETURN 1

    RETURN 0
END

GO

PHPMailer: SMTP Error: Could not connect to SMTP host

Since this is a popular error, check out the PHPMailer Wiki on troubleshooting.

Also this worked for me

$mailer->Port = '587';

How to create correct JSONArray in Java using JSONObject

Small reusable method can be written for creating person json object to avoid duplicate code

JSONObject  getPerson(String firstName, String lastName){
   JSONObject person = new JSONObject();
   person .put("firstName", firstName);
   person .put("lastName", lastName);
   return person ;
} 

public JSONObject getJsonResponse(){

    JSONArray employees = new JSONArray();
    employees.put(getPerson("John","Doe"));
    employees.put(getPerson("Anna","Smith"));
    employees.put(getPerson("Peter","Jones"));

    JSONArray managers = new JSONArray();
    managers.put(getPerson("John","Doe"));
    managers.put(getPerson("Anna","Smith"));
    managers.put(getPerson("Peter","Jones"));

    JSONObject response= new JSONObject();
    response.put("employees", employees );
    response.put("manager", managers );
    return response;
  }

C++ auto keyword. Why is it magic?

This functionality hasn't been there your whole life. It's been supported in Visual Studio since the 2010 version. It's a new C++11 feature, so it's not exclusive to Visual Studio and is/will be portable. Most compilers support it already.

Is Fortran easier to optimize than C for heavy calculations?

This is more than somewhat subjective, because it gets into the quality of compilers and such more than anything else. However, to more directly answer your question, speaking from a language/compiler standpoint there is nothing about Fortran over C that is going to make it inherently faster or better than C. If you are doing heavy math operations, it will come down to the quality of the compiler, the skill of the programmer in each language and the intrinsic math support libraries that support those operations to ultimately determine which is going to be faster for a given implementation.

EDIT: Other people such as @Nils have raised the good point about the difference in the use of pointers in C and the possibility for aliasing that perhaps makes the most naive implementations slower in C. However, there are ways to deal with that in C99, via compiler optimization flags and/or in how the C is actually written. This is well covered in @Nils answer and the subsequent comments that follow on his answer.

SQL Server SELECT into existing table

If the destination table does exist but you don't want to specify column names:

DECLARE @COLUMN_LIST NVARCHAR(MAX);
DECLARE @SQL_INSERT NVARCHAR(MAX);

SET @COLUMN_LIST = (SELECT DISTINCT
    SUBSTRING(
        (
            SELECT ', table1.' + SYSCOL1.name  AS [text()]
            FROM sys.columns SYSCOL1
            WHERE SYSCOL1.object_id = SYSCOL2.object_id and SYSCOL1.is_identity <> 1
            ORDER BY SYSCOL1.object_id
            FOR XML PATH ('')
        ), 2, 1000)
FROM
    sys.columns SYSCOL2
WHERE
    SYSCOL2.object_id = object_id('dbo.TableOne') )

SET @SQL_INSERT =  'INSERT INTO dbo.TableTwo SELECT ' + @COLUMN_LIST + ' FROM dbo.TableOne table1 WHERE col3 LIKE ' + @search_key
EXEC sp_executesql @SQL_INSERT

.NET / C# - Convert char[] to string

Use the constructor of string which accepts a char[]

char[] c = ...;
string s = new string(c);

Uncaught TypeError: Cannot set property 'value' of null

guys This error because of Element Id not Visible from js Try to inspect element from UI and paste it on javascript file:

before :

document.getElementById('form:salesoverviewform:ticketstatusid').value =topping;

After :

document.getElementById('form:salesoverviewform:j_idt190:ticketstatusid').value =topping;

Credits to Divya Akka .... :)

Updating .class file in jar

An alternative is not to replace the .class file in the jar file. Instead put it into a new jar file and ensure that it appears earlier on your classpath than the original jar file.

Not sure I would recommend this for production software but for development it is quick and easy.

Spring MVC - HttpMediaTypeNotAcceptableException

Just something important to keep in mind: Spring versions prior to 3.1.2 are compatible with JACKSON 1.x and NOT with JACKSON 2.x. This is because going from JACKSON 1.x to 2.x the classes's package names were changed. In JACKSON 1.x classes are under org.codehaus.jackson while in JACKSON 2.x they are under com.fasterxml.jackson.

To address this issue, starting with Spring 3.1.2 they added a new MappingJackson2HttpMessageConverter to replace MappingJacksonHttpMessageConverter.

You could find more details regarding compatibility issues in this link: Jackson annotations being ignored in Spring

Exit/save edit to sudoers file? Putty SSH

Just open file by nano /file_name

Once done, press CTRL+O and then Enter to save. Then press CTRL+X to return.

Here CTRL+O : is CTRL and O for Orange Not 0 Zero

Global variables in header file

There are 3 scenarios, you describe:

  1. with 2 .c files and with int i; in the header.
  2. With 2 .c files and with int i=100; in the header (or any other value; that doesn't matter).
  3. With 1 .c file and with int i=100; in the header.

In each scenario, imagine the contents of the header file inserted into the .c file and this .c file compiled into a .o file and then these linked together.

Then following happens:

  1. works fine because of the already mentioned "tentative definitions": every .o file contains one of them, so the linker says "ok".

  2. doesn't work, because both .o files contain a definition with a value, which collide (even if they have the same value) - there may be only one with any given name in all .o files which are linked together at a given time.

  3. works of course, because you have only one .o file and so no possibility for collision.

IMHO a clean thing would be

  • to put either extern int i; or just int i; into the header file,
  • and then to put the "real" definition of i (namely int i = 100;) into file1.c. In this case, this initialization gets used at the start of the program and the corresponding line in main() can be omitted. (Besides, I hope the naming is only an example; please don't name any global variables as i in real programs.)

find: missing argument to -exec

For anyone else having issues when using GNU find binary in a Windows command prompt. The semicolon needs to be escaped with ^

find.exe . -name "*.rm" -exec ffmpeg -i {} -sameq {}.mp3 ^;

npm install doesn't create node_modules directory

If you have a package-lock.json file, you may have to delete that file then run npm i. That worked for me

How can I write text on a HTML5 canvas element?

_x000D_
_x000D_
var canvas = document.getElementById("my-canvas");_x000D_
var context = canvas.getContext("2d");_x000D_
_x000D_
context.fillStyle = "blue";_x000D_
context.font = "bold 16px Arial";_x000D_
context.fillText("Zibri", (canvas.width / 2) - 17, (canvas.height / 2) + 8);
_x000D_
#my-canvas {_x000D_
  background: #FF0;_x000D_
}
_x000D_
<canvas id="my-canvas" width="200" height="120"></canvas>
_x000D_
_x000D_
_x000D_

Keyboard shortcut to clear cell output in Jupyter notebook

I just looked and found cell|all output|clear which worked with:

Server Information: You are using Jupyter notebook.

The version of the notebook server is: 6.1.5 The server is running on this version of Python: Python 3.8.3 (tags/v3.8.3:6f8c832, May 13 2020, 22:37:02) [MSC v.1924 64 bit (AMD64)]

Current Kernel Information: Python 3.8.3 (tags/v3.8.3:6f8c832, May 13 2020, 22:37:02) [MSC v.1924 64 bit (AMD64)] Type 'copyright', 'credits' or 'license' for more information IPython 7.19.0 -- An enhanced Interactive Python. Type '?' for help.

How to fade changing background image

If your trying to fade the backgound image but leave the foreground text/images you could use css to separate the background image into a new div and position it over the div containing the text/images then fade the background div.

Java simple code: java.net.SocketException: Unexpected end of file from server

I do get this error when I do not set the Authentication header or I set wrong credentials.

good example of Javadoc

The page How to Write Doc Coments for the Javadoc Tool contains a good number of good examples. One section is called Examples of Doc Comments and contains quite a few usages.

Also, the Javadoc FAQ contains some more examples to illustrate the answers.

node.js string.replace doesn't work?

Strings are always modelled as immutable (atleast in heigher level languages python/java/javascript/Scala/Objective-C).

So any string operations like concatenation, replacements always returns a new string which contains intended value, whereas the original string will still be same.

The import android.support cannot be resolved

I followed the instructions above by Gene in Android Studio 1.5.1 but it added this to my build.gradle file:

compile 'platforms:android:android-support-v4:23.1.1'

so I changed it to:

compile 'com.android.support:support-v4:23.1.1'

And it started working.

How do I declare a namespace in JavaScript?

Sample:

var namespace = {};
namespace.module1 = (function(){

    var self = {};
    self.initialized = false;

    self.init = function(){
        setTimeout(self.onTimeout, 1000)
    };

    self.onTimeout = function(){
        alert('onTimeout')
        self.initialized = true;
    };

    self.init(); /* If it needs to auto-initialize, */
    /* You can also call 'namespace.module1.init();' from outside the module. */
    return self;
})()

You can optionally declare a local variable, same, like self and assign local.onTimeout if you want it to be private.

The openssl extension is required for SSL/TLS protection

The same error occurred to me. I fixed it by turning off TLS for Composer, it's not safe but I assumed the risk on my develop machine.

try this:

composer config -g -- disable-tls true

and re-run your Composer. It works to me!

But it's unsecure and not recommended for your Server. The official website says:

If set to true all HTTPS URLs will be tried with HTTP instead and no network-level encryption is performed. Enabling this is a security risk and is NOT recommended. The better way is to enable the php_openssl extension in php.ini.

If you don't want to enable unsecure layer in your machine/server, then setup your php to enable openssl and it also works. Make sure the PHP Openssl extension has been installed and enable it on php.ini file.


To enable OpenSSL, add or find and uncomment this line on your php.ini file:

Linux/OSx:

extension=php_openssl.so

Windows:

extension=php_openssl.dll

And reload your php-fpm / web-server if needed!

Smooth scrolling with just pure css

You can do this with pure CSS but you will need to hard code the offset scroll amounts, which may not be ideal should you be changing page content- or should dimensions of your content change on say window resize.

You're likely best placed to use e.g. jQuery, specifically:

$('html, body').stop().animate({
   scrollTop: element.offset().top
}, 1000);

A complete implementation may be:

$('#up, #down').on('click', function(e){
    e.preventDefault();
    var target= $(this).get(0).id == 'up' ? $('#down') : $('#up');
    $('html, body').stop().animate({
       scrollTop: target.offset().top
    }, 1000);
});

Where element is the target element to scroll to and 1000 is the delay in ms before completion.

Demo Fiddle

The benefit being, no matter what changes to your content dimensions, the function will not need to be altered.

Spring Security exclude url patterns in security annotation configurartion

Where are you configuring your authenticated URL pattern(s)? I only see one uri in your code.

Do you have multiple configure(HttpSecurity) methods or just one? It looks like you need all your URIs in the one method.

I have a site which requires authentication to access everything so I want to protect /*. However in order to authenticate I obviously want to not protect /login. I also have static assets I'd like to allow access to (so I can make the login page pretty) and a healthcheck page that shouldn't require auth.

In addition I have a resource, /admin, which requires higher privledges than the rest of the site.

The following is working for me.

@Override
protected void configure(HttpSecurity http) throws Exception {

    http.authorizeRequests()
        .antMatchers("/login**").permitAll()
        .antMatchers("/healthcheck**").permitAll()
        .antMatchers("/static/**").permitAll()
        .antMatchers("/admin/**").access("hasRole('ROLE_ADMIN')")
        .antMatchers("/**").access("hasRole('ROLE_USER')")
        .and()
            .formLogin().loginPage("/login").failureUrl("/login?error")
                .usernameParameter("username").passwordParameter("password")
        .and()
            .logout().logoutSuccessUrl("/login?logout")
        .and()
            .exceptionHandling().accessDeniedPage("/403")
        .and()
            .csrf();

}

NOTE: This is a first match wins so you may need to play with the order. For example, I originally had /** first:

        .antMatchers("/**").access("hasRole('ROLE_USER')")
        .antMatchers("/login**").permitAll()
        .antMatchers("/healthcheck**").permitAll()

Which caused the site to continually redirect all requests for /login back to /login. Likewise I had /admin/** last:

        .antMatchers("/**").access("hasRole('ROLE_USER')")
        .antMatchers("/admin/**").access("hasRole('ROLE_ADMIN')")

Which resulted in my unprivledged test user "guest" having access to the admin interface (yikes!)

Is there an alternative to string.Replace that is case-insensitive?

Regex.Replace(strInput, strToken.Replace("$", "[$]"), strReplaceWith, RegexOptions.IgnoreCase);

using mailto to send email with an attachment

this is not possible in "mailto" function.

please go with server side coding(C#).make sure open vs in administrative permission.

Microsoft.Office.Interop.Outlook.Application oApp = new Microsoft.Office.Interop.Outlook.Application();
Microsoft.Office.Interop.Outlook.MailItem oMsg = (Microsoft.Office.Interop.Outlook.MailItem)oApp.CreateItem(Microsoft.Office.Interop.Outlook.OlItemType.olMailItem);

oMsg.Subject = "emailSubject";
oMsg.BodyFormat = Microsoft.Office.Interop.Outlook.OlBodyFormat.olFormatHTML;
oMsg.BCC = "emailBcc";
oMsg.To = "emailRecipient";

string body = "emailMessage";

oMsg.HTMLBody = "body";              
oMsg.Attachments.Add(Convert.ToString(@"/my_location_virtual_path/myfile.txt"), Microsoft.Office.Interop.Outlook.OlAttachmentType.olByValue, Type.Missing, Type.Missing);

oMsg.Display(false); //In order to displ

MySQL timezone change?

Here is how to synchronize PHP (>=5.3) and MySQL timezones per session and user settings. Put this where it runs when you need set and synchronized timezones.

date_default_timezone_set($my_timezone);
$n = new \DateTime();
$h = $n->getOffset()/3600;
$i = 60*($h-floor($h));
$offset = sprintf('%+d:%02d', $h, $i);
$this->db->query("SET time_zone='$offset'");

Where $my_timezone is one in the list of PHP timezones: http://www.php.net/manual/en/timezones.php

The PHP timezone has to be converted into the hour and minute offset for MySQL. That's what lines 1-4 do.

What's is the difference between include and extend in use case diagram?

Let's make this clearer. We use include every time we want to express the fact that the existence of one case depends on the existence of another.

EXAMPLES:

A user can do shopping online only after he has logged in his account. In other words, he can't do any shopping until he has logged in his account.

A user can't download from a site before the material had been uploaded. So, I can't download if nothing has been uploaded.

Do you get it?

It's about conditioned consequence. I can't do this if previously I didn't do that.

At least, I think this is the right way we use Include. I tend to think the example with Laptop and warranty from right above is the most convincing!

Regular expression to check if password is "8 characters including 1 uppercase letter, 1 special character, alphanumeric characters"

You can use below class for validation:

public class PasswordValidator{

  private Pattern pattern;
  private Matcher matcher;

  private static final String PASSWORD_PATTERN =
          "((?=.*\\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[@#$%]).{6,20})";

  public PasswordValidator(){
      pattern = Pattern.compile(PASSWORD_PATTERN);
  }

  /**
   * Validate password with regular expression
   * @param password password for validation
   * @return true valid password, false invalid password
   */
  public boolean validate(final String password){

      matcher = pattern.matcher(password);
      return matcher.matches();

  }
}

where 6 and 20 are minimum and maximum length for the password.

How do I change the font size of a UILabel in Swift?

SWIFT 3.1

Label.font = Label.font.withSize(NewValue)

Move an array element from one array position to another

Immutable version without array copy:

const moveInArray = (arr, fromIndex, toIndex) => {
  if (toIndex === fromIndex || toIndex >= arr.length) return arr;

  const toMove = arr[fromIndex];
  const movedForward = fromIndex < toIndex;

  return arr.reduce((res, next, index) => {
    if (index === fromIndex) return res;
    if (index === toIndex) return res.concat(
      movedForward ? [next, toMove] : [toMove, next]
    );

    return res.concat(next);
  }, []);
};

How to remove all .svn directories from my application directories

As an important issue, when you want to utilize shell to delete .svn folders You need -depth argument to prevent find command entering the directory that was just deleted and showing error messages like e.g.

"find: ./.svn: No such file or directory"

As a result, You can use find command like below:

cd [dir_to_delete_svn_folders]
find . -depth -name .svn -exec rm -fr {} \;

Is there a jQuery unfocus method?

$('#textarea').blur()

Documentation at: http://api.jquery.com/blur/

Break or return from Java 8 stream forEach?

Update with Java 9+ with takeWhile:

MutableBoolean ongoing = MutableBoolean.of(true);
someobjects.stream()...takeWhile(t -> ongoing.value()).forEach(t -> {
    // doing something.
    if (...) { // want to break;
        ongoing.setFalse();
    }
});

TABLOCK vs TABLOCKX

This is more of an example where TABLOCK did not work for me and TABLOCKX did.

I have 2 sessions, that both use the default (READ COMMITTED) isolation level:

Session 1 is an explicit transaction that will copy data from a linked server to a set of tables in a database, and takes a few seconds to run. [Example, it deletes Questions] Session 2 is an insert statement, that simply inserts rows into a table that Session 1 doesn't make changes to. [Example, it inserts Answers].

(In practice there are multiple sessions inserting multiple records into the table, simultaneously, while Session 1 is running its transaction).

Session 1 has to query the table Session 2 inserts into because it can't delete records that depend on entries that were added by Session 2. [Example: Delete questions that have not been answered].

So, while Session 1 is executing and Session 2 tries to insert, Session 2 loses in a deadlock every time.

So, a delete statement in Session 1 might look something like this: DELETE tblA FROM tblQ LEFT JOIN tblX on ... LEFT JOIN tblA a ON tblQ.Qid = tblA.Qid WHERE ... a.QId IS NULL and ...

The deadlock seems to be caused from contention between querying tblA while Session 2, [3, 4, 5, ..., n] try to insert into tblA.

In my case I could change the isolation level of Session 1's transaction to be SERIALIZABLE. When I did this: The transaction manager has disabled its support for remote/network transactions.

So, I could follow instructions in the accepted answer here to get around it: The transaction manager has disabled its support for remote/network transactions

But a) I wasn't comfortable with changing the isolation level to SERIALIZABLE in the first place- supposedly it degrades performance and may have other consequences I haven't considered, b) didn't understand why doing this suddenly caused the transaction to have a problem working across linked servers, and c) don't know what possible holes I might be opening up by enabling network access.

There seemed to be just 6 queries within a very large transaction that are causing the trouble.

So, I read about TABLOCK and TabLOCKX.

I wasn't crystal clear on the differences, and didn't know if either would work. But it seemed like it would. First I tried TABLOCK and it didn't seem to make any difference. The competing sessions generated the same deadlocks. Then I tried TABLOCKX, and no more deadlocks.

So, in six places, all I needed to do was add a WITH (TABLOCKX).

So, a delete statement in Session 1 might look something like this: DELETE tblA FROM tblQ q LEFT JOIN tblX x on ... LEFT JOIN tblA a WITH (TABLOCKX) ON tblQ.Qid = tblA.Qid WHERE ... a.QId IS NULL and ...

Way to read first few lines for pandas dataframe

I think you can use the nrows parameter. From the docs:

nrows : int, default None

    Number of rows of file to read. Useful for reading pieces of large files

which seems to work. Using one of the standard large test files (988504479 bytes, 5344499 lines):

In [1]: import pandas as pd

In [2]: time z = pd.read_csv("P00000001-ALL.csv", nrows=20)
CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
Wall time: 0.00 s

In [3]: len(z)
Out[3]: 20

In [4]: time z = pd.read_csv("P00000001-ALL.csv")
CPU times: user 27.63 s, sys: 1.92 s, total: 29.55 s
Wall time: 30.23 s

SQL SELECT multi-columns INTO multi-variable

SELECT @variable1 = col1, @variable2 = col2
FROM table1

iloc giving 'IndexError: single positional indexer is out-of-bounds'

This error is caused by:

Y = Dataset.iloc[:,18].values

Indexing is out of bounds here most probably because there are less than 19 columns in your Dataset, so column 18 does not exist. The following code you provided doesn't use Y at all, so you can just comment out this line for now.

What's is the difference between train, validation and test set, in neural networks?

The training and validation sets are used during training.

for each epoch
    for each training data instance
        propagate error through the network
        adjust the weights
        calculate the accuracy over training data
    for each validation data instance
        calculate the accuracy over the validation data
    if the threshold validation accuracy is met
        exit training
    else
        continue training

Once you're finished training, then you run against your testing set and verify that the accuracy is sufficient.

Training Set: this data set is used to adjust the weights on the neural network.

Validation Set: this data set is used to minimize overfitting. You're not adjusting the weights of the network with this data set, you're just verifying that any increase in accuracy over the training data set actually yields an increase in accuracy over a data set that has not been shown to the network before, or at least the network hasn't trained on it (i.e. validation data set). If the accuracy over the training data set increases, but the accuracy over the validation data set stays the same or decreases, then you're overfitting your neural network and you should stop training.

Testing Set: this data set is used only for testing the final solution in order to confirm the actual predictive power of the network.

Start systemd service after specific service?

In the .service file under the [Unit] section:

[Unit]
Description=My Website
After=syslog.target network.target mongodb.service

The important part is the mongodb.service

The manpage describes it however due to formatting it's not as clear on first sight

systemd.unit - well formatted

systemd.unit - not so well formatted

Differences between key, superkey, minimal superkey, candidate key and primary key

Largely based on the accepted answer, but with a few tweaks to fit better the definitions taught in some courses:

  • Key: A set of = 1 columns.
  • Superkey: A key that ? a candidate key.
    • Therefore, a superkey must contain > 1 columns.
    • Minimal Super key = Candidate Key: A key that can uniquely identify each row in a table.
    • Primary Key: The chosen Candidate Key for doing that.
    • Secondary key / Alternate key: A Candidate Key not chosen for doing that.
  • Search Key: A key used for locating records.
  • Composite key or concatenate key: A key with > 1 columns.
    • Usually implies "composite primary key", although "composite alternate key" is also a thing.
  • Sort or control key: A key used to physically sequence the stored data.
  • Foreign Key A key in one table that matches the Primary Key of another table.
    • The table in which foreign key resides is called as dependent table.
    • The table to which foreign key refers is known as parent table.

what's data-reactid attribute in html?

That's the HTML data attribute. See this for more detail: http://html5doctor.com/html5-custom-data-attributes/

Basically it's just a container of your custom data while still making the HTML valid. It's data- plus some unique identifier.

How to remove \n from a list element?

From Python3 onwards

map no longer returns a list but a mapObject, thus the answer will look something like

>>> map(lambda x:x.strip(),l)
<map object at 0x7f00b1839fd0>

You can read more about it on What’s New In Python 3.0.

map() and filter() return iterators. If you really need a list, a quick fix is e.g. list(map(...))

So now what are the ways of getting trough this?


Case 1 - The list call over map with a lambda

map returns an iterator. list is a function that can convert an iterator to a list. Hence you will need to wrap a list call around map. So the answer now becomes,

>>> l = ['Name1', '7.3', '6.9', '6.6', '6.6', '6.1', '6.4', '7.3\n']
>>> list(map(lambda x:x.strip(),l))
['Name1', '7.3', '6.9', '6.6', '6.6', '6.1', '6.4', '7.3']

Very good, we get the output. Now we check the amount of time it takes for this piece of code to execute.

$ python3 -m timeit "l = ['Name1', '7.3', '6.9', '6.6', '6.6', '6.1', '6.4', '7.3\n'];list(map(lambda x:x.strip(),l))"
100000 loops, best of 3: 2.22 usec per loop

2.22 microseconds. That is not so bad. But are there more efficient ways?


Case 2 - The list call over map withOUT a lambda

lambda is frowned upon by many in the Python community (including Guido). Apart from that it will greatly reduce the speed of the program. Hence we need to avoid that as much as possible. The toplevel function str.strip. Comes to our aid here.

The map can be re-written without using lambda using str.strip as

>>> list(map(str.strip,l))
['Name1', '7.3', '6.9', '6.6', '6.6', '6.1', '6.4', '7.3']

And now for the times.

$ python3 -m timeit "l = ['Name1', '7.3', '6.9', '6.6', '6.6', '6.1', '6.4', '7.3\n'];list(map(str.strip,l))"
1000000 loops, best of 3: 1.38 usec per loop

Fantastic. You can see the efficiency differences between the two ways. It is nearly 60% faster. Thus the approach without using a lambda is a better choice here.


Case 3 - Following Guidelines, The Regular way

Another important point from What’s New In Python 3.0 is that it advices us to avoid map where possible.

Particularly tricky is map() invoked for the side effects of the function; the correct transformation is to use a regular for loop (since creating a list would just be wasteful).

So we can solve this problem without a map by using a regular for loop.

The trivial way of solving (the brute-force) would be:-

>>> l = ['Name1', '7.3', '6.9', '6.6', '6.6', '6.1', '6.4', '7.3\n']
>>> final_list = []
>>> for i in l:
...     final_list.append(i.strip())
... 
>>> final_list
['Name1', '7.3', '6.9', '6.6', '6.6', '6.1', '6.4', '7.3']

The timing setup

def f():
    l = ['Name1', '7.3', '6.9', '6.6', '6.6', '6.1', '6.4', '7.3\n']
    final_list = []
    for i in l:
         final_list.append(i.strip())
import timeit
print(min(timeit.repeat("f()","from __main__ import f")))

And the result.

1.5322505849981098

As you can see the brute-force is a bit slower here. But it is definitely more readable to a common programmer than a map clause.


Case 4 - List Comprehensions

A list comprehension here is also possible and is the same as in Python2.

>>> [i.strip() for i in l]
['Name1', '7.3', '6.9', '6.6', '6.6', '6.1', '6.4', '7.3']

Now for the timings:

$ python3 -m timeit "l = ['Name1', '7.3', '6.9', '6.6', '6.6', '6.1', '6.4', '7.3\n'];[i.strip() for i in l]"
1000000 loops, best of 3: 1.28 usec per loop

As you can see the list-comprehension is more effective than map (even that without a lambda). Hence the thumb rule in Python3 is to use a list comprehension instead of map


Case 5 - In-Place mechanisms and Space Efficiency (T-M-T)

A final way is to make the changes in-place within the list itself. This will save a lot of memory space. This can be done using enumerate.

>>> l = ['Name1', '7.3', '6.9', '6.6', '6.6', '6.1', '6.4', '7.3\n']
>>> for i,s in enumerate(l):
...     l[i] = s.strip()
... 
>>> l
['Name1', '7.3', '6.9', '6.6', '6.6', '6.1', '6.4', '7.3']

The timing result would be 1.4806894720022683. But however this way is space effective.


Conclusion

A comparitive list of timings (Both Python 3.4.3 and Python 3.5.0)

----------------------------------------------------
|Case| method          | Py3.4 |Place| Py3.5 |Place|
|----|-----------------|-------|-----|-------|-----|
| 1  | map with lambda | 2.22u | 5   | 2.85u | 5   |
| 2  | map w/o lambda  | 1.38u | 2   | 2.00u | 2   |
| 3  | brute-force     | 1.53u | 4   | 2.22u | 4   |
| 4  | list comp       | 1.28u | 1   | 1.25u | 1   |
| 5  | in-place        | 1.48u | 3   | 2.14u | 3   |
----------------------------------------------------

Finally note that the list-comprehension is the best way and the map using lambda is the worst. But again --- ONLY IN PYTHON3

Convert date from 'Thu Jun 09 2011 00:00:00 GMT+0530 (India Standard Time)' to 'YYYY-MM-DD' in javascript

You can parse the date using the Date constructor, then spit out the individual time components:

_x000D_
_x000D_
function convert(str) {_x000D_
  var date = new Date(str),_x000D_
    mnth = ("0" + (date.getMonth() + 1)).slice(-2),_x000D_
    day = ("0" + date.getDate()).slice(-2);_x000D_
  return [date.getFullYear(), mnth, day].join("-");_x000D_
}_x000D_
_x000D_
console.log(convert("Thu Jun 09 2011 00:00:00 GMT+0530 (India Standard Time)"))_x000D_
//-> "2011-06-08"
_x000D_
_x000D_
_x000D_

As you can see from the result though, this will parse the date into the local time zone. If you want to keep the date based on the original time zone, the easiest approach is to split the string and extract the parts you need:

_x000D_
_x000D_
function convert(str) {_x000D_
  var mnths = {_x000D_
      Jan: "01",_x000D_
      Feb: "02",_x000D_
      Mar: "03",_x000D_
      Apr: "04",_x000D_
      May: "05",_x000D_
      Jun: "06",_x000D_
      Jul: "07",_x000D_
      Aug: "08",_x000D_
      Sep: "09",_x000D_
      Oct: "10",_x000D_
      Nov: "11",_x000D_
      Dec: "12"_x000D_
    },_x000D_
    date = str.split(" ");_x000D_
_x000D_
  return [date[3], mnths[date[1]], date[2]].join("-");_x000D_
}_x000D_
_x000D_
console.log(convert("Thu Jun 09 2011 00:00:00 GMT+0530 (India Standard Time)"))_x000D_
//-> "2011-06-09"
_x000D_
_x000D_
_x000D_

How to get the day of week and the month of the year?

Use the standard javascript Date class. No need for arrays. No need for extra libraries.

See https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Date/toLocaleDateString

_x000D_
_x000D_
var options = {  weekday: 'long', year: 'numeric', month: 'long', day: 'numeric', hour: '2-digit', minute: '2-digit', second: '2-digit', hour12: false };_x000D_
var prnDt = 'Printed on ' + new Date().toLocaleTimeString('en-us', options);_x000D_
_x000D_
console.log(prnDt);
_x000D_
_x000D_
_x000D_

What are the retransmission rules for TCP?

There's no fixed time for retransmission. Simple implementations estimate the RTT (round-trip-time) and if no ACK to send data has been received in 2x that time then they re-send.

They then double the wait-time and re-send once more if again there is no reply. Rinse. Repeat.

More sophisticated systems make better estimates of how long it should take for the ACK as well as guesses about exactly which data has been lost.

The bottom-line is that there is no hard-and-fast rule about exactly when to retransmit. It's up to the implementation. All retransmissions are triggered solely by the sender based on lack of response from the receiver.

TCP never drops data so no, there is no way to indicate a server should forget about some segment.

Remove a specific string from an array of string

Define "remove".

Arrays are fixed length and can not be resized once created. You can set an element to null to remove an object reference;

for (int i = 0; i < myStringArray.length(); i++)
{
    if (myStringArray[i].equals(stringToRemove))
    {
        myStringArray[i] = null;
        break;
    }
}

or

myStringArray[indexOfStringToRemove] = null;

If you want a dynamically sized array where the object is actually removed and the list (array) size is adjusted accordingly, use an ArrayList<String>

myArrayList.remove(stringToRemove); 

or

myArrayList.remove(indexOfStringToRemove);

Edit in response to OP's edit to his question and comment below

String r = myArrayList.get(rgenerator.nextInt(myArrayList.size()));

How does C compute sin() and other math functions?

If you want an implementation in software, not hardware, the place to look for a definitive answer to this question is Chapter 5 of Numerical Recipes. My copy is in a box, so I can't give details, but the short version (if I remember this right) is that you take tan(theta/2) as your primitive operation and compute the others from there. The computation is done with a series approximation, but it's something that converges much more quickly than a Taylor series.

Sorry I can't rembember more without getting my hand on the book.

Java 8 stream map on entry set

Please make the following part of the Collectors API:

<K, V> Collector<? super Map.Entry<K, V>, ?, Map<K, V>> toMap() {
  return Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue);
}

How can I clear previous output in Terminal in Mac OS X?

I couldn't get any of the previous answers to work (on macOS).

A combination worked for me -

IO.write "\e[H\e[2J\e[3J"

This clears the buffer and the screen.

Which Radio button in the group is checked?

You could use LINQ:

var checkedButton = container.Controls.OfType<RadioButton>()
                                      .FirstOrDefault(r => r.Checked);

Note that this requires that all of the radio buttons be directly in the same container (eg, Panel or Form), and that there is only one group in the container. If that is not the case, you could make List<RadioButton>s in your constructor for each group, then write list.FirstOrDefault(r => r.Checked).

Is there a Google Keep API?

No there's not and developers still don't know why google doesn't pay attention to this request!

As you can see in this link it's one of the most popular issues with many stars in google code but still no response from google! You can also add stars to this issue, maybe google hears that!

Troubleshooting "Warning: session_start(): Cannot send session cache limiter - headers already sent"

This should solve your problem. session_start() should be called before any character is sent back to the browser. In your case, HTML and blank lines were sent before you called session_start(). Documentation here.

To further explain your question of why it works when you submit to a different page, that page either do not use session_start() or calls session_start() before sending any character back to the client! This page on the other hand was calling session_start() much later when a lot of HTML has been sent back to the client (browser).

The better way to code is to have a common header file that calls connects to MySQL database, calls session_start() and does other common things for all pages and include that file on top of each page like below:

include "header.php";

This will stop issues like you are having as also allow you to have a common set of code to manage across a project. Something definitely for you to think about I would suggest after looking at your code.

<?php
session_start();

                if (isset($_SESSION['error']))

                {

                    echo "<span id=\"error\"><p>" . $_SESSION['error'] . "</p></span>";

                    unset($_SESSION['error']);

                }

                ?>

                <form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post" enctype="multipart/form-data">

                <p>
                 <label class="style4">Category Name</label>

                   &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <input type="text" name="categoryname" /><br /><br />

                    <label class="style4">Category Image</label>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;

                    <input type="file" name="image" /><br />

                    <input type="hidden" name="MAX_FILE_SIZE" value="100000" />

                   <br />
<br />
 <input type="submit" id="submit" value="UPLOAD" />

                </p>

                </form>




                             <?php



require("includes/conn.php");


function is_valid_type($file)

{

    $valid_types = array("image/jpg", "image/jpeg", "image/bmp", "image/gif", "image/png");



    if (in_array($file['type'], $valid_types))

        return 1;

    return 0;
}

function showContents($array)

{

    echo "<pre>";

    print_r($array);

    echo "</pre>";
}


$TARGET_PATH = "images/category";

$cname = $_POST['categoryname'];

$image = $_FILES['image'];

$cname = mysql_real_escape_string($cname);

$image['name'] = mysql_real_escape_string($image['name']);

$TARGET_PATH .= $image['name'];

if ( $cname == "" || $image['name'] == "" )

{

    $_SESSION['error'] = "All fields are required";

    header("Location: managecategories.php");

    exit;

}

if (!is_valid_type($image))

{

    $_SESSION['error'] = "You must upload a jpeg, gif, or bmp";

    header("Location: managecategories.php");

    exit;

}




if (file_exists($TARGET_PATH))

{

    $_SESSION['error'] = "A file with that name already exists";

    header("Location: managecategories.php");

    exit;

}


if (move_uploaded_file($image['tmp_name'], $TARGET_PATH))

{



    $sql = "insert into Categories (CategoryName, FileName) values ('$cname', '" . $image['name'] . "')";

    $result = mysql_query($sql) or die ("Could not insert data into DB: " . mysql_error());

  header("Location: mangaecategories.php");

    exit;

}

else

{





    $_SESSION['error'] = "Could not upload file.  Check read/write persmissions on the directory";

    header("Location: mangagecategories.php");

    exit;

}

?> 

Convert String to Carbon

Why not try using the following:

$dateTimeString = $aDateString." ".$aTimeString;
$dueDateTime = Carbon::createFromFormat('Y-m-d H:i:s', $dateTimeString, 'Europe/London');   

How to use variables in a command in sed?

This may also can help

input="inputtext"
output="outputtext"
sed "s/$input/${output}/" inputfile > outputfile

Uncaught TypeError: Cannot read property 'toLowerCase' of undefined

your $(this).val() has no scope in your ajax call, because its not in change event function scope

May be you implemented that ajax call in your change event itself first, in that case it works fine. but when u created a function and calling that funciton in change event, scope for $(this).val() is not valid.

simply get the value using id selector instead of

$(#CourseSelect).val()

whole code should be like this:

 $(document).ready(function () 
{
    $("#CourseSelect").change(loadTeachers);
    loadTeachers();
});

function loadTeachers()
{
    $.ajax({ type:'GET', url:'/Manage/getTeachers/' + $(#CourseSelect).val(), dataType:'json', cache:false,
        success:function(data)
        { 
            $('#TeacherSelect').get(0).options.length = 0;    

            $.each(data, function(i, teacher) 
            {
                var option = $('<option />');
                option.val(teacher.employeeId);
                option.text(teacher.name);
                $('#TeacherSelect').append(option);
            });
        }, error:function(){ alert("Error while getting results"); }
    });
}

file_get_contents("php://input") or $HTTP_RAW_POST_DATA, which one is better to get the body of JSON request?

For JSON data, it's much easier to POST it as "application/json" content-type. If you use GET, you have to URL-encode the JSON in a parameter and it's kind of messy. Also, there is no size limit when you do POST. GET's size if very limited (4K at most).

The difference between sys.stdout.write and print?

Are there situations in which sys.stdout.write() is preferable to print?

For example I'm working on small function which prints stars in pyramid format upon passing the number as argument, although you can accomplish this using end="" to print in a separate line, I used sys.stdout.write in co-ordination with print to make this work. To elaborate on this stdout.write prints in the same line where as print always prints its contents in a separate line.

import sys

def printstars(count):

    if count >= 1:
        i = 1
        while (i <= count):
            x=0
            while(x<i):
                sys.stdout.write('*')
                x = x+1
            print('')
            i=i+1

printstars(5)

How to do case insensitive string comparison?

Use RegEx for string match or comparison.

In JavaScript, you can use match() for string comparison, don't forget to put iin RegEx.

Example:

var matchString = "Test";
if (matchString.match(/test/i)) {
  alert('String matched');
}
else {
 alert('String not matched');
}

How to customise the Jackson JSON mapper implicitly used by Spring Boot?

The right way to add further configurations to the Spring Boot peconfigured ObjectMapper is to define a Jackson2ObjectMapperBuilderCustomizer. Else you are overwriting Springs configuration, which you do not want to lose.

 @Configuration
public class MyJacksonConfigurer implements Jackson2ObjectMapperBuilderCustomizer {
    @Override
    public void customize(Jackson2ObjectMapperBuilder builder) {
        builder.deserializerByType(LocalDate.class, new MyOwnJsonLocalDateTimeDeserializer());
    }
}

PHP Converting Integer to Date, reverse of strtotime

I guess you are asking why is 1388516401 equal to 2014-01-01...?

There is an historical reason for that. There is a 32-bit integer variable, called time_t, that keeps the count of the time elapsed since 1970-01-01 00:00:00. Its value expresses time in seconds. This means that in 2014-01-01 00:00:01 time_t will be equal to 1388516401.

This leads us for sure to another interesting fact... In 2038-01-19 03:14:07 time_t will reach 2147485547, the maximum value for a 32-bit number. Ever heard about John Titor and the Year 2038 problem? :D

Persistent invalid graphics state error when using ggplot2

You likely don't need to reinstall ggplot2

Solution: go back to plot that didn't work previously. Take the below console output for example. The figure margins (the window that displays your plots) were too small to display the pairs(MinusInner) plot. Then when I tried to make the next qplot, R was still hung up on previous error.

pairs(MinusInner) Error in plot.new() : figure margins too large qplot(Sample.Type, BAE,data=MinusInner, geom="boxplot") Error in .Call.graphics(C_palette2, .Call(C_palette2, NULL)) : invalid graphics state

I fixed the first error by expanding the plot window and rerunning the pairs(MinusInner) plot. Then blam, it worked.

pairs(MinusInner) qplot(Sample.Type, BAE,data=MinusInner, geom="boxplot")

Error: Unfortunately you can't have non-Gradle Java modules and > Android-Gradle modules in one project

  1. Close the project
  2. Just delete the modules.xml in .idea folder.
  3. Open the project again.

How do I know if jQuery has an Ajax request pending?

We have to utilize $.ajax.abort() method to abort request if the request is active. This promise object uses readyState property to check whether the request is active or not.

HTML

<h3>Cancel Ajax Request on Demand</h3>
<div id="test"></div>
<input type="button" id="btnCancel" value="Click to Cancel the Ajax Request" />

JS Code

//Initial Message
var ajaxRequestVariable;
$("#test").html("Please wait while request is being processed..");

//Event handler for Cancel Button
$("#btnCancel").on("click", function(){
if (ajaxRequestVariable !== undefined)

if (ajaxRequestVariable.readyState > 0 && ajaxRequestVariable.readyState < 4)
{
  ajaxRequestVariable.abort();
  $("#test").html("Ajax Request Cancelled.");
}
});

//Ajax Process Starts
ajaxRequestVariable = $.ajax({
            method: "POST",
            url: '/echo/json/',
            contentType: "application/json",
            cache: false,
            dataType: "json",
            data: {
        json: JSON.encode({
         data:
             [
                            {"prop1":"prop1Value"},
                    {"prop1":"prop2Value"}
                  ]         
        }),
        delay: 11
    },

            success: function (response) {
            $("#test").show();
            $("#test").html("Request is completed");           
            },
            error: function (error) {

            },
            complete: function () {

            }
        });

Cannot find reference 'xxx' in __init__.py - Python / Pycharm

You can mark source directory as a source root like so:

  • Right-click on source directory
  • Mark Directory As --> Source Root
  • File --> Invalidate Caches / Restart... -> Invalidate and Restart

What are .NET Assemblies?

In addition to the accepted answer, I want to give you an example!

For instance, we all use

System.Console.WriteLine()

But Where is the code for System.Console.WriteLine!?
which is the code that actually puts the text on the console?

If you look at the first page of the documentation for the Console class, you‘ll see near the top the following: Assembly: mscorlib (in mscorlib.dll) This indicates that the code for the Console class is located in an assem-bly named mscorlib. An assembly can consist of multiple files, but in this case it‘s only one file, which is the dynamic link library mscorlib.dll.

The mscorlib.dll file is very important in .NET, It is the main DLL for class libraries in .NET, and it contains all the basic .NET classes and structures.

if you know C or C++, generally you need a #include directive at the top that references a header file. The include file provides function prototypes to the compiler. on the contrast The C# compiler does not need header files. During compilation, the C# compiler access the mscorlib.dll file directly and obtains information from metadata in that file concerning all the classes and other types defined therein.

The C# compiler is able to establish that mscorlib.dll does indeed contain a class named Console in a namespace named System with a method named WriteLine that accepts a single argument of type string.

The C# compiler can determine that the WriteLine call is valid, and the compiler establishes a reference to the mscorlib assembly in the executable.

by default The C# compiler will access mscorlib.dll, but for other DLLs, you‘ll need to tell the compiler the assembly in which the classes are located. These are known as references.

I hope that it's clear now!

From DotNetBookZero Charles pitzold

Recommended method for escaping HTML in Java

On android (API 16 or greater) you can:

Html.escapeHtml(textToScape);

or for lower API:

TextUtils.htmlEncode(textToScape);

Change value of variable with dplyr

We can use replace to change the values in 'mpg' to NA that corresponds to cyl==4.

mtcars %>%
     mutate(mpg=replace(mpg, cyl==4, NA)) %>%
     as.data.frame()

What does -> mean in C++?

member b of object pointed to by a a->b

Appending an element to the end of a list in Scala

That's because you shouldn't do it (at least with an immutable list). If you really really need to append an element to the end of a data structure and this data structure really really needs to be a list and this list really really has to be immutable then do eiher this:

(4 :: List(1,2,3).reverse).reverse

or that:

List(1,2,3) ::: List(4)

Unable to load Private Key. (PEM routines:PEM_read_bio:no start line:pem_lib.c:648:Expecting: ANY PRIVATE KEY)

Open the key file in Notepad++ and verify the encoding. If it says UTF-8-BOM then change it to UTF-8. Save the file and try again.

Changing Vim indentation behavior by file type

edit your ~/.vimrc, and add different file types for different indents,e.g. I want html/rb indent for 2 spaces, and js/coffee files indent for 4 spaces:

" by default, the indent is 2 spaces. 
set shiftwidth=2
set softtabstop=2
set tabstop=2

" for html/rb files, 2 spaces
autocmd Filetype html setlocal ts=2 sw=2 expandtab
autocmd Filetype ruby setlocal ts=2 sw=2 expandtab

" for js/coffee/jade files, 4 spaces
autocmd Filetype javascript setlocal ts=4 sw=4 sts=0 expandtab
autocmd Filetype coffeescript setlocal ts=4 sw=4 sts=0 expandtab
autocmd Filetype jade setlocal ts=4 sw=4 sts=0 expandtab

refer to: Setting Vim whitespace preferences by filetype

Missing Authentication Token while accessing API Gateway?

To contribute:

I had a similar error because my return response did not contain the 'body' like this:

return { 'statusCode': 200, 'body': "must contain the body tag if you replace it won't work" }

Listening for variable changes in JavaScript

If you're using jQuery {UI} (which everyone should be using :-) ), you can use .change() with a hidden <input/> element.

Java ElasticSearch None of the configured nodes are available

You should check the node's port, you could do it using head. These ports are not same. Example,

The web URL you can open is localhost:9200, but the node's port is 9300, so none of the configured nodes are available if you use the 9200 as the port.

Bulk Insert to Oracle using .NET

To follow up on Theo's suggestion with my findings (apologies - I don't currently have enough reputation to post this as a comment)

First, this is how to use several named parameters:

String commandString = "INSERT INTO Users (Name, Desk, UpdateTime) VALUES (:Name, :Desk, :UpdateTime)";
using (OracleCommand command = new OracleCommand(commandString, _connection, _transaction))
{
    command.Parameters.Add("Name", OracleType.VarChar, 50).Value = strategy;
    command.Parameters.Add("Desk", OracleType.VarChar, 50).Value = deskName ?? OracleString.Null;
    command.Parameters.Add("UpdateTime", OracleType.DateTime).Value = updated;
    command.ExecuteNonQuery();
}

However, I saw no variation in speed between:

  • constructing a new commandString for each row (String.Format)
  • constructing a now parameterized commandString for each row
  • using a single commandString and changing the parameters

I'm using System.Data.OracleClient, deleting and inserting 2500 rows inside a transaction

How to create the pom.xml for a Java project with Eclipse

Right click on Project -> Add FrameWork Support -> Maven

Get: TypeError: 'dict_values' object does not support indexing when using python 3.2.3

In Python 3 the dict.values() method returns a dictionary view object, not a list like it does in Python 2. Dictionary views have a length, can be iterated, and support membership testing, but don't support indexing.

To make your code work in both versions, you could use either of these:

{names[i]:value for i,value in enumerate(d.values())}

    or

values = list(d.values())
{name:values[i] for i,name in enumerate(names)}

By far the simplest, fastest way to do the same thing in either version would be:

dict(zip(names, d.values()))

Note however, that all of these methods will give you results that will vary depending on the actual contents of d. To overcome that, you may be able use an OrderedDict instead, which remembers the order that keys were first inserted into it, so you can count on the order of what is returned by the values() method.

jquery how to use multiple ajax calls one after the end of the other

You could also use jquery when and then functions. for example

 $.when( $.ajax( "test.aspx" ) ).then(function( data, textStatus, jqXHR ) {
  //another ajax call
});

https://api.jquery.com/jQuery.when/

How can you find out which process is listening on a TCP or UDP port on Windows?

netstat -aof | findstr :8080 (Change 8080 for any port)

Validating input using java.util.Scanner

For checking Strings for letters you can use regular expressions for example:

someString.matches("[A-F]");

For checking numbers and stopping the program crashing, I have a quite simple class you can find below where you can define the range of values you want. Here

    public int readInt(String prompt, int min, int max)
    {
    Scanner scan = new Scanner(System.in);

    int number = 0;

    //Run once and loop until the input is within the specified range.
    do 
    {
        //Print users message.
        System.out.printf("\n%s > ", prompt);

        //Prevent string input crashing the program.
        while (!scan.hasNextInt()) 
        {
            System.out.printf("Input doesn't match specifications. Try again.");
            System.out.printf("\n%s > ", prompt);
            scan.next(); 
        }

        //Set the number.
        number = scan.nextInt();

        //If the number is outside range print an error message.
        if (number < min || number > max)
            System.out.printf("Input doesn't match specifications. Try again.");

    } while (number < min || number > max);

    return number;
}

Check if Variable is Empty - Angular 2

if( myVariable ) 
{ 
    //mayVariable is not : 
    //null 
    //undefined 
    //NaN 
    //empty string ("") 
    //0 
    //false 
}

Check if process returns 0 with batch file

This is not exactly the answer to the question, but I end up here every time I want to find out how to get my batch file to exit with and error code when a process returns an nonzero code.

So here is the answer to that:

if %ERRORLEVEL% NEQ 0 exit %ERRORLEVEL%

HTTP Status 500 - Servlet.init() for servlet Dispatcher threw exception

You map your dispatcher on *.do:

<servlet-mapping>
   <servlet-name>Dispatcher</servlet-name>
   <url-pattern>*.do</url-pattern>
</servlet-mapping>

but your controller is mapped on an url without .do:

@RequestMapping("/editPresPage")

Try changing this to:

@RequestMapping("/editPresPage.do")

Logo image and H1 heading on the same line

Try this:

  1. Put both elements in a container DIV.
  2. Give that container the property overflow:auto
  3. Float both elements to the left using float:left
  4. Give the H1 a width so that it doesn't take up the full width of it's parent container.

Remove empty array elements

function trim_array($Array)
{
    foreach ($Array as $value) {
        if(trim($value) === '') {
            $index = array_search($value, $Array);
            unset($Array[$index]);
        }
    }
    return $Array;
}

check if "it's a number" function in Oracle

One additional idea, mentioned here is to use a regular expression to check:

SELECT  foo 
FROM    bar
WHERE   REGEXP_LIKE (foo,'^[[:digit:]]+$');

The nice part is you do not need a separate PL/SQL function. The potentially problematic part is that a regular expression may not be the most efficient method for a large number of rows.

error: strcpy was not declared in this scope

When you say:

 #include <cstring>

the g++ compiler should put the <string.h> declarations it itself includes into the std:: AND the global namespaces. It looks for some reason as if it is not doing that. Try replacing one instance of strcpy with std::strcpy and see if that fixes the problem.

How large should my recv buffer be when calling recv in the socket library

The answers to these questions vary depending on whether you are using a stream socket (SOCK_STREAM) or a datagram socket (SOCK_DGRAM) - within TCP/IP, the former corresponds to TCP and the latter to UDP.

How do you know how big to make the buffer passed to recv()?

  • SOCK_STREAM: It doesn't really matter too much. If your protocol is a transactional / interactive one just pick a size that can hold the largest individual message / command you would reasonably expect (3000 is likely fine). If your protocol is transferring bulk data, then larger buffers can be more efficient - a good rule of thumb is around the same as the kernel receive buffer size of the socket (often something around 256kB).

  • SOCK_DGRAM: Use a buffer large enough to hold the biggest packet that your application-level protocol ever sends. If you're using UDP, then in general your application-level protocol shouldn't be sending packets larger than about 1400 bytes, because they'll certainly need to be fragmented and reassembled.

What happens if recv gets a packet larger than the buffer?

  • SOCK_STREAM: The question doesn't really make sense as put, because stream sockets don't have a concept of packets - they're just a continuous stream of bytes. If there's more bytes available to read than your buffer has room for, then they'll be queued by the OS and available for your next call to recv.

  • SOCK_DGRAM: The excess bytes are discarded.

How can I know if I have received the entire message?

  • SOCK_STREAM: You need to build some way of determining the end-of-message into your application-level protocol. Commonly this is either a length prefix (starting each message with the length of the message) or an end-of-message delimiter (which might just be a newline in a text-based protocol, for example). A third, lesser-used, option is to mandate a fixed size for each message. Combinations of these options are also possible - for example, a fixed-size header that includes a length value.

  • SOCK_DGRAM: An single recv call always returns a single datagram.

Is there a way I can make a buffer not have a fixed amount of space, so that I can keep adding to it without fear of running out of space?

No. However, you can try to resize the buffer using realloc() (if it was originally allocated with malloc() or calloc(), that is).

jQuery get the location of an element relative to window

function getWindowRelativeOffset(parentWindow, elem) {
        var offset = {
            left : 0,
            top : 0
        };
        // relative to the target field's document
        offset.left = elem.getBoundingClientRect().left;
        offset.top = elem.getBoundingClientRect().top;
        // now we will calculate according to the current document, this current
        // document might be same as the document of target field or it may be
        // parent of the document of the target field
        var childWindow = elem.document.frames.window;
        while (childWindow != parentWindow) {
            offset.left = offset.left + childWindow.frameElement.getBoundingClientRect().left;
            offset.top = offset.top + childWindow.frameElement.getBoundingClientRect().top;
            childWindow = childWindow.parent;
        }
        return offset;
    };

you can call it like this

getWindowRelativeOffset(top, inputElement);

I focus for IE only as per my requirement but similar can be done for other browsers

No log4j2 configuration file found. Using default configuration: logging only errors to the console

I have been dealing with this problem for a while. I have changed everything as described in this post and even thought error occured. In that case make sure that you clean the project when changing settings in .xml or .properties file. In eclipse environment. Choose Project -> Clean

How to save a base64 image to user's disk using JavaScript?

This Works

function saveBase64AsFile(base64, fileName) {
    var link = document.createElement("a");
    document.body.appendChild(link);
    link.setAttribute("type", "hidden");
    link.href = "data:text/plain;base64," + base64;
    link.download = fileName;
    link.click();  
    document.body.removeChild(link);
}

Based on the answer above but with some changes

Directly export a query to CSV using SQL Developer

After Ctrl+End, you can do the Ctrl+A to select all in the buffer and then paste into Excel. Excel even put each Oracle column into its own column instead of squishing the whole row into one column. Nice..

How to find if div with specific id exists in jQuery?

You can handle it in different ways,

Objective is to check if the div exist then execute the code. Simple.

Condition:

$('#myDiv').length

Note:

#myDiv -> < div id='myDiv' > <br>
.myDiv -> < div class='myDiv' > 

This will return a number every time it is executed so if there is no div it will give a Zero [0], and as we no 0 can be represented as false in binary so you can use it in if statement. And you can you use it as a comparison with a none number. while any there are three statement given below

// Statement 0
// jQuery/Ajax has replace [ document.getElementById with $ sign ] and etc
// if you don't want to use jQuery/ajax 

   if (document.getElementById(name)) { 
      $("div#page-content div#chatbar").append("<div class='labels'>" + name + "</div><div id='" + name + "'></div>");
    }

// Statement 1
   if ($('#'+ name).length){ // if 0 then false ; if not 0 then true
       $("div#page-content div#chatbar").append("<div class='labels'>" + name + "</div><div id='" + name + "'></div>");
    }

// Statement 2
    if(!$('#'+ name).length){ // ! Means Not. So if it 0 not then [0 not is 1]
           $("div#page-content div#chatbar").append("<div class='labels'>" + name + "</div><div id='" + name + "'></div>"); 
    }
// Statement 3
    if ($('#'+ name).length > 0 ) {
      $("div#page-content div#chatbar").append("<div class='labels'>" + name + "</div><div id='" + name + "'></div>");
    }

// Statement 4
    if ($('#'+ name).length !== 0 ) { // length not equal to 0 which mean exist.
       $("div#page-content div#chatbar").append("<div class='labels'>" + name + "</div><div id='" + name + "'></div>");
    }

Missing maven .m2 folder

Use mvn -X or mvn --debug to find out from which different locations Maven reads settings.xml. This switch activates debug logging. Just check the first lines of mvn --debug | findstr /i /c:using /c:reading.


Right, Maven uses the Java system property user.home as location for the .m2 folder.

But user.home does not always resolve to %USERPROFILE%\.m2. If you have moved the location of your Desktop folder to another place, user.home might resolve to the parent directory of this new Desktop folder. This happens when using Windows Vista or a more recent Windows together with Java 7 or any older Java version.

The blog post Java’s “user.home” is Wrong on Windows describes it very well and gives links to the official bug reports. The bug is marked as resolved in Java 8. The comment of the blog's visitor Lars proposes a nice workaround.

javax vs java package

I think it's a historical thing - if a package is introduced as an addition to an existing JRE, it comes in as javax. If it's first introduced as part of a JRE (like NIO was, I believe) then it comes in as java. Not sure why the new date and time API will end up as javax following this logic though... unless it will also be available separately as a library to work with earlier versions (which would be useful). Note from many years later: it actually ended up being in java after all.

I believe there are restrictions on the java package - I think classloaders are set up to only allow classes within java.* to be loaded from rt.jar or something similar. (There's certainly a check in ClassLoader.preDefineClass.)

EDIT: While an official explanation (the search orbfish suggested didn't yield one in the first page or so) is no doubt about "core" vs "extension", I still suspect that in many cases the decision for any particular package has an historical reason behind it too. Is java.beans really that "core" to Java, for example?

ORA-01652 Unable to extend temp segment by in tablespace

Create a new datafile by running the following command:

alter tablespace TABLE_SPACE_NAME add datafile 'D:\oracle\Oradata\TEMP04.dbf'            
   size 2000M autoextend on;

How can I change Eclipse theme?

enter image description here My Theme plugin provide full featured customization for Eclipse 4. Try it. Visit Plugin Page

What is the full path to the Packages folder for Sublime text 2 on Mac OS Lion

1. Solution

Open Sublime Text console ? paste in opened field:

sublime.packages_path()

? Enter. You get result in console output.


2. Relevance

This answer is relevant for April 2018. In the future, the data of this answer may be obsolete.


3. Not recommended

I'm not recommended @osiris answer. Arguments:

  1. In new versions of Sublime Text and/or operating systems (e.g. Sublime Text 4, macOS 14) paths may be changed.
  2. It doesn't take portable Sublime Text on Windows. In portable Sublime Text on Windows another path of Packages folder.
  3. It less simple.

4. Additional link

Passing variables, creating instances, self, The mechanics and usage of classes: need explanation

class Foo          (object):
    # ^class name  #^ inherits from object

    bar = "Bar" #Class attribute.

    def __init__(self):
        #        #^ The first variable is the class instance in methods.  
        #        #  This is called "self" by convention, but could be any name you want.
        #^ double underscore (dunder) methods are usually special.  This one 
        #  gets called immediately after a new instance is created.

        self.variable = "Foo" #instance attribute.
        print self.variable, self.bar  #<---self.bar references class attribute
        self.bar = " Bar is now Baz"   #<---self.bar is now an instance attribute
        print self.variable, self.bar  

    def method(self, arg1, arg2):
        #This method has arguments.  You would call it like this:  instance.method(1, 2)
        print "in method (args):", arg1, arg2
        print "in method (attributes):", self.variable, self.bar


a = Foo() # this calls __init__ (indirectly), output:
                 # Foo bar
                 # Foo  Bar is now Baz
print a.variable # Foo
a.variable = "bar"
a.method(1, 2) # output:
               # in method (args): 1 2
               # in method (attributes): bar  Bar is now Baz
Foo.method(a, 1, 2) #<--- Same as a.method(1, 2).  This makes it a little more explicit what the argument "self" actually is.

class Bar(object):
    def __init__(self, arg):
        self.arg = arg
        self.Foo = Foo()

b = Bar(a)
b.arg.variable = "something"
print a.variable # something
print b.Foo.variable # Foo

How to understand nil vs. empty vs. blank in Ruby

A special case is when trying to assess if a boolean value is nil:

false.present? == false
false.blank? == true
false.nil? == false

In this case the recommendation would be to use .nil?

Plot width settings in ipython notebook

If you're not in an ipython notebook (like the OP), you can also just declare the size when you declare the figure:

width = 12
height = 12
plt.figure(figsize=(width, height))

Connecting an input stream to an outputstream

You can use a circular buffer :

Code

// buffer all data in a circular buffer of infinite size
CircularByteBuffer cbb = new CircularByteBuffer(CircularByteBuffer.INFINITE_SIZE);
class1.putDataOnOutputStream(cbb.getOutputStream());
class2.processDataFromInputStream(cbb.getInputStream());


Maven dependency

<dependency>
    <groupId>org.ostermiller</groupId>
    <artifactId>utils</artifactId>
    <version>1.07.00</version>
</dependency>


Mode details

http://ostermiller.org/utils/CircularBuffer.html

What is the significance of 1/1/1753 in SQL Server?

This is whole story how date problem was and how Big DBMSs handled these problems.

During the period between 1 A.D. and today, the Western world has actually used two main calendars: the Julian calendar of Julius Caesar and the Gregorian calendar of Pope Gregory XIII. The two calendars differ with respect to only one rule: the rule for deciding what a leap year is. In the Julian calendar, all years divisible by four are leap years. In the Gregorian calendar, all years divisible by four are leap years, except that years divisible by 100 (but not divisible by 400) are not leap years. Thus, the years 1700, 1800, and 1900 are leap years in the Julian calendar but not in the Gregorian calendar, while the years 1600 and 2000 are leap years in both calendars.

When Pope Gregory XIII introduced his calendar in 1582, he also directed that the days between October 4, 1582, and October 15, 1582, should be skipped—that is, he said that the day after October 4 should be October 15. Many countries delayed changing over, though. England and her colonies didn't switch from Julian to Gregorian reckoning until 1752, so for them, the skipped dates were between September 4 and September 14, 1752. Other countries switched at other times, but 1582 and 1752 are the relevant dates for the DBMSs that we're discussing.

Thus, two problems arise with date arithmetic when one goes back many years. The first is, should leap years before the switch be calculated according to the Julian or the Gregorian rules? The second problem is, when and how should the skipped days be handled?

This is how the Big DBMSs handle these questions:

  • Pretend there was no switch. This is what the SQL Standard seems to require, although the standard document is unclear: It just says that dates are "constrained by the natural rules for dates using the Gregorian calendar"—whatever "natural rules" are. This is the option that DB2 chose. When there is a pretence that a single calendar's rules have always applied even to times when nobody heard of the calendar, the technical term is that a "proleptic" calendar is in force. So, for example, we could say that DB2 follows a proleptic Gregorian calendar.
  • Avoid the problem entirely. Microsoft and Sybase set their minimum date values at January 1, 1753, safely past the time that America switched calendars. This is defendable, but from time to time complaints surface that these two DBMSs lack a useful functionality that the other DBMSs have and that the SQL Standard requires.
  • Pick 1582. This is what Oracle did. An Oracle user would find that the date-arithmetic expression October 15 1582 minus October 4 1582 yields a value of 1 day (because October 5–14 don't exist) and that the date February 29 1300 is valid (because the Julian leap-year rule applies). Why did Oracle go to extra trouble when the SQL Standard doesn't seem to require it? The answer is that users might require it. Historians and astronomers use this hybrid system instead of a proleptic Gregorian calendar. (This is also the default option that Sun picked when implementing the GregorianCalendar class for Java—despite the name, GregorianCalendar is a hybrid calendar.)

Source 1 and 2

How do I obtain a list of all schemas in a Sql Server database

SELECT s.name + '.' + ao.name
       , s.name
FROM sys.all_objects ao
INNER JOIN sys.schemas s ON s.schema_id = ao.schema_id
WHERE ao.type='u';

converting list to json format - quick and easy way

You could return the value using return JsonConvert.SerializeObject(objName); And send it to the front end

Unable to install Maven on Windows: "JAVA_HOME is set to an invalid directory"

My situation was a bit different.

  • JAVA_HOME was set properly to point to 1.7
  • Other Maven projects were working/building fine with 1.7 features.
  • PATH was set properly.
  • Everything was up-to-date.

Still my simple new Maven project was not working. What I noticed was the difference in the logs when I ran mvn clean install. For my older Maven projects, it showed

[INFO] --- maven-compiler-plugin:2.3.2:compile (default-compile) @ oldProject---

But for my new project it showed:

[INFO] --- maven-compiler-plugin:2.0.2:compile (default-compile) @ newProject ---

So, I looked at the POM.xml and noticed this thing in the old project's POM:

<build>
    <plugins>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-compiler-plugin</artifactId>
            <version>2.3.2</version>
            <configuration>
                <source>1.7</source>
                <target>1.7</target>
            </configuration>
        </plugin>
    </plugins>
</build>

Basically, this plugin tells which compiler version to use for compilation. Just added it to the new project's POM.xml and things worked.

Hope it is useful to someone.

How to use getJSON, sending data with post method?

The $.getJSON() method does an HTTP GET and not POST. You need to use $.post()

$.post(url, dataToBeSent, function(data, textStatus) {
  //data contains the JSON object
  //textStatus contains the status: success, error, etc
}, "json");

In that call, dataToBeSent could be anything you want, although if are sending the contents of a an html form, you can use the serialize method to create the data for the POST from your form.

var dataToBeSent = $("form").serialize();

Shared-memory objects in multiprocessing

Like Robert Nishihara mentioned, Apache Arrow makes this easy, specifically with the Plasma in-memory object store, which is what Ray is built on.

I made brain-plasma specifically for this reason - fast loading and reloading of big objects in a Flask app. It's a shared-memory object namespace for Apache Arrow-serializable objects, including pickle'd bytestrings generated by pickle.dumps(...).

The key difference with Apache Ray and Plasma is that it keeps track of object IDs for you. Any processes or threads or programs that are running on locally can share the variables' values by calling the name from any Brain object.

$ pip install brain-plasma
$ plasma_store -m 10000000 -s /tmp/plasma

from brain_plasma import Brain
brain = Brain(path='/tmp/plasma/)

brain['a'] = [1]*10000

brain['a']
# >>> [1,1,1,1,...]

Pressed <button> selector

You can do this if you use an <a> tag instead of a button. I know it's not exactly what you asked for, but it might give you some other options if you cannot find a solution to this:

Borrowing from a demo from another answer here I produced this:

_x000D_
_x000D_
a {_x000D_
  display: block;_x000D_
  font-size: 18px;_x000D_
  border: 2px solid gray;_x000D_
  border-radius: 100px;_x000D_
  width: 100px;_x000D_
  height: 100px;_x000D_
  text-align: center;_x000D_
  line-height: 100px;_x000D_
}_x000D_
_x000D_
a:active {_x000D_
  font-size: 18px;_x000D_
  border: 2px solid green;_x000D_
  border-radius: 100px;_x000D_
  width: 100px;_x000D_
  height: 100px;_x000D_
}_x000D_
_x000D_
a:target {_x000D_
  font-size: 18px;_x000D_
  border: 2px solid red;_x000D_
  border-radius: 100px;_x000D_
  width: 100px;_x000D_
  height: 100px;_x000D_
}
_x000D_
<a id="btn" href="#btn">Demo</a>
_x000D_
_x000D_
_x000D_

Notice the use of :target; this will be the style applied when the element is targeted via the hash. Which also means your HTML will need to be this: <a id="btn" href="#btn">Demo</a> a link targeting itself. and the demo http://jsfiddle.net/rlemon/Awdq5/4/

Thanks to @BenjaminGruenbaum here is a better demo: http://jsfiddle.net/agzVt/

Also, as a footnote: this should really be done with JavaScript and applying / removing CSS classes from the element. It would be much less convoluted.

How to get the primary IP address of the local machine on Linux and OS X?

The shortest way to get your local ipv4-address on your linux system:

hostname -I | awk '{print $1}'

Convert categorical data in pandas dataframe

For a certain column, if you don't care about the ordering, use this

df['col1_num'] = df['col1'].apply(lambda x: np.where(df['col1'].unique()==x)[0][0])

If you care about the ordering, specify them as a list and use this

df['col1_num'] = df['col1'].apply(lambda x: ['first', 'second', 'third'].index(x))

Cassandra cqlsh - connection refused

Got into this issue for [cqlsh 5.0.1 | Cassandra 3.11.4 | CQL spec 3.4.4 | Native protocol v4] had to set start_native_transport: true in cassandra.yaml file.

For verification,

  • try opening tailf /var/log/cassandra/system.log file in one-tab
  • update cassandra.yaml
  • restart cassandra sudo service cassandra restart

In logfile is shows.

INFO  [main] 2019-03-15 19:53:06,156 Server.java:156 - Starting listening for CQL clients on /10.139.45.34:9042 (unencrypted)...

How do I create a readable diff of two spreadsheets using git diff?

If you have TortoiseSVN then you can CTRL click the two files to select them in Windows Explorer and then right-click, TortoiseSVN->Diff.

This works particularly well if you are looking for a small change in a large data set.

What is the maximum length of a table name in Oracle?

Oracle database object names maximum length is 30 bytes.

Object Name Rules: http://docs.oracle.com/database/121/SQLRF/sql_elements008.htm

How do I split a string by a multi-character delimiter in C#?

Or use this code; ( same : new String[] )

.Split(new[] { "Test Test" }, StringSplitOptions.None)

'too many values to unpack', iterating over a dict. key=>string, value=>list

Can't be iterating directly in dictionary. So you can through converting into tuple.

first_names = ['foo', 'bar']
last_names = ['gravy', 'snowman']

fields = {
    'first_names': first_names,
    'last_name': last_names,
         } 
tup_field=tuple(fields.items())
for names in fields.items():
     field,possible_values = names
     tup_possible_values=tuple(possible_values)
     for pvalue in tup_possible_values:
           print (field + "is" + pvalue)

Eclipse error, "The selection cannot be launched, and there are no recent launches"

Follow these steps to run your application on the device connected. 1. Change directories to the root of your Android project and execute: ant debug 2. Make sure the Android SDK platform-tools/ directory is included in your PATH environment variable, then execute: adb install bin/<*your app name*>-debug.apk On your device, locate <*your app name*> and open it.

Refer Running App

Error in model.frame.default: variable lengths differ

Its simple, just make sure the data type in your columns are the same. For e.g. I faced the same error, that and an another error:

Error in contrasts<-(*tmp*, value = contr.funs[1 + isOF[nn]]) : contrasts can be applied only to factors with 2 or more levels

So, I went back to my excel file or csv file, set a filter on the variable throwing me an error and checked if the distinct datatypes are the same. And... Oh! it had numbers and strings, so I converted numbers to string and it worked just fine for me.

Using gdb to single-step assembly code outside specified executable causes error "cannot find bounds of current function"

Instead of gdb, run gdbtui. Or run gdb with the -tui switch. Or press C-x C-a after entering gdb. Now you're in GDB's TUI mode.

Enter layout asm to make the upper window display assembly -- this will automatically follow your instruction pointer, although you can also change frames or scroll around while debugging. Press C-x s to enter SingleKey mode, where run continue up down finish etc. are abbreviated to a single key, allowing you to walk through your program very quickly.

   +---------------------------------------------------------------------------+
B+>|0x402670 <main>         push   %r15                                        |
   |0x402672 <main+2>       mov    %edi,%r15d                                  |
   |0x402675 <main+5>       push   %r14                                        |
   |0x402677 <main+7>       push   %r13                                        |
   |0x402679 <main+9>       mov    %rsi,%r13                                   |
   |0x40267c <main+12>      push   %r12                                        |
   |0x40267e <main+14>      push   %rbp                                        |
   |0x40267f <main+15>      push   %rbx                                        |
   |0x402680 <main+16>      sub    $0x438,%rsp                                 |
   |0x402687 <main+23>      mov    (%rsi),%rdi                                 |
   |0x40268a <main+26>      movq   $0x402a10,0x400(%rsp)                       |
   |0x402696 <main+38>      movq   $0x0,0x408(%rsp)                            |
   |0x4026a2 <main+50>      movq   $0x402510,0x410(%rsp)                       |
   +---------------------------------------------------------------------------+
child process 21518 In: main                            Line: ??   PC: 0x402670
(gdb) file /opt/j64-602/bin/jconsole
Reading symbols from /opt/j64-602/bin/jconsole...done.
(no debugging symbols found)...done.
(gdb) layout asm
(gdb) start
(gdb)

Pointers in Python?

>> id(1)
1923344848  # identity of the location in memory where 1 is stored
>> id(1)
1923344848  # always the same
>> a = 1
>> b = a  # or equivalently b = 1, because 1 is immutable
>> id(a)
1923344848
>> id(b)  # equal to id(a)
1923344848

As you can see a and b are just two different names that reference to the same immutable object (int) 1. If later you write a = 2, you reassign the name a to a different object (int) 2, but the b continues referencing to 1:

>> id(2)
1923344880
>> a = 2
>> id(a)
1923344880  # equal to id(2)
>> b
1           # b hasn't changed
>> id(b)
1923344848  # equal to id(1)

What would happen if you had a mutable object instead, such as a list [1]?

>> id([1])
328817608
>> id([1])
328664968  # different from the previous id, because each time a new list is created
>> a = [1]
>> id(a)
328817800
>> id(a)
328817800 # now same as before
>> b = a
>> id(b)
328817800  # same as id(a)

Again, we are referencing to the same object (list) [1] by two different names a and b. However now we can mutate this list while it remains the same object, and a, b will both continue referencing to it

>> a[0] = 2
>> a
[2]
>> b
[2]
>> id(a)
328817800  # same as before
>> id(b)
328817800  # same as before

Is mathematics necessary for programming?

Programming requires you to master, or at least learn, two subjects. Programming itself and what ever domain your program is for. If you are writing accounting software, you need to learn accounting, if you are programming robot kinematics, then you need to understand forward and reverse kinematics. Account might only take basic math skills, other domains take other types of math.

How do I do an initial push to a remote repository with Git?

You can try this:

on Server:

adding new group to /etc/group like (example)

mygroup:1001:michael,nir

create new git repository:

mkdir /srv/git
cd /srv/git
mkdir project_dir
cd project_dir
git --bare init (initial git repository )
chgrp -R mygroup objects/ refs/ (change owner of directory )
chmod -R g+w objects/ refs/ (give permission write)

on Client:

mkdir my_project
cd my_project
touch .gitignore
git init
git add .
git commit -m "Initial commit"
git remote add origin [email protected]:/path/to/my_project.git
git push origin master

(Thanks Josh Lindsey for client side)

after Client, do on Server this commands:

cd /srv/git/project_dir
chmod -R g+w objects/ refs/

If got this error after git pull:

There is no tracking information for the current branch. Please specify which branch you want to merge with. See git-pull(1) for details

git pull <remote> <branch>
If you wish to set tracking information for this branch you can do so with:

git branch --set-upstream new origin/<branch>

try:

git push -u origin master

It will help.

How to open google chrome from terminal?

On Linux, just use this command in a terminal:

google-chrome

Why Does OAuth v2 Have Both Access and Refresh Tokens?

To further simplify B T's answer: Use refresh tokens when you don't typically want the user to have to type in credentials again, but still want the power to be able to revoke the permissions (by revoking the refresh token)

You cannot revoke an access token, only a refresh token.

Liquibase lock - reasons?

The problem was the buggy implementation of SequenceExists in Liquibase. Since the changesets with these statements took a very long time and was accidently aborted. Then the next try executing the liquibase-scripts the lock was held.

  <changeSet author="user" id="123">
    <preConditions onFail="CONTINUE">
      <not><sequenceExists sequenceName="SEQUENCE_NAME_SEQ" /></not>
    </preConditions>
    <createSequence sequenceName="SEQUENCE_NAME_SEQ"/>
  </changeSet>

A work around is using plain SQL to check this instead:

  <changeSet author="user" id="123">
    <preConditions onFail="CONTINUE">
            <sqlCheck expectedResult="0">
              select count(*) from user_sequences where sequence_name = 'SEQUENCE_NAME_SEQ';
            </sqlCheck>
    </preConditions>
    <createSequence sequenceName="SEQUENCE_NAME_SEQ"/>
  </changeSet>

Lockdata is stored in the table DATABASECHANGELOCK. To get rid of the lock you just change 1 to 0 or drop that table and recreate.

DateTimePicker: pick both date and time

Go to the Properties of your dateTimePickerin Visual Studio and set Format to Custom. Under CustomFormat enter your format. In my case I used MMMMdd, yyyy | hh:mm

enter image description here
dateTimePickerProperties

Assign a synthesizable initial value to a reg in Verilog

The other answers are all good. For Xilinx FPGA designs, it is best not to use global reset lines, and use initial blocks for reset conditions for most logic. Here is the white paper from Ken Chapman (Xilinx FPGA guru)

http://japan.xilinx.com/support/documentation/white_papers/wp272.pdf

How to customize the configuration file of the official PostgreSQL Docker image?

Using docker compose you can mount a volume with postgresql.auto.conf. Example:

version: '2'

services:
  db:
    image: postgres:10.9-alpine
    volumes:
      - postgres:/var/lib/postgresql/data:z
      - ./docker/postgres/postgresql.auto.conf:/var/lib/postgresql/data/postgresql.auto.conf
    ports:
      - 5432:5432

Return Max Value of range that is determined by an Index & Match lookup

You don't need an index match formula. You can use this array formula. You have to press CTL + SHIFT + ENTER after you enter the formula.

=MAX(IF((A1:A6=A10)*(B1:B6=B10),C1:F6))

SNAPSHOT

enter image description here

Open button in new window?

<input type="button" onclick="window.open(); return false;" value="click me" />

http://www.javascript-coder.com/window-popup/javascript-window-open.phtml

How to allow only numeric (0-9) in HTML inputbox using jQuery?

This answer was perfect, but we can even make it better and more powerful by combining it with the jQuery.Validation plugin.

By using the number() method, we can develop something like this:

$('.numberOnly').keydown(function (event) { 
  if ((!event.shiftKey && !event.ctrlKey && !event.altKey) && 
    ((event.keyCode >= 48 && event.keyCode <= 57) || (event.keyCode >= 96 && event.keyCode <= 105))) 
  // 0-9 or numpad 0-9, disallow shift, ctrl, and alt 
  { 
    // check textbox value now and tab over if necessary 
  } 
  else if (event.keyCode != 8 && event.keyCode != 13 && event.keyCode != 46 && event.keyCode != 37 
    && event.keyCode != 39 && event.keyCode != 9 && event.keyCode != 109 
    && event.keyCode != 189 && event.keyCode != 110 && event.keyCode != 190) 
  // not backsapce (8), enter (13), del (46), left arrow (37), right arrow (39), tab (9), negetive sign (- : 109, 189), or point (. : 110, 190) 
  { 
    event.preventDefault(); 
  } 
  // else the key should be handled normally 
}); 
// _____________________________________________
jQuery.validator.setDefaults({ 
  debug: true, 
  success: "valid" 
}); 
// _____________________________________________
$(document).ready(function(){ 
  $('#myFormId').validate({ 
    rules: { 
      field: { 
        required: true, 
        number: true 
      } 
    } 
  }); 
}); 

So, any Textbox in the "#myFormId" form, with "numberOnly" class, accept only number including decimal, float, and even negative number. Voila :)

PS: In my case, for some reason I used jQuery.validator.addMethod() instead of .validate():

jQuery.validator.addMethod("numberOnly", function (value, element) { 
var result = !isNaN(value); 
return this.optional(element) || result; 
}, jQuery.format("Please enter a valid number.")); 

(it works fine inside my ASP.NET MVC 3 project + unobtrusive JavaScript validation, hooooooooray!)

How to customize the back button on ActionBar

I had the same issue of Action-bar Home button icon direction,because of miss managing of Icon in Gradle Resource directory icon

like in Arabic Gradle resource directory you put icon in x-hdpi and in English Gradle resource same icon name you put in different density folder like xx-hdpi ,so that in APK there will be two same icon names in different directories,so your device will pick density dependent icon may be RTL or LTR

How can I troubleshoot Python "Could not find platform independent libraries <prefix>"

My pycharm ce had the same error, was easy to fix it, if someone has that error, just uninstall and delete the folder, use ctrl+h if you can't find the folder in your documents, install the software again and should work again.

Remember to save the scratches folder before erasing the pycharm folder.

How to improve performance of ngRepeat over a huge dataset (angular.js)?

Sometimes what happened,you get the data from server (or back-end) in few ms (for example I'm I am assuming it 100ms) but it takes more time to display in our web page (let's say it is taking 900ms to display).

So, What is happening here is 800ms It is taking just to render web page.

What I have done in my web application is, I have used pagination (or you can use infinite scrolling also) to display list of data. Let's say I am showing 50 data/page.

So I will not load render all the data at once,only 50 data I am loading initially which takes only 50ms (I'm assuming here).

so total time here decreased from 900ms to 150ms, once user request next page then display next 50 data and so on.

Hope this will help you to improve the performance. All the best

Compare two files report difference in python

hosts0 = open("C:path\\a.txt","r")
hosts1 = open("C:path\\b.txt","r")

lines1 = hosts0.readlines()

for i,lines2 in enumerate(hosts1):
    if lines2 != lines1[i]:
        print "line ", i, " in hosts1 is different \n"
        print lines2
    else:
        print "same"

The above code is working for me. Can you please indicate what error you are facing?

Update Fragment from ViewPager

In your PagerAdapter override getItemPosition

@Override
public int getItemPosition(Object object) {
// POSITION_NONE makes it possible to reload the PagerAdapter
return POSITION_NONE;
}

After that add viewPager.getAdapter().notifyDataSetChanged(); this code like below

viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
        @Override
        public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

        }

        @Override
        public void onPageSelected(int position) {
            viewPager.getAdapter().notifyDataSetChanged();
        }

        @Override
        public void onPageScrollStateChanged(int state) {

        }
    });

should work.

How do I pick 2 random items from a Python set?

Use the random module: http://docs.python.org/library/random.html

import random
random.sample(set([1, 2, 3, 4, 5, 6]), 2)

This samples the two values without replacement (so the two values are different).

How can I list the contents of a directory in Python?

Below code will list directories and the files within the dir. The other one is os.walk

def print_directory_contents(sPath):
        import os                                       
        for sChild in os.listdir(sPath):                
            sChildPath = os.path.join(sPath,sChild)
            if os.path.isdir(sChildPath):
                print_directory_contents(sChildPath)
            else:
                print(sChildPath)

org.apache.poi.POIXMLException: org.apache.poi.openxml4j.exceptions.InvalidFormatException:

You are trying to access an XLS file. However, you are using XSSFWorkbook and XSSFSheet class objects. These classes are mainly used for XLSX files.

For XLS file: HSSFWorkbook & HSSFSheet
For XLSX file: XSSFSheet & XSSFSheet

So in place of XSSFWorkbook use HSSFWorkbook and in place of XSSFSheet use HSSFSheet.

So your code should look like this after the changes are made:

HSSFWorkbook workbook = new HSSFWorkbook(file);

HSSFSheet sheet = workbook.getSheetAt(0);

Java: How to get input from System.console()

Try this. hope this will help.

    String cls0;
    String cls1;

    Scanner in = new Scanner(System.in);  
    System.out.println("Enter a string");  
    cls0 = in.nextLine();  

    System.out.println("Enter a string");  
    cls1 = in.nextLine(); 

Converting SVG to PNG using C#

You can call the command-line version of inkscape to do this:

http://harriyott.com/2008/05/converting-svg-images-to-png-in-c.aspx

Also there is a C# SVG rendering engine, primarily designed to allow SVG files to be used on the web on codeplex that might suit your needs if that is your problem:

Original Project
http://www.codeplex.com/svg

Fork with fixes and more activity: (added 7/2013)
https://github.com/vvvv/SVG

How can I get the baseurl of site?

The popular GetLeftPart solution is not supported in the PCL version of Uri, unfortunately. GetComponents is, however, so if you need portability, this should do the trick:

uri.GetComponents(
    UriComponents.SchemeAndServer | UriComponents.UserInfo, UriFormat.Unescaped);

javascript set cookie with expire time

Below are code snippets to create and delete a cookie. The cookie is set for 1 day.

// 1 Day = 24 Hrs = 24*60*60 = 86400.
  1. By using max-age:

    • Creating the cookie:

    document.cookie = "cookieName=cookieValue; max-age=86400; path=/;";
    
    • Deleting the cookie:

    document.cookie = "cookieName=; max-age=- (any digit); path=/;";
    
  2. By using expires:

    • Syntax for creating the cookie for one day:

    var expires = (new Date(Date.now()+ 86400*1000)).toUTCString();
    document.cookie = "cookieName=cookieValue; expires=" + expires + 86400) + ";path=/;"
    

Trying to use fetch and pass in mode: no-cors

The simple solution: Add the following to the very top of the php file you are requesting the data from.

header("Access-Control-Allow-Origin: *");

iterating through json object javascript

You use a for..in loop for this. Be sure to check if the object owns the properties or all inherited properties are shown as well. An example is like this:

var obj = {a: 1, b: 2};
for (var key in obj) {
  if (obj.hasOwnProperty(key)) {
    var val = obj[key];
    console.log(val);
  }
}

Or if you need recursion to walk through all the properties:

var obj = {a: 1, b: 2, c: {a: 1, b: 2}};
function walk(obj) {
  for (var key in obj) {
    if (obj.hasOwnProperty(key)) {
      var val = obj[key];
      console.log(val);
      walk(val);
    }
  }
}
walk(obj);

How can I make XSLT work in chrome?

I had the same problem on localhost. Running around the Internet looking for the answer and I approve that adding --allow-file-access-from-files works. I work on Mac, so for me I had to go through terminal sudo /Applications/Google\ Chrome.app/Contents/MacOS/Google\ Chrome --allow-file-access-from-files and enter your password (if you have one).

Another small thing - nothing will work unless you add to your .xml file the reference to your .xsl file as follows <?xml-stylesheet type="text/xsl" href="<path to file>"?>. Another small thing I didn't realise immediately - you should be opening your .xml file in browser, no the .xsl.

How to create and write to a txt file using VBA

Use FSO to create the file and write to it.

Dim fso as Object
Set fso = CreateObject("Scripting.FileSystemObject")
Dim oFile as Object
Set oFile = FSO.CreateTextFile(strPath)
oFile.WriteLine "test" 
oFile.Close
Set fso = Nothing
Set oFile = Nothing    

See the documentation here:

Log4Net configuring log level

Yes. It is done with a filter on the appender.

Here is the appender configuration I normally use, limited to only INFO level.

<appender name="RollingFileAppender" type="log4net.Appender.RollingFileAppender">
  <file value="${HOMEDRIVE}\\PI.Logging\\PI.ECSignage.${COMPUTERNAME}.log" />
  <appendToFile value="true" />
  <maxSizeRollBackups value="30" />
  <maximumFileSize value="5MB" />
  <rollingStyle value="Size" />     <!--A maximum number of backup files when rolling on date/time boundaries is not supported. -->
  <staticLogFileName value="false" />
  <lockingModel type="log4net.Appender.FileAppender+MinimalLock" />
  <layout type="log4net.Layout.PatternLayout">
        <param name="ConversionPattern" value="%date{yyyy-MM-dd HH:mm:ss.ffff} [%2thread] %-5level %20.20type{1}.%-25method at %-4line| (%-30.30logger) %message%newline" />
  </layout>

  <filter type="log4net.Filter.LevelRangeFilter">
        <levelMin value="INFO" />
        <levelMax value="INFO" />
  </filter>
</appender>    

No grammar constraints (DTD or XML schema) detected for the document

I too had the same problem in eclipse using web.xml file
it showed me this " no grammar constraints referenced in the document "

but it can be resolved by adding tag
after the xml tag i.e. <?xml version = "1.0" encoding = "UTF-8"?>

Authorize attribute in ASP.NET MVC

Using [Authorize] attributes can help prevent security holes in your application. The way that MVC handles URL's (i.e. routing them to a controller rather than to an actual file) makes it difficult to actually secure everything via the web.config file.

Read more here: http://blogs.msdn.com/b/rickandy/archive/2012/03/23/securing-your-asp-net-mvc-4-app-and-the-new-allowanonymous-attribute.aspx (via archive.org)

Spring 3 MVC resources and tag <mvc:resources />

@Nanocom's answer works for me. It may be that lines have to be at the end, or could be because has to be after of some the bean class like this:

<bean class="org.springframework.web.servlet.mvc.support.ControllerClassNameHandlerMapping" />
<bean class="org.springframework.web.servlet.resource.ResourceHttpRequestHandler" />    

<mvc:resources mapping="/resources/**" 
               location="/resources/" 
               cache-period="10000" />

Sending an HTTP POST request on iOS

Objective C

Post API with parameters and validate with url to navigate if json
response key with status:"success"

NSString *string= [NSString stringWithFormat:@"url?uname=%@&pass=%@&uname_submit=Login",self.txtUsername.text,self.txtPassword.text];
    NSLog(@"%@",string);
    NSURL *url = [NSURL URLWithString:string];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    [request setHTTPMethod:@"POST"];
    NSURLResponse *response;
    NSError *err;
    NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&err];
    NSLog(@"responseData: %@", responseData);
    NSString *str = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
    NSLog(@"responseData: %@", str);
        NSDictionary* json = [NSJSONSerialization JSONObjectWithData:responseData
                                                         options:kNilOptions
                                                           error:nil];
    NSDictionary* latestLoans = [json objectForKey:@"status"];
    NSString *str2=[NSString stringWithFormat:@"%@", latestLoans];
    NSString *str3=@"success";
    if ([str3 isEqualToString:str2 ])
    {
        [self performSegueWithIdentifier:@"move" sender:nil];
        NSLog(@"successfully.");
    }
    else
    {
        UIAlertController *alert= [UIAlertController
                                 alertControllerWithTitle:@"Try Again"
                                 message:@"Username or Password is Incorrect."
                                 preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction* ok = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleDefault
                                                   handler:^(UIAlertAction * action){
                                                       [self.view endEditing:YES];
                                                   }
                             ];
        [alert addAction:ok];
        [[UIView appearanceWhenContainedIn:[UIAlertController class], nil] setTintColor:[UIColor redColor]];
        [self presentViewController:alert animated:YES completion:nil];
        [self.view endEditing:YES];
      }

JSON Response : {"status":"success","user_id":"58","user_name":"dilip","result":"You have been logged in successfully"} Working code

**

Android ADB device offline, can't issue commands

None of these answers worked for me, tried Wireless too. I noticed adb.exe was constantly running in my system processes. Right clicked on them and found adb was running automatically from an installed app (Droid Explorer in my case). Once I uninstalled the app that was automatically starting ADB, i could kill the process and see that adb was no longer running on it's own. Ran the updated adb from platform-tools and good to go! Hope this helps someone.

Hide Spinner in Input Number - Firefox 29

In SASS/SCSS style, you can write like this:

input[type='number'] {
  -moz-appearance: textfield;/*For FireFox*/

  &::-webkit-inner-spin-button { /*For Webkits like Chrome and Safari*/
    -webkit-appearance: none;
    margin: 0;
  }
}

Definitely this code style can use in PostCSS.

How to pass values between Fragments

I´ve made something really easy for begginers like me. I made a textview in my activity_main.xml and put

id=index
visibility=invisible

then I get this textview from the first fragment

index= (Textview) getActivity().findviewbyid(R.id.index)
index.setText("fill me with the value")

and then in the second fragment I get the value

index= (Textview) getActivity().findviewbyid(R.id.index)
String get_the_value= index.getText().toString();

Getting the document object of an iframe

In my case, it was due to Same Origin policies. To explain it further, MDN states the following:

If the iframe and the iframe's parent document are Same Origin, returns a Document (that is, the active document in the inline frame's nested browsing context), else returns null.

var functionName = function() {} vs function functionName() {}

About performance:

New versions of V8 introduced several under-the-hood optimizations and so did SpiderMonkey.

There is almost no difference now between expression and declaration.
Function expression appears to be faster now.

Chrome 62.0.3202 Chrome test

FireFox 55 Firefox test

Chrome Canary 63.0.3225 Chrome Canary test


Anonymous function expressions appear to have better performance against Named function expression.


Firefox Firefox named_anonymous Chrome Canary Chrome canary named_anonymous Chrome Chrome named_anonymous

Switching a DIV background image with jQuery

Mine is animated:

$(this).animate({
    opacity: 0
}, 100, function() {
    // Callback
    $(this).css("background-image", "url(" + new_img + ")").promise().done(function(){
        // Callback of the callback :)
        $(this).animate({
            opacity: 1
        }, 600)
    });    
});

Changing project port number in Visual Studio 2013

There are two project types in VS for ASP.NET projects:

Web Application Projects (which notably have a .csproj or .vbproj file to store these settings) have a Properties node under the project. On the Web tab, you can configure the Project URL (assuming IIS Express or IIS) to use whatever port you want, and just click the Create Virtual Directory button. These settings are saved to the project file:

<ProjectExtensions>
  <VisualStudio>
    <FlavorProperties GUID="{349c5851-65df-11da-9384-00065b846f21}">
      <WebProjectProperties>
       <DevelopmentServerPort>10531</DevelopmentServerPort>
       ...
     </WebProjectProperties>
    </FlavorProperties>
  </VisualStudio>
</ProjectExtensions>

Web Site Projects are different. They don't have a .*proj file to store settings in; instead, the settings are set in the solution file. In VS2013, the settings look something like this:

Project("{E24C65DC-7377-472B-9ABA-BC803B73C61A}") = "WebSite1(1)", "http://localhost:10528", "{401397AC-86F6-4661-A71B-67B4F8A3A92F}"
    ProjectSection(WebsiteProperties) = preProject
        UseIISExpress = "true"
        TargetFrameworkMoniker = ".NETFramework,Version%3Dv4.5"
        ...
        SlnRelativePath = "..\..\WebSites\WebSite1\"
        DefaultWebSiteLanguage = "Visual Basic"
    EndProjectSection
EndProject

Because the project is identified by the URL (including port), there isn't a way in the VS UI to change this. You should be able to modify the solution file though, and it should work.

how to set default culture info for entire c# application

Not for entire application or particular class.

CurrentUICulture and CurrentCulture are settable per thread as discussed here Is there a way of setting culture for a whole application? All current threads and new threads?. You can't change InvariantCulture at all.

Sample code to change cultures for current thread:

CultureInfo ci = new CultureInfo(theCultureString);
Thread.CurrentThread.CurrentCulture = ci;
Thread.CurrentThread.CurrentUICulture = ci;

For class you can set/restore culture inside critical methods, but it would be significantly safe to use appropriate overrides for most formatting related methods that take culture as one of arguments:

(3.3).ToString(new CultureInfo("fr-FR"))

Resize external website content to fit iFrame width

Tip for 1 website resizing the height. But you can change to 2 websites.

Here is my code to resize an iframe with an external website. You need insert a code into the parent (with iframe code) page and in the external website as well, so, this won't work with you don't have access to edit the external website.

  • local (iframe) page: just insert a code snippet
  • remote (external) page: you need a "body onload" and a "div" that holds all contents. And body needs to be styled to "margin:0"

Local:

<IFRAME STYLE="width:100%;height:1px" SRC="http://www.remote-site.com/" FRAMEBORDER="no" BORDER="0" SCROLLING="no" ID="estframe"></IFRAME>

<SCRIPT>
var eventMethod = window.addEventListener ? "addEventListener" : "attachEvent";
var eventer = window[eventMethod];
var messageEvent = eventMethod == "attachEvent" ? "onmessage" : "message";
eventer(messageEvent,function(e) {
  if (e.data.substring(0,3)=='frm') document.getElementById('estframe').style.height = e.data.substring(3) + 'px';
},false);
</SCRIPT>

You need this "frm" prefix to avoid problems with other embeded codes like Twitter or Facebook plugins. If you have a plain page, you can remove the "if" and the "frm" prefix on both pages (script and onload).

Remote:

You need jQuery to accomplish about "real" page height. I cannot realize how to do with pure JavaScript since you'll have problem when resize the height down (higher to lower height) using body.scrollHeight or related. For some reason, it will return always the biggest height (pre-redimensioned).

<BODY onload="parent.postMessage('frm'+$('#master').height(),'*')" STYLE="margin:0">
<SCRIPT SRC="path-to-jquery/jquery.min.js"></SCRIPT>
<DIV ID="master">
your content
</DIV>

So, parent page (iframe) has a 1px default height. The script inserts a "wait for message/event" from the iframe. When a message (post message) is received and the first 3 chars are "frm" (to avoid the mentioned problem), will get the number from 4th position and set the iframe height (style), including 'px' unit.

The external site (loaded in the iframe) will "send a message" to the parent (opener) with the "frm" and the height of the main div (in this case id "master"). The "*" in postmessage means "any source".

Hope this helps. Sorry for my english.

How to "properly" print a list?

Here's an interactive session showing some of the steps in @TokenMacGuy's one-liner. First he uses the map function to convert each item in the list to a string (actually, he's making a new list, not converting the items in the old list). Then he's using the string method join to combine those strings with ', ' between them. The rest is just string formatting, which is pretty straightforward. (Edit: this instance is straightforward; string formatting in general can be somewhat complex.)

Note that using join is a simple and efficient way to build up a string from several substrings, much more efficient than doing it by successively adding strings to strings, which involves a lot of copying behind the scenes.

>>> mylist = ['x', 3, 'b']
>>> m = map(str, mylist)
>>> m
['x', '3', 'b']
>>> j = ', '.join(m)
>>> j
'x, 3, b'

How to style HTML5 range input to have different color before and after slider?

Yes, it is possible. Though I wouldn't recommend it because input range is not really supported properly by all browsers because is an new element added in HTML5 and HTML5 is only a draft (and will be for long) so going as far as to styling it is perhaps not the best choice.

Also, you'll need a bit of JavaScript too. I took the liberty of using jQuery library for this, for simplicity purposes.

Here you go: http://jsfiddle.net/JnrvG/1/.

How to disable Compatibility View in IE

The answer given by FelixFett worked for me. To reiterate:

<meta http-equiv="X-UA-Compatible" content="IE=11; IE=10; IE=9; IE=8; IE=7; IE=EDGE" />

I have it as the first 'meta' tag in my code. I added 10 and 11 as those are versions that are published now for Internet Explorer.

I would've just commented on his answer but I do not have a high enough reputation...

Can't connect to local MySQL server through socket '/tmp/mysql.sock' (2)

I hope this helps somebody. I was getting the same error, but seemingly for a much different reason than other people.

I have 2 CentOS machines.

I copied my.cnf to the new machine, not realizing that I had upgraded the old machine to MySQL 5.6, and the new machine had 5.5 installed. When I commented out the 5.6-only directives, MySQL started as expected. (and now I am running the upgrade so I can apply the massively useful innodb_buffer_pool_dump_at_shutdown and innodb_buffer_pool_load_at_startup directives)

I would suggest trying a bare minimum my.cnf. If MySQL starts up, then you've found the source of your problem.

Base64: java.lang.IllegalArgumentException: Illegal character

I encountered this error since my encoded image started with data:image/png;base64,iVBORw0....

This answer led me to the solution:

String partSeparator = ",";
if (data.contains(partSeparator)) {
  String encodedImg = data.split(partSeparator)[1];
  byte[] decodedImg = Base64.getDecoder().decode(encodedImg.getBytes(StandardCharsets.UTF_8));
  Path destinationFile = Paths.get("/path/to/imageDir", "myImage.jpg");
  Files.write(destinationFile, decodedImg);
}

getColor(int id) deprecated on Android 6.0 Marshmallow (API 23)

For all the Kotlin users out there:

context?.let {
    val color = ContextCompat.getColor(it, R.color.colorPrimary)
    // ...
}

Redirect on Ajax Jquery Call

For ExpressJs router:

router.post('/login', async(req, res) => {
    return res.send({redirect: '/yoururl'});
})

Client-side:

    success: function (response) {
        if (response.redirect) {
            window.location = response.redirect
        }
    },

What is float in Java?

In JAVA, values like:

  1. 8.5
  2. 3.9
  3. (and so on..)

Is assumed as double and not float.

You can also perform a cast in order to solve the problem:

float b = (float) 3.5;

Another solution:

float b = 3.5f;

How can I get a list of users from active directory?

Include the System.DirectoryServices.dll, then use the code below:

DirectoryEntry directoryEntry = new DirectoryEntry("WinNT://" + Environment.MachineName);
string userNames="Users: ";

foreach (DirectoryEntry child in directoryEntry.Children)
{
    if (child.SchemaClassName == "User")
    {
        userNames += child.Name + Environment.NewLine   ;         
    }

}
MessageBox.Show(userNames);

Set custom attribute using JavaScript

Please use dataset

var article = document.querySelector('#electriccars'),
    data = article.dataset;

// data.columns -> "3"
// data.indexnumber -> "12314"
// data.parent -> "cars"

so in your case for setting data:

getElementById('item1').dataset.icon = "base2.gif";

What is the printf format specifier for bool?

I prefer an answer from Best way to print the result of a bool as 'false' or 'true' in c?, just like

printf("%s\n", "false\0true"+6*x);
  • x == 0, "false\0true"+ 0" it means "false";
  • x == 1, "false\0true"+ 6" it means "true";

How correctly produce JSON by RESTful web service?

You could use a package like org.json http://www.json.org/java/

Because you will need to use JSONObjects more often.

There you can easily create JSONObjects and put some values in it:

 JSONObject json = new JSONObject();
 JSONArray array=new JSONArray();
    array.put("1");
    array.put("2");
    json.put("friends", array);

    System.out.println(json.toString(2));


    {"friends": [
      "1",
      "2"
    ]}

edit This has the advantage that you can build your responses in different layers and return them as an object

Seeing the console's output in Visual Studio 2010?

System.Diagnostics.Debug.WriteLine() will work, but you have to be looking in the right place for the output. In Visual Studio 2010, on the menu bar, click Debug -> Windows -> Output. Now, at the bottom of the screen docked next to your error list, there should be an output tab. Click it and double check it's showing output from the debug stream on the dropdown list.

P.S.: I think the output window shows on a fresh install, but I can't remember. If it doesn't, or if you closed it by accident, follow these instructions.

What and When to use Tuple?

Tuple classes allow developers to be 'quick and lazy' by not defining a specific class for a specific use.

The property names are Item1, Item2, Item3 ..., which may not be meaningful in some cases or without documentation.

Tuple classes have strongly typed generic parameters. Still users of the Tuple classes may infer from the type of generic parameters.

Using Excel VBA to export data to MS Access table

@Ahmed

Below is code that specifies fields from a named range for insertion into MS Access. The nice thing about this code is that you can name your fields in Excel whatever the hell you want (If you use * then the fields have to match exactly between Excel and Access) as you can see I have named an Excel column "Haha" even though the Access column is called "dte".

Sub test()
    dbWb = Application.ActiveWorkbook.FullName
    dsh = "[" & Application.ActiveSheet.Name & "$]" & "Data2"  'Data2 is a named range


sdbpath = "C:\Users\myname\Desktop\Database2.mdb"
sCommand = "INSERT INTO [main] ([dte], [test1], [values], [values2]) SELECT [haha],[test1],[values],[values2] FROM [Excel 8.0;HDR=YES;DATABASE=" & dbWb & "]." & dsh

Dim dbCon As New ADODB.Connection
Dim dbCommand As New ADODB.Command

dbCon.Open "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & sdbpath & "; Jet OLEDB:Database Password=;"
dbCommand.ActiveConnection = dbCon

dbCommand.CommandText = sCommand
dbCommand.Execute

dbCon.Close


End Sub

How do I use the Simple HTTP client in Android?

public static void connect(String url)
{

    HttpClient httpclient = new DefaultHttpClient();

    // Prepare a request object
    HttpGet httpget = new HttpGet(url); 

    // Execute the request
    HttpResponse response;
    try {
        response = httpclient.execute(httpget);
        // Examine the response status
        Log.i("Praeda",response.getStatusLine().toString());

        // Get hold of the response entity
        HttpEntity entity = response.getEntity();
        // If the response does not enclose an entity, there is no need
        // to worry about connection release

        if (entity != null) {

            // A Simple JSON Response Read
            InputStream instream = entity.getContent();
            String result= convertStreamToString(instream);
            // now you have the string representation of the HTML request
            instream.close();
        }


    } catch (Exception e) {}
}

    private static String convertStreamToString(InputStream is) {
    /*
     * To convert the InputStream to String we use the BufferedReader.readLine()
     * method. We iterate until the BufferedReader return null which means
     * there's no more data to read. Each line will appended to a StringBuilder
     * and returned as String.
     */
    BufferedReader reader = new BufferedReader(new InputStreamReader(is));
    StringBuilder sb = new StringBuilder();

    String line = null;
    try {
        while ((line = reader.readLine()) != null) {
            sb.append(line + "\n");
        }
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        try {
            is.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    return sb.toString();
}

C# Lambda expressions: Why should I use them?

Microsoft has given us a cleaner, more convenient way of creating anonymous delegates called Lambda expressions. However, there is not a lot of attention being paid to the expressions portion of this statement. Microsoft released a entire namespace, System.Linq.Expressions, which contains classes to create expression trees based on lambda expressions. Expression trees are made up of objects that represent logic. For example, x = y + z is an expression that might be part of an expression tree in .Net. Consider the following (simple) example:

using System;
using System.Linq;
using System.Linq.Expressions;


namespace ExpressionTreeThingy
{
    class Program
    {
        static void Main(string[] args)
        {
            Expression<Func<int, int>> expr = (x) => x + 1; //this is not a delegate, but an object
            var del = expr.Compile(); //compiles the object to a CLR delegate, at runtime
            Console.WriteLine(del(5)); //we are just invoking a delegate at this point
            Console.ReadKey();
        }
    }
}

This example is trivial. And I am sure you are thinking, "This is useless as I could have directly created the delegate instead of creating an expression and compiling it at runtime". And you would be right. But this provides the foundation for expression trees. There are a number of expressions available in the Expressions namespaces, and you can build your own. I think you can see that this might be useful when you don't know exactly what the algorithm should be at design or compile time. I saw an example somewhere for using this to write a scientific calculator. You could also use it for Bayesian systems, or for genetic programming (AI). A few times in my career I have had to write Excel-like functionality that allowed users to enter simple expressions (addition, subtrations, etc) to operate on available data. In pre-.Net 3.5 I have had to resort to some scripting language external to C#, or had to use the code-emitting functionality in reflection to create .Net code on the fly. Now I would use expression trees.

Facebook OAuth "The domain of this URL isn't included in the app's domain"

This worked for me:

Here's the main thing to understand: Facebook will always check for the "WWW" domain. So make sure www.your_domain.dev is working on your browser first.

It is possible that if you have multiple virtual hosts on your local server, some other virtual host overrides "www.your_domain.dev". So please check that. Apache will pick the FIRST definition of domain (or ports, or something in these terms - I'm no expert on this, but learned by mistakes). An easy quick fix for this virtual host overriding is to put "www.your_domain.dev virtual host definition on the very top of the file "httpd-vhosts.conf".

Go to "/apache/conf/https-vhosts.conf" and put this on the very top of the file:

<VirtualHost *:80>
<Directory "C:/your_app_folder_path/">
    Options FollowSymLinks Indexes
    AllowOverride All
    Order deny,allow
    allow from All
</Directory>
ServerName your_domain.dev
ServerAlias your_domain.dev
DocumentRoot "C:/your_app_folder_path/"
</VirtualHost>

###### FOR SSL #####
<VirtualHost *:443>
    DocumentRoot "C:/your_app_folder_path/"
    ServerName your_domain.dev
    ServerAlias www.your_domain.dev
    SSLEngine on
    SSLCertificateFile "conf/ssl.crt/server.crt"
    SSLCertificateKeyFile "conf/ssl.key/server.key"
    <Directory "C:/your_app_folder_path/">
        Options All
        AllowOverride All
        Require all granted 
    </Directory>
</VirtualHost>

Next: If you are using Windows system, edit your "hosts" file in "C:\Windows\System32\drivers\etc" by adding two lines:

127.0.0.1 your_domain.dev
127.0.0.1 www.your_domain.dev

Next: Restart your Apache server and everything should work now.


I hope this will help you and save your time. I wasted almost a whole day searching around the web and was pulling my hair out and couldn't find anything helpful until I found this.

Passing arguments to require (when loading module)

Based on your comments in this answer, I do what you're trying to do like this:

module.exports = function (app, db) {
    var module = {};

    module.auth = function (req, res) {
        // This will be available 'outside'.
        // Authy stuff that can be used outside...
    };

    // Other stuff...
    module.pickle = function(cucumber, herbs, vinegar) {
        // This will be available 'outside'.
        // Pickling stuff...
    };

    function jarThemPickles(pickle, jar) {
        // This will be NOT available 'outside'.
        // Pickling stuff...

        return pickleJar;
    };

    return module;
};

I structure pretty much all my modules like that. Seems to work well for me.

How to access your website through LAN in ASP.NET

You may also need to enable the World Wide Web Service inbound firewall rule.

On Windows 7: Start -> Control Panel -> Windows Firewall -> Advanced Settings -> Inbound Rules

Find World Wide Web Services (HTTP Traffic-In) in the list and select to enable the rule. Change is pretty much immediate.

how get yesterday and tomorrow datetime in c#

Beware of adding an unwanted timezone to your results, especially if the date is going to be sent out via a Web API. Use UtcNow instead, to make it timezone-less.

ASP.NET / C#: DropDownList SelectedIndexChanged in server control not firing

First, I would like to clarify something. Is this a post back (trip back to server) never occur, or is it the post back occurs, but it never gets into the ddlCountry_SelectedIndexChanged event handler?

I am not sure which case you are having, but if it is the second case, I can offer some suggestion. If it is the first case, then the following is FYI.

For the second case (event handler never fires even though request made), you may want to try the following suggestions:

  1. Query the Request.Params[ddlCountries.UniqueID] and see if it has value. If it has, manually fire the event handler.
  2. As long as view state is on, only bind the list data when it is not a post back.
  3. If view state has to be off, then put the list data bind in OnInit instead of OnLoad.

Beware that when calling Control.DataBind(), view state and post back information would no longer be available from the control. In the case of view state is on, between post back, values of the DropDownList would be kept intact (the list does not to be rebound). If you issue another DataBind in OnLoad, it would clear out its view state data, and the SelectedIndexChanged event would never be fired.

In the case of view state is turned off, you have no choice but to rebind the list every time. When a post back occurs, there are internal ASP.NET calls to populate the value from Request.Params to the appropriate controls, and I suspect happen at the time between OnInit and OnLoad. In this case, restoring the list values in OnInit will enable the system to fire events correctly.

Thanks for your time reading this, and welcome everyone to correct if I am wrong.

Find Java classes implementing an interface

If you were asking from the perspective of working this out with a running program then you need to look to the java.lang.* package. If you get a Class object, you can use the isAssignableFrom method to check if it is an interface of another Class.

There isn't a simple built in way of searching for these, tools like Eclipse build an index of this information.

If you don't have a specific list of Class objects to test you can look to the ClassLoader object, use the getPackages() method and build your own package hierarchy iterator.

Just a warning though that these methods and classes can be quite slow.

How do I print an IFrame from javascript in Safari/Chrome

One thing to note is if you are testing this locally using file:///, it will not work on chrome as the function in the iframe will appear as undefined. However once on a web server it will work.

React JS Error: is not defined react/jsx-no-undef

its very similar with nodejs

var User= require('./Users');

in this case its React:

import User from './User'

right now you can use

return (
      <Users></Users>
    )

Single-threaded apartment - cannot instantiate ActiveX control

Go ahead and add [STAThread] to the main entry of your application, this indicates the COM threading model is single-threaded apartment (STA)

example:

static class Program
{
    /// <summary>
    /// The main entry point for the application.
    /// </summary>
    [STAThread]
    static void Main()
    {
        Application.EnableVisualStyles();
        Application.SetCompatibleTextRenderingDefault(false);
        Application.Run(new WebBrowser());
    }
}

How to change package name of Android Project in Eclipse?

Just get Far Manager and search through for the old name. Then manually (in Far Manager) replace everywhere. Sadly, this is the only method that works in 100% of the possible cases.

Color picker utility (color pipette) in Ubuntu

I recommend GPick:

sudo apt-get install gpick

Applications -> Graphics -> GPick

It has many more features than gcolor2 but is still extremely simple to use: click on one of the hex swatches, move your mouse around the screen over the colours you want to pick, then press the Space bar to add to your swatch list.

If that doesn't work, another way is to click-and-drag from the centre of the hexagon and release your mouse over the pixel that you want to sample. Then immediately hit Space to copy that color into the next swatch in rotation.

It also has a traditional colour picker (like gcolor2) in the bottom right-hand corner of the window to allow you to pick individual colours with magnification.

How can I exclude one word with grep?

Invert match using grep -v:

grep -v "unwanted word" file pattern

byte array to pdf

You shouldn't be using the BinaryFormatter for this - that's for serializing .Net types to a binary file so they can be read back again as .Net types.

If it's stored in the database, hopefully, as a varbinary - then all you need to do is get the byte array from that (that will depend on your data access technology - EF and Linq to Sql, for example, will create a mapping that makes it trivial to get a byte array) and then write it to the file as you do in your last line of code.

With any luck - I'm hoping that fileContent here is the byte array? In which case you can just do

System.IO.File.WriteAllBytes("hello.pdf", fileContent);

How to truncate milliseconds off of a .NET DateTime

2 Extension methods for the solutions mentioned above

    public static bool LiesAfterIgnoringMilliseconds(this DateTime theDate, DateTime compareDate, DateTimeKind kind)
    {
        DateTime thisDate = new DateTime(theDate.Year, theDate.Month, theDate.Day, theDate.Hour, theDate.Minute, theDate.Second, kind);
        compareDate = new DateTime(compareDate.Year, compareDate.Month, compareDate.Day, compareDate.Hour, compareDate.Minute, compareDate.Second, kind);

        return thisDate > compareDate;
    }


    public static bool LiesAfterOrEqualsIgnoringMilliseconds(this DateTime theDate, DateTime compareDate, DateTimeKind kind)
    {
        DateTime thisDate = new DateTime(theDate.Year, theDate.Month, theDate.Day, theDate.Hour, theDate.Minute, theDate.Second, kind);
        compareDate = new DateTime(compareDate.Year, compareDate.Month, compareDate.Day, compareDate.Hour, compareDate.Minute, compareDate.Second, kind);

        return thisDate >= compareDate;
    }

usage:

bool liesAfter = myObject.DateProperty.LiesAfterOrEqualsIgnoringMilliseconds(startDateTime, DateTimeKind.Utc);

How to Solve Max Connection Pool Error

Here's what u can also try....

run your application....while it is still running launch your command prompt

while your application is running type netstat -n on the command prompt. You should see a list of TCP/IP connections. Check if your list is not very long. Ideally you should have less than 5 connections in the list. Check the status of the connections.
If you have too many connections with a TIME_WAIT status it means the connection has been closed and is waiting for the OS to release the resources. If you are running on Windows, the default ephemeral port rang is between 1024 and 5000 and the default time it takes Windows to release the resource from TIME_WAIT status is 4 minutes. So if your application used more then 3976 connections in less then 4 minutes, you will get the exception you got.

Suggestions to fix it:

  1. Add a connection pool to your connection string.

If you continue to receive the same error message (which is highly unlikely) you can then try the following: (Please don't do it if you are not familiar with the Windows registry)

  1. Run regedit from your run command. In the registry editor look for this registry key: HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\Tcpip\Parameters:

Modify the settings so they read:

MaxUserPort = dword:00004e20 (10,000 decimal) TcpTimedWaitDelay = dword:0000001e (30 decimal)

This will increase the number of ports to 10,000 and reduce the time to release freed tcp/ip connections.

Only use suggestion 2 if 1 fails.

Thank you.

How to create file execute mode permissions in Git on Windows?

I have no touch and chmod command in my cmd.exe and git update-index --chmod=+x foo.sh doesn't work for me.

I finally resolve it by setting skip-worktree bit:

git update-index --skip-worktree --chmod=+x foo.sh

Check if a number has a decimal place/is a whole number

Function for check number is Decimal or whole number

function IsDecimalExist(p_decimalNumber) {
    var l_boolIsExist = true;

    if (p_decimalNumber % 1 == 0)
        l_boolIsExist = false;

    return l_boolIsExist;
}

Setting up a JavaScript variable from Spring model by using Thymeleaf

var message =/*[[${message}]]*/ 'defaultanyvalue';