Programs & Examples On #Urlrewriting.net

UrlRewritingNet.UrlRewrite is an Open Source Component for easy and reliable rewriting URLs with ASP.NET

How to find pg_config path

You can find the pg_config directory using its namesake:

$ pg_config --bindir
/usr/lib/postgresql/9.1/bin
$ 

Tested on Mac and Debian. The only wrinkle is that I can't see how to find the bindir for different versions of postgres installed on the same machine. It's fairly easy to guess though! :-)

Note: I updated my pg_config to 9.5 on Debian with:

sudo apt-get install postgresql-server-dev-9.5

Preprocessor check if multiple defines are not defined

FWIW, @SergeyL's answer is great, but here is a slight variant for testing. Note the change in logical or to logical and.

main.c has a main wrapper like this:

#if !defined(TEST_SPI) && !defined(TEST_SERIAL) && !defined(TEST_USB)
int main(int argc, char *argv[]) {
  // the true main() routine.
}

spi.c, serial.c and usb.c have main wrappers for their respective test code like this:

#ifdef TEST_USB
int main(int argc, char *argv[]) {
  // the  main() routine for testing the usb code.
}

config.h Which is included by all the c files has an entry like this:

// Uncomment below to test the serial
//#define TEST_SERIAL


// Uncomment below to test the spi code
//#define TEST_SPI

// Uncomment below to test the usb code
#define TEST_USB

JavaScript: Get image dimensions

naturalWidth and naturalHeight

var img = document.createElement("img");
img.onload = function (event)
{
    console.log("natural:", img.naturalWidth, img.naturalHeight);
    console.log("width,height:", img.width, img.height);
    console.log("offsetW,offsetH:", img.offsetWidth, img.offsetHeight);
}
img.src = "image.jpg";
document.body.appendChild(img);

// css for tests
img { width:50%;height:50%; }

Using Gradle to build a jar with dependencies

The answer by @felix almost brought me there. I had two issues:

  1. With Gradle 1.5, the manifest tag was not recognised inside the fatJar task, so the Main-Class attribute could not directly be set
  2. the jar had conflicting external META-INF files.

The following setup resolves this

jar {
  manifest {
    attributes(
      'Main-Class': 'my.project.main',
    )
  }
}

task fatJar(type: Jar) {
  manifest.from jar.manifest
  classifier = 'all'
  from {
    configurations.runtimeClasspath.collect { it.isDirectory() ? it : zipTree(it) }
  } {
    exclude "META-INF/*.SF"
    exclude "META-INF/*.DSA"
    exclude "META-INF/*.RSA"
  }
  with jar
}

To add this to the standard assemble or build task, add:

artifacts {
    archives fatJar
}

Edit: thanks to @mjaggard: in recent versions of Gradle, change configurations.runtime to configurations.runtimeClasspath

C# Java HashMap equivalent

From C# equivalent to Java HashMap

I needed a Dictionary which accepted a "null" key, but there seems to be no native one, so I have written my own. It's very simple, actually. I inherited from Dictionary, added a private field to hold the value for the "null" key, then overwritten the indexer. It goes like this :

public class NullableDictionnary : Dictionary<string, string>
{
    string null_value;

    public StringDictionary this[string key]
    {
        get
        {
            if (key == null) 
            {
                return null_value;
            }
            return base[key];
        }
        set
        {
            if (key == null)
            {
                null_value = value;
            }
            else 
            {
                base[key] = value;
            }
        }
    }
}

Hope this helps someone in the future.

==========

I modified it to this format

public class NullableDictionnary : Dictionary<string, object>

Add all files to a commit except a single file?

Try this:

git checkout -- main/dontcheckmein.txt

Uncaught TypeError: Cannot read property 'split' of undefined

ogdate is itself a string, why are you trying to access it's value property that it doesn't have ?

console.log(og_date.split('-'));

JSFiddle

How to allow http content within an iframe on a https site

You will always get warnings of blocked content in most browsers when trying to display non secure content on an https page. This is tricky if you want to embed stuff from other sites that aren't behind ssl. You can turn off the warnings or remove the blocking in your own browser but for other visitors it's a problem.

One way to do it is to load the content server side and save the images and other things to your server and display them from https.

You can also try using a service like embed.ly and get the content through them. They have support for getting the content behind https.

Wampserver icon not going green fully, mysql services not starting up?

I was running Wamp Server for more than a year,
Now I faced a problem that I couldn't start Wamp server (The icon just stay red and the error message appear)

I managed to uninstall Wamp and reinstall it again, and so I did, but before that I copied the folder from mysql/data to my desktop then when I reinstall it I copied that files to the original location.

Then mysql just got confused... And phpmyadmin is not working so I fixed that by restoring the fresh install folder contents..
But I couldn't start mysql (the wamp servers icon still on yellow)

So after I googled a lot, I deleted every thing in the mysql/data except for:-

mysql
test
performance_schema

And my problem solved :)

Communication between tabs or windows

This is a development storage part of Tomas M answer for Chrome. We must add listener

window.addEventListener("storage", (e)=> { console.log(e) } );

Load/save item in storage not runt this event - we MUST trigger it manually by

window.dispatchEvent( new Event('storage') ); // THIS IS IMPORTANT ON CHROME

and now, all open tab-s will receive event

Is generator.next() visible in Python 3?

Try:

next(g)

Check out this neat table that shows the differences in syntax between 2 and 3 when it comes to this.

no overload for matches delegate 'system.eventhandler'

Change the klik method as follows:

public void klik(object pea, EventArgs e)
{
    Bitmap c = this.DrawMandel();
    Button btn = pea as Button;
    Graphics gr = btn.CreateGraphics();
    gr.DrawImage(b, 150, 200);
}

Call Stored Procedure within Create Trigger in SQL Server

finally...

set ANSI_NULLS ON
set QUOTED_IDENTIFIER ON

GO
ALTER TRIGGER [dbo].[RA2Newsletter] 
   ON  [dbo].[Reiseagent] 
   AFTER INSERT
 AS
    declare
    @rAgent_Name nvarchar(50),
    @rAgent_Email nvarchar(50),
    @rAgent_IP nvarchar(50),
    @hotelID int,
    @retval int


BEGIN
    SET NOCOUNT ON;

    -- Insert statements for trigger here
    Select @rAgent_Name=rAgent_Name,@rAgent_Email=rAgent_Email,@rAgent_IP=rAgent_IP,@hotelID=hotelID  From Inserted
    EXEC insert2Newsletter '','',@rAgent_Name,@rAgent_Email,@rAgent_IP,@hotelID,'RA', @retval

END

How do I generate a random int number?

I wanted to add a cryptographically secure version:

RNGCryptoServiceProvider Class (MSDN or dotnetperls)

It implements IDisposable.

using (RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider())
{
   byte[] randomNumber = new byte[4];//4 for int32
   rng.GetBytes(randomNumber);
   int value = BitConverter.ToInt32(randomNumber, 0);
}

How to install latest version of git on CentOS 7.x/6.x

Build latest version of git on Centos 6/7

Preparing system to building rpms

  1. Install epel:

    For EL6, use:

    sudo yum install https://dl.fedoraproject.org/pub/epel/epel-release-latest-6.noarch.rpm  
    

    For EL7, use:

    sudo yum install https://dl.fedoraproject.org/pub/epel/epel-release-latest-7.noarch.rpm
    
  2. Install fedpkg:

    sudo yum install fedpkg
    
  3. Add yourself into group mock (you might need to re-login to server after this change):

    sudo usermod -a -G mock $USER
    

Download git

  1. Download git sources:

    fedpkg clone -a git && cd git
    fedpkg sources
    
  2. Verify sources:

    sha512sum -c sources
    

Build rpm

  1. Create srmp. Use el6 for RHEL6, el7 for RHEL7.

    fedpkg --dist el7 srpm
    
  2. Build package in mock:

    mock -r epel-7-x86_64 git-2.16.0-1.el7.src.rpm
    
  3. Install latest version of git rpm from /var/lib/mock/epel-7-x86_64/result/. Note, you might need to uninstall existing version of the git from your system first.

This instruction is based on the mailing list post by Todd Zullinger.

JavaScript window resize event

Solution for 2018+:

You should use ResizeObserver. It is a browser-native solution that has a much better performance than to use the resize event. In addition, it not only supports the event on the document but also on arbitrary elements.

var ro = new ResizeObserver( entries => {
  for (let entry of entries) {
    const cr = entry.contentRect;
    console.log('Element:', entry.target);
    console.log(`Element size: ${cr.width}px x ${cr.height}px`);
    console.log(`Element padding: ${cr.top}px ; ${cr.left}px`);
  }
});

// Observe one or multiple elements
ro.observe(someElement);

Currently, Firefox, Chrome, Safari, and Edge support it. For other (and older) browsers you have to use a polyfill.

Check if a process is running or not on Windows with Python

Would you be happy with your Python command running another program to get the info?

If so, I'd suggest you have a look at PsList and all its options. For example, The following would tell you about any running iTunes process

PsList itunes

If you can work out how to interpret the results, this should hopefully get you going.

Edit:

When I'm not running iTunes, I get the following:

pslist v1.29 - Sysinternals PsList
Copyright (C) 2000-2009 Mark Russinovich
Sysinternals

Process information for CLARESPC:

Name                Pid Pri Thd  Hnd   Priv        CPU Time    Elapsed Time
iTunesHelper       3784   8  10  229   3164     0:00:00.046     3:41:05.053

With itunes running, I get this one extra line:

iTunes              928   8  24  813 106168     0:00:08.734     0:02:08.672

However, the following command prints out info only about the iTunes program itself, i.e. with the -e argument:

pslist -e itunes

Object of class mysqli_result could not be converted to string in

The mysqli_query() method returns an object resource to your $result variable, not a string.

You need to loop it up and then access the records. You just can't directly use it as your $result variable.

while ($row = $result->fetch_assoc()) {
    echo $row['classtype']."<br>";
}

Reloading submodules in IPython

On Jupyter Notebooks on Anaconda, doing this:

%load_ext autoreload
%autoreload 2

produced the message:

The autoreload extension is already loaded. To reload it, use: %reload_ext autoreload

It looks like it's preferable to do:

%reload_ext autoreload
%autoreload 2

Version information:

The version of the notebook server is 5.0.0 and is running on: Python 3.6.2 |Anaconda, Inc.| (default, Sep 20 2017, 13:35:58) [MSC v.1900 32 bit (Intel)]

how to have two headings on the same line in html

The following code will allow you to have two headings on the same line, the first left-aligned and the second right-aligned, and has the added advantage of keeping both headings on the same baseline.

The HTML Part:

<h1 class="text-left-right">
    <span class="left-text">Heading Goes Here</span>
    <span class="byline">Byline here</span>
</h1>

And the CSS:

.text-left-right {
    text-align: right;
    position: relative;
}
.left-text {
    left: 0;
    position: absolute;
}
.byline {
    font-size: 16px;
    color: rgba(140, 140, 140, 1);
}

How do I check if a string is a number (float)?

use following it handles all cases:-

import re
a=re.match('((\d+[\.]\d*$)|(\.)\d+$)' ,  '2.3') 
a=re.match('((\d+[\.]\d*$)|(\.)\d+$)' ,  '2.')
a=re.match('((\d+[\.]\d*$)|(\.)\d+$)' ,  '.3')
a=re.match('((\d+[\.]\d*$)|(\.)\d+$)' ,  '2.3sd')
a=re.match('((\d+[\.]\d*$)|(\.)\d+$)' ,  '2.3')

Trim Whitespaces (New Line and Tab space) in a String in Oracle

Fowloing code remove newline from both side of string:

select ltrim(rtrim('asbda'||CHR(10)||CHR(13) ,''||CHR(10)||CHR(13)),''||CHR(10)||CHR(13))  from dual

but in most cases this one is just enought :

select rtrim('asbda'||CHR(10)||CHR(13) ,''||CHR(10)||CHR(13)))  from dual

Access-Control-Allow-Origin Multiple Origin Domains?

For multiple domains, in your .htaccess:

<IfModule mod_headers.c>
    SetEnvIf Origin "http(s)?://(www\.)?(domain1.example|domain2.example)$" AccessControlAllowOrigin=$0$1
    Header add Access-Control-Allow-Origin %{AccessControlAllowOrigin}e env=AccessControlAllowOrigin
    Header set Access-Control-Allow-Credentials true
</IfModule>

Download/Stream file from URL - asp.net

Download url to bytes and convert bytes into stream:

using (var client = new WebClient())
{
    var content = client.DownloadData(url);
    using (var stream = new MemoryStream(content))
    {
        ...
    }
}   

How can I remove punctuation from input text in Java?

This first removes all non-letter characters, folds to lowercase, then splits the input, doing all the work in a single line:

String[] words = instring.replaceAll("[^a-zA-Z ]", "").toLowerCase().split("\\s+");

Spaces are initially left in the input so the split will still work.

By removing the rubbish characters before splitting, you avoid having to loop through the elements.

JQuery find first parent element with specific class prefix

Jquery later allowed you to to find the parents with the .parents() method.

Hence I recommend using:

var $div = $('#divid').parents('div[class^="div-a"]');

This gives all parent nodes matching the selector. To get the first parent matching the selector use:

var $div = $('#divid').parents('div[class^="div-a"]').eq(0);

For other such DOM traversal queries, check out the documentation on traversing the DOM.

Show diff between commits

If you want to see the changes introduced with each commit, try "git log -p"

How to return a 200 HTTP Status Code from ASP.NET MVC 3 controller

200 is just the normal HTTP header for a successful request. If that's all you need, just have the controller return new EmptyResult();

Add (insert) a column between two columns in a data.frame

df <- data.frame(a=c(1,2), b=c(3,4), c=c(5,6))
df %>%
  mutate(d= a/2) %>%
  select(a, b, d, c)

results

  a b   d c
1 1 3 0.5 5
2 2 4 1.0 6

I suggest to use dplyr::select after dplyr::mutate. It has many helpers to select/de-select subset of columns.

In the context of this question the order by which you select will be reflected in the output data.frame.

Sum columns with null values in oracle

The top-rated answer with NVL is totally valid. If you have any interest in making your SQL code more portable, you might want to use CASE, which is supported with the same syntax in both Oracle and SQL Server:

select 
  type,craft,
  SUM(
    case when regular is null
         then 0
         else regular
    end
    +
    case when overtime is null
         then 0
         else overtime
    end
  ) as total_hours
from 
  hours_t
group by
  type
 ,craft
order by
  type
 ,craft

C# 4.0 optional out/ref arguments

Use an overloaded method without the out parameter to call the one with the out parameter for C# 6.0 and lower. I'm not sure why a C# 7.0 for .NET Core is even the correct answer for this thread when it was specifically asked if C# 4.0 can have an optional out parameter. The answer is NO!

Internal vs. Private Access Modifiers

internal members are accessible within the assembly (only accessible in the same project)

private members are accessible within the same class

Example for Beginners

There are 2 projects in a solution (Project1, Project2) and Project1 has a reference to Project2.

  • Public method written in Project2 will be accessible in Project2 and the Project1
  • Internal method written in Project2 will be accessible in Project2 only but not in Project1
  • private method written in class1 of Project2 will only be accessible to the same class. It will neither be accessible in other classes of Project 2 not in Project 1.

Load properties file in JAR?

The problem is that you are using getSystemResourceAsStream. Use simply getResourceAsStream. System resources load from the system classloader, which is almost certainly not the class loader that your jar is loaded into when run as a webapp.

It works in Eclipse because when launching an application, the system classloader is configured with your jar as part of its classpath. (E.g. java -jar my.jar will load my.jar in the system class loader.) This is not the case with web applications - application servers use complex class loading to isolate webapplications from each other and from the internals of the application server. For example, see the tomcat classloader how-to, and the diagram of the classloader hierarchy used.

EDIT: Normally, you would call getClass().getResourceAsStream() to retrieve a resource in the classpath, but as you are fetching the resource in a static initializer, you will need to explicitly name a class that is in the classloader you want to load from. The simplest approach is to use the class containing the static initializer, e.g.

[public] class MyClass {
  static
  {
    ...
    props.load(MyClass.class.getResourceAsStream("/someProps.properties"));
  }
}

The type initializer for 'Oracle.DataAccess.Client.OracleConnection' threw an exception

You need the oracle client driver installed for those classes to work.

There might be 3rd party connection frameworks out there that can handle Oracle, perhaps someone else might know of some specific ones.

Should I learn C before learning C++?

Learning C forces you to think harder about some issues such as explicit and implicit memory management or storage sizes of basic data types at the time you write your code.

Once you have reached a point where you feel comfortable around C's features and misfeatures, you will probably have less trouble learning and writing in C++.

It is entirely possible that the C++ code you have seen did not look much different from standard C, but that may well be because it was not object oriented and did not use exceptions, object-orientation, templates or other advanced features.

Adding a caption to an equation in LaTeX

As in this forum post by Gonzalo Medina, a third way may be:

\documentclass{article}
\usepackage{caption}

\DeclareCaptionType{equ}[][]
%\captionsetup[equ]{labelformat=empty}

\begin{document}

Some text

\begin{equ}[!ht]
  \begin{equation}
    a=b+c
  \end{equation}
\caption{Caption of the equation}
\end{equ}

Some other text
 
\end{document}

More details of the commands used from package caption: here.

A screenshot of the output of the above code:

screenshot of output

Search and replace a particular string in a file using Perl

A one liner:

perl -pi.back -e 's/<PREF>/ABCD/g;' inputfile

ArrayList of int array in java

First of all, for initializing a container you cannot use a primitive type (i.e. int; you can use int[] but as you want just an array of integers, I see no use in that). Instead, you should use Integer, as follows:

ArrayList<Integer> arl = new ArrayList<Integer>();

For adding elements, just use the add function:

arl.add(1);  
arl.add(22);
arl.add(-2);

Last, but not least, for printing the ArrayList you may use the build-in functionality of toString():

System.out.println("Arraylist contains: " + arl.toString());  

If you want to access the i element, where i is an index from 0 to the length of the array-1, you can do a :

int i = 0; // Index 0 is of the first element
System.out.println("The first element is: " + arl.get(i));

I suggest reading first on Java Containers, before starting to work with them.

Is Spring annotation @Controller same as @Service?

If you look at the definitions of @Controller, @Service annotations, then you'll find that these are special type of @Component annotation.

@Component
public @interface Service {
    ….
}

 

@Component
public @interface Controller {
    …
}

So what's the difference?

@Controller

The @Controller annotation indicates that a particular class serves the role of a controller. The @Controller annotation acts as a stereotype for the annotated class, indicating its role.

What’s special about @Controller?

You cannot switch this annotation with any other like @Service or @Repository, even though they look same. The dispatcher scans the classes annotated with @Controller and detects @RequestMapping annotations within them. You can only use @RequestMapping on @Controller annotated classes.


@Service

@Services hold business logic and call method in repository layer.

What’s special about @Service?

Apart from the fact that it is used to indicate that it's holding the business logic, there’s no noticeable specialty that this annotation provides, but who knows, spring may add some additional exceptional in future.

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

How can change width of dropdown list?

This:

<select style="width: XXXpx;">

XXX = Any Number

Works great in Google Chrome v70.0.3538.110

Where does Android app package gets installed on phone

->List all the packages by :

adb shell su 0 pm list packages -f

->Search for your package name by holding keys "ctrl+alt+f".

->Once found, look for the location associated with it.

Differences between TCP sockets and web sockets, one more time

When you send bytes from a buffer with a normal TCP socket, the send function returns the number of bytes of the buffer that were sent. If it is a non-blocking socket or a non-blocking send then the number of bytes sent may be less than the size of the buffer. If it is a blocking socket or blocking send, then the number returned will match the size of the buffer but the call may block. With WebSockets, the data that is passed to the send method is always either sent as a whole "message" or not at all. Also, browser WebSocket implementations do not block on the send call.

But there are more important differences on the receiving side of things. When the receiver does a recv (or read) on a TCP socket, there is no guarantee that the number of bytes returned corresponds to a single send (or write) on the sender side. It might be the same, it may be less (or zero) and it might even be more (in which case bytes from multiple send/writes are received). With WebSockets, the recipient of a message is event-driven (you generally register a message handler routine), and the data in the event is always the entire message that the other side sent.

Note that you can do message based communication using TCP sockets, but you need some extra layer/encapsulation that is adding framing/message boundary data to the messages so that the original messages can be re-assembled from the pieces. In fact, WebSockets is built on normal TCP sockets and uses frame headers that contains the size of each frame and indicate which frames are part of a message. The WebSocket API re-assembles the TCP chunks of data into frames which are assembled into messages before invoking the message event handler once per message.

node.js, socket.io with SSL

This is how I managed to set it up with express:

var fs = require( 'fs' );
var app = require('express')();
var https        = require('https');
var server = https.createServer({
    key: fs.readFileSync('./test_key.key'),
    cert: fs.readFileSync('./test_cert.crt'),
    ca: fs.readFileSync('./test_ca.crt'),
    requestCert: false,
    rejectUnauthorized: false
},app);
server.listen(8080);

var io = require('socket.io').listen(server);

io.sockets.on('connection',function (socket) {
    ...
});

app.get("/", function(request, response){
    ...
})


I hope that this will save someone's time.

Update : for those using lets encrypt use this

var server = https.createServer({ 
                key: fs.readFileSync('privkey.pem'),
                cert: fs.readFileSync('fullchain.pem') 
             },app);

Must declare the scalar variable

The reason you are getting the DECLARE error from your dynamic statement is because dynamic statements are handled in separate batches, which boils down to a matter of scope. While there may be a more formal definition of the scopes available in SQL Server, I've found it sufficient to generally keep the following three in mind, ordered from highest availability to lowest availability:

Global:

Objects that are available server-wide, such as temporary tables created with a double hash/pound sign ( ##GLOBALTABLE, however you like to call # ). Be very wary of global objects, just as you would with any application, SQL Server or otherwise; these types of things are generally best avoided altogether. What I'm essentially saying is to keep this scope in mind specifically as a reminder to stay out of it.

IF ( OBJECT_ID( 'tempdb.dbo.##GlobalTable' ) IS NULL )
BEGIN
    CREATE TABLE ##GlobalTable
    (
        Val             BIT
    );

    INSERT INTO ##GlobalTable ( Val )
    VALUES ( 1 );
END;
GO

-- This table may now be accessed by any connection in any database,
-- assuming the caller has sufficient privileges to do so, of course.

Session:

Objects which are reference locked to a specific spid. Off the top of my head, the only type of session object I can think of is a normal temporary table, defined like #Table. Being in session scope essentially means that after the batch ( terminated by GO ) completes, references to this object will continue to resolve successfully. These are technically accessible by other sessions, but it would be somewhat of a feat do to so programmatically as they get sort of randomized names in tempdb and accessing them is a bit of a pain in the ass anyway.

-- Start of session;
-- Start of batch;
IF ( OBJECT_ID( 'tempdb.dbo.#t_Test' ) IS NULL )
BEGIN
    CREATE TABLE #t_Test
    (
        Val     BIT
    );

    INSERT INTO #t_Test ( Val )
    VALUES ( 1 );
END;
GO 
-- End of batch;

-- Start of batch;
SELECT  *
FROM    #t_Test;
GO
-- End of batch;

Opening a new session ( a connection with a separate spid ), the second batch above would fail, as that session would be unable to resolve the #t_Test object name.

Batch:

Normal variables, such as your @value1 and @value2, are scoped only for the batch in which they are declared. Unlike #Temp tables, as soon as your query block hits a GO, those variables stop being available to the session. This is the scope level which is generating your error.

-- Start of session;
-- Start of batch;
DECLARE @test   BIT = 1;

PRINT @test;
GO
-- End of batch;

-- Start of batch;
PRINT @Test;  -- Msg 137, Level 15, State 2, Line 2
              -- Must declare the scalar variable "@Test".
GO
-- End of batch;

Okay, so what?

What is happening here with your dynamic statement is that the EXECUTE() command effectively evaluates as a separate batch, without breaking the batch you executed it from. EXECUTE() is good and all, but since the introduction of sp_executesql(), I use the former only in the most simple of instances ( explicitly, when there is very little "dynamic" element of my statements at all, primarily to "trick" otherwise unaccommodating DDL CREATE statements to run in the middle of other batches ). @AaronBertrand's answer above is similar and will be similar in performance to the following, leveraging the function of the optimizer when evaluating dynamic statements, but I thought it might be worthwhile to expand on the @param, well, parameter.

IF NOT EXISTS ( SELECT  1
                FROM    sys.objects
                WHERE   name = 'TblTest'
                    AND type = 'U' )
BEGIN
    --DROP TABLE dbo.TblTest;
    CREATE TABLE dbo.TblTest
    (
        ID      INTEGER,
        VALUE1  VARCHAR( 1 ),
        VALUE2  VARCHAR( 1 )
    );

    INSERT INTO dbo.TblTest ( ID, VALUE1, VALUE2 )
    VALUES ( 61, 'A', 'B' );
END;

SET NOCOUNT ON;

DECLARE @SQL    NVARCHAR( MAX ),
        @PRM    NVARCHAR( MAX ),
        @value1 VARCHAR( MAX ),
        @value2 VARCHAR( 200 ),
        @Table  VARCHAR( 32 ),
        @ID     INTEGER;

    SET @Table = 'TblTest';
    SET @ID = 61;

    SET @PRM = '
        @_ID        INTEGER,
        @_value1    VARCHAR( MAX ) OUT,
        @_value2    VARCHAR( 200 ) OUT';
    SET @SQL = '
        SELECT  @_value1 = VALUE1,
                @_value2 = VALUE2
        FROM    dbo.[' + REPLACE( @Table, '''', '' ) + ']
        WHERE   ID = @_ID;';

EXECUTE dbo.sp_executesql @statement = @SQL, @param = @PRM,
            @_ID = @ID, @_value1 = @value1 OUT, @_value2 = @value2 OUT;

PRINT @value1 + ' ' + @value2;

SET NOCOUNT OFF;

C++: constructor initializer for arrays

Only the default constructor can be called when creating objects in an array.

How do I install cURL on cygwin?

I just copied the folder "curl-7.43.0" from zip file that I downloaded from curl website curl.haxx.se into cygwin64 folder on drive C:. And then I have used it with prefix curl in cygwin command terminal.

My actual download location from softpedia, I have used Softpedia Mirror (US)

What is the most efficient/elegant way to parse a flat table into a tree?

Now that MySQL 8.0 supports recursive queries, we can say that all popular SQL databases support recursive queries in standard syntax.

WITH RECURSIVE MyTree AS (
    SELECT * FROM MyTable WHERE ParentId IS NULL
    UNION ALL
    SELECT m.* FROM MyTABLE AS m JOIN MyTree AS t ON m.ParentId = t.Id
)
SELECT * FROM MyTree;

I tested recursive queries in MySQL 8.0 in my presentation Recursive Query Throwdown in 2017.

Below is my original answer from 2008:


There are several ways to store tree-structured data in a relational database. What you show in your example uses two methods:

  • Adjacency List (the "parent" column) and
  • Path Enumeration (the dotted-numbers in your name column).

Another solution is called Nested Sets, and it can be stored in the same table too. Read "Trees and Hierarchies in SQL for Smarties" by Joe Celko for a lot more information on these designs.

I usually prefer a design called Closure Table (aka "Adjacency Relation") for storing tree-structured data. It requires another table, but then querying trees is pretty easy.

I cover Closure Table in my presentation Models for Hierarchical Data with SQL and PHP and in my book SQL Antipatterns: Avoiding the Pitfalls of Database Programming.

CREATE TABLE ClosureTable (
  ancestor_id   INT NOT NULL REFERENCES FlatTable(id),
  descendant_id INT NOT NULL REFERENCES FlatTable(id),
  PRIMARY KEY (ancestor_id, descendant_id)
);

Store all paths in the Closure Table, where there is a direct ancestry from one node to another. Include a row for each node to reference itself. For example, using the data set you showed in your question:

INSERT INTO ClosureTable (ancestor_id, descendant_id) VALUES
  (1,1), (1,2), (1,4), (1,6),
  (2,2), (2,4),
  (3,3), (3,5),
  (4,4),
  (5,5),
  (6,6);

Now you can get a tree starting at node 1 like this:

SELECT f.* 
FROM FlatTable f 
  JOIN ClosureTable a ON (f.id = a.descendant_id)
WHERE a.ancestor_id = 1;

The output (in MySQL client) looks like the following:

+----+
| id |
+----+
|  1 | 
|  2 | 
|  4 | 
|  6 | 
+----+

In other words, nodes 3 and 5 are excluded, because they're part of a separate hierarchy, not descending from node 1.


Re: comment from e-satis about immediate children (or immediate parent). You can add a "path_length" column to the ClosureTable to make it easier to query specifically for an immediate child or parent (or any other distance).

INSERT INTO ClosureTable (ancestor_id, descendant_id, path_length) VALUES
  (1,1,0), (1,2,1), (1,4,2), (1,6,1),
  (2,2,0), (2,4,1),
  (3,3,0), (3,5,1),
  (4,4,0),
  (5,5,0),
  (6,6,0);

Then you can add a term in your search for querying the immediate children of a given node. These are descendants whose path_length is 1.

SELECT f.* 
FROM FlatTable f 
  JOIN ClosureTable a ON (f.id = a.descendant_id)
WHERE a.ancestor_id = 1
  AND path_length = 1;

+----+
| id |
+----+
|  2 | 
|  6 | 
+----+

Re comment from @ashraf: "How about sorting the whole tree [by name]?"

Here's an example query to return all nodes that are descendants of node 1, join them to the FlatTable that contains other node attributes such as name, and sort by the name.

SELECT f.name
FROM FlatTable f 
JOIN ClosureTable a ON (f.id = a.descendant_id)
WHERE a.ancestor_id = 1
ORDER BY f.name;

Re comment from @Nate:

SELECT f.name, GROUP_CONCAT(b.ancestor_id order by b.path_length desc) AS breadcrumbs
FROM FlatTable f 
JOIN ClosureTable a ON (f.id = a.descendant_id) 
JOIN ClosureTable b ON (b.descendant_id = a.descendant_id) 
WHERE a.ancestor_id = 1 
GROUP BY a.descendant_id 
ORDER BY f.name

+------------+-------------+
| name       | breadcrumbs |
+------------+-------------+
| Node 1     | 1           |
| Node 1.1   | 1,2         |
| Node 1.1.1 | 1,2,4       |
| Node 1.2   | 1,6         |
+------------+-------------+

A user suggested an edit today. SO moderators approved the edit, but I am reversing it.

The edit suggested that the ORDER BY in the last query above should be ORDER BY b.path_length, f.name, presumably to make sure the ordering matches the hierarchy. But this doesn't work, because it would order "Node 1.1.1" after "Node 1.2".

If you want the ordering to match the hierarchy in a sensible way, that is possible, but not simply by ordering by the path length. For example, see my answer to MySQL Closure Table hierarchical database - How to pull information out in the correct order.

Data binding for TextBox

I Recommend you implement INotifyPropertyChanged and change your databinding code to this:

this.textBox.DataBindings.Add("Text",
                                this.Food,
                                "Name",
                                false,
                                DataSourceUpdateMode.OnPropertyChanged);

That'll fix it.

Note that the default DataSourceUpdateMode is OnValidation, so if you don't specify OnPropertyChanged, the model object won't be updated until after your validations have occurred.

How to convert a hex string to hex number

Try this:

hex_str = "0xAD4"
hex_int = int(hex_str, 16)
new_int = hex_int + 0x200
print hex(new_int)

If you don't like the 0x in the beginning, replace the last line with

print hex(new_int)[2:]

Hex transparency in colors

enter image description here

This might be very late answer. But this chart kills it.

All percentage values are mapped to the hexadecimal values.

http://online.sfsu.edu/chrism/hexval.html

Adding VirtualHost fails: Access Forbidden Error 403 (XAMPP) (Windows 7)

After so many changes and tries and answers. For

SOs: Windows 7 / Windows 10

Xampp Version: Xampp or Xampp portable 7.1.18 / 7.3.7 (control panel v3.2.4)

Installers: win32-7.1.18-0-VC14-installer / xampp-windows-x64-7.3.7-0-VC15-installer

  1. Do not edit other files like httpd-xampp

  2. Stop Apache

  3. Open httpd-vhosts.conf located in **your_xampp_directory**\apache\conf\extra\ (your XAMPP directory might be by default: C:/xampp/htdocs)

  4. Remove hash before the following line (aprox. line 20): NameVirtualHost *:80 (this might be optional)

  5. Add the following virtual hosts at the end of the file, considering your directories paths:

    ##127.0.0.1
    <VirtualHost *:80>
        DocumentRoot "C:/xampp/htdocs"
        ServerName localhost
        ErrorLog "logs/localhost-error.log"
        CustomLog "logs/localhost-access.log" common
    </VirtualHost>
    
    ##127.0.0.2
    <VirtualHost *:80>
        DocumentRoot "F:/myapp/htdocs/"
        ServerName test1.localhost
        ServerAlias www.test1.localhost
        ErrorLog "logs/myapp-error.log"
        CustomLog "logs/myapp-access.log" common
        <Directory  "F:/myapp/htdocs/">
            #Options All # Deprecated
            #AllowOverride All # Deprecated
            Require all granted  
        </Directory>
    </VirtualHost>
    
  6. Edit (with admin access) your host file (located at Windows\System32\drivers\etc, but with the following tip, only one loopback ip for every domain:

    127.0.0.1 localhost
    127.0.0.2 test1.localhost
    127.0.0.2 www.test1.localhost
    

For every instance, repeat the second block, the first one is the main block only for "default" purposes.

Copy/duplicate database without using mysqldump

You can duplicate a table without data by running:

CREATE TABLE x LIKE y;

(See the MySQL CREATE TABLE Docs)

You could write a script that takes the output from SHOW TABLES from one database and copies the schema to another. You should be able to reference schema+table names like:

CREATE TABLE x LIKE other_db.y;

As far as the data goes, you can also do it in MySQL, but it's not necessarily fast. After you've created the references, you can run the following to copy the data:

INSERT INTO x SELECT * FROM other_db.y;

If you're using MyISAM, you're better off to copy the table files; it'll be much faster. You should be able to do the same if you're using INNODB with per table table spaces.

If you do end up doing an INSERT INTO SELECT, be sure to temporarily turn off indexes with ALTER TABLE x DISABLE KEYS!

EDIT Maatkit also has some scripts that may be helpful for syncing data. It may not be faster, but you could probably run their syncing scripts on live data without much locking.

Referencing value in a closed Excel workbook using INDIRECT?

If you know the number of sheet you want to reference you can use below function to find out the name. Than you can use it in INDIRECT funcion.

Public Function GETSHEETNAME(address As String, Optional SheetNumber As Integer = 1) As String

    Set WS = GetObject(address).Worksheets
    GETSHEETNAME = WS(SheetNumber).Name

End Function

This solution doesn't require referenced workbook to be open - Excel gonna open it by itself (but it's gonna be hidden).

Angular.js vs Knockout.js vs Backbone.js

It depends on the nature of your application. And, since you did not describe it in great detail, it is an impossible question to answer. I find Backbone to be the easiest, but I work in Angular all day. Performance is more up to the coder than the framework, in my opinion.

Are you doing heavy DOM manipulation? I would use jQuery and Backbone.

Very data driven app? Angular with its nice data binding.

Game programming? None - direct to canvas; maybe a game engine.

What is difference between MVC, MVP & MVVM design pattern in terms of coding c#

Some basic differences can be written in short:

MVC:

Traditional MVC is where there is a

  1. Model: Acts as the model for data
  2. View : Deals with the view to the user which can be the UI
  3. Controller: Controls the interaction between Model and View, where view calls the controller to update model. View can call multiple controllers if needed.

MVP:

Similar to traditional MVC but Controller is replaced by Presenter. But the Presenter, unlike Controller is responsible for changing the view as well. The view usually does not call the presenter.

MVVM

The difference here is the presence of View Model. It is kind of an implementation of Observer Design Pattern, where changes in the model are represented in the view as well, by the VM. Eg: If a slider is changed, not only the model is updated but the data which may be a text, that is displayed in the view is updated as well. So there is a two-way data binding.

How do I test a single file using Jest?

Simple solution that works:

yarn test -g fileName or

npm test -g fileName

Example:

yarn test -g cancelTransaction or

npm test -g cancelTransaction

More about test filters:

Test Filters
--fgrep, -f Only run tests containing this string [string]
--grep, -g Only run tests matching this string or regexp [string]
--invert, -i Inverts --grep and --fgrep matches [boolean]

Partial Dependency (Databases)

Partial dependency means that a nonprime attribute is functionally dependent on part of a candidate key. (A nonprime attribute is an attribute that's not part of any candidate key.)

For example, let's start with R{ABCD}, and the functional dependencies AB->CD and A->C.

The only candidate key for R is AB. C and D are a nonprime attributes. C is functionally dependent on A. A is part of a candidate key. That's a partial dependency.

Which is the best Linux C/C++ debugger (or front-end to gdb) to help teaching programming?

Perhaps it is indirect to gdb (because it's an IDE), but my recommendations would be KDevelop. Being quite spoiled with Visual Studio's debugger (professionally at work for many years), I've so far felt the most comfortable debugging in KDevelop (as hobby at home, because I could not afford Visual Studio for personal use - until Express Edition came out). It does "look something similar to" Visual Studio compared to other IDE's I've experimented with (including Eclipse CDT) when it comes to debugging step-through, step-in, etc (placing break points is a bit awkward because I don't like to use mouse too much when coding, but it's not difficult).

How to check if a class inherits another class without instantiating it?

To check for assignability, you can use the Type.IsAssignableFrom method:

typeof(SomeType).IsAssignableFrom(typeof(Derived))

This will work as you expect for type-equality, inheritance-relationships and interface-implementations but not when you are looking for 'assignability' across explicit / implicit conversion operators.

To check for strict inheritance, you can use Type.IsSubclassOf:

typeof(Derived).IsSubclassOf(typeof(SomeType))

Type converting slices of interfaces

Try interface{} instead. To cast back as slice, try

func foo(bar interface{}) {
    s := bar.([]string)
    // ...
}

Getting the first character of a string with $str[0]

Yes. Strings can be seen as character arrays, and the way to access a position of an array is to use the [] operator. Usually there's no problem at all in using $str[0] (and I'm pretty sure is much faster than the substr() method).

There is only one caveat with both methods: they will get the first byte, rather than the first character. This is important if you're using multibyte encodings (such as UTF-8). If you want to support that, use mb_substr(). Arguably, you should always assume multibyte input these days, so this is the best option, but it will be slightly slower.

Variables within app.config/web.config

A slightly more complicated, but far more flexible, alternative is to create a class that represents a configuration section. In your app.config / web.config file, you can have this:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
    <!-- This section must be the first section within the <configuration> node -->
    <configSections>
        <section name="DirectoryInfo" type="MyProjectNamespace.DirectoryInfoConfigSection, MyProjectAssemblyName" />
    </configSections>

    <DirectoryInfo>
        <Directory MyBaseDir="C:\MyBase" Dir1="Dir1" Dir2="Dir2" />
    </DirectoryInfo>
</configuration>

Then, in your .NET code (I'll use C# in my example), you can create two classes like this:

using System;
using System.Configuration;

namespace MyProjectNamespace {

    public class DirectoryInfoConfigSection : ConfigurationSection {

        [ConfigurationProperty("Directory")]
        public DirectoryConfigElement Directory {
            get {
                return (DirectoryConfigElement)base["Directory"];
            }
    }

    public class DirectoryConfigElement : ConfigurationElement {

        [ConfigurationProperty("MyBaseDir")]
        public String BaseDirectory {
            get {
                return (String)base["MyBaseDir"];
            }
        }

        [ConfigurationProperty("Dir1")]
        public String Directory1 {
            get {
                return (String)base["Dir1"];
            }
        }

        [ConfigurationProperty("Dir2")]
        public String Directory2 {
            get {
                return (String)base["Dir2"];
            }
        }
        // You can make custom properties to combine your directory names.
        public String Directory1Resolved {
            get {
                return System.IO.Path.Combine(BaseDirectory, Directory1);
            }
        }
    }
}

Finally, in your program code, you can access your app.config variables, using your new classes, in this manner:

DirectoryInfoConfigSection config =
  (DirectoryInfoConfigSection)ConfigurationManager.GetSection("DirectoryInfo");
String dir1Path = config.Directory.Directory1Resolved;  // This value will equal "C:\MyBase\Dir1"

How do I set the focus to the first input element in an HTML form independent from the id?

Tried lots of the answers above and they weren't working. Found this one at: http://www.kolodvor.net/2008/01/17/set-focus-on-first-field-with-jquery/#comment-1317 Thank you Kolodvor.

$("input:text:visible:first").focus();

How do I tell if .NET 3.5 SP1 is installed?

You could go to SmallestDotNet using IE from the server. That will tell you the version and also provide a download link if you're out of date.

How to remove all listeners in an element?

Here's a function that is also based on cloneNode, but with an option to clone only the parent node and move all the children (to preserve their event listeners):

function recreateNode(el, withChildren) {
  if (withChildren) {
    el.parentNode.replaceChild(el.cloneNode(true), el);
  }
  else {
    var newEl = el.cloneNode(false);
    while (el.hasChildNodes()) newEl.appendChild(el.firstChild);
    el.parentNode.replaceChild(newEl, el);
  }
}

Remove event listeners on one element:

recreateNode(document.getElementById("btn"));

Remove event listeners on an element and all of its children:

recreateNode(document.getElementById("list"), true);

If you need to keep the object itself and therefore can't use cloneNode, then you have to wrap the addEventListener function and track the listener list by yourself, like in this answer.

Angular2 - Focusing a textbox on component load

you can use $ (jquery) :

<div>
    <form role="form" class="form-horizontal ">        
        <div [ngClass]="{showElement:IsEditMode, hidden:!IsEditMode}">
            <div class="form-group">
                <label class="control-label col-md-1 col-sm-1" for="name">Name</label>
                <div class="col-md-7 col-sm-7">
                    <input id="txtname`enter code here`" type="text" [(ngModel)]="person.Name" class="form-control" />

                </div>
                <div class="col-md-2 col-sm-2">
                    <input type="button" value="Add" (click)="AddPerson()" class="btn btn-primary" />
                </div>
            </div>
        </div>
        <div [ngClass]="{showElement:!IsEditMode, hidden:IsEditMode}">
            <div class="form-group">
                <label class="control-label col-md-1 col-sm-1" for="name">Person</label>
                <div class="col-md-7 col-sm-7">
                    <select [(ngModel)]="SelectedPerson.Id"  (change)="PersonSelected($event.target.value)" class="form-control">
                        <option *ngFor="#item of PeopleList" value="{{item.Id}}">{{item.Name}}</option>
                    </select>
                </div>
            </div>
        </div>        
    </form>
</div>

then in ts :

    declare var $: any;

    @Component({
      selector: 'app-my-comp',
      templateUrl: './my-comp.component.html',
      styleUrls: ['./my-comp.component.css']
    })
    export class MyComponent  {

    @ViewChild('loadedComponent', { read: ElementRef, static: true }) loadedComponent: ElementRef<HTMLElement>;

    setFocus() {
    const elem = this.loadedComponent.nativeElement.querySelector('#txtname');
          $(elem).focus();
    }
    }

How do I force git pull to overwrite everything on every pull?

You could try this:

git reset --hard HEAD
git pull

(from How do I force "git pull" to overwrite local files?)

Another idea would be to delete the entire git and make a new clone.

Laravel Eloquent ORM Transactions

For some reason it is quite difficult to find this information anywhere, so I decided to post it here, as my issue, while related to Eloquent transactions, was exactly changing this.

After reading THIS stackoverflow answer, I realized my database tables were using MyISAM instead of InnoDB.

For transactions to work on Laravel (or anywhere else as it seems), it is required that your tables are set to use InnoDB

Why?

Quoting MySQL Transactions and Atomic Operations docs (here):

MySQL Server (version 3.23-max and all versions 4.0 and above) supports transactions with the InnoDB and BDB transactional storage engines. InnoDB provides full ACID compliance. See Chapter 14, Storage Engines. For information about InnoDB differences from standard SQL with regard to treatment of transaction errors, see Section 14.2.11, “InnoDB Error Handling”.

The other nontransactional storage engines in MySQL Server (such as MyISAM) follow a different paradigm for data integrity called “atomic operations.” In transactional terms, MyISAM tables effectively always operate in autocommit = 1 mode. Atomic operations often offer comparable integrity with higher performance.

Because MySQL Server supports both paradigms, you can decide whether your applications are best served by the speed of atomic operations or the use of transactional features. This choice can be made on a per-table basis.

A cycle was detected in the build path of project xxx - Build Path Problem

Sometimes marking as Warning

Windows -> Preferences -> Java-> Compiler -> Building -> Circular Dependencies

doesn't solve the problem because eclipse don't compile the projects that have another project in the dependencies that isn't compiled.

So to solve this problem you can try forcing Eclipse to compile every class that it be able to.

To make this just:

  1. Deselect

Windows -> Preferences -> Java-> Compiler -> Building -> Abort build when build path error occur

  1. Clean and rebuild all project

Project -> Clean...

  1. Reselect:

Windows -> Preferences -> Java-> Compiler -> Building -> Abort build when build path error occur

If you have the Automatic Build selected then you will not need to do this every time that you change the code

Group array items using object

Try (h={})

myArray.forEach(x=> h[x.group]= (h[x.group]||[]).concat(x.color) );
myArray = Object.keys(h).map(k=> ({group:k, color:h[k]}))

_x000D_
_x000D_
let myArray = [_x000D_
  {group: "one", color: "red"},_x000D_
  {group: "two", color: "blue"},_x000D_
  {group: "one", color: "green"},_x000D_
  {group: "one", color: "black"},_x000D_
];_x000D_
_x000D_
let h={};_x000D_
_x000D_
myArray.forEach(x=> h[x.group]= (h[x.group]||[]).concat(x.color) );_x000D_
myArray = Object.keys(h).map(k=> ({group:k, color:h[k]}))_x000D_
_x000D_
console.log(myArray);
_x000D_
_x000D_
_x000D_

jQuery UI Tabs - How to Get Currently Selected Tab Index

For JQuery UI versions before 1.9: ui.index from the event is what you want.

For JQuery UI 1.9 or later: see the answer by Giorgio Luparia, below.

The easiest way to transform collection to array?

For example, you have collection ArrayList with elements Student class:

List stuList = new ArrayList();
Student s1 = new Student("Raju");
Student s2 = new Student("Harish");
stuList.add(s1);
stuList.add(s2);
//now you can convert this collection stuList to Array like this
Object[] stuArr = stuList.toArray();           // <----- toArray() function will convert collection to array

where is create-react-app webpack config and files?

The files are located in your node_modules/react-scripts folder:

Webpack config:

https://github.com/facebook/create-react-app/blob/master/packages/react-scripts/config/webpack.config.js

Start Script:

https://github.com/facebook/create-react-app/blob/master/packages/react-scripts/scripts/start.js

Build Script:

https://github.com/facebook/create-react-app/blob/master/packages/react-scripts/scripts/build.js

Test Script:

https://github.com/facebook/create-react-app/blob/master/packages/react-scripts/scripts/test.js

and so on ...

Now, the purpose of CRA is not to worry about these.

From the documentation:

You don’t need to install or configure tools like Webpack or Babel. They are preconfigured and hidden so that you can focus on the code.

If you want to have access to the config files, you need to eject by running:

npm run eject

Note: this is a one-way operation. Once you eject, you can’t go back!

In most scenarios, it is best not to eject and try to find a way to make it work for you in another way.

If you need to override some of the config options, you can have a look at https://github.com/gsoft-inc/craco

Run a command over SSH with JSch

This is a shameless plug, but I'm just now writing some extensive Javadoc for JSch.

Also, there is now a Manual in the JSch Wiki (written mainly by me).


About the original question, there is not really an example for handling the streams. Reading/writing a stream is done as always.

But there simply can't be a sure way to know when one command in a shell has finished just from reading the shell's output (this is independent of the SSH protocol).

If the shell is interactive, i.e. it has a terminal attached, it will usually print a prompt, which you could try to recognize. But at least theoretically this prompt string could also occur in normal output from a command. If you want to be sure, open individual exec channels for each command instead of using a shell channel. The shell channel is mainly used for interactive use by a human user, I think.

JavaScript array to CSV

The following code were written in ES6 and it will work in most of the browsers without an issue.

_x000D_
_x000D_
var test_array = [["name1", 2, 3], ["name2", 4, 5], ["name3", 6, 7], ["name4", 8, 9], ["name5", 10, 11]];_x000D_
_x000D_
// Construct the comma seperated string_x000D_
// If a column values contains a comma then surround the column value by double quotes_x000D_
const csv = test_array.map(row => row.map(item => (typeof item === 'string' && item.indexOf(',') >= 0) ? `"${item}"`: String(item)).join(',')).join('\n');_x000D_
_x000D_
// Format the CSV string_x000D_
const data = encodeURI('data:text/csv;charset=utf-8,' + csv);_x000D_
_x000D_
// Create a virtual Anchor tag_x000D_
const link = document.createElement('a');_x000D_
link.setAttribute('href', data);_x000D_
link.setAttribute('download', 'export.csv');_x000D_
_x000D_
// Append the Anchor tag in the actual web page or application_x000D_
document.body.appendChild(link);_x000D_
_x000D_
// Trigger the click event of the Anchor link_x000D_
link.click();_x000D_
_x000D_
// Remove the Anchor link form the web page or application_x000D_
document.body.removeChild(link);
_x000D_
_x000D_
_x000D_

Installing Oracle Instant Client

If you want to use SQL Server Management Studio, you want to install the full Oracle client, not the Instant Client. The full Oracle client is on the same download page as the Oracle database. Assuming that you are installing on a 64-bit version of Windows, I expect you want the "Oracle Database 11g Release 2 Client (11.2.0.1.0) for Microsoft Windows (x64)" download. This is several hundred MB rather than a couple of MB for the Instant Client.

How do I disable orientation change on Android?

In OnCreate method of your activity use this code:

    @Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);

Now your orientation will be set to portrait and will never change.

Get and set position with jQuery .offset()

It's doable but you have to know that using offset() sets the position of the element relative to the document:

$('.layer1').offset( $('.layer2').offset() );

Embed Google Map code in HTML with marker

Learning Google's JavaScript library is a good option. If you don't feel like getting into coding you might find Maps Engine Lite useful.

It is a tool recently published by Google where you can create your personal maps (create markers, draw geometries and adapt the colors and styles).

Here is an useful tutorial I found: Quick Tip: Embedding New Google Maps

Classes residing in App_Code is not accessible

make sure that you are using the same namespace as your pages

Android API 21 Toolbar Padding

Simpley add this two line in toolbar. Then we get new removed left side space bcoz by default it 16dp.

android:contentInsetStart="0dp"
app:contentInsetStart="0dp"

Plotting of 1-dimensional Gaussian distribution function

With the excellent matplotlib and numpy packages

from matplotlib import pyplot as mp
import numpy as np

def gaussian(x, mu, sig):
    return np.exp(-np.power(x - mu, 2.) / (2 * np.power(sig, 2.)))

x_values = np.linspace(-3, 3, 120)
for mu, sig in [(-1, 1), (0, 2), (2, 3)]:
    mp.plot(x_values, gaussian(x_values, mu, sig))

mp.show()

will produce something like plot showing one-dimensional gaussians produced by matplotlib

How can a LEFT OUTER JOIN return more records than exist in the left table?

It isn't impossible. The number of records in the left table is the minimum number of records it will return. If the right table has two records that match to one record in the left table, it will return two records.

Keyboard shortcut for Jump to Previous View Location (Navigate back/forward) in IntelliJ IDEA

For Ubuntu, Ctrl + Alt + Left and Ctrl + Alt + Right work fine.

By default these keys are assigned for Ubuntu's workspace navigation.

You need to disable that by going to :

System Settings > Keyboard > Shortcuts Tab > Navigation and disable Switch to workspace left and Switch to workspace right by pressing Backspace.

Or you can choose to change shortcuts in Intellij itself:

File > Settings > Keymap > Main menu > Navigate > Back/Forward

About catching ANY exception

To catch all possible exceptions, catch BaseException. It's on top of the Exception hierarchy:

Python 3: https://docs.python.org/3.9/library/exceptions.html#exception-hierarchy

Python 2.7: https://docs.python.org/2.7/library/exceptions.html#exception-hierarchy

try:
    something()
except BaseException as error:
    print('An exception occurred: {}'.format(error))

But as other people mentioned, you would usually not need this, only for specific cases.

Get Absolute Position of element within the window in wpf

I think what BrandonS wants is not the position of the mouse relative to the root element, but rather the position of some descendant element.

For that, there is the TransformToAncestor method:

Point relativePoint = myVisual.TransformToAncestor(rootVisual)
                              .Transform(new Point(0, 0));

Where myVisual is the element that was just double-clicked, and rootVisual is Application.Current.MainWindow or whatever you want the position relative to.

Send JSON data with jQuery

Because you haven't specified neither request content type, nor correct JSON request. Here's the correct way to send a JSON request:

var arr = { City: 'Moscow', Age: 25 };
$.ajax({
    url: 'Ajax.ashx',
    type: 'POST',
    data: JSON.stringify(arr),
    contentType: 'application/json; charset=utf-8',
    dataType: 'json',
    async: false,
    success: function(msg) {
        alert(msg);
    }
});

Things to notice:

  • Usage of the JSON.stringify method to convert a javascript object into a JSON string which is native and built-into modern browsers. If you want to support older browsers you might need to include json2.js
  • Specifying the request content type using the contentType property in order to indicate to the server the intent of sending a JSON request
  • The dataType: 'json' property is used for the response type you expect from the server. jQuery is intelligent enough to guess it from the server Content-Type response header. So if you have a web server which respects more or less the HTTP protocol and responds with Content-Type: application/json to your request jQuery will automatically parse the response into a javascript object into the success callback so that you don't need to specify the dataType property.

Things to be careful about:

  • What you call arr is not an array. It is a javascript object with properties (City and Age). Arrays are denoted with [] in javascript. For example [{ City: 'Moscow', Age: 25 }, { City: 'Paris', Age: 30 }] is an array of 2 objects.

Change the value in app.config file dynamically

You have to update your app.config file manually

// Load the app.config file
XmlDocument xml = new XmlDocument();
xml.Load(AppDomain.CurrentDomain.SetupInformation.ConfigurationFile);

// Do whatever you need, like modifying the appSettings section

// Save the new setting
xml.Save(AppDomain.CurrentDomain.SetupInformation.ConfigurationFile);

And then tell your application to reload any section you modified

ConfigurationManager.RefreshSection("appSettings");

Modify tick label text

I noticed that all the solutions posted here that use set_xticklabels() are not preserving the offset, which is a scaling factor applied to the ticks values to create better-looking tick labels. For instance, if the ticks are on the order of 0.00001 (1e-5), matplotlib will automatically add a scaling factor (or offset) of 1e-5, so the resultant tick labels may end up as 1 2 3 4, rather than 1e-5 2e-5 3e-5 4e-5.

Below gives an example:

The x array is np.array([1, 2, 3, 4])/1e6, and y is y=x**2. So both are very small values.

Left column: manually change the 1st and 3rd labels, as suggested by @Joe Kington. Note that the offset is lost.

Mid column: similar as @iipr suggested, using a FuncFormatter.

Right column: My suggested offset-preserving solution.

Figure here: enter image description here

Complete code here:

import matplotlib.pyplot as plt
import numpy as np

# create some *small* data to plot
x = np.arange(5)/1e6
y = x**2

fig, axes = plt.subplots(1, 3, figsize=(10,6))

#------------------The set_xticklabels() solution------------------
ax1 = axes[0]
ax1.plot(x, y)
fig.canvas.draw()
labels = [item.get_text() for item in ax1.get_xticklabels()]

# Modify specific labels
labels[1] = 'Testing'
labels[3] = 'Testing2'
ax1.set_xticklabels(labels)
ax1.set_title('set_xticklabels()')

#--------------FuncFormatter solution--------------
import matplotlib.ticker as mticker

def update_ticks(x, pos):
    if pos==1:
        return 'testing'
    elif pos==3:
        return 'testing2'
    else:
        return x

ax2=axes[1]
ax2.plot(x,y)
ax2.xaxis.set_major_formatter(mticker.FuncFormatter(update_ticks))
ax2.set_title('Func Formatter')

#-------------------My solution-------------------
def changeLabels(axis, pos, newlabels):
    '''Change specific x/y tick labels

    Args:
        axis (Axis): .xaxis or .yaxis obj.
        pos (list): indices for labels to change.
        newlabels (list): new labels corresponding to indices in <pos>.
    '''

    if len(pos) != len(newlabels):
        raise Exception("Length of <pos> doesn't equal that of <newlabels>.")

    ticks = axis.get_majorticklocs()
    # get the default tick formatter
    formatter = axis.get_major_formatter()
    # format the ticks into strings
    labels = formatter.format_ticks(ticks)

    # Modify specific labels
    for pii, lii in zip(pos, newlabels):
        labels[pii] = lii

    # Update the ticks and ticklabels. Order is important here.
    # Need to first get the offset (1e-6 in this case):
    offset = formatter.get_offset()
    # Then set the modified labels:
    axis.set_ticklabels(labels)
    # In doing so, matplotlib creates a new FixedFormatter and sets it to the xaxis
    # and the new FixedFormatter has no offset. So we need to query the
    # formatter again and re-assign the offset:
    axis.get_major_formatter().set_offset_string(offset)

    return

ax3 = axes[2]
ax3.plot(x, y)

changeLabels(ax3.xaxis, [1, 3], ['Testing', 'Testing2'])
ax3.set_title('With offset')

fig.show()
plt.savefig('tick_labels.png')

Caveat: it appears that solutions that use set_xticklabels(), including my own, relies on FixedFormatter, which is static and doesn't respond to figure resizing. To observe the effect, change the figure to a smaller size, e.g. fig, axes = plt.subplots(1, 3, figsize=(6,6)) and enlarge the figure window. You will notice that that only the mid column responds to resizing and adds more ticks as the figure gets larger. The left and right column will have empty tick labels (see figure below).

Caveat 2: I also noticed that if your tick values are floats, calling set_xticklabels(ticks) directly might give you ugly-looking strings, like 1.499999999998 instead of 1.5.

enter image description here

Add CSS or JavaScript files to layout head from views or partial views

I had a similar problem, and ended up applying Kalman's excellent answer with the code below (not quite as neat, but arguably more expansible):

namespace MvcHtmlHelpers
{
    //http://stackoverflow.com/questions/5110028/add-css-or-js-files-to-layout-head-from-views-or-partial-views#5148224
    public static partial class HtmlExtensions
    {
        public static AssetsHelper Assets(this HtmlHelper htmlHelper)
        {
            return AssetsHelper.GetInstance(htmlHelper);
        }
    }
    public enum BrowserType { Ie6=1,Ie7=2,Ie8=4,IeLegacy=7,W3cCompliant=8,All=15}
    public class AssetsHelper
    {
        public static AssetsHelper GetInstance(HtmlHelper htmlHelper)
        {
            var instanceKey = "AssetsHelperInstance";
            var context = htmlHelper.ViewContext.HttpContext;
            if (context == null) {return null;}
            var assetsHelper = (AssetsHelper)context.Items[instanceKey];
            if (assetsHelper == null){context.Items.Add(instanceKey, assetsHelper = new AssetsHelper(htmlHelper));}
            return assetsHelper;
        }
        private readonly List<string> _styleRefs = new List<string>();
        public AssetsHelper AddStyle(string stylesheet)
        {
            _styleRefs.Add(stylesheet);
            return this;
        }
        private readonly List<string> _scriptRefs = new List<string>();
        public AssetsHelper AddScript(string scriptfile)
        {
            _scriptRefs.Add(scriptfile);
            return this;
        }
        public IHtmlString RenderStyles()
        {
            ItemRegistrar styles = new ItemRegistrar(ItemRegistrarFormatters.StyleFormat,_urlHelper);
            styles.Add(Libraries.UsedStyles());
            styles.Add(_styleRefs);
            return styles.Render();
        }
        public IHtmlString RenderScripts()
        {
            ItemRegistrar scripts = new ItemRegistrar(ItemRegistrarFormatters.ScriptFormat, _urlHelper);
            scripts.Add(Libraries.UsedScripts());
            scripts.Add(_scriptRefs);
            return scripts.Render();
        }
        public LibraryRegistrar Libraries { get; private set; }
        private UrlHelper _urlHelper;
        public AssetsHelper(HtmlHelper htmlHelper)
        {
            _urlHelper = new UrlHelper(htmlHelper.ViewContext.RequestContext);
            Libraries = new LibraryRegistrar();
        }
    }
    public class LibraryRegistrar
    {
        public class Component
        {
            internal class HtmlReference
            {
                internal string Url { get; set; }
                internal BrowserType ServeTo { get; set; }
            }
            internal List<HtmlReference> Styles { get; private set; }
            internal List<HtmlReference> Scripts { get; private set; }
            internal List<string> RequiredLibraries { get; private set; }

            public Component()
            {
                Styles = new List<HtmlReference>();
                Scripts = new List<HtmlReference>();
                RequiredLibraries = new List<string>();
            }
            public Component Requires(params string[] libraryNames)
            {
                foreach (var lib in libraryNames)
                {
                    if (!RequiredLibraries.Contains(lib))
                        { RequiredLibraries.Add(lib); }
                }
                return this;
            }
            public Component AddStyle(string url, BrowserType serveTo = BrowserType.All)
            {
                Styles.Add(new HtmlReference { Url = url, ServeTo=serveTo });
                return this;
            }
            public Component AddScript(string url, BrowserType serveTo = BrowserType.All)
            {
                Scripts.Add(new HtmlReference { Url = url, ServeTo = serveTo });
                return this;
            }
        }
        private readonly Dictionary<string, Component> _allLibraries = new Dictionary<string, Component>();
        private List<string> _usedLibraries = new List<string>();
        internal IEnumerable<string> UsedScripts()
        {
            SetOrder();
            var returnVal = new List<string>();
            foreach (var key in _usedLibraries)
            {
                returnVal.AddRange(from s in _allLibraries[key].Scripts
                                   where IncludesCurrentBrowser(s.ServeTo)
                                   select s.Url);
            }
            return returnVal;
        }
        internal IEnumerable<string> UsedStyles()
        {
            SetOrder();
            var returnVal = new List<string>();
            foreach (var key in _usedLibraries)
            {
                returnVal.AddRange(from s in _allLibraries[key].Styles
                                   where IncludesCurrentBrowser(s.ServeTo)
                                   select s.Url);
            }
            return returnVal;
        }
        public void Uses(params string[] libraryNames)
        {
            foreach (var name in libraryNames)
            {
                if (!_usedLibraries.Contains(name)){_usedLibraries.Add(name);}
            }
        }
        public bool IsUsing(string libraryName)
        {
            SetOrder();
            return _usedLibraries.Contains(libraryName);
        }
        private List<string> WalkLibraryTree(List<string> libraryNames)
        {
            var returnList = new List<string>(libraryNames);
            int counter = 0;
            foreach (string libraryName in libraryNames)
            {
                WalkLibraryTree(libraryName, ref returnList, ref counter);
            }
            return returnList;
        }
        private void WalkLibraryTree(string libraryName, ref List<string> libBuild, ref int counter)
        {
            if (counter++ > 1000) { throw new System.Exception("Dependancy library appears to be in infinate loop - please check for circular reference"); }
            Component library;
            if (!_allLibraries.TryGetValue(libraryName, out library))
                { throw new KeyNotFoundException("Cannot find a definition for the required style/script library named: " + libraryName); }
            foreach (var childLibraryName in library.RequiredLibraries)
            {
                int childIndex = libBuild.IndexOf(childLibraryName);
                if (childIndex!=-1)
                {
                    //child already exists, so move parent to position before child if it isn't before already
                    int parentIndex = libBuild.LastIndexOf(libraryName);
                    if (parentIndex>childIndex)
                    {
                        libBuild.RemoveAt(parentIndex);
                        libBuild.Insert(childIndex, libraryName);
                    }
                }
                else
                {
                    libBuild.Add(childLibraryName);
                    WalkLibraryTree(childLibraryName, ref libBuild, ref counter);
                }
            }
            return;
        }
        private bool _dependenciesExpanded;
        private void SetOrder()
        {
            if (_dependenciesExpanded){return;}
            _usedLibraries = WalkLibraryTree(_usedLibraries);
            _usedLibraries.Reverse();
            _dependenciesExpanded = true;
        }
        public Component this[string index]
        {
            get
            {
                if (_allLibraries.ContainsKey(index))
                    { return _allLibraries[index]; }
                var newComponent = new Component();
                _allLibraries.Add(index, newComponent);
                return newComponent;
            }
        }
        private BrowserType _requestingBrowser;
        private BrowserType RequestingBrowser
        {
            get
            {
                if (_requestingBrowser == 0)
                {
                    var browser = HttpContext.Current.Request.Browser.Type;
                    if (browser.Length > 2 && browser.Substring(0, 2) == "IE")
                    {
                        switch (browser[2])
                        {
                            case '6':
                                _requestingBrowser = BrowserType.Ie6;
                                break;
                            case '7':
                                _requestingBrowser = BrowserType.Ie7;
                                break;
                            case '8':
                                _requestingBrowser = BrowserType.Ie8;
                                break;
                            default:
                                _requestingBrowser = BrowserType.W3cCompliant;
                                break;
                        }
                    }
                    else
                    {
                        _requestingBrowser = BrowserType.W3cCompliant;
                    }
                }
                return _requestingBrowser;
            }
        }
        private bool IncludesCurrentBrowser(BrowserType browserType)
        {
            if (browserType == BrowserType.All) { return true; }
            return (browserType & RequestingBrowser) != 0;
        }
    }
    public class ItemRegistrar
    {
        private readonly string _format;
        private readonly List<string> _items;
        private readonly UrlHelper _urlHelper;

        public ItemRegistrar(string format, UrlHelper urlHelper)
        {
            _format = format;
            _items = new List<string>();
            _urlHelper = urlHelper;
        }
        internal void Add(IEnumerable<string> urls)
        {
            foreach (string url in urls)
            {
                Add(url);
            }
        }
        public ItemRegistrar Add(string url)
        {
            url = _urlHelper.Content(url);
            if (!_items.Contains(url))
                { _items.Add( url); }
            return this;
        }
        public IHtmlString Render()
        {
            var sb = new StringBuilder();
            foreach (var item in _items)
            {
                var fmt = string.Format(_format, item);
                sb.AppendLine(fmt);
            }
            return new HtmlString(sb.ToString());
        }
    }
    public class ItemRegistrarFormatters
    {
        public const string StyleFormat = "<link href=\"{0}\" rel=\"stylesheet\" type=\"text/css\" />";
        public const string ScriptFormat = "<script src=\"{0}\" type=\"text/javascript\"></script>";
    }
}

The project contains a static AssignAllResources method:

assets.Libraries["jQuery"]
        .AddScript("~/Scripts/jquery-1.10.0.min.js", BrowserType.IeLegacy)
        .AddScript("~/Scripts//jquery-2.0.1.min.js",BrowserType.W3cCompliant);
        /* NOT HOSTED YET - CHECK SOON 
        .AddScript("//ajax.googleapis.com/ajax/libs/jquery/2.0.1/jquery.min.js",BrowserType.W3cCompliant);
        */
    assets.Libraries["jQueryUI"].Requires("jQuery")
        .AddScript("//ajax.googleapis.com/ajax/libs/jqueryui/1.9.2/jquery-ui.min.js",BrowserType.Ie6)
        .AddStyle("//ajax.aspnetcdn.com/ajax/jquery.ui/1.9.2/themes/eggplant/jquery-ui.css",BrowserType.Ie6)
        .AddScript("//ajax.googleapis.com/ajax/libs/jqueryui/1.10.3/jquery-ui.min.js", ~BrowserType.Ie6)
        .AddStyle("//ajax.aspnetcdn.com/ajax/jquery.ui/1.10.3/themes/eggplant/jquery-ui.css", ~BrowserType.Ie6);
    assets.Libraries["TimePicker"].Requires("jQueryUI")
        .AddScript("~/Scripts/jquery-ui-sliderAccess.min.js")
        .AddScript("~/Scripts/jquery-ui-timepicker-addon-1.3.min.js")
        .AddStyle("~/Content/jQueryUI/jquery-ui-timepicker-addon.css");
    assets.Libraries["Validation"].Requires("jQuery")
        .AddScript("//ajax.aspnetcdn.com/ajax/jquery.validate/1.11.1/jquery.validate.min.js")
        .AddScript("~/Scripts/jquery.validate.unobtrusive.min.js")
        .AddScript("~/Scripts/mvcfoolproof.unobtrusive.min.js")
        .AddScript("~/Scripts/CustomClientValidation-1.0.0.min.js");
    assets.Libraries["MyUtilityScripts"].Requires("jQuery")
        .AddScript("~/Scripts/GeneralOnLoad-1.0.0.min.js");
    assets.Libraries["FormTools"].Requires("Validation", "MyUtilityScripts");
    assets.Libraries["AjaxFormTools"].Requires("FormTools", "jQueryUI")
        .AddScript("~/Scripts/jquery.unobtrusive-ajax.min.js");
    assets.Libraries["DataTables"].Requires("MyUtilityScripts")
        .AddScript("//ajax.aspnetcdn.com/ajax/jquery.dataTables/1.9.4/jquery.dataTables.min.js")
        .AddStyle("//ajax.aspnetcdn.com/ajax/jquery.dataTables/1.9.4/css/jquery.dataTables.css")
        .AddStyle("//ajax.aspnetcdn.com/ajax/jquery.dataTables/1.9.4/css/jquery.dataTables_themeroller.css");
    assets.Libraries["MvcDataTables"].Requires("DataTables", "jQueryUI")
        .AddScript("~/Scripts/jquery.dataTables.columnFilter.min.js");
    assets.Libraries["DummyData"].Requires("MyUtilityScripts")
        .AddScript("~/Scripts/DummyData.js")
        .AddStyle("~/Content/DummyData.css");     

in the _layout page

@{
    var assets = Html.Assets();
    CurrentResources.AssignAllResources(assets);
    Html.Assets().RenderStyles()
}
</head>
...
    @Html.Assets().RenderScripts()
</body>

and in the partial(s) and views

Html.Assets().Libraries.Uses("DataTables");
Html.Assets().AddScript("~/Scripts/emailGridUtilities.js");

Can typescript export a function?

To answer the title of your question directly because this comes up in Google first:

YES, TypeScript can export a function!

Here is a direct quote from the TS Documentation:

"Any declaration (such as a variable, function, class, type alias, or interface) can be exported by adding the export keyword."

Reference Link

Difference between @Before, @BeforeClass, @BeforeEach and @BeforeAll

The code marked @Before is executed before each test, while @BeforeClass runs once before the entire test fixture. If your test class has ten tests, @Before code will be executed ten times, but @BeforeClass will be executed only once.

In general, you use @BeforeClass when multiple tests need to share the same computationally expensive setup code. Establishing a database connection falls into this category. You can move code from @BeforeClass into @Before, but your test run may take longer. Note that the code marked @BeforeClass is run as static initializer, therefore it will run before the class instance of your test fixture is created.

In JUnit 5, the tags @BeforeEach and @BeforeAll are the equivalents of @Before and @BeforeClass in JUnit 4. Their names are a bit more indicative of when they run, loosely interpreted: 'before each tests' and 'once before all tests'.

What is the best way to implement constants in Java?

What is the difference

1.

public interface MyGlobalConstants {
    public static final int TIMEOUT_IN_SECS = 25;
}

2.

public class MyGlobalConstants {
    private MyGlobalConstants () {} // Prevents instantiation
    public static final int TIMEOUT_IN_SECS = 25;
}

and using MyGlobalConstants.TIMEOUT_IN_SECS wherever we need this constant. I think both are same.

what is reverse() in Django

The reverse() is used to adhere the django DRY principle i.e if you change the url in future then you can reference that url using reverse(urlname).

Powershell: Get FQDN Hostname

I have the following add.. I need to separate out the dns suffix from the hostname.. and I only "know" the servers alias shortname... and want to know what the dns suffix is

#example:
#serveralias:     MyAppServer.us.fred.com
#actualhostname:  server01.us.fred.com 
#I "know":        "MyAppServer" .. I pass this on as an env var called myjumpbox .. this could also be $env:computername


$forname                 = $env:myjumpbox
$fqdn                    = [System.Net.Dns]::GetHostByName($forname).Hostname
$shortname               = $fqdn.split('.')[0]
$domainname              = $fqdn -split $fqdn.split('.')[0]+"."
$dnssuf                  = $domainname[1]  
" name parts are- alias: " + $forname + " actual hostname: " + $shortname + " suffix: " + $dnssuf

#returns

name parts are- alias: MyAppServer actual hostname: server01 suffix: us.fred.com

How to put two divs on the same line with CSS in simple_form in rails?

why not use flexbox ? so wrap them into another div like that

_x000D_
_x000D_
.flexContainer { _x000D_
   _x000D_
  margin: 2px 10px;_x000D_
  display: flex;_x000D_
} _x000D_
_x000D_
.left {_x000D_
  flex-basis : 30%;_x000D_
}_x000D_
_x000D_
.right {_x000D_
  flex-basis : 30%;_x000D_
}
_x000D_
<form id="new_production" class="simple_form new_production" novalidate="novalidate" method="post" action="/projects/1/productions" accept-charset="UTF-8">_x000D_
    <div style="margin:0;padding:0;display:inline">_x000D_
        <input type="hidden" value="?" name="utf8">_x000D_
        <input type="hidden" value="2UQCUU+tKiKKtEiDtLLNeDrfBDoHTUmz5Sl9+JRVjALat3hFM=" name="authenticity_token">_x000D_
    </div>_x000D_
    <div class="flexContainer">_x000D_
      <div class="left">Proj Name:</div>_x000D_
      <div class="right">must have a name</div>_x000D_
    </div>_x000D_
    <div class="input string required"> </div>_x000D_
 </form>
_x000D_
_x000D_
_x000D_

feel free to play with flex-basis percentage to get more customized space.

how to check if List<T> element contains an item with a Particular Property Value

var item = pricePublicList.FirstOrDefault(x => x.Size == 200);
if (item != null) {
   // There exists one with size 200 and is stored in item now
}
else {
  // There is no PricePublicModel with size 200
}

Property 'catch' does not exist on type 'Observable<any>'

With RxJS 5.5+, the catch operator is now deprecated. You should now use the catchError operator in conjunction with pipe.

RxJS v5.5.2 is the default dependency version for Angular 5.

For each RxJS Operator you import, including catchError you should now import from 'rxjs/operators' and use the pipe operator.

Example of catching error for an Http request Observable

import { Observable } from 'rxjs';
import { catchError } from 'rxjs/operators';
...

export class ExampleClass {
  constructor(private http: HttpClient) {
    this.http.request(method, url, options).pipe(
      catchError((err: HttpErrorResponse) => {
        ...
      }
    )
  }
  ...
}

Notice here that catch is replaced with catchError and the pipe operator is used to compose the operators in similar manner to what you're used to with dot-chaining.


See the rxjs documentation on pipable (previously known as lettable) operators for more info.

Get underlined text with Markdown

In GitHub markdown <ins>text</ins>works just fine.

pros and cons between os.path.exists vs os.path.isdir

Most of the time, it is the same.

But, path can exist physically whereas path.exists() returns False. This is the case if os.stat() returns False for this file.

If path exists physically, then path.isdir() will always return True. This does not depend on platform.

How to escape JSON string?

String.Format("X", c);

That just outputs: X

Try this instead:

string t = ((int)c).ToString("X");

sb.Append("\\u" + t.PadLeft(4, '0'));

Java : Accessing a class within a package, which is the better way?

They're equivalent. The access is the same.

The import is just a convention to save you from having to type the fully-resolved class name each time. You can write all your Java without using import, as long as you're a fast touch typer.

But there's no difference in efficiency or class loading.

How to open a second activity on click of button in android app

Button btn = (Button) findViewById(R.id.button1);

btn.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        Intent myIntent = new Intent(MainActivity.this, MainActivity2.class);
        MainActivity.this.startActivity(myIntent);       
    }  
});

The answer for the complete noob from a complete noob: MainActivity is the name of the first activity. MainActivity2 is the name of the second activity. button1 is the I.D of the button in xml for MainActivity Activity.

DELETE_FAILED_INTERNAL_ERROR Error while Installing APK

If Emulator is opened, please close it.

And Restart the android studio.It worked for me.

Give a try.

Log4Net configuring log level

Within the definition of the appender, I believe you can do something like this:

<appender name="AdoNetAppender" type="log4net.Appender.AdoNetAppender">
    <filter type="log4net.Filter.LevelRangeFilter">
        <param name="LevelMin" value="INFO"/>
        <param name="LevelMax" value="INFO"/>
    </filter>
    ...
</appender>

Error: Selection does not contain a main type

I had this happen repeatedly after adding images to a project in Eclipse and making them part of the build path. The solution was to right-click on the class containing the main method, and then choose Run As -> Java Application. It seems that when you add a file to the build path, Eclipse automatically assumes that file is where the main method is. By going through the Run As menu instead of just clicking the green Run As button, it allows you to specify the correct entry-point.

Create multiple threads and wait all of them to complete

I've made a very simple extension method to wait for all threads of a collection:

using System.Collections.Generic;
using System.Threading;

namespace Extensions
{
    public static class ThreadExtension
    {
        public static void WaitAll(this IEnumerable<Thread> threads)
        {
            if(threads!=null)
            {
                foreach(Thread thread in threads)
                { thread.Join(); }
            }
        }
    }
}

Then you simply call:

List<Thread> threads=new List<Thread>();
// Add your threads to this collection
threads.WaitAll();

Named capturing groups in JavaScript regex?

ECMAScript 2018 introduces named capturing groups into JavaScript regexes.

Example:

  const auth = 'Bearer AUTHORIZATION_TOKEN'
  const { groups: { token } } = /Bearer (?<token>[^ $]*)/.exec(auth)
  console.log(token) // "Prints AUTHORIZATION_TOKEN"

If you need to support older browsers, you can do everything with normal (numbered) capturing groups that you can do with named capturing groups, you just need to keep track of the numbers - which may be cumbersome if the order of capturing group in your regex changes.

There are only two "structural" advantages of named capturing groups I can think of:

  1. In some regex flavors (.NET and JGSoft, as far as I know), you can use the same name for different groups in your regex (see here for an example where this matters). But most regex flavors do not support this functionality anyway.

  2. If you need to refer to numbered capturing groups in a situation where they are surrounded by digits, you can get a problem. Let's say you want to add a zero to a digit and therefore want to replace (\d) with $10. In JavaScript, this will work (as long as you have fewer than 10 capturing group in your regex), but Perl will think you're looking for backreference number 10 instead of number 1, followed by a 0. In Perl, you can use ${1}0 in this case.

Other than that, named capturing groups are just "syntactic sugar". It helps to use capturing groups only when you really need them and to use non-capturing groups (?:...) in all other circumstances.

The bigger problem (in my opinion) with JavaScript is that it does not support verbose regexes which would make the creation of readable, complex regular expressions a lot easier.

Steve Levithan's XRegExp library solves these problems.

What's the best way to center your HTML email content in the browser window (or email client preview pane)?

Align the table to center.

<table width="100%" border="0" cellspacing="0" cellpadding="0">
    <tr>
        <td align="center">
            Your Content
        </td>
    </tr>
</table>

Where you have "your content" if it is a table, set it to the desired width and you will have centred content.

ExpressJS - throw er Unhandled error event

This worked for me.

http://www.codingdefined.com/2015/09/how-to-solve-nodejs-error-listen.html

Just change the port number from the Project properties.

Adb over wireless without usb cable at all for not rooted phones

This might help:

If the adb connection is ever lost:

Make sure that your host is still connected to the same Wi-Fi network your Android device is. Reconnect by executing the "adb connect IP" step. (IP is obviously different when you change location.) Or if that doesn't work, reset your adb host: adb kill-server and then start over from the beginning.

Save multiple sheets to .pdf

In Excel 2013 simply select multiple sheets and do a "Save As" and select PDF as the file type. The multiple pages will open in PDF when you click save.

Finding child element of parent pure javascript

If you already have var parent = document.querySelector('.parent'); you can do this to scope the search to parent's children:

parent.querySelector('.child')

linux find regex

Well, you may try this '.*[0-9]'

Selecting multiple columns with linq query and lambda expression

You can use:

public YourClass[] AllProducts()
{
    try
    {
        using (UserDataDataContext db = new UserDataDataContext())
        {
            return db.mrobProducts.Where(x => x.Status == 1)
                           .OrderBy(x => x.ID)
                           .Select(x => new YourClass { ID = x.ID, Name = x.Name, Price = x.Price})
                           .ToArray();
        }
    }
    catch
    {
        return null;
    }
}

And here is YourClass implementation:

public class YourClass
{
  public string Name {get; set;}
  public int ID {get; set;}
  public int Price {get; set;}
}

And your AllProducts method's return type must be YourClass[].

<button> background image

Try changing your CSS to this

button #rock {
    background: url('img/rock.png') no-repeat;
}

...provided that the image is in that place

How do you run `apt-get` in a dockerfile behind a proxy?

and If you want to set proxy for wget you should put these line in your Dockerfile

ENV http_proxy YOUR-PROXY-IP:PORT/
ENV https_proxy YOUR-PROXY-IP:PORT/
ENV all_proxy YOUR-PROXY-IP:PORT/

How do I get a file's directory using the File object?

File API File.getParent or File.getParentFile should return you Directory of file.

Your code should be like :

    File file = new File("c:\\temp\\java\\testfile");
    if(!file.exists()){
        file = file.getParentFile();
    }

You can additionally check your parent file is directory using File.isDirectory API

if(file.isDirectory()){
    System.out.println("file is directory ");
}

How do I unload (reload) a Python module?

It can be especially difficult to delete a module if it is not pure Python.

Here is some information from: How do I really delete an imported module?

You can use sys.getrefcount() to find out the actual number of references.

>>> import sys, empty, os
>>> sys.getrefcount(sys)
9
>>> sys.getrefcount(os)
6
>>> sys.getrefcount(empty)
3

Numbers greater than 3 indicate that it will be hard to get rid of the module. The homegrown "empty" (containing nothing) module should be garbage collected after

>>> del sys.modules["empty"]
>>> del empty

as the third reference is an artifact of the getrefcount() function.

Javascript: Extend a Function

Another option could be:

var initial = function() {
    console.log( 'initial function!' );
}

var iWantToExecuteThisOneToo = function () {
    console.log( 'the other function that i wanted to execute!' );
}

function extendFunction( oldOne, newOne ) {
    return (function() {
        oldOne();
        newOne();
    })();
}

var extendedFunction = extendFunction( initial, iWantToExecuteThisOneToo );

Generate MD5 hash string with T-SQL

For data up to 8000 characters use:

CONVERT(VARCHAR(32), HashBytes('MD5', '[email protected]'), 2)

Demo

For binary data (without the limit of 8000 bytes) use:

CONVERT(VARCHAR(32), master.sys.fn_repl_hash_binary(@binary_data), 2)

Demo

How can I sort a dictionary by key?

I come up with single line dict sorting.

>> a = {2:3, 1:89, 4:5, 3:0}
>> c = {i:a[i] for i in sorted(a.keys())}
>> print(c)
{1: 89, 2: 3, 3: 0, 4: 5}
[Finished in 0.4s]

Hope this will be helpful.

Query for documents where array size is greater than 1

I know its old question, but I am trying this with $gte and $size in find. I think to find() is faster.

db.getCollection('collectionName').find({ name : { $gte : {  $size : 1 } }})

Head and tail in one line

Building on the Python 2 solution from @GarethLatty, the following is a way to get a single line equivalent without intermediate variables in Python 2.

t=iter([1, 1, 2, 3, 5, 8, 13, 21, 34, 55]);h,t = [(h,list(t)) for h in t][0]

If you need it to be exception-proof (i.e. supporting empty list), then add:

t=iter([]);h,t = ([(h,list(t)) for h in t]+[(None,[])])[0]

If you want to do it without the semicolon, use:

h,t = ([(h,list(t)) for t in [iter([1,2,3,4])] for h in t]+[(None,[])])[0]

How can I undo a mysql statement that I just executed?

Basically: If you're doing a transaction just do a rollback. Otherwise, you can't "undo" a MySQL query.

Understanding lambda in python and using it to pass multiple arguments

Why do you need to state both 'x' and 'y' before the ':'?

You could actually in some situations(when you have only one argument) do not put the x and y before ":".

>>> flist = []
>>> for i in range(3):
...     flist.append(lambda : i)

but the i in the lambda will be bound by name, so,

>>> flist[0]()
2
>>> flist[2]()
2
>>>

different from what you may want.

Spring boot: Unable to start embedded Tomcat servlet container

For me, I just had to put a -X flag with mvn. Look at the debug log; there was an issue with Spring while locating the .properties file.

Can we rely on String.isEmpty for checking null condition on a String in Java?

String s1=""; // empty string assigned to s1 , s1 has length 0, it holds a value of no length string

String s2=null; // absolutely nothing, it holds no value, you are not assigning any value to s2

so null is not the same as empty.

hope that helps!!!

Monitoring the Full Disclosure mailinglist

Two generic ways to do the same thing... I'm not aware of any specific open solutions to do this, but it'd be rather trivial to do.

You could write a daily or weekly cron/jenkins job to scrape the previous time period's email from the archive looking for your keyworkds/combinations. Sending a batch digest with what it finds, if anything.

But personally, I'd Setup a specific email account to subscribe to the various security lists you're interested in. Add a simple automated script to parse the new emails for various keywords or combinations of keywords, when it finds a match forward that email on to you/your team. Just be sure to keep the keywords list updated with new products you're using.

You could even do this with a gmail account and custom rules, which is what I currently do, but I have setup an internal inbox in the past with a simple python script to forward emails that were of interest.

Run bash command on jenkins pipeline

I'm sure that the above answers work perfectly. However, I had the difficulty of adding the double quotes as my bash lines where closer to 100. So, the following way helped me. (In a nutshell, no double quotes around each line of the shell)

Also, when I had "bash '''#!/bin/bash" within steps, I got the following error java.lang.NoSuchMethodError: No such DSL method '**bash**' found among steps

pipeline {
    agent none

    stages {

        stage ('Hello') {
            agent any

            steps {
                echo 'Hello, '

                sh '''#!/bin/bash

                    echo "Hello from bash"
                    echo "Who I'm $SHELL"
                '''
            }
        }
    }
}

The result of the above execution is

enter image description here

Better way to convert file sizes in Python

Here's a version that matches the output of ls -lh.

def human_size(num: int) -> str:
    base = 1
    for unit in ['B', 'K', 'M', 'G', 'T', 'P', 'E', 'Z', 'Y']:
        n = num / base
        if n < 9.95 and unit != 'B':
            # Less than 10 then keep 1 decimal place
            value = "{:.1f}{}".format(n, unit)
            return value
        if round(n) < 1000:
            # Less than 4 digits so use this
            value = "{}{}".format(round(n), unit)
            return value
        base *= 1024
    value = "{}{}".format(round(n), unit)
    return value

How can I convert a hex string to a byte array?

I did some research and found out that byte.Parse is even slower than Convert.ToByte. The fastest conversion I could come up with uses approximately 15 ticks per byte.

    public static byte[] StringToByteArrayFastest(string hex) {
        if (hex.Length % 2 == 1)
            throw new Exception("The binary key cannot have an odd number of digits");

        byte[] arr = new byte[hex.Length >> 1];

        for (int i = 0; i < hex.Length >> 1; ++i)
        {
            arr[i] = (byte)((GetHexVal(hex[i << 1]) << 4) + (GetHexVal(hex[(i << 1) + 1])));
        }

        return arr;
    }

    public static int GetHexVal(char hex) {
        int val = (int)hex;
        //For uppercase A-F letters:
        //return val - (val < 58 ? 48 : 55);
        //For lowercase a-f letters:
        //return val - (val < 58 ? 48 : 87);
        //Or the two combined, but a bit slower:
        return val - (val < 58 ? 48 : (val < 97 ? 55 : 87));
    }

// also works on .NET Micro Framework where (in SDK4.3) byte.Parse(string) only permits integer formats.

How do I debug error ECONNRESET in Node.js?

I just figured this out, at least in my use case.

I was getting ECONNRESET. It turned out that the way my client was set up, it was hitting the server with an API call a ton of times really quickly -- and it only needed to hit the endpoint once.

When I fixed that, the error was gone.

SQL Inner join more than two tables

select WucsName as WUCS_Name,Year,Tot_Households,Tot_Households,Tot_Male_Farmers  from tbl_Gender
INNER JOIN tblWUCS
ON tbl_Gender.WUCS_id =tblWUCS .WucsId 
INNER JOIN tblYear
ON tbl_Gender.YearID=tblYear.yearID

There are 3 Tables 1. tbl_Gender 2. tblWUCS 3. tblYear

Adding a simple UIAlertView

As a supplementary to the two previous answers (of user "sudo rm -rf" and "Evan Mulawski"), if you don't want to do anything when your alert view is clicked, you can just allocate, show and release it. You don't have to declare the delegate protocol.

How to add url parameter to the current url?

In case you want to add the URL parameter in JavaScript, see this answer. As suggested there, you can use the URLSeachParams API in modern browsers as follows:

<script>
function addUrlParameter(name, value) {
  var searchParams = new URLSearchParams(window.location.search)
  searchParams.set(name, value)
  window.location.search = searchParams.toString()
}
</script>

<body>
...
  <a onclick="addUrlParameter('like', 'like')">Like this page</a>
...
</body>

Remove padding from columns in Bootstrap 3

Wrap your columns in a .row and add to that div a class called "no-gutter"

<div class="container">
  <div class="row no-gutter">
    <h2>OntoExplorer<span style="color:#b92429">.</span></h2>

    <div class="col-md-4">
        <div class="widget">
            <div class="widget-header">
                <h3>Dimensions</h3>
            </div>
            <div class="widget-content">
            </div>
        </div>
    </div>

    <div class="col-md-8">
        <div class="widget">
            <div class="widget-header">
                <h3>Results</h3>
            </div>
            <div class="widget-content">
            </div>
        </div>
    </div>
</div>

Then paste below contents to your CSS file

.row.no-gutter {
  margin-left: 0;
  margin-right: 0;
}

.row.no-gutter [class*='col-']:not(:first-child),
.row.no-gutter [class*='col-']:not(:last-child) {
  padding-right: 0;
  padding-left: 0;
}

how to use XPath with XDocument?

you can use the example from Microsoft - for you without namespace:

using System.Xml.Linq;
using System.Xml.XPath;
var e = xdoc.XPathSelectElement("./Report/ReportInfo/Name");     

should do it

How can the Euclidean distance be calculated with NumPy?

import math

dist = math.hypot(math.hypot(xa-xb, ya-yb), za-zb)

Java array reflection: isArray vs. instanceof

In the latter case, if obj is null you won't get a NullPointerException but a false.

Add Auto-Increment ID to existing table?

ALTER TABLE users CHANGE id int( 30 ) NOT NULL AUTO_INCREMENT

the integer parameter is based on my default sql setting have a nice day

'module' object has no attribute 'DataFrame'

I have faced similar problem, 'int' object has no attribute 'DataFrame',

This was because i have mistakenly used pd as a variable in my code and assigned an integer to it, while using the same pd as my pandas dataframe object by declaring - import pandas as pd.

I realized this, and changed my variable to something else, and fixed the error.

How to unescape a Java string literal in Java?

I came across the same problem, but I wasn't enamoured by any of the solutions I found here. So, I wrote one that iterates over the characters of the string using a matcher to find and replace the escape sequences. This solution assumes properly formatted input. That is, it happily skips over nonsensical escapes, and it decodes Unicode escapes for line feed and carriage return (which otherwise cannot appear in a character literal or a string literal, due to the definition of such literals and the order of translation phases for Java source). Apologies, the code is a bit packed for brevity.

import java.util.Arrays;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Decoder {

    // The encoded character of each character escape.
    // This array functions as the keys of a sorted map, from encoded characters to decoded characters.
    static final char[] ENCODED_ESCAPES = { '\"', '\'', '\\',  'b',  'f',  'n',  'r',  't' };

    // The decoded character of each character escape.
    // This array functions as the values of a sorted map, from encoded characters to decoded characters.
    static final char[] DECODED_ESCAPES = { '\"', '\'', '\\', '\b', '\f', '\n', '\r', '\t' };

    // A pattern that matches an escape.
    // What follows the escape indicator is captured by group 1=character 2=octal 3=Unicode.
    static final Pattern PATTERN = Pattern.compile("\\\\(?:(b|t|n|f|r|\\\"|\\\'|\\\\)|((?:[0-3]?[0-7])?[0-7])|u+(\\p{XDigit}{4}))");

    public static CharSequence decodeString(CharSequence encodedString) {
        Matcher matcher = PATTERN.matcher(encodedString);
        StringBuffer decodedString = new StringBuffer();
        // Find each escape of the encoded string in succession.
        while (matcher.find()) {
            char ch;
            if (matcher.start(1) >= 0) {
                // Decode a character escape.
                ch = DECODED_ESCAPES[Arrays.binarySearch(ENCODED_ESCAPES, matcher.group(1).charAt(0))];
            } else if (matcher.start(2) >= 0) {
                // Decode an octal escape.
                ch = (char)(Integer.parseInt(matcher.group(2), 8));
            } else /* if (matcher.start(3) >= 0) */ {
                // Decode a Unicode escape.
                ch = (char)(Integer.parseInt(matcher.group(3), 16));
            }
            // Replace the escape with the decoded character.
            matcher.appendReplacement(decodedString, Matcher.quoteReplacement(String.valueOf(ch)));
        }
        // Append the remainder of the encoded string to the decoded string.
        // The remainder is the longest suffix of the encoded string such that the suffix contains no escapes.
        matcher.appendTail(decodedString);
        return decodedString;
    }

    public static void main(String... args) {
        System.out.println(decodeString(args[0]));
    }
}

I should note that Apache Commons Lang3 doesn't seem to suffer the weaknesses indicated in the accepted solution. That is, StringEscapeUtils seems to handle octal escapes and multiple u characters of Unicode escapes. That means unless you have some burning reason to avoid Apache Commons, you should probably use it rather than my solution (or any other solution here).

Git merge two local branches

If you or another dev will not work on branchB further, I think it's better to keep commits in order to make reverts without headaches. So ;

git checkout branchA
git pull --rebase branchB

It's important that branchB shouldn't be used anymore.

For more ; https://www.derekgourlay.com/blog/git-when-to-merge-vs-when-to-rebase/

Git - Ignore node_modules folder everywhere

Add below line to your .gitignore

*/node_modules/*

This will ignore all node_modules in your current directory as well as subdirectory.

How to access the request body when POSTing using Node.js and Express?

Install Body Parser by below command

$ npm install --save body-parser

Configure Body Parser

const bodyParser = require('body-parser');
app.use(bodyParser);
app.use(bodyParser.json()); //Make sure u have added this line
app.use(bodyParser.urlencoded({ extended: false }));

String comparison using '==' vs. 'strcmp()'

Summing up all answers :

  • == is a bad idea for string comparisons.
    It will give you "surprising" results in many cases. Don't trust it.

  • === is fine, and will give you the best performance.

  • strcmp() should be used if you need to determine which string is "greater", typically for sorting operations.

How to fix the Hibernate "object references an unsaved transient instance - save the transient instance before flushing" error

beside all other good answers, this could happen if you use merge to persist an object and accidentally forget to use merged reference of the object in the parent class. consider the following example

merge(A);
B.setA(A);
persist(B);

In this case, you merge A but forget to use merged object of A. to solve the problem you must rewrite the code like this.

A=merge(A);//difference is here
B.setA(A);
persist(B);

Convert Json String to C# Object List

public static class Helper
{
    public static string AsJsonList<T>(List<T> tt)
    {
        return new JavaScriptSerializer().Serialize(tt);
    }
    public static string AsJson<T>(T t)
    {
        return new JavaScriptSerializer().Serialize(t);
    }
    public static List<T> AsObjectList<T>(string tt)
    {
        return new JavaScriptSerializer().Deserialize<List<T>>(tt);
    }
    public static T AsObject<T>(string t)
    {
        return new JavaScriptSerializer().Deserialize<T>(t);
    }
}

Android Fragment onAttach() deprecated

If you use the the framework fragments and the SDK version of the device is lower than 23, OnAttach(Context context) wouldn't be called.

I use support fragments instead, so deprecation is fixed and onAttach(Context context) always gets called.

How to dynamically create columns in datatable and assign values to it?

If you want to create dynamically/runtime data table in VB.Net then you should follow these steps as mentioned below :

  • Create Data table object.
  • Add columns into that data table object.
  • Add Rows with values into the object.

For eg.

Dim dt As New DataTable

dt.Columns.Add("Id", GetType(Integer))
dt.Columns.Add("FirstName", GetType(String))
dt.Columns.Add("LastName", GetType(String))

dt.Rows.Add(1, "Test", "data")
dt.Rows.Add(15, "Robert", "Wich")
dt.Rows.Add(18, "Merry", "Cylon")
dt.Rows.Add(30, "Tim", "Burst")

Selenium WebDriver: I want to overwrite value in field instead of appending to it with sendKeys using Java

The original question says clear() cannot be used. This does not apply to that situation. I'm adding my working example here as this SO post was one of the first Google results for clearing an input before entering a value.

For input where here is no additional restriction I'm including a browser agnostic method for Selenium using NodeJS. This snippet is part of a common library I import with var test = require( 'common' ); in my test scripts. It is for a standard node module.exports definition.

when_id_exists_type : function( id, value ) {
driver.wait( webdriver.until.elementLocated( webdriver.By.id( id ) ) , 3000 )
    .then( function() {
        var el = driver.findElement( webdriver.By.id( id ) );
        el.click();
        el.clear();
        el.sendKeys( value );
    });
},

Find the element, click it, clear it, then send the keys.

This page has a complete code sample and article that may help.

Remove directory which is not empty

//without use of any third party lib

const fs = require('fs');
var FOLDER_PATH = "./dirname";
var files = fs.readdirSync(FOLDER_PATH);
files.forEach(element => {
    fs.unlinkSync(FOLDER_PATH + "/" + element);
});
fs.rmdirSync(FOLDER_PATH);

Using OR operator in a jquery if statement

Update: using .indexOf() to detect if stat value is one of arr elements

Pure JavaScript

_x000D_
_x000D_
var arr = [20,30,40,50,60,70,80,90,100];_x000D_
//or detect equal to all_x000D_
//var arr = [10,10,10,10,10,10,10];_x000D_
    var stat = 10;_x000D_
_x000D_
if(arr.indexOf(stat)==-1)alert("stat is not equal to one more elements of array");
_x000D_
_x000D_
_x000D_

Uninstalling an MSI file from the command line without using msiexec

I'm assuming that when you type int file.msi into the command line, Windows is automatically calling msiexec file.msi for you. I'm assuming this because when you type in picture.png it brings up the default picture viewer.

C++ catching all exceptions

  1. Can you run your JNI-using Java application from a console window (launch it from a java command line) to see if there is any report of what may have been detected before the JVM was crashed. When running directly as a Java window application, you may be missing messages that would appear if you ran from a console window instead.

  2. Secondly, can you stub your JNI DLL implementation to show that methods in your DLL are being entered from JNI, you are returning properly, etc?

  3. Just in case the problem is with an incorrect use of one of the JNI-interface methods from the C++ code, have you verified that some simple JNI examples compile and work with your setup? I'm thinking in particular of using the JNI-interface methods for converting parameters to native C++ formats and turning function results into Java types. It is useful to stub those to make sure that the data conversions are working and you are not going haywire in the COM-like calls into the JNI interface.

  4. There are other things to check, but it is hard to suggest any without knowing more about what your native Java methods are and what the JNI implementation of them is trying to do. It is not clear that catching an exception from the C++ code level is related to your problem. (You can use the JNI interface to rethrow the exception as a Java one, but it is not clear from what you provide that this is going to help.)

How can I search Git branches for a file or directory?

git ls-tree might help. To search across all existing branches:

for branch in `git for-each-ref --format="%(refname)" refs/heads`; do
  echo $branch :; git ls-tree -r --name-only $branch | grep '<foo>'
done

The advantage of this is that you can also search with regular expressions for the file name.

How to change the display name for LabelFor in razor in mvc3?

Decorate the model property with the DisplayName attribute.

How to change btn color in Bootstrap

I had run into the similar problem recently, and managed to fix it with adding classes

  body .btn-primary {
    background-color: #7bc143;
    border-color: #7bc143;
    color: #FFF; }
    body .btn-primary:hover, body .btn-primary:focus {
      border-color: #6fb03a;
      background-color: #6fb03a;
      color: #FFF; }
    body .btn-primary:active, body .btn-primary:visited, body .btn-primary:active:focus, body .btn-primary:active:hover {
      border-color: #639d34;
      background-color: #639d34;
      color: #FFF; }

Also pay attention to [disabled] and [disabled]:hover, if this class is used on input[type=submit]. Like this:

body .btn-primary[disabled], body .btn-primary[disabled]:hover {
  background-color: #7bc143;
  border-color: #7bc143; }

Create XML file using java

Have look at dom4j or jdom. Both libraries allow creating a Document and allow printing the document as xml. Both are widly used, pretty easy to use and you'll find a lot of examples and snippets.

dom4j - Quick start guide

Loop code for each file in a directory

Check out the DirectoryIterator class.

From one of the comments on that page:

// output all files and directories except for '.' and '..'
foreach (new DirectoryIterator('../moodle') as $fileInfo) {
    if($fileInfo->isDot()) continue;
    echo $fileInfo->getFilename() . "<br>\n";
}

The recursive version is RecursiveDirectoryIterator.

How do I move a table into a schema in T-SQL

Short answer:

ALTER SCHEMA new_schema TRANSFER old_schema.table_name

I can confirm that the data in the table remains intact, which is probably quite important :)

Long answer as per MSDN docs,

ALTER SCHEMA schema_name 
   TRANSFER [ Object | Type | XML Schema Collection ] securable_name [;]

If it's a table (or anything besides a Type or XML Schema collection), you can leave out the word Object since that's the default.

Method to Add new or update existing item in Dictionary

The only problem could be if one day

map[key] = value

will transform to -

map[key]++;

and that will cause a KeyNotFoundException.

MySQL Insert with While Loop

You cannot use WHILE like that; see: mysql DECLARE WHILE outside stored procedure how?

You have to put your code in a stored procedure. Example:

CREATE PROCEDURE myproc()
BEGIN
    DECLARE i int DEFAULT 237692001;
    WHILE i <= 237692004 DO
        INSERT INTO mytable (code, active, total) VALUES (i, 1, 1);
        SET i = i + 1;
    END WHILE;
END

Fiddle: http://sqlfiddle.com/#!2/a4f92/1

Alternatively, generate a list of INSERT statements using any programming language you like; for a one-time creation, it should be fine. As an example, here's a Bash one-liner:

for i in {2376921001..2376921099}; do echo "INSERT INTO mytable (code, active, total) VALUES ($i, 1, 1);"; done

By the way, you made a typo in your numbers; 2376921001 has 10 digits, 237692200 only 9.

Only numbers. Input number in React

Simply way in React

<input
      onKeyPress={(event) => {
        if (!/[0-9]/.test(event.key)) {
          event.preventDefault();
        }
      }}
    />

java.rmi.ConnectException: Connection refused to host: 127.0.1.1;

When I got the same error on my machine ("connection is refused"), the reason was that I had defined the following on the server side:

 Naming.rebind("rmi://localhost:8080/AddService"
   ,addService); 

Thus the server binds both the IP = 127.0.0.1 and the port 8080.

But on the client side I had used:

AddServerInterface st = (AddServerInterface)Naming.lookup("rmi://localhost"
                        +"/AddService");

Thus I forgot to add the port number after the localhost, so I rewrote the above command and added the port number 8080 as follows:

AddServerInterface st = (AddServerInterface)Naming.lookup("rmi://localhost:8080"
                        +"/AddService");

and everything worked fine.

Swap x and y axis without manually swapping values

-Right click on either axis

-Click "Select Data..."

-Then Press the "Edit" button

-Copy the "Series X values" to the "Series Y values" and vise versa finally hit ok

I found this answer on this youtube video https://www.youtube.com/watch?v=xLKIWWIWltE

How to convert Hexadecimal #FFFFFF to System.Drawing.Color

string hex = "#FFFFFF";
Color _color = System.Drawing.ColorTranslator.FromHtml(hex);

Note: the hash is important!

How to make a UILabel clickable?

Swift 5

Similar to @liorco, but need to replace @objc with @IBAction.

class DetailViewController: UIViewController {

    @IBOutlet weak var tripDetails: UILabel!

    override func viewDidLoad() {
        super.viewDidLoad()
        ...

        let tap = UITapGestureRecognizer(target: self, action: #selector(DetailViewController.tapFunction))
        tripDetails.isUserInteractionEnabled = true
        tripDetails.addGestureRecognizer(tap)
    }

    @IBAction func tapFunction(sender: UITapGestureRecognizer) {
        print("tap working")
    }
}

This is working on Xcode 10.2.

How can I set the maximum length of 6 and minimum length of 6 in a textbox?

You could do it with JavaScript with something like this:

<input onblur="checkLength(this)" id="groupidtext" type="text" style="width: 100px;" maxlength="6" />
<!-- Or use event onkeyup instead if you want to check every character strike -->

function checkLength(el) {
  if (el.value.length != 6) {
    alert("length must be exactly 6 characters")
  }
}

Note this would work in older browsers which don't support HTML 5, but it relies on the user having JavaScript switched on.

How do you get git to always pull from a specific branch?

git branch --set-upstream master origin/master

This will add the following info to your config file:

[branch "master"]
    remote = origin
    merge = refs/heads/master

If you have branch.autosetuprebase = always then it will also add:

    rebase = true

SQL select join: is it possible to prefix all columns as 'prefix.*'?

I totally understand your problem about duplicated field names.

I needed that too until I coded my own function to solve it. If you are using PHP you can use it, or code yours in the language you are using for if you have this following facilities.

The trick here is that mysql_field_table() returns the table name and mysql_field_name() the field for each row in the result if it's got with mysql_num_fields() so you can mix them in a new array.

This prefixes all columns ;)

Regards,

function mysql_rows_with_columns($query) {
    $result = mysql_query($query);
    if (!$result) return false; // mysql_error() could be used outside
    $fields = mysql_num_fields($result);
    $rows = array();
    while ($row = mysql_fetch_row($result)) { 
        $newRow = array();
        for ($i=0; $i<$fields; $i++) {
            $table = mysql_field_table($result, $i);
            $name = mysql_field_name($result, $i);
            $newRow[$table . "." . $name] = $row[$i];
        }
        $rows[] = $newRow;
    }
    mysql_free_result($result);
    return $rows;
}

Mailbox unavailable. The server response was: 5.7.1 Unable to relay Error

I use Windows Server 2012 for hosting for a long time and it just stop working after a more than years without any problem. My solution was to add public IP address of the server to list of relays and enabled Windows Integrated Authentication.

I just made two changes and I don't which help.

Go to IIS 6 Manager

Go to IIS 6 Manager

Select properties of SMTP server

Select properties of SMTP server

On tab Access, select Relays

On tab Access, select Relays

Add your public IP address

Add your public IP address

Close the dialog and on the same tab click to Authentication button.

Add Integrated Windows Authentication

Add Integrated Windows Authentication

Maybe some step is not needed, but it works.

else & elif statements not working in Python

In IDLE and the interactive python, you entered two consecutive CRLF which brings you out of the if statement. It's the problem of IDLE or interactive python. It will be ok when you using any kind of editor, just make sure your indentation is right.

Https to http redirect using htaccess

The difference between http and https is that https requests are sent over an ssl-encrypted connection. The ssl-encrypted connection must be established between the browser and the server before the browser sends the http request.

Https requests are in fact http requests that are sent over an ssl encrypted connection. If the server rejects to establish an ssl encrypted connection then the browser will have no connection to send the request over. The browser and the server will have no way of talking to each other. The browser will not be able to send the url that it wants to access and the server will not be able to respond with a redirect to another url.

So this is not possible. If you want to respond to https links, then you need an ssl certificate.

ArrayBuffer to base64 encoded string

For those who like it short, here's an other one using Array.reduce which will not cause stack overflow:

var base64 = btoa(
  new Uint8Array(arrayBuffer)
    .reduce((data, byte) => data + String.fromCharCode(byte), '')
);

java.lang.NoSuchMethodError: org.apache.commons.codec.binary.Base64.encodeBase64String() in Java EE application

@Adam Augusta is right, One more thing

Apache-HTTP client jars also comes in same category as some google-apis.

org.apache.httpcomponents.httpclient_4.2.jar and commons-codec-1.4.jar both on classpath, This is very possible that you will get this problem.

This prove to all jars which are using early version of common-codec internally and at the same time someone using common-codec explicitly on classpath too.

What does %s and %d mean in printf in the C language?

The first argument denotes placeholders for the variables / parameters that follow.
For example, %s indicates that you're expecting a String to be your first print parameter.

Java also has a printf, which is very similar.

good postgresql client for windows?

I recommend Navicat strongly. What I found particularly excellent are it's import functions - you can import almost any data format (Access, Excel, DBF, Lotus ...), define a mapping between the source and destination which can be saved and is repeatable (I even keep my mappings under version control).

I have tried SQLMaestro and found it buggy (particularly for data import); PGAdmin is limited.

Writing JSON object to a JSON file with fs.writeFileSync

When sending data to a web server, the data has to be a string (here). You can convert a JavaScript object into a string with JSON.stringify(). Here is a working example:

var fs = require('fs');

var originalNote = {
  title: 'Meeting',
  description: 'Meeting John Doe at 10:30 am'
};

var originalNoteString = JSON.stringify(originalNote);

fs.writeFileSync('notes.json', originalNoteString);

var noteString = fs.readFileSync('notes.json');

var note = JSON.parse(noteString);

console.log(`TITLE: ${note.title} DESCRIPTION: ${note.description}`);

Hope it could help.

How do I get the localhost name in PowerShell?

Don't forget that all your old console utilities work just fine in PowerShell:

PS> hostname
KEITH1

Make anchor link go some pixels above where it's linked to

Put this in style :

.hash_link_tag{margin-top: -50px; position: absolute;}

and use this class in separate div tag before the links, example:

<div class="hash_link_tag" id="link1"></div> 
<a href="#link1">Link1</a>

or use this php code for echo link tag:

function HashLinkTag($id)
{
    echo "<div id='$id' class='hash_link_tag'></div>";
}

Generate insert script for selected records?

If possible use Visual Studio. The Microsoft SQL Server Data Tools (SSDT) bring a built in functionality for this since the March 2014 release:

  1. Open Visual Studio
  2. Open "View" ? "SQL Server Object Explorer"
  3. Add a connection to your Server
  4. Expand the relevant database
  5. Expand the "Tables" folder
  6. Right click on relevant table
  7. Select "View Data" from context menu
  8. In the new window, viewing the data use the "Sort and filter dataset" functionality in the tool bar to apply your filter. Note that this functionality is limited and you can't write explicit SQL queries.
  9. After you have applied your filter and see only the data you want, click on "Script" or "Script to file" in the tool bar
  10. Voilà - Here you have your insert script for your filtered data

Note: Be careful, the "View Data" window is just like SSMS "Edit Top 200 Rows"- you can edit data right away

(Tested with Visual Studio 2015 with Microsoft SQL Server Data Tools (SSDT) Version 14.0.60812.0 and Microsoft SQL Server 2012)

#1064 -You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version

Rule 1: You can not add a new table without specifying the primary key constraint[not a good practice if you create it somehow]. So the code:

CREATE TABLE transactions( 
id int NOT NULL AUTO_INCREMENT, 
location varchar(50) NOT NULL, 
description varchar(50) NOT NULL, 
category varchar(50) NOT NULL, 
amount double(10,9) NOT NULL, 
type varchar(6) NOT NULL,  
notes varchar(512), 
receipt int(10), 
PRIMARY KEY(id));

Rule 2: You are not allowed to use the keywords(words with predefined meaning) as a field name. Here type is something like that is used(commonly used with Join Types). So the code:

CREATE TABLE transactions( 
id int NOT NULL AUTO_INCREMENT, 
location varchar(50) NOT NULL, 
description varchar(50) NOT NULL, 
category varchar(50) NOT NULL, 
amount double(10,9) NOT NULL, 
transaction_type varchar(6) NOT NULL,  
notes varchar(512), 
receipt int(10), 
PRIMARY KEY(id));

Now you please try with this code. First check it in your database user interface(I am running HeidiSQL, or you can try it in your xampp/wamp server also)and make sure this code works. Now delete the table from your db and execute the code in your program. Thank You.

Which equals operator (== vs ===) should be used in JavaScript comparisons?

Equality comparison:

Operator ==

Returns true, when both operands are equal. The operands are converted to the same type before being compared.

>>> 1 == 1
true
>>> 1 == 2
false
>>> 1 == '1'
true

Equality and type comparison:

Operator ===

Returns true if both operands are equal and of the same type. It's generally better and safer if you compare this way, because there's no behind-the-scenes type conversions.

>>> 1 === '1'
false
>>> 1 === 1
true

standard size for html newsletter template

Bdizzle,

I would recommend that you read this link

You will see that Newsletters can have different widths, There seems to be no major standard, What is recommended is that the width will be about 95% of the page width, as different browsers use the extra margins differently. You will also find that email readers have problems when reading css so applying the guide lines in this tutorial might help you save some time and trouble-shooting down the road.

Be happy, Julian

How to convert milliseconds into a readable date?

This is a solution. Later you can split by ":" and take the values of the array

 /**
 * Converts milliseconds to human readeable language separated by ":"
 * Example: 190980000 --> 2:05:3 --> 2days 5hours 3min
 */
function dhm(t){
    var cd = 24 * 60 * 60 * 1000,
        ch = 60 * 60 * 1000,
        d = Math.floor(t / cd),
        h = '0' + Math.floor( (t - d * cd) / ch),
        m = '0' + Math.round( (t - d * cd - h * ch) / 60000);
    return [d, h.substr(-2), m.substr(-2)].join(':');
}

//Example
var delay = 190980000;                   
var fullTime = dhm(delay);
console.log(fullTime);

Reset all changes after last commit in git

First, reset any changes

This will undo any changes you've made to tracked files and restore deleted files:

git reset HEAD --hard

Second, remove new files

This will delete any new files that were added since the last commit:

git clean -fd

Files that are not tracked due to .gitignore are preserved; they will not be removed

Warning: using -x instead of -fd would delete ignored files. You probably don't want to do this.

What's the difference between import java.util.*; and import java.util.Date; ?

The toString() implementation of java.util.Date does not depend on the way the class is imported. It always returns a nice formatted date.

The toString() you see comes from another class.

Specific import have precedence over wildcard imports.

in this case

import other.Date
import java.util.*

new Date();

refers to other.Date and not java.util.Date.

The odd thing is that

import other.*
import java.util.*

Should give you a compiler error stating that the reference to Date is ambiguous because both other.Date and java.util.Date matches.

Android - How to regenerate R class?

This problem normally happens when importing from an existing project. Try to fix all errors from all .xml files in res folder, as well as Manifest file. Most likely the errors are shown at "match_parent" parameter, change it to "fill_parent". When all errors are clear, R.java will be appeared.

If there is no error on any .xml file. Try edit any xml file (like delete a letter and type it back) and then save the file, this will cause to generate the R.java.

What does the JSLint error 'body of a for in should be wrapped in an if statement' mean?

Just to add on to the topic of for in/for/$.each, I added a jsperf test case for using $.each vs for in: http://jsperf.com/each-vs-for-in/2

Different browsers/versions handle it differently, but it seems $.each and straight out for in are the cheapest options performance-wise.

If you're using for in to iterate through an associative array/object, knowing what you're after and ignoring everything else, use $.each if you use jQuery, or just for in (and then a break; once you've reached what you know should be the last element)

If you're iterating through an array to perform something with each key pair in it, should use the hasOwnProperty method if you DON'T use jQuery, and use $.each if you DO use jQuery.

Always use for(i=0;i<o.length;i++) if you don't need an associative array though... lol chrome performed that 97% faster than a for in or $.each

SQL Server 2008- Get table constraints

I used the following query to retrieve the information of constraints in the SQL Server 2012, and works perfectly. I hope it would be useful for you.

SELECT 
    tab.name AS [Table]
    ,tab.id AS [Table Id]
    ,constr.name AS [Constraint Name]
    ,constr.xtype AS [Constraint Type]
    ,CASE constr.xtype WHEN 'PK' THEN 'Primary Key' WHEN 'UQ' THEN 'Unique' ELSE '' END AS [Constraint Name]
    ,i.index_id AS [Index ID]
    ,ic.column_id AS [Column ID]
    ,clmns.name AS [Column Name]
    ,clmns.max_length AS [Column Max Length]
    ,clmns.precision AS [Column Precision]
    ,CASE WHEN clmns.is_nullable = 0 THEN 'NO' ELSE 'YES' END AS [Column Nullable]
    ,CASE WHEN clmns.is_identity = 0 THEN 'NO' ELSE 'YES' END AS [Column IS IDENTITY]
FROM SysObjects AS tab
INNER JOIN SysObjects AS constr ON(constr.parent_obj = tab.id AND constr.type = 'K')
INNER JOIN sys.indexes AS i ON( (i.index_id > 0 and i.is_hypothetical = 0) AND (i.object_id=tab.id) AND i.name = constr.name )
INNER JOIN sys.index_columns AS ic ON (ic.column_id > 0 and (ic.key_ordinal > 0 or ic.partition_ordinal = 0 or ic.is_included_column != 0)) 
                                    AND (ic.index_id=CAST(i.index_id AS int) 
                                    AND ic.object_id=i.object_id)
INNER JOIN sys.columns AS clmns ON clmns.object_id = ic.object_id and clmns.column_id = ic.column_id
WHERE tab.xtype = 'U'
ORDER BY tab.name

Switch statement for greater-than/less-than

This is another option:

     switch (true) {
         case (value > 100):
             //do stuff
             break;
         case (value <= 100)&&(value > 75):
             //do stuff
             break;
         case (value < 50):
            //do stuff
             break;
     }

WPF - add static items to a combo box

Here is the code from MSDN and the link - Article Link, which you should check out for more detail.

<ComboBox Text="Is not open">
    <ComboBoxItem Name="cbi1">Item1</ComboBoxItem>
    <ComboBoxItem Name="cbi2">Item2</ComboBoxItem>
    <ComboBoxItem Name="cbi3">Item3</ComboBoxItem>
</ComboBox>

Java program to find the largest & smallest number in n numbers without using arrays

@user3168844: try the below code:

import java.util.Scanner;

public class LargestSmallestNum {

    public void findLargestSmallestNo() {

        int smallest = Integer.MAX_VALUE;
        int large = 0;
        int num;

        System.out.println("enter the number");

        Scanner input = new Scanner(System.in);

        int n = input.nextInt();

        for (int i = 0; i < n; i++) {

            num = input.nextInt();

            if (num > large)
                large = num;

            if (num < smallest)
                smallest = num;

            System.out.println("the largest is:" + large);
            System.out.println("Smallest no is : "  + smallest);
        }
    }

    public static void main(String...strings){
        LargestSmallestNum largestSmallestNum = new LargestSmallestNum();
        largestSmallestNum.findLargestSmalestNo();
    }
}

100% width Twitter Bootstrap 3 template

You're right using div.container-fluid and you also need a div.row child. Then, the content must be placed inside without any grid columns. If you have a look at the docs you can find this text:

  • Rows must be placed within a .container (fixed-width) or .container-fluid (full-width) for proper alignment and padding.
  • Use rows to create horizontal groups of columns.

Not using grid columns it's ok as stated here:

  • Content should be placed within columns, and only columns may be immediate children of rows.

And looking at this example, you can read this text:

Full width, single column: No grid classes are necessary for full-width elements.

Here's a live example showing some elements using the correct layout. This way you don't need any custom CSS or hack.

Notification not showing in Oreo

fun pushNotification(message: String?, clickAtion: String?) {
        val ii = Intent(clickAtion)
        ii.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP)
        val pendingIntent = PendingIntent.getActivity(this, REQUEST_CODE, ii, PendingIntent.FLAG_ONE_SHOT)

        val soundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION)

        val largIcon = BitmapFactory.decodeResource(applicationContext.resources,
                R.mipmap.ic_launcher)


        val notificationManager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager

        val channelId = "default_channel_id"
        val channelDescription = "Default Channel"
// Since android Oreo notification channel is needed.
//Check if notification channel exists and if not create one
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
            var notificationChannel = notificationManager.getNotificationChannel(channelId)
            if (notificationChannel != null) {
                val importance = NotificationManager.IMPORTANCE_HIGH //Set the importance level
                notificationChannel = NotificationChannel(channelId, channelDescription, importance)
               // notificationChannel.lightColor = Color.GREEN //Set if it is necesssary
                notificationChannel.enableVibration(true) //Set if it is necesssary
                notificationManager.createNotificationChannel(notificationChannel)


                val noti_builder = NotificationCompat.Builder(this)
                        .setContentTitle("MMH")
                        .setContentText(message)
                        .setSmallIcon(R.drawable.ic_launcher_background)
                        .setChannelId(channelId)
                        .build()
                val random = Random()
                val id = random.nextInt()
                notificationManager.notify(id,noti_builder)

            }

        }
        else
        {
            val notificationBuilder = NotificationCompat.Builder(this)
                    .setSmallIcon(R.mipmap.ic_launcher).setColor(resources.getColor(R.color.colorPrimary))
                    .setVibrate(longArrayOf(200, 200, 0, 0, 0))
                    .setContentTitle(getString(R.string.app_name))

                    .setLargeIcon(largIcon)
                    .setContentText(message)
                    .setAutoCancel(true)
                    .setStyle(NotificationCompat.BigTextStyle().bigText(message))
                    .setSound(soundUri)
                    .setContentIntent(pendingIntent)


            val random = Random()
            val id = random.nextInt()
            notificationManager.notify(id, notificationBuilder.build())

        }



    }

Truncate to three decimals in Python

How about this:

In [1]: '%.3f' % round(1324343032.324325235 * 1000 / 1000,3)
Out[1]: '1324343032.324'

Possible duplicate of round() in Python doesn't seem to be rounding properly

[EDIT]

Given the additional comments I believe you'll want to do:

In : Decimal('%.3f' % (1324343032.324325235 * 1000 / 1000))
Out: Decimal('1324343032.324')

The floating point accuracy isn't going to be what you want:

In : 3.324
Out: 3.3239999999999998

(all examples are with Python 2.6.5)