Programs & Examples On #Reportdocument

The type initializer for 'CrystalDecisions.CrystalReports.Engine.ReportDocument' threw an exception

The type initializer for CrystalDecisions.CrystalReports.Engine.ReportDocument threw an exception.

I changed the target platform from x86 to Any CPU and it resolved the issue.

How can I delay a :hover effect in CSS?

div {
     background: #dbdbdb;
    -webkit-transition: .5s all;   
    -webkit-transition-delay: 5s; 
    -moz-transition: .5s all;   
    -moz-transition-delay: 5s; 
    -ms-transition: .5s all;   
    -ms-transition-delay: 5s; 
    -o-transition: .5s all;   
    -o-transition-delay: 5s; 
    transition: .5s all;   
    transition-delay: 5s; 
}

div:hover {
    background:#5AC900;
    -webkit-transition-delay: 0s;
    -moz-transition-delay: 0s;
    -ms-transition-delay: 0s;
    -o-transition-delay: 0s;
    transition-delay: 0s;
}

This will add a transition delay, which will be applicable to almost every browser..

How to give a Blob uploaded as FormData a file name?

When you are using Google Chrome you can use/abuse the Google Filesystem API for this. Here you can create a file with a specified name and write the content of a blob to it. Then you can return the result to the user.

I have not found a good way for Firefox yet; probably a small piece of Flash like downloadify is required to name a blob.

IE10 has a msSaveBlob() function in the BlobBuilder.

Maybe this is more for downloading a blob, but it is related.

How to add http:// if it doesn't exist in the URL

At the time of writing, none of the answers used a built-in function for this:

function addScheme($url, $scheme = 'http://')
{
  return parse_url($url, PHP_URL_SCHEME) === null ?
    $scheme . $url : $url;
}

echo addScheme('google.com'); // "http://google.com"
echo addScheme('https://google.com'); // "https://google.com"

See also: parse_url()

R command for setting working directory to source file location in Rstudio

Here is another way to do it:

set2 <- function(name=NULL) {
  wd <- rstudioapi::getSourceEditorContext()$path
  if (!is.null(name)) {
    if (substr(name, nchar(name) - 1, nchar(name)) != '.R') 
      name <- paste0(name, '.R')
  }
  else {
    name <- stringr::word(wd, -1, sep='/')
  }
  wd <- gsub(wd, pattern=paste0('/', name), replacement = '')
  no_print <- eval(expr=setwd(wd), envir = .GlobalEnv)
}
set2()

How to match any non white space character except a particular one?

This worked for me using sed [Edit: comment below points out sed doesn't support \s]

[^ ]

while

[^\s] 

didn't

# Delete everything except space and 'g'
echo "ghai ghai" | sed "s/[^\sg]//g"
gg

echo "ghai ghai" | sed "s/[^ g]//g"
g g

Android app unable to start activity componentinfo

Your null pointer exception seems to be on this line:

String url = intent.getExtras().getString("userurl");

because intent.getExtras() returns null when the intent doesn't have any extras.

You have to realize that this piece of code:

Intent Main = new Intent(this, ToClass.class);
Main.putExtra("userurl", url);
startActivity(Main);

doesn't start the activity you wrote in Main.java, it will attempt to start an activity called ToClass and if that doesn't exist, your app crashes.

Also, there is no such thing as "android.intent.action.start" so the manifest should look more like:

<activity android:name=".start" android:label="@string/app_name">
    <intent-filter>
        <action android:name="android.intent.action.MAIN" />
        <category android:name="android.intent.category.LAUNCHER" />
    </intent-filter>
</activity>
<activity android:name= ".Main">
</activity>

I hope this fixes some of the issues you are encountering but I strongly suggest you check out some "getting started" tutorials for android development and build up from there.

How can I use pickle to save a dict?

>>> import pickle
>>> with open("/tmp/picklefile", "wb") as f:
...     pickle.dump({}, f)
... 

normally it's preferable to use the cPickle implementation

>>> import cPickle as pickle
>>> help(pickle.dump)
Help on built-in function dump in module cPickle:

dump(...)
    dump(obj, file, protocol=0) -- Write an object in pickle format to the given file.

    See the Pickler docstring for the meaning of optional argument proto.

Android Fragment handle back button press

If you want to handle hardware Back key event than you have to do following code in your onActivityCreated() method of Fragment.

You also need to check Action_Down or Action_UP event. If you will not check then onKey() Method will call 2 times.

Also, If your rootview(getView()) will not contain focus then it will not work. If you have clicked on any control then again you need to give focus to rootview using getView().requestFocus(); After this only onKeydown() will call.

getView().setFocusableInTouchMode(true);
getView().requestFocus();

getView().setOnKeyListener(new OnKeyListener() {
        @Override
        public boolean onKey(View v, int keyCode, KeyEvent event) {
                if (event.getAction() == KeyEvent.ACTION_DOWN) {
                    if (keyCode == KeyEvent.KEYCODE_BACK) {
                        Toast.makeText(getActivity(), "Back Pressed", Toast.LENGTH_SHORT).show();
                    return true;
                    }
                }
                return false;
            }
        });

Working very well for me.

Inserting data into a MySQL table using VB.NET

your str_carSql should be exactly like this:

str_carSql = "insert into members_car (car_id, member_id, model, color, chassis_id, plate_number, code) values (@id,@m_id,@model,@color,@ch_id,@pt_num,@code)"

Good Luck

How to read .pem file to get private and public key

Read public key from pem (PK or Cert). Depends on Bouncycastle.

private static PublicKey getPublicKeyFromPEM(Reader reader) throws IOException {

    PublicKey key;

    try (PEMParser pem = new PEMParser(reader)) {
        JcaPEMKeyConverter jcaPEMKeyConverter = new JcaPEMKeyConverter();
        Object pemContent = pem.readObject();
        if (pemContent instanceof PEMKeyPair) {
            PEMKeyPair pemKeyPair = (PEMKeyPair) pemContent;
            KeyPair keyPair = jcaPEMKeyConverter.getKeyPair(pemKeyPair);
            key = keyPair.getPublic();
        } else if (pemContent instanceof SubjectPublicKeyInfo) {
            SubjectPublicKeyInfo keyInfo = (SubjectPublicKeyInfo) pemContent;
            key = jcaPEMKeyConverter.getPublicKey(keyInfo);
        } else if (pemContent instanceof X509CertificateHolder) {
            X509CertificateHolder cert = (X509CertificateHolder) pemContent;
            key = jcaPEMKeyConverter.getPublicKey(cert.getSubjectPublicKeyInfo());
        } else {
            throw new IllegalArgumentException("Unsupported public key format '" +
                pemContent.getClass().getSimpleName() + '"');
        }
    }

    return key;
}

Read private key from PEM:

private static PrivateKey getPrivateKeyFromPEM(Reader reader) throws IOException {

    PrivateKey key;

    try (PEMParser pem = new PEMParser(reader)) {
        JcaPEMKeyConverter jcaPEMKeyConverter = new JcaPEMKeyConverter();
        Object pemContent = pem.readObject();
        if (pemContent instanceof PEMKeyPair) {
            PEMKeyPair pemKeyPair = (PEMKeyPair) pemContent;
            KeyPair keyPair = jcaPEMKeyConverter.getKeyPair(pemKeyPair);
            key = keyPair.getPrivate();
        } else if (pemContent instanceof PrivateKeyInfo) {
            PrivateKeyInfo privateKeyInfo = (PrivateKeyInfo) pemContent;
            key = jcaPEMKeyConverter.getPrivateKey(privateKeyInfo);
        } else {
            throw new IllegalArgumentException("Unsupported private key format '" +
                pemContent.getClass().getSimpleName() + '"');
        }
    }

    return key;
}

Adding two numbers concatenates them instead of calculating the sum

You need to use javaScript's parseInt() method to turn the strings back into numbers. Right now they are strings so adding two strings concatenates them, which is why you're getting "12".

IPython/Jupyter Problems saving notebook as PDF

To convert notebooks to PDF you first need to have nbconvert installed.

pip install nbconvert
# OR
conda install nbconvert

Next, if you aren't using Anaconda or haven't already, you must install pandoc either by following the instructions on their website or, on Linux, as follows:

sudo apt-get install pandoc

After that you need to have XeTex installed on your machine:

You can now navigate to the folder that holds your IPython Notebook and run the following command:

jupyter nbconvert --to pdf MyNotebook.ipynb

for further reference, please check out this link.

Set adb vendor keys

look at this url Android adb devices unauthorized else briefly do the following:

  1. look for adbkey with not extension in the platform-tools/.android and delete this file
  2. look at C:\Users\*username*\.android) and delete adbkey
  3. C:\Windows\System32\config\systemprofile\.android and delete adbkey

You may find it in one of the directories above. Or just search adbkey in the Parent folders above then locate and delete.

Creating a REST API using PHP

In your example, it’s fine as it is: it’s simple and works. The only things I’d suggest are:

  1. validating the data POSTed
  2. make sure your API is sending the Content-Type header to tell the client to expect a JSON response:

    header('Content-Type: application/json');
    echo json_encode($response);
    

Other than that, an API is something that takes an input and provides an output. It’s possible to “over-engineer” things, in that you make things more complicated that need be.

If you wanted to go down the route of controllers and models, then read up on the MVC pattern and work out how your domain objects fit into it. Looking at the above example, I can see maybe a MathController with an add() action/method.

There are a few starting point projects for RESTful APIs on GitHub that are worth a look.

How to keep one variable constant with other one changing with row in excel

=(B0+4)/($A$0)

$ means keep same (press a few times F4 after typing A4 to flip through combos quick!)

The imported project "C:\Microsoft.CSharp.targets" was not found

In my case, I opened my .csproj file in notepad and removed the following three lines. Worked like a charm:

<Import Project="..\packages\Microsoft.CodeDom.Providers.DotNetCompilerPlatform.1.0.0\build\Microsoft.CodeDom.Providers.DotNetCompilerPlatform.props" Condition="Exists('..\packages\Microsoft.CodeDom.Providers.DotNetCompilerPlatform.1.0.0\build\Microsoft.CodeDom.Providers.DotNetCompilerPlatform.props')" />
<Import Project="..\packages\Microsoft.Net.Compilers.1.0.0\build\Microsoft.Net.Compilers.props" Condition="Exists('..\packages\Microsoft.Net.Compilers.1.0.0\build\Microsoft.Net.Compilers.props')" />
<Import Project="..\packages\Microsoft.Net.Compilers.1.3.2\build\Microsoft.Net.Compilers.props" Condition="Exists('..\packages\Microsoft.Net.Compilers.1.3.2\build\Microsoft.Net.Compilers.props')" />

jQuery append text inside of an existing paragraph tag

If you want to append text or html to span then you can do it as below.

$('p span#add_here').append('text goes here');

append will add text to span tag at the end.

to replace entire text or html inside of span you can use .text() or .html()

Bash or KornShell (ksh)?

This is a bit of a Unix vs Linux battle. Most if not all Linux distributions have bash installed and ksh optional. Most Unix systems, like Solaris, AIX and HPUX have ksh as default.

Personally I always use ksh, I love the vi completion and I pretty much use Solaris for everything.

Inserting image into IPython notebook markdown

You can find your current working directory by 'pwd' command in jupyter notebook without quotes.

How to automatically convert strongly typed enum into int?

Strongly typed enums aiming to solve multiple problems and not only scoping problem as you mentioned in your question:

  1. Provide type safety, thus eliminating implicit conversion to integer by integral promotion.
  2. Specify underlying types.
  3. Provide strong scoping.

Thus, it is impossible to implicitly convert a strongly typed enum to integers, or even its underlying type - that's the idea. So you have to use static_cast to make conversion explicit.

If your only problem is scoping and you really want to have implicit promotion to integers, then you better off using not strongly typed enum with the scope of the structure it is declared in.

Delete all nodes and relationships in neo4j 1.8

Neo4j cannot delete nodes that have a relation. You have to delete the relations before you can delete the nodes.

But, it is simple way to delete "ALL" nodes and "ALL" relationships with a simple chyper. This is the code:

MATCH (n) DETACH DELETE n

--> DETACH DELETE will remove all of the nodes and relations by Match

The remote host closed the connection. The error code is 0x800704CD

As m.edmondson mentioned, "The remote host closed the connection." occurs when a user or browser cancels something, or the network connection drops etc. It doesn't necessarily have to be a file download however, just any request for any resource that results in a response to the client. Basically the error means that the response could not be sent because the server can no longer talk to the client(browser).

There are a number of steps that you can take in order to stop it happening. If you are manually sending something in the response with a Response.Write, Response.Flush, returning data from a web servivce/page method or something similar, then you should consider checking Response.IsClientConnected before sending the response. Also, if the response is likely to take a long time or a lot of server-side processing is required, you should check this periodically until the response.end if called. See the following for details on this property:

http://msdn.microsoft.com/en-us/library/system.web.httpresponse.isclientconnected.aspx

Alternatively, which I believe is most likely in your case, the error is being caused by something inside the framework. The following link may by of use:

http://blog.whitesites.com/fixing-The-remote-host-closed-the-connection-The-error-code-is-0x80070057__633882307305519259_blog.htm

The following stack-overflow post might also be of interest:

"The remote host closed the connection" in Response.OutputStream.Write

How can I fill a column with random numbers in SQL? I get the same value in every row

While I do love using CHECKSUM, I feel that a better way to go is using NEWID(), just because you don't have to go through a complicated math to generate simple numbers .

ROUND( 1000 *RAND(convert(varbinary, newid())), 0)

You can replace the 1000 with whichever number you want to set as the limit, and you can always use a plus sign to create a range, let's say you want a random number between 100 and 200, you can do something like :

100 + ROUND( 100 *RAND(convert(varbinary, newid())), 0)

Putting it together in your query :

UPDATE CattleProds 
SET SheepTherapy= ROUND( 1000 *RAND(convert(varbinary, newid())), 0)
WHERE SheepTherapy IS NULL

selecting unique values from a column

Depends on what you need.

In this case I suggest:

SELECT DISTINCT(Date) AS Date FROM buy ORDER BY Date DESC;

because there are few fields and the execution time of DISTINCT is lower than the execution of GROUP BY.

In other cases, for example where there are many fields, I prefer:

SELECT * FROM buy GROUP BY date ORDER BY date DESC;

Download a specific tag with Git

Use the --single-branch switch (available as of Git 1.7.10). The syntax is:

git clone -b <tag_name> --single-branch <repo_url> [<dest_dir>] 

For example:

git clone -b 'v1.9.5' --single-branch https://github.com/git/git.git git-1.9.5

The benefit: Git will receive objects and (need to) resolve deltas for the specified branch/tag only - while checking out the exact same amount of files! Depending on the source repository, this will save you a lot of disk space. (Plus, it'll be much quicker.)

jQuery UI DatePicker to show month year only

I needed a Month/Year picker for two fields (From & To) and when one was chosen the Max/Min was set on the other one...a la picking airline ticket dates. I was having issues setting the max and min...the dates of the other field would get erased. Thanks to several of the above posts...I finally figured it out. You have to set options and dates in a very specific order.

See this fiddle for the full solution: Month/Year Picker @ JSFiddle

Code:

var searchMinDate = "-2y";
var searchMaxDate = "-1m";
if ((new Date()).getDate() <= 5) {
    searchMaxDate = "-2m";
}
$("#txtFrom").datepicker({
    dateFormat: "M yy",
    changeMonth: true,
    changeYear: true,
    showButtonPanel: true,
    showAnim: "",
    minDate: searchMinDate,
    maxDate: searchMaxDate,
    showButtonPanel: true,
    beforeShow: function (input, inst) {
        if ((datestr = $("#txtFrom").val()).length > 0) {
            var year = datestr.substring(datestr.length - 4, datestr.length);
            var month = jQuery.inArray(datestr.substring(0, datestr.length - 5), "#txtFrom").datepicker('option', 'monthNamesShort'));
        $("#txtFrom").datepicker('option', 'defaultDate', new Date(year, month, 1));
                $("#txtFrom").datepicker('setDate', new Date(year, month, 1));
            }
        },
        onClose: function (input, inst) {
            var month = $("#ui-datepicker-div .ui-datepicker-month :selected").val();
            var year = $("#ui-datepicker-div .ui-datepicker-year :selected").val();
            $("#txtFrom").datepicker('option', 'defaultDate', new Date(year, month, 1));
            $("#txtFrom").datepicker('setDate', new Date(year, month, 1));
            var to = $("#txtTo").val();
            $("#txtTo").datepicker('option', 'minDate', new Date(year, month, 1));
            if (to.length > 0) {
                var toyear = to.substring(to.length - 4, to.length);
                var tomonth = jQuery.inArray(to.substring(0, to.length - 5), $("#txtTo").datepicker('option', 'monthNamesShort'));
                $("#txtTo").datepicker('option', 'defaultDate', new Date(toyear, tomonth, 1));
                $("#txtTo").datepicker('setDate', new Date(toyear, tomonth, 1));
            }
        }
    });
    $("#txtTo").datepicker({
        dateFormat: "M yy",
        changeMonth: true,
        changeYear: true,
        showButtonPanel: true,
        showAnim: "",
        minDate: searchMinDate,
        maxDate: searchMaxDate,
        showButtonPanel: true,
        beforeShow: function (input, inst) {
            if ((datestr = $("#txtTo").val()).length > 0) {
                var year = datestr.substring(datestr.length - 4, datestr.length);
                var month = jQuery.inArray(datestr.substring(0, datestr.length - 5), $("#txtTo").datepicker('option', 'monthNamesShort'));
                $("#txtTo").datepicker('option', 'defaultDate', new Date(year, month, 1));
                $("#txtTo").datepicker('setDate', new Date(year, month, 1));
            }
        },
        onClose: function (input, inst) {
            var month = $("#ui-datepicker-div .ui-datepicker-month :selected").val();
            var year = $("#ui-datepicker-div .ui-datepicker-year :selected").val();
            $("#txtTo").datepicker('option', 'defaultDate', new Date(year, month, 1));
            $("#txtTo").datepicker('setDate', new Date(year, month, 1));
            var from = $("#txtFrom").val();
            $("#txtFrom").datepicker('option', 'maxDate', new Date(year, month, 1));
            if (from.length > 0) {
                var fryear = from.substring(from.length - 4, from.length);
                var frmonth = jQuery.inArray(from.substring(0, from.length - 5), $("#txtFrom").datepicker('option', 'monthNamesShort'));
                $("#txtFrom").datepicker('option', 'defaultDate', new Date(fryear, frmonth, 1));
                $("#txtFrom").datepicker('setDate', new Date(fryear, frmonth, 1));
            }

        }
    });

Also add this to a style block as mentioned above:

.ui-datepicker-calendar { display: none !important; }

Why do table names in SQL Server start with "dbo"?

Microsoft introduced schema in version 2008. For those who didn’t know about schema, and those who didn’t care, objects were put into a default schema dbo.

dbo stands for DataBase Owner, but that’s not really important.

Think of a schema as you would a folder for files:

  • You don’t need to refer to the schema if the object is in the same or default schema
  • You can reference an object in a different schema by using the schema as a prefix, the way you can reference a file in a different folder.
  • You can’t have two objects with the same name in a single schema, but you can in different schema
  • Using schema can help you to organise a larger number of objects
  • Schema can also be assigned to particular users and roles, so you can control access to who can do what.

You can always access any object from any schema.

Because dbo is the default, you normally don’t need to specify it within a single database:

SELECT * FROM customers;
SELECT * FROM dbo.customers;

mean the same thing.

I am inclined to disagree with the notion of always using the dbo. prefix, since the more you clutter your code with unnecessary detail, the harder it is to read and manage.

For the most part, you can ignore the schema. However, the schema will make itself apparent in the following situations:

  1. If you view the tables in either the object navigator or in an external application, such as Microsoft Excel or Access, you will see the dbo. prefix. You can still ignore it.

  2. If you reference a table in another database, you will need its full name in the form database.schema.table:

    SELECT * FROM bookshop.dbo.customers;
    
  3. For historical reasons, if you write a user defined scalar function, you will need to call it with the schema prefix:

    CREATE FUNCTION tax(@amount DECIMAL(6,2) RETURNS DECIMAL(6,2) AS
    BEGIN
        RETURN @amount * 0.1;
    END;
    GO
    SELECT total, dbo.tax(total) FROM pricelist;
    

    This does not apply to other objects, such as table functions, procedures and views.

You can use schema to overcome naming conflicts. For example, if every user has a personal schema, they can create additional objects without having to fight with other users over the name.

How to refresh datagrid in WPF

From MSDN -

CollectionViewSource.GetDefaultView(myGrid.ItemsSource).Refresh();

Tools: replace not replacing in Android manifest

I also went through this problem and changed that:

<application  android:debuggable="true" android:icon="@drawable/app_icon" android:label="@string/app_name" android:supportsRtl="true" android:allowBackup="false" android:fullBackupOnly="false" android:theme="@style/UnityThemeSelector">

to

 <application tools:replace="android:allowBackup" android:debuggable="true" android:icon="@drawable/app_icon" android:label="@string/app_name" android:supportsRtl="true" android:allowBackup="false" android:fullBackupOnly="false" android:theme="@style/UnityThemeSelector">

Powershell send-mailmessage - email to multiple recipients

That's right, each address needs to be quoted. If you have multiple addresses listed on the command line, the Send-MailMessage likes it if you specify both the human friendly and the email address parts.

Should I add the Visual Studio .suo and .user files to source control?

They contain the specific settings about the project that are typically assigned to a single developer (like, for example, the starting project and starting page to start when you debug your application).

So it's better not adding them to version control, leaving VS recreate them so that each developer can have the specific settings they want.

Arduino IDE can't find ESP8266WiFi.h file

When programming the NODEMCU card with the Arduino IDE, you need to customize it and you must have selected the correct card.

Open Arduino IDE and go to files and click on the preference in the Arduino IDE.

Add the following link to the Additional Manager URLS section: "http://arduino.esp8266.com/stable/package_esp8266com_index.json" and press the OK button.

Then click Tools> Board Manager. Type "ESP8266" in the text box to search and install the ESP8266 software for Arduino IDE.

You will be successful when you try to program again by selecting the NodeMCU card after these operations. I hope I could help.

How to see the changes in a Git commit?

In case of checking the source change in a graphical view,

$gitk (Mention your commit id here)

for example:

$gitk HEAD~1 

How to use 'find' to search for files created on a specific date?

As pointed out by Max, you can't, but checking files modified or accessed is not all that hard. I wrote a tutorial about this, as late as today. The essence of which is to use -newerXY and ! -newerXY:

Example: To find all files modified on the 7th of June, 2007:

$ find . -type f -newermt 2007-06-07 ! -newermt 2007-06-08

To find all files accessed on the 29th of september, 2008:

$ find . -type f -newerat 2008-09-29 ! -newerat 2008-09-30

Or, files which had their permission changed on the same day:

$ find . -type f -newerct 2008-09-29 ! -newerct 2008-09-30

If you don't change permissions on the file, 'c' would normally correspond to the creation date, though.

Neither BindingResult nor plain target object for bean name available as request attribute

I had problem like this, but with several "actions". My solution looks like this:

    <form method="POST" th:object="${searchRequest}" action="searchRequest" >
          <input type="text" th:field="*{name}"/>
          <input type="submit" value="find" th:value="find" />
    </form>
        ...
    <form method="POST" th:object="${commodity}" >
        <input type="text" th:field="*{description}"/>
        <input type="submit" value="add" />
    </form>

And controller

@Controller
@RequestMapping("/goods")
public class GoodsController {
    @RequestMapping(value = "add", method = GET)
    public String showGoodsForm(Model model){
           model.addAttribute(new Commodity());
           model.addAttribute("searchRequest", new SearchRequest());
           return "goodsForm";
    }
    @RequestMapping(value = "add", method = POST)
    public ModelAndView processAddCommodities(
            @Valid Commodity commodity,
            Errors errors) {
        if (errors.hasErrors()) {
            ModelAndView model = new ModelAndView("goodsForm");
            model.addObject("searchRequest", new SearchRequest());
            return model;
        }
        ModelAndView model = new ModelAndView("redirect:/goods/" + commodity.getName());
        model.addObject(new Commodity());
        model.addObject("searchRequest", new SearchRequest());
        return model;
    }
    @RequestMapping(value="searchRequest", method=POST)
    public String processFindCommodity(SearchRequest commodity, Model model) {
    ...
        return "catalog";
    }

I'm sure - here is not "best practice", but it is works without "Neither BindingResult nor plain target object for bean name available as request attribute".

Get rid of "The value for annotation attribute must be a constant expression" message

The value for an annotation must be a compile time constant, so there is no simple way of doing what you are trying to do.

See also here: How to supply value to an annotation from a Constant java

It is possible to use some compile time tools (ant, maven?) to config it if the value is known before you try to run the program.

How to find duplicate records in PostgreSQL

The basic idea will be using a nested query with count aggregation:

select * from yourTable ou
where (select count(*) from yourTable inr
where inr.sid = ou.sid) > 1

You can adjust the where clause in the inner query to narrow the search.


There is another good solution for that mentioned in the comments, (but not everyone reads them):

select Column1, Column2, count(*)
from yourTable
group by Column1, Column2
HAVING count(*) > 1

Or shorter:

SELECT (yourTable.*)::text, count(*)
FROM yourTable
GROUP BY yourTable.*
HAVING count(*) > 1

onclick open window and specific size

window.open('http://somelocation.com','mywin','width=500,height=500');

What's the difference between equal?, eql?, ===, and ==?

I wrote a simple test for all the above.

def eq(a, b)
  puts "#{[a, '==',  b]} : #{a == b}"
  puts "#{[a, '===', b]} : #{a === b}"
  puts "#{[a, '.eql?', b]} : #{a.eql?(b)}"
  puts "#{[a, '.equal?', b]} : #{a.equal?(b)}"
end

eq("all", "all")
eq(:all, :all)
eq(Object.new, Object.new)
eq(3, 3)
eq(1, 1.0)

How do I handle ImeOptions' done button click?

More details on how to set the OnKeyListener, and have it listen for the Done button.

First add OnKeyListener to the implements section of your class. Then add the function defined in the OnKeyListener interface:

/*
 * Respond to soft keyboard events, look for the DONE press on the password field.
 */
public boolean onKey(View v, int keyCode, KeyEvent event)
{
    if ((event.getAction() == KeyEvent.ACTION_DOWN) &&
        (keyCode == KeyEvent.KEYCODE_ENTER))
    {
        // Done pressed!  Do something here.
    }
    // Returning false allows other listeners to react to the press.
    return false;
}

Given an EditText object:

EditText textField = (EditText)findViewById(R.id.MyEditText);
textField.setOnKeyListener(this);

How to run test methods in specific order in JUnit4?

Migration to TestNG seems the best way, but I see no clear solution here for jUnit. Here is most readable solution / formatting I found for jUnit:

@FixMethodOrder(MethodSorters.NAME_ASCENDING)
public class SampleTest {
    @Test
    void stage1_prepareAndTest(){};

    @Test
    void stage2_checkSomething(){};

    @Test
    void stage2_checkSomethingElse(){};

    @Test
    void stage3_thisDependsOnStage2(){};

    @Test
    void callTimeDoesntMatter(){}
}

This ensures stage2 methods are called after stage1 ones and before stage3 ones.

Count unique values using pandas groupby

I think you can use SeriesGroupBy.nunique:

print (df.groupby('param')['group'].nunique())
param
a    2
b    1
Name: group, dtype: int64

Another solution with unique, then create new df by DataFrame.from_records, reshape to Series by stack and last value_counts:

a = df[df.param.notnull()].groupby('group')['param'].unique()
print (pd.DataFrame.from_records(a.values.tolist()).stack().value_counts())
a    2
b    1
dtype: int64

How to use ScrollView in Android?

There are two options. You can make your entire layout to be scrollable or only the TextView to be scrollable.

For the first case,

<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent" >

    <RelativeLayout
        android:layout_width="fill_parent"
        android:layout_height="fill_parent" >

        <TableLayout
            android:layout_width="fill_parent"
            android:layout_height="fill_parent"
            android:stretchColumns="1" >

            <TableRow>

                <ImageView
                    android:id="@+id/imageView"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_marginLeft="5dip"
                    android:layout_marginRight="5dip"
                    android:layout_marginTop="10dip"
                    android:src="@drawable/icon"
                    android:tint="#55ff0000" >
                </ImageView>
            </TableRow>

            <TableRow>

                <TextView
                    android:id="@+id/name"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:padding="3dip"
                    android:text="  Name " >
                </TextView>

                <TextView
                    android:id="@+id/name1"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:gravity="left"
                    android:text="Veer" >
                </TextView>
            </TableRow>

            <TableRow>

                <TextView
                    android:id="@+id/age"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:padding="3dip"
                    android:text="  Age" >
                </TextView>

                <TextView
                    android:id="@+id/age1"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:gravity="left"
                    android:text="23" >
                </TextView>
            </TableRow>

            <TableRow>

                <TextView
                    android:id="@+id/gender"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:padding="3dip"
                    android:text="  Gender" >
                </TextView>

                <TextView
                    android:id="@+id/gender1"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:gravity="left"
                    android:text="Male" >
                </TextView>
            </TableRow>

            <TableRow>

                <TextView
                    android:id="@+id/profession"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:padding="3dip"
                    android:text="  Professsion" >
                </TextView>

                <TextView
                    android:id="@+id/profession1"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:gravity="left"
                    android:text="Mobile Developer" >
                </TextView>
            </TableRow>

            <TableRow>

                <TextView
                    android:id="@+id/phone"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:padding="3dip"
                    android:text="  Phone" >
                </TextView>

                <TextView
                    android:id="@+id/phone1"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:gravity="left"
                    android:text="03333736767" >
                </TextView>
            </TableRow>

            <TableRow>

                <TextView
                    android:id="@+id/email"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:padding="3dip"
                    android:text="  Email" >
                </TextView>

                <TextView
                    android:id="@+id/email1"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:gravity="left"
                    android:text="[email protected]" >
                </TextView>
            </TableRow>

            <TableRow>

                <TextView
                    android:id="@+id/hobby"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:padding="3dip"
                    android:text="  Hobby" >
                </TextView>

                <TextView
                    android:id="@+id/hobby1"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:gravity="left"
                    android:text="Play Games" >
                </TextView>
            </TableRow>

            <TableRow>

                <TextView
                    android:id="@+id/ilike"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:padding="3dip"
                    android:text="  I like" >
                </TextView>

                <TextView
                    android:id="@+id/ilike1"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:gravity="left"
                    android:text="Java, Objective-c" >
                </TextView>
            </TableRow>

            <TableRow>

                <TextView
                    android:id="@+id/idislike"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:padding="3dip"
                    android:text="  I dislike" >
                </TextView>

                <TextView
                    android:id="@+id/idislike1"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:gravity="left"
                    android:text="Microsoft" >
                </TextView>
            </TableRow>

            <TableRow>

                <TextView
                    android:id="@+id/address"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:padding="3dip"
                    android:text="  Address" >
                </TextView>

                <TextView
                    android:id="@+id/address1"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:gravity="left"
                    android:text="Johar Mor" >
                </TextView>
            </TableRow>

            <Relativelayout>
            </Relativelayout>
        </TableLayout>
    </RelativeLayout>

</ScrollView>

or, as I said you can use scrollView for TextView alone.

Java List.contains(Object with field value equal to x)

Predicate

If you dont use Java 8, or library which gives you more functionality for dealing with collections, you could implement something which can be more reusable than your solution.

interface Predicate<T>{
        boolean contains(T item);
    }

    static class CollectionUtil{

        public static <T> T find(final Collection<T> collection,final  Predicate<T> predicate){
            for (T item : collection){
                if (predicate.contains(item)){
                    return item;
                }
            }
            return null;
        }
    // and many more methods to deal with collection    
    }

i'm using something like that, i have predicate interface, and i'm passing it implementation to my util class.

What is advantage of doing this in my way? you have one method which deals with searching in any type collection. and you dont have to create separate methods if you want to search by different field. alll what you need to do is provide different predicate which can be destroyed as soon as it no longer usefull/

if you want to use it, all what you need to do is call method and define tyour predicate

CollectionUtil.find(list, new Predicate<MyObject>{
    public boolean contains(T item){
        return "John".equals(item.getName());
     }
});

Java, reading a file from current directory?

try using "." E.g.

File currentDirectory = new File(".");

This worked for me

Make iframe automatically adjust height according to the contents without using scrollbar?

I did it with AngularJS. Angular doesn't have an ng-load, but a 3rd party module was made; install with bower below, or find it here: https://github.com/andrefarzat/ng-load

Get the ngLoad directive: bower install ng-load --save

Setup your iframe:

<iframe id="CreditReportFrame" src="about:blank" frameborder="0" scrolling="no" ng-load="resizeIframe($event)" seamless></iframe>

Controller resizeIframe function:

$scope.resizeIframe = function (event) {
    console.log("iframe loaded!");
    var iframe = event.target;
    iframe.style.height = iframe.contentWindow.document.body.scrollHeight + 'px';
};

How to refresh page on back button click?

This simple solution posted here Force page refresh on back button worked ...

I've tried to force a page to be downloaded again by browser when user clicks back button, but nothing worked. I appears that modern browsers have separate cache for pages, which stores complete state of a page (including JavaScript generated DOM elements), so when users presses back button, previous page is shown instantly in state the user has left it. If you want to force browser to reload page on back button, add onunload="" to your (X)HTML body element:

<body onunload="">

This disables special cache and forces page reload when user presses back button. Think twice before you use it. Fact of needing such solution is a hint your site navigation concept is flawed.

MSSQL Regular expression

Disclaimer: The original question was about MySQL. The SQL Server answer is below.

MySQL

In MySQL, the regex syntax is the following:

SELECT * FROM YourTable WHERE (`url` NOT REGEXP '^[-A-Za-z0-9/.]+$') 

Use the REGEXP clause instead of LIKE. The latter is for pattern matching using % and _ wildcards.


SQL Server

Since you made a typo, and you're using SQL Server (not MySQL), you'll have to create a user-defined CLR function to expose regex functionality.

Take a look at this article for more details.

Given an RGB value, how do I create a tint (or shade)?

Some definitions

  • A shade is produced by "darkening" a hue or "adding black"
  • A tint is produced by "ligthening" a hue or "adding white"

Creating a tint or a shade

Depending on your Color Model, there are different methods to create a darker (shaded) or lighter (tinted) color:

  • RGB:

    • To shade:

      newR = currentR * (1 - shade_factor)
      newG = currentG * (1 - shade_factor)
      newB = currentB * (1 - shade_factor)
      
    • To tint:

      newR = currentR + (255 - currentR) * tint_factor
      newG = currentG + (255 - currentG) * tint_factor
      newB = currentB + (255 - currentB) * tint_factor
      
    • More generally, the color resulting in layering a color RGB(currentR,currentG,currentB) with a color RGBA(aR,aG,aB,alpha) is:

      newR = currentR + (aR - currentR) * alpha
      newG = currentG + (aG - currentG) * alpha
      newB = currentB + (aB - currentB) * alpha
      

    where (aR,aG,aB) = black = (0,0,0) for shading, and (aR,aG,aB) = white = (255,255,255) for tinting

  • HSV or HSB:

    • To shade: lower the Value / Brightness or increase the Saturation
    • To tint: lower the Saturation or increase the Value / Brightness
  • HSL:
    • To shade: lower the Lightness
    • To tint: increase the Lightness

There exists formulas to convert from one color model to another. As per your initial question, if you are in RGB and want to use the HSV model to shade for example, you can just convert to HSV, do the shading and convert back to RGB. Formula to convert are not trivial but can be found on the internet. Depending on your language, it might also be available as a core function :

Comparing the models

  • RGB has the advantage of being really simple to implement, but:
    • you can only shade or tint your color relatively
    • you have no idea if your color is already tinted or shaded
  • HSV or HSB is kind of complex because you need to play with two parameters to get what you want (Saturation & Value / Brightness)
  • HSL is the best from my point of view:
    • supported by CSS3 (for webapp)
    • simple and accurate:
      • 50% means an unaltered Hue
      • >50% means the Hue is lighter (tint)
      • <50% means the Hue is darker (shade)
    • given a color you can determine if it is already tinted or shaded
    • you can tint or shade a color relatively or absolutely (by just replacing the Lightness part)

How can I set the request header for curl?

To pass multiple headers in a curl request you simply add additional -H or --header to your curl command.

Example

//Simplified
$ curl -v -H 'header1:val' -H 'header2:val' URL

//Explanatory
$ curl -v -H 'Connection: keep-alive' -H 'Content-Type: application/json'  https://www.example.com

Going Further

For standard HTTP header fields such as User-Agent, Cookie, Host, there is actually another way to setting them. The curl command offers designated options for setting these header fields:

  • -A (or --user-agent): set "User-Agent" field.
  • -b (or --cookie): set "Cookie" field.
  • -e (or --referer): set "Referer" field.
  • -H (or --header): set "Header" field

For example, the following two commands are equivalent. Both of them change "User-Agent" string in the HTTP header.

    $ curl -v -H "Content-Type: application/json" -H "User-Agent: UserAgentString" https://www.example.com
    $ curl -v -H "Content-Type: application/json" -A "UserAgentString" https://www.example.com

Screenshot sizes for publishing android app on Google Play

The files need to be in a JPEG or PNG format of 24 bits, in a 2:1 ratio if it is a portrait and a 16:9 ratio for landscapes. Be careful that if you go for different sizes: the maximum size should not be more than twice bigger than the minimum size.

PHP: convert spaces in string into %20?

The plus sign is the historic encoding for a space character in URL parameters, as documented in the help for the urlencode() function.

That same page contains the answer you need - use rawurlencode() instead to get RFC 3986 compatible encoding.

ERROR 1452: Cannot add or update a child row: a foreign key constraint fails

check the no. of record in parent table that matches with child table and also primary key must match with foreign key reference. This works for me.

Referencing a string in a string array resource with xml

The better option would be to just use the resource returned array as an array, meaning :

getResources().getStringArray(R.array.your_array)[position]

This is a shortcut approach of above mentioned approaches but does the work in the fashion you want. Otherwise android doesnt provides direct XML indexing for xml based arrays.

gdb: how to print the current line or find the current line number?

Keep in mind that gdb is a powerful command -capable of low level instructions- so is tied to assembly concepts.

What you are looking for is called de instruction pointer, i.e:

The instruction pointer register points to the memory address which the processor will next attempt to execute. The instruction pointer is called ip in 16-bit mode, eip in 32-bit mode,and rip in 64-bit mode.

more detail here

all registers available on gdb execution can be shown with:

(gdb) info registers

with it you can find which mode your program is running (looking which of these registers exist)

then (here using most common register rip nowadays, replace with eip or very rarely ip if needed):

(gdb)info line *$rip

will show you line number and file source

(gdb) list *$rip

will show you that line with a few before and after

but probably

(gdb) frame

should be enough in many cases.

How to execute Ant build in command line

is it still actual?

As I can see you wrote <target depends="build-subprojects,build-project" name="build"/>, then you wrote <target name="build-subprojects"/> (it does nothing). Could it be a reason? Does this <echo message="${ant.project.name}: ${ant.file}"/> print appropriate message? If no then target is not running. Take a look at the next link http://www.sqaforums.com/showflat.php?Number=623277

How to upload & Save Files with Desired name

You can grab the demo source code from here: http://abhinavsingh.com/blog/2008/05/gmail-type-attachment-how-to-make-one/

It is ready to use, or you can modify to suit your application needs. Hope it helps :)

Java HotSpot(TM) 64-Bit Server VM warning: ignoring option MaxPermSize

-XX:MaxPermSize=size

Sets the maximum permanent generation space size (in bytes). This option was deprecated in JDK 8, and superseded by the -XX:MaxMetaspaceSize option.

-XX:PermSize=size

Sets the space (in bytes) allocated to the permanent generation that triggers a garbage collection if it is exceeded. This option was deprecated in JDK 8, and superseded by the -XX:MetaspaceSize option.

How to Set Opacity (Alpha) for View in Android

Much more easier from the above. Default alpha attribute is there for button

android:alpha="0.5"

The range is between 0 for complete transparent and 1 for complete opacity.

pthread function from a class

My guess would be this is b/c its getting mangled up a bit by C++ b/c your sending it a C++ pointer, not a C function pointer. There is a difference apparently. Try doing a

(void)(*p)(void) = ((void) *(void)) &c[0].print; //(check my syntax on that cast)

and then sending p.

I've done what your doing with a member function also, but i did it in the class that was using it, and with a static function - which i think made the difference.

How to rename a file using Python

One important point to note here, we should check if any files exists with the new filename.

suppose if b.kml file exists then renaming other file with the same filename leads to deletion of existing b.kml.

import os

if not os.path.exists('b.kml')
    os.rename('a.txt','b.kml')

How to filter array when object key value is in array

In 2019 using ES6:

_x000D_
_x000D_
const ids = [1, 4, 5],_x000D_
  data = {_x000D_
    records: [{_x000D_
      "empid": 1,_x000D_
      "fname": "X",_x000D_
      "lname": "Y"_x000D_
    }, {_x000D_
      "empid": 2,_x000D_
      "fname": "A",_x000D_
      "lname": "Y"_x000D_
    }, {_x000D_
      "empid": 3,_x000D_
      "fname": "B",_x000D_
      "lname": "Y"_x000D_
    }, {_x000D_
      "empid": 4,_x000D_
      "fname": "C",_x000D_
      "lname": "Y"_x000D_
    }, {_x000D_
      "empid": 5,_x000D_
      "fname": "C",_x000D_
      "lname": "Y"_x000D_
    }]_x000D_
  };_x000D_
_x000D_
_x000D_
data.records = data.records.filter( i => ids.includes( i.empid ) );_x000D_
_x000D_
console.info( data );
_x000D_
_x000D_
_x000D_

What are the specific differences between .msi and setup.exe file?

An MSI is a Windows Installer database. Windows Installer (a service installed with Windows) uses this to install software on your system (i.e. copy files, set registry values, etc...).

A setup.exe may either be a bootstrapper or a non-msi installer. A non-msi installer will extract the installation resources from itself and manage their installation directly. A bootstrapper will contain an MSI instead of individual files. In this case, the setup.exe will call Windows Installer to install the MSI.

Some reasons you might want to use a setup.exe:

  • Windows Installer only allows one MSI to be installing at a time. This means that it is difficult to have an MSI install other MSIs (e.g. dependencies like the .NET framework or C++ runtime). Since a setup.exe is not an MSI, it can be used to install several MSIs in sequence.
  • You might want more precise control over how the installation is managed. An MSI has very specific rules about how it manages the installations, including installing, upgrading, and uninstalling. A setup.exe gives complete control over the software configuration process. This should only be done if you really need the extra control since it is a lot of work, and it can be tricky to get it right.

Count unique values with pandas per groups

You need nunique:

df = df.groupby('domain')['ID'].nunique()

print (df)
domain
'facebook.com'    1
'google.com'      1
'twitter.com'     2
'vk.com'          3
Name: ID, dtype: int64

If you need to strip ' characters:

df = df.ID.groupby([df.domain.str.strip("'")]).nunique()
print (df)
domain
facebook.com    1
google.com      1
twitter.com     2
vk.com          3
Name: ID, dtype: int64

Or as Jon Clements commented:

df.groupby(df.domain.str.strip("'"))['ID'].nunique()

You can retain the column name like this:

df = df.groupby(by='domain', as_index=False).agg({'ID': pd.Series.nunique})
print(df)
    domain  ID
0       fb   1
1      ggl   1
2  twitter   2
3       vk   3

The difference is that nunique() returns a Series and agg() returns a DataFrame.

What does 'x packages are looking for funding' mean when running `npm install`?

When you run npm update in the command prompt, when it is done it will recommend you type a new command called npm fund.

When you run npm fund it will list all the modules and packages you have installed that were created by companies or organizations that need money for their IT projects. You will see a list of webpages where you can send them money. So "funds" means "Angular packages you installed that could use some money from you as an option to help support their businesses".

It's basically a list of the modules you have that need contributions or donations of money to their projects and which list websites where you can enter a credit card to help pay for them.

Why would Oracle.ManagedDataAccess not work when Oracle.DataAccess does?

I had the similar issue......to solve this what I did was to uninstall the ODP. Net and re-install in the same directory as oracle server......with server option you will notice that most of the products are already installed (while 12c database installation) so just select the other features and finally finish the installation....

Please note that this workaround works only if you have installed 12c on the same machine i.e. on your laptop............

If your database is located on the server machine other than your laptop then please select client option and not the server and then include TNS_ADMIN in your app.config and do not forget to specify the version...

since my installation is on my laptop so my App.config is as below:

<?xml version="1.0" encoding="utf-8"?>
<configuration>
    <startup> 
        <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.0"/>
    </startup>
</configuration>


 /////////the below code is a sample from oracle company////////////////


using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.Common;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Oracle.ManagedDataAccess.Client;

///copy these lines in a button click event 
    string constr = "User Id=system; Password=manager; Data Source=orcl;";
// Click here and then press F9 to insert a breakpoint
        DbProviderFactory factory =
    DbProviderFactories.GetFactory("Oracle.ManagedDataAccess.Client");
            using (DbConnection conn = factory.CreateConnection())
            {
                conn.ConnectionString = constr;
                try
                {
                    conn.Open();
                    OracleCommand cmd = (OracleCommand)factory.CreateCommand();
                    cmd.Connection = (OracleConnection)conn;

//to gain access to ROWIDs of the table
//cmd.AddRowid = true;
                    cmd.CommandText = "select * from all_users";

                    OracleDataReader reader = cmd.ExecuteReader();

                    int visFC = reader.VisibleFieldCount; //Results in 2
                    int hidFC = reader.HiddenFieldCount;  // Results in 1

                    MessageBox.Show(" Visible field count: " + visFC);

                    MessageBox.Show(" Hidden field count: " + hidFC);


                    reader.Dispose();
                    cmd.Dispose();
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                      MessageBox.Show(ex.StackTrace);
                }
            }

How to play videos in android from assets folder or raw folder?

PlayVideoActivity.java:

public class PlayVideoActivity extends Activity {

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_play_video);

        VideoView videoView = (VideoView) findViewById(R.id.video_view);
        MediaController mediaController = new MediaController(this);
        mediaController.setAnchorView(videoView);
        videoView.setMediaController(mediaController);
        videoView.setVideoURI(Uri.parse("android.resource://" + getPackageName() + "/" + R.raw.documentariesandyou));
        videoView.start();
    }
}

activity_play_video.xml:

<?xml version="1.0" encoding="utf-8"?>
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:gravity="center" >

    <VideoView
        android:id="@+id/video_view"
        android:layout_width="match_parent"
        android:layout_height="match_parent" >
    </VideoView>

</LinearLayout>

How to check if JavaScript object is JSON

Try this

if ( typeof is_json != "function" )
function is_json( _obj )
{
    var _has_keys = 0 ;
    for( var _pr in _obj )
    {
        if ( _obj.hasOwnProperty( _pr ) && !( /^\d+$/.test( _pr ) ) )
        {
           _has_keys = 1 ;
           break ;
        }
    }

    return ( _has_keys && _obj.constructor == Object && _obj.constructor != Array ) ? 1 : 0 ;
}

It works for the example below

var _a = { "name" : "me",
       "surname" : "I",
       "nickname" : {
                      "first" : "wow",
                      "second" : "super",
                      "morelevel" : {
                                      "3level1" : 1,
                                      "3level2" : 2,
                                      "3level3" : 3
                                    }
                    }
     } ;

var _b = [ "name", "surname", "nickname" ] ;
var _c = "abcdefg" ;

console.log( is_json( _a ) );
console.log( is_json( _b ) );
console.log( is_json( _c ) );

How to install MySQLdb package? (ImportError: No module named setuptools)

I resolved this issue on centos5.4 by running the following command to install setuptools

yum install python-setuptools

I hope that helps.

Use virtualenv with Python with Visual Studio Code in Ubuntu

I got this from YouTube Setting up Python Visual Studio Code... Venv

OK, the video really didn't help me all that much, but... the first comment under (by the person who posted the video) makes a lot of sense and is pure gold.

Basically, open up Visual Studio Code' built-in Terminal. Then source <your path>/activate.sh, the usual way you choose a venv from the command line. I have a predefined Bash function to find & launch the right script file and that worked just fine.

Quoting that YouTube comment directly (all credit to aneuris ap):

(you really only need steps 5-7)

1. Open your command line/terminal and type `pip virtualenv`.
2. Create a folder in which the virtualenv will be placed in.
3. 'cd' to the script folder in the virtualenv and run activate.bat (CMD).
4. Deactivate to turn of the virtualenv (CMD).
5. Open the project in Visual Studio Code and use its built-in terminal to 'cd' to the script folder in you virtualenv.
6. Type source activates (in Visual Studio Code I use the Git terminal).
7. Deactivate to turn off the virtualenv.

As you may notice, he's talking about activate.bat. So, if it works for me on a Mac, and it works on Windows too, chances are it's pretty robust and portable.

Else clause on Python while statement

In reply to Is there a specific reason?, here is one interesting application: breaking out of multiple levels of looping.

Here is how it works: the outer loop has a break at the end, so it would only be executed once. However, if the inner loop completes (finds no divisor), then it reaches the else statement and the outer break is never reached. This way, a break in the inner loop will break out of both loops, rather than just one.

for k in [2, 3, 5, 7, 11, 13, 17, 25]:
    for m in range(2, 10):
        if k == m:
            continue
        print 'trying %s %% %s' % (k, m)
        if k % m == 0:
            print 'found a divisor: %d %% %d; breaking out of loop' % (k, m)
            break
    else:
        continue
    print 'breaking another level of loop'
    break
else:
    print 'no divisor could be found!'

For both while and for loops, the else statement is executed at the end, unless break was used.

In most cases there are better ways to do this (wrapping it into a function or raising an exception), but this works!

C# Convert a Base64 -> byte[]

This may be helpful

byte[] bytes = System.Convert.FromBase64String(stringInBase64);

How do I detect if Python is running as a 64-bit application?

import platform
platform.architecture()

From the Python docs:

Queries the given executable (defaults to the Python interpreter binary) for various architecture information.

Returns a tuple (bits, linkage) which contain information about the bit architecture and the linkage format used for the executable. Both values are returned as strings.

Is there a regular expression to detect a valid regular expression?

/
^                                             # start of string
(                                             # first group start
  (?:
    (?:[^?+*{}()[\]\\|]+                      # literals and ^, $
     | \\.                                    # escaped characters
     | \[ (?: \^?\\. | \^[^\\] | [^\\^] )     # character classes
          (?: [^\]\\]+ | \\. )* \]
     | \( (?:\?[:=!]|\?<[=!]|\?>)? (?1)?? \)  # parenthesis, with recursive content
     | \(\? (?:R|[+-]?\d+) \)                 # recursive matching
     )
    (?: (?:[?+*]|\{\d+(?:,\d*)?\}) [?+]? )?   # quantifiers
  | \|                                        # alternative
  )*                                          # repeat content
)                                             # end first group
$                                             # end of string
/

This is a recursive regex, and is not supported by many regex engines. PCRE based ones should support it.

Without whitespace and comments:

/^((?:(?:[^?+*{}()[\]\\|]+|\\.|\[(?:\^?\\.|\^[^\\]|[^\\^])(?:[^\]\\]+|\\.)*\]|\((?:\?[:=!]|\?<[=!]|\?>)?(?1)??\)|\(\?(?:R|[+-]?\d+)\))(?:(?:[?+*]|\{\d+(?:,\d*)?\})[?+]?)?|\|)*)$/

.NET does not support recursion directly. (The (?1) and (?R) constructs.) The recursion would have to be converted to counting balanced groups:

^                                         # start of string
(?:
  (?: [^?+*{}()[\]\\|]+                   # literals and ^, $
   | \\.                                  # escaped characters
   | \[ (?: \^?\\. | \^[^\\] | [^\\^] )   # character classes
        (?: [^\]\\]+ | \\. )* \]
   | \( (?:\?[:=!]
         | \?<[=!]
         | \?>
         | \?<[^\W\d]\w*>
         | \?'[^\W\d]\w*'
         )?                               # opening of group
     (?<N>)                               #   increment counter
   | \)                                   # closing of group
     (?<-N>)                              #   decrement counter
   )
  (?: (?:[?+*]|\{\d+(?:,\d*)?\}) [?+]? )? # quantifiers
| \|                                      # alternative
)*                                        # repeat content
$                                         # end of string
(?(N)(?!))                                # fail if counter is non-zero.

Compacted:

^(?:(?:[^?+*{}()[\]\\|]+|\\.|\[(?:\^?\\.|\^[^\\]|[^\\^])(?:[^\]\\]+|\\.)*\]|\((?:\?[:=!]|\?<[=!]|\?>|\?<[^\W\d]\w*>|\?'[^\W\d]\w*')?(?<N>)|\)(?<-N>))(?:(?:[?+*]|\{\d+(?:,\d*)?\})[?+]?)?|\|)*$(?(N)(?!))

From the comments:

Will this validate substitutions and translations?

It will validate just the regex part of substitutions and translations. s/<this part>/.../

It is not theoretically possible to match all valid regex grammars with a regex.

It is possible if the regex engine supports recursion, such as PCRE, but that can't really be called regular expressions any more.

Indeed, a "recursive regular expression" is not a regular expression. But this an often-accepted extension to regex engines... Ironically, this extended regex doesn't match extended regexes.

"In theory, theory and practice are the same. In practice, they're not." Almost everyone who knows regular expressions knows that regular expressions does not support recursion. But PCRE and most other implementations support much more than basic regular expressions.

using this with shell script in the grep command , it shows me some error.. grep: Invalid content of {} . I am making a script that could grep a code base to find all the files that contain regular expressions

This pattern exploits an extension called recursive regular expressions. This is not supported by the POSIX flavor of regex. You could try with the -P switch, to enable the PCRE regex flavor.

Regex itself "is not a regular language and hence cannot be parsed by regular expression..."

This is true for classical regular expressions. Some modern implementations allow recursion, which makes it into a Context Free language, although it is somewhat verbose for this task.

I see where you're matching []()/\. and other special regex characters. Where are you allowing non-special characters? It seems like this will match ^(?:[\.]+)$, but not ^abcdefg$. That's a valid regex.

[^?+*{}()[\]\\|] will match any single character, not part of any of the other constructs. This includes both literal (a - z), and certain special characters (^, $, .).

How to declare an array of strings in C++?

Problems - no way to get the number of strings automatically (that i know of).

There is a bog-standard way of doing this, which lots of people (including MS) define macros like arraysize for:

#define arraysize(ar)  (sizeof(ar) / sizeof(ar[0]))

Select all contents of textbox when it receives focus (Vanilla JS or jQuery)

This is not just a Chrome/Safari issue, I experienced a quite similar behavior with Firefox 18.0.1. The funny part is that this does not happen on MSIE! The problem here is the first mouseup event that forces to unselect the input content, so just ignore the first occurence.

$(':text').focus(function(){
    $(this).one('mouseup', function(event){
        event.preventDefault();
    }).select();
});

The timeOut approach causes a strange behavior, and blocking every mouseup event you can not remove the selection clicking again on the input element.

How do I generate a list with a specified increment step?

Executing seq(1, 10, 1) does what 1:10 does. You can change the last parameter of seq, i.e. by, to be the step of whatever size you like.

> #a vector of even numbers
> seq(0, 10, by=2) # Explicitly specifying "by" only to increase readability 
> [1]  0  2  4  6  8 10

right align an image using CSS HTML

<img style="float: right;" alt="" src="http://example.com/image.png" />
<div style="clear: right">
   ...text...
</div>    

jsFiddle.

twig: IF with multiple conditions

If I recall correctly Twig doesn't support || and && operators, but requires or and and to be used respectively. I'd also use parentheses to denote the two statements more clearly although this isn't technically a requirement.

{%if ( fields | length > 0 ) or ( trans_fields | length > 0 ) %}

Expressions

Expressions can be used in {% blocks %} and ${ expressions }.

Operator    Description
==          Does the left expression equal the right expression?
+           Convert both arguments into a number and add them.
-           Convert both arguments into a number and substract them.
*           Convert both arguments into a number and multiply them.
/           Convert both arguments into a number and divide them.
%           Convert both arguments into a number and calculate the rest of the integer division.
~           Convert both arguments into a string and concatenate them.
or          True if the left or the right expression is true.
and         True if the left and the right expression is true.
not         Negate the expression.

For more complex operations, it may be best to wrap individual expressions in parentheses to avoid confusion:

{% if (foo and bar) or (fizz and (foo + bar == 3)) %}

Change class on mouseover in directive

I have run into problems in the past with IE and the css:hover selector so the approach that I have taken, is to use a custom directive.

.directive('hoverClass', function () {
    return {
        restrict: 'A',
        scope: {
            hoverClass: '@'
        },
        link: function (scope, element) {
            element.on('mouseenter', function() {
                element.addClass(scope.hoverClass);
            });
            element.on('mouseleave', function() {
                element.removeClass(scope.hoverClass);
            });
        }
    };
})

then on the element itself you can add the directive with the class names that you want enabled when the mouse is over the the element for example:

<li data-ng-repeat="item in social" hover-class="hover tint" class="social-{{item.name}}" ng-mouseover="hoverItem(true);" ng-mouseout="hoverItem(false);"
                index="{{$index}}"><i class="{{item.icon}}"
                box="course-{{$index}}"></i></li>

This should add the class hover and tint when the mouse is over the element and doesn't run the risk of a scope variable name collision. I haven't tested but the mouseenter and mouseleave events should still bubble up to the containing element so in the given scenario the following should still work

<div hover-class="hover" data-courseoverview data-ng-repeat="course in courses | orderBy:sortOrder | filter:search"
 data-ng-controller ="CourseItemController"
 data-ng-class="{ selected: isSelected }">

providing of course that the li's are infact children of the parent div

Verify a method call using Moq

You're checking the wrong method. Moq requires that you Setup (and then optionally Verify) the method in the dependency class.

You should be doing something more like this:

class MyClassTest
{
    [TestMethod]
    public void MyMethodTest()
    {
        string action = "test";
        Mock<SomeClass> mockSomeClass = new Mock<SomeClass>();

        mockSomeClass.Setup(mock => mock.DoSomething());

        MyClass myClass = new MyClass(mockSomeClass.Object);
        myClass.MyMethod(action);

        // Explicitly verify each expectation...
        mockSomeClass.Verify(mock => mock.DoSomething(), Times.Once());

        // ...or verify everything.
        // mockSomeClass.VerifyAll();
    }
}

In other words, you are verifying that calling MyClass#MyMethod, your class will definitely call SomeClass#DoSomething once in that process. Note that you don't need the Times argument; I was just demonstrating its value.

MS Access - execute a saved query by name in VBA

You can do it the following way:

DoCmd.OpenQuery "yourQueryName", acViewNormal, acEdit

OR

CurrentDb.OpenRecordset("yourQueryName")

Checking for empty or null JToken in a JObject

To check whether a property exists on a JObject, you can use the square bracket syntax and see whether the result is null or not. If the property exists, a JToken will be always be returned (even if it has the value null in the JSON).

JToken token = jObject["param"];
if (token != null)
{
    // the "param" property exists
}

If you have a JToken in hand and you want to see if it is non-empty, well, that depends on what type of JToken it is and how you define "empty". I usually use an extension method like this:

public static class JsonExtensions
{
    public static bool IsNullOrEmpty(this JToken token)
    {
        return (token == null) ||
               (token.Type == JTokenType.Array && !token.HasValues) ||
               (token.Type == JTokenType.Object && !token.HasValues) ||
               (token.Type == JTokenType.String && token.ToString() == String.Empty) ||
               (token.Type == JTokenType.Null);
    }
}

How can I find where Python is installed on Windows?

If You want the Path After successful installation then first open you CMD and type python or python -i

It Will Open interactive shell for You and Then type

import sys

sys.executable

Hit enter and you will get path where your python is installed ...

Checking for a null int value from a Java ResultSet

With java 8 you can do this:

Long nVal = Optional.ofNullable(resultSet.getBigDecimal("col_name"))
                    .map(BigDecimal::longValue).orElse(null));

In that case you ensure that the nVal will be null (and not zero) if the SQL value is NULL

Extract subset of key-value pairs from Python dictionary object?

You can also use map (which is a very useful function to get to know anyway):

sd = dict(map(lambda k: (k, l.get(k, None)), l))

Example:

large_dictionary = {'a1':123, 'a2':45, 'a3':344}
list_of_keys = ['a1', 'a3']
small_dictionary = dict(map(lambda key: (key, large_dictionary.get(key, None)), list_of_keys))

PS: I borrowed the .get(key, None) from a previous answer :)

Step-by-step debugging with IPython

Looks like the approach in @gaborous's answer is deprecated.

The new approach seems to be:

from IPython.core import debugger
debug = debugger.Pdb().set_trace

def buggy_method():
    debug()

Should I use Vagrant or Docker for creating an isolated environment?

I preface my reply by admitting I have no experience with Docker, other than as an avid observer of what looks to be a really neat solution that's gaining a lot of traction.

I do have a decent amount of experience with Vagrant and can highly recommend it. It's certainly a more heavyweight solution in terms of it being VM based instead of LXC based. However, I've found a decent laptop (8 GB RAM, i5/i7 CPU) has no trouble running a VM using Vagrant/VirtualBox alongside development tooling.

One of the really great things with Vagrant is the integration with Puppet/Chef/shell scripts for automating configuration. If you're using one of these options to configure your production environment, you can create a development environment which is as close to identical as you're going to get, and this is exactly what you want.

The other great thing with Vagrant is that you can version your Vagrantfile along with your application code. This means that everyone else on your team can share this file and you're guaranteed that everyone is working with the same environment configuration.

Interestingly, Vagrant and Docker may actually be complimentary. Vagrant can be extended to support different virtualization providers, and it may be possible that Docker is one such provider which gets support in the near future. See https://github.com/dotcloud/docker/issues/404 for recent discussion on the topic.

Cannot run Eclipse; JVM terminated. Exit code=13

I just had the same issue, and spend about an hour trying to solve the problem. In the end it was a '#' character in the path.

So I renamed "C:\# IDE\eclipse 3.7\" to "C:\+ IDE\eclipse 3.7\" and that solved the problem.

How do I check whether a file exists without exceptions?

Prefer the try statement. It's considered better style and avoids race conditions.

Don't take my word for it. There's plenty of support for this theory. Here's a couple:

How to remove close button on the jQuery UI dialog?

$(".ui-button-icon-only").hide();

How can I repeat a character in Bash?

This is the longer version of what Eliah Kagan was espousing:

while [ $(( i-- )) -gt 0 ]; do echo -n "  "; done

Of course you can use printf for that as well, but not really to my liking:

printf "%$(( i*2 ))s"

This version is Dash compatible:

until [ $(( i=i-1 )) -lt 0 ]; do echo -n "  "; done

with i being the initial number.

Get an element by index in jQuery

You could skip the jquery and just use CSS style tagging:

 <ul>
 <li>India</li>
 <li>Indonesia</li>
 <li style="background-color:#343434;">China</li>
 <li>United States</li>
 <li>United Kingdom</li>
 </ul>

How to calculate percentage with a SQL statement

Instead of using a separate CTE to get the total, you can use a window function without the "partition by" clause.

If you are using:

count(*)

to get the count for a group, you can use:

sum(count(*)) over ()

to get the total count.

For example:

select Grade, 100. * count(*) / sum(count(*)) over ()
from table
group by Grade;

It tends to be faster in my experience, but I think it might internally use a temp table in some cases (I've seen "Worktable" when running with "set statistics io on").

EDIT: I'm not sure if my example query is what you are looking for, I was just illustrating how the windowing functions work.

Full Page <iframe>

Put this in your CSS.

iframe {
  width: 100%;
  height: 100vh;
}

Converting a char to ASCII?

A char is an integral type. When you write

char ch = 'A';

you're setting the value of ch to whatever number your compiler uses to represent the character 'A'. That's usually the ASCII code for 'A' these days, but that's not required. You're almost certainly using a system that uses ASCII.

Like any numeric type, you can initialize it with an ordinary number:

char ch = 13;

If you want do do arithmetic on a char value, just do it: ch = ch + 1; etc.

However, in order to display the value you have to get around the assumption in the iostreams library that you want to display char values as characters rather than numbers. There are a couple of ways to do that.

std::cout << +ch << '\n';
std::cout << int(ch) << '\n'

Rmi connection refused with localhost

had a simliar problem with that connection exception. it is thrown either when the registry is not started yet (like in your case) or when the registry is already unexported (like in my case).

but a short comment to the difference between the 2 ways to start the registry:

Runtime.getRuntime().exec("rmiregistry 2020");

runs the rmiregistry.exe in javas bin-directory in a new process and continues parallel with your java code.

LocateRegistry.createRegistry(2020);

the rmi method call starts the registry, returns the reference to that registry remote object and then continues with the next statement.

in your case the registry is not started in time when you try to bind your object

Send response to all clients except sender

use this coding

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

    socket.on('mousemove', function (data) {

        socket.broadcast.emit('moving', data);
    });

this socket.broadcast.emit() will emit everthing in the function except to the server which is emitting

How can I create a "Please Wait, Loading..." animation using jQuery?

Note that when using ASP.Net MVC, with using (Ajax.BeginForm(..., setting the ajaxStart will not work.

Use the AjaxOptions to overcome this issue:

(Ajax.BeginForm("ActionName", new AjaxOptions { OnBegin = "uiOfProccessingAjaxAction", OnComplete = "uiOfProccessingAjaxActionComplete" }))

How can I use "e" (Euler's number) and power operation in python 2.7

Power is ** and e^ is math.exp:

x.append(1 - math.exp(-0.5 * (value1*value2)**2))

Unable to create/open lock file: /data/mongod.lock errno:13 Permission denied

In my case (AWS EC2 instance, Ubuntu) helped:

$ sudo mkdir -p /data/db/
$ sudo chown `USERNAME` /data/db

And after that everything worked fine.

How do I pretty-print existing JSON data with Java?

Underscore-java library has methods U.formatJson(json) and U.formatXml(xml). I am the maintainer of the project.

Apache is not running from XAMPP Control Panel ( Error: Apache shutdown unexpectedly. This may be due to a blocked port)

Accompanying Timmay's answer, You need to do two changes-

Listen 80 --> Listen 81 (near line 58)

ServerName localhost:80 --> ServerName localhost:81 (near line 218)

How to make the corners of a button round?

Is there an easy way to achieve this in Android?

Yes, today there is, and it is very simple.
Just use the MaterialButton in the Material Components library with the app:cornerRadius attribute.

Something like:

    <com.google.android.material.button.MaterialButton
        android:text="BUTTON"
        app:cornerRadius="8dp"
        ../>

enter image description here

It is enough to obtain a Button with rounded corners.

You can use one of Material button styles. For example:

<com.google.android.material.button.MaterialButton
    style="@style/Widget.MaterialComponents.Button.OutlinedButton"
    .../>

enter image description here

Also starting from the version 1.1.0 you can also change the shape of your button. Just use the shapeAppearanceOverlay attribute in the button style:

  <style name="MyButtonStyle" parent="Widget.MaterialComponents.Button">
    <item name="shapeAppearanceOverlay">@style/ShapeAppearanceOverlay.MyApp.Button.Rounded</item>
  </style>

  <style name="ShapeAppearanceOverlay.MyApp.Button.Rounded" parent="">
    <item name="cornerFamily">rounded</item>
    <item name="cornerSize">16dp</item>
  </style>

Then just use:

<com.google.android.material.button.MaterialButton
   style="@style/MyButtonStyle"
   .../>

You can also apply the shapeAppearanceOverlay in the xml layout:

<com.google.android.material.button.MaterialButton
   app:shapeAppearanceOverlay="@style/ShapeAppearanceOverlay.MyApp.Button.Rounded"
   .../>

The shapeAppearance allows also to have different shape and dimension for each corner:

<style name="ShapeAppearanceOverlay.MyApp.Button.Rounded" parent="">
    <item name="cornerFamily">rounded</item>
    <item name="cornerFamilyTopRight">cut</item>
    <item name="cornerFamilyBottomRight">cut</item>
    <item name="cornerSizeTopLeft">32dp</item>
    <item name="cornerSizeBottomLeft">32dp</item>
</style>

enter image description here

How to determine whether a Pandas Column contains a particular value

Simple condition:

if any(str(elem) in ['a','b'] for elem in df['column'].tolist()):

Best practice: PHP Magic Methods __set and __get

You should use stdClass if you want magic members, if you write a class - define what it contains.

Tomcat Server Error - Port 8080 already in use

If you want to regain the 8080 port number you do so by opening the task manager and then process tab, right click java.exe process and click on end process as shown in image attached.

screen shot

Jquery ajax call click event submit button

You did not add # before id of the button. You do not have right selector in your jquery code. So jquery is never execute in your button click. its submitted your form directly not passing any ajax request.

See documentation: http://api.jquery.com/category/selectors/
its your friend.

Try this:

It seems that id: $("#Shareitem").val() is wrong if you want to pass the value of

<input type="hidden" name="id" value="" id="id">

you need to change this line:

id: $("#Shareitem").val()

by

id: $("#id").val()

All together:

 <script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
    <script>
    $(document).ready(function(){
      $("#Shareitem").click(function(e){
          e.preventDefault();
        $.ajax({type: "POST",
                url: "/imball-reagens/public/shareitem",
                data: { id: $("#Shareitem").val(), access_token: $("#access_token").val() },
                success:function(result){
          $("#sharelink").html(result);
        }});
      });
    });
    </script>

How to read a .xlsx file using the pandas Library in iPython?

pd.read_excel(file_name) 

sometimes this code gives an error for xlsx files as: XLRDError:Excel xlsx file; not supported

instead , you can use openpyxl engine to read excel file.

df_samples = pd.read_excel(r'filename.xlsx', engine='openpyxl')

It worked for me

Convert date yyyyMMdd to system.datetime format

string time = "19851231";
DateTime theTime= DateTime.ParseExact(time,
                                        "yyyyMMdd",
                                        CultureInfo.InvariantCulture,
                                        DateTimeStyles.None);

First letter capitalization for EditText

I can assure you both the answers will make first letter capital and will not make edittext single line.

If you want to do it in XMl below is the code

android:inputType="textCapWords|textCapSentences"

If want to do it in activity/fragment etc below is the code

momentTextView.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_FLAG_CAP_WORDS | InputType.TYPE_TEXT_FLAG_MULTI_LINE)

PS: If you are having nay other property also you can easily add it with a pipe "|" symbol, just make sure there is no space in xml between the attribute properties

How to Right-align flex item?

If you want to use flexbox for this, you should be able to, by doing this (display: flex on the container, flex: 1 on the items, and text-align: right on .c):

.main { display: flex; }
.a, .b, .c {
    background: #efefef;
    border: 1px solid #999;
    flex: 1;
}
.b { text-align: center; }
.c { text-align: right; }

...or alternatively (even simpler), if the items don't need to meet, you can use justify-content: space-between on the container and remove the text-align rules completely:

.main { display: flex; justify-content: space-between; }
.a, .b, .c { background: #efefef; border: 1px solid #999; }

Here's a demo on Codepen to allow you to quickly try the above.

How to add a downloaded .box file to Vagrant?

First rename the Vagrantfile then

vagrant box add new-box name-of-the-box.box
vagrant init new-box
vagrant up

Just to check status

vagrant status

that's all

Java abstract interface

Every interface is implicitly abstract.
This modifier is obsolete and should not be used in new programs.

[The Java Language Specification - 9.1.1.1 abstract Interfaces]

Also note that interface member methods are implicitly public abstract.
[The Java Language Specification - 9.2 Interface Members]

Why are those modifiers implicit? There is no other modifier (not even the 'no modifier'-modifier) that would be useful here, so you don't explicitly have to type it.

For files in directory, only echo filename (no path)

Use basename:

echo $(basename /foo/bar/stuff)

Gradle sync failed: failed to find Build Tools revision 24.0.0 rc1

Go to Build Gradle (Module:app) Change the following. In my case, I choose 25.0.3

android {

    compileSdkVersion 25
    buildToolsVersion "25.0.3"
    defaultConfig {
        applicationId "com.example.cesarhcq.viisolutions"
        minSdkVersion 15
        targetSdkVersion 25

After that, it works fine!

multiple conditions for JavaScript .includes() method

You can use the .some method referenced here.

The some() method tests whether at least one element in the array passes the test implemented by the provided function.

_x000D_
_x000D_
// test cases
var str1 = 'hi, how do you do?';
var str2 = 'regular string';

// do the test strings contain these terms?
var conditions = ["hello", "hi", "howdy"];

// run the tests against every element in the array
var test1 = conditions.some(el => str1.includes(el));
var test2 = conditions.some(el => str2.includes(el));

// display results
console.log(str1, ' ===> ', test1);
console.log(str2, ' ===> ', test2);
_x000D_
_x000D_
_x000D_

The Controls collection cannot be modified because the control contains code blocks (i.e. <% ... %>)

Just in case if you are using Telerik components and you have a reference in your javascript with <%= .... %> then wrap your script tag with a RadScriptBlock.

 <telerik:RadScriptBlock ID="radSript1" runat="server">
   <script type="text/javascript">
        //Your javascript
   </script>
</telerik>

Regards Örvar

BACKUP LOG cannot be performed because there is no current database backup

Simply you can use this method:

  1. If you have a database with same name: WIN+R -> services.msc -> SQL SERVER(MSSQLSERVER) -> Stop
  2. Go to your MySQL Data folder path and delete previews database files
  3. Start sql service
  4. Right click on database and select Restore database
  5. in Files tab change Data file folder and Log file folder
  6. Click on OK to restore your database

my problem was solved with this method BY...

Difference between Visual Basic 6.0 and VBA

It's VBA. VBA means Visual Basic for Applications, and it is used for macros on Office documents. It doesn't have access to VB.NET features, so it's more like a modified version of VB6, with add-ons to be able to work on the document (like Worksheet in VBA for Excel).

Input placeholders for Internet Explorer

Best one in my experience is https://github.com/mathiasbynens/jquery-placeholder (recommended by html5please.com). http://afarkas.github.com/webshim/demos/index.html also has a good solution among its much more extensive library of polyfills.

Transparent scrollbar with css

With pure css it is not possible to make it transparent. You have to use transparent background image like this:

::-webkit-scrollbar-track-piece:start {
    background: transparent url('images/backgrounds/scrollbar.png') repeat-y !important;
}

::-webkit-scrollbar-track-piece:end {
    background: transparent url('images/backgrounds/scrollbar.png') repeat-y !important;
}

Setting DEBUG = False causes 500 Error

I have a hilarious story for all. After reaching this page I said "Eureka! I'm saved. That MUST be my problem." So I inserted the required ALLOWED_HOSTS list in setting.py and... nothing. Same old 500 error. And no, it wasn't for lack of a 404.html file.

So for 2 days I busied myself with wild theories, such as that it had something to do with serving static files (understand that I am a noob and noobs don't know what they're doing).

So what was it? It is now Mr. Moderator that we come to a useful tip. Whereas my development Django is version 1.5.something, my production server version is 1.5.something+1... or maybe plus 2. Whatever. And so after I added the ALLOWED_HOSTS to the desktop version of settings.py, which lacked what hwjp requested--- a "default value in settings.py, perhaps with an explanatory comment"--- I did the same on the production server with the proper domain for it.

But I failed to notice that on the production server with the later version of Django there WAS a default value in settings.py with an explanatory comment. It was well below where I made my entry, out of sight on the monitor. And of course the list was empty. Hence my waste of time.

Clear terminal in Python

As for me, the most elegant variant:

import os
os.system('cls||clear')

Show / hide div on click with CSS

HTML

<input type="text" value="CLICK TO SHOW CONTENT">
<div id="content">
and the content will show.
</div>

CSS

_x000D_
_x000D_
#content {
  display: none;
}
input[type="text"]{
    color: transparent;
    text-shadow: 0 0 0 #000;
    padding: 6px 12px;
    width: 150px;
    cursor: pointer;
}
input[type="text"]:focus{
    outline: none;
}
input:focus + div#content {
  display: block;
}
_x000D_
<input type="text" value="CLICK TO SHOW CONTENT">
<div id="content">
and the content will show.
</div>
_x000D_
_x000D_
_x000D_

Which is faster: multiple single INSERTs or one multiple-row INSERT?

In general, multiple inserts will be slower because of the connection overhead. Doing multiple inserts at once will reduce the cost of overhead per insert.

Depending on which language you are using, you can possibly create a batch in your programming/scripting language before going to the db and add each insert to the batch. Then you would be able to execute a large batch using one connect operation. Here's an example in Java.

How to for each the hashmap?

I generally do the same as cx42net, but I don't explicitly create an Entry.

HashMap<String, HashMap> selects = new HashMap<String, HashMap>();
for (String key : selects.keySet())
{
    HashMap<innerKey, String> boxHolder = selects.get(key);
    ComboBox cb = new ComboBox();
    for (InnerKey innerKey : boxHolder.keySet())
    {
        cb.items.add(boxHolder.get(innerKey));
    }
}

This just seems the most intuitive to me, I think I'm prejudiced against iterating over the values of a map.

How to reset or change the passphrase for a GitHub SSH key?

You can change the passphrase for your private key by doing:

ssh-keygen -f ~/.ssh/id_rsa -p

New Line Issue when copying data from SQL Server 2012 to Excel

This sometimes happens with Excel when you've recently used "Text to Columns."

Try exiting out of excel, reopening, and pasting again. That usually works for me, but I've heard you sometimes have to restart your computer altogether.

jQuery selector for the label of a checkbox

Thanks Kip, for those who may be looking to achieve the same using $(this) whilst iterating or associating within a function:

$("label[for="+$(this).attr("id")+"]").addClass( "orienSel" );

I looked for a while whilst working this project but couldn't find a good example so I hope this helps others who may be looking to resolve the same issue.

In the example above, my objective was to hide the radio inputs and style the labels to provide a slicker user experience (changing the orientation of the flowchart).

You can see an example here

If you like the example, here is the css:

.orientation {      position: absolute; top: -9999px;   left: -9999px;}
    .orienlabel{background:#1a97d4 url('http://www.ifreight.solutions/process.html/images/icons/flowChart.png') no-repeat 2px 5px; background-size: 40px auto;color:#fff; width:50px;height:50px;display:inline-block; border-radius:50%;color:transparent;cursor:pointer;}
    .orR{   background-position: 9px -57px;}
    .orT{   background-position: 2px -120px;}
    .orB{   background-position: 6px -177px;}

    .orienSel {background-color:#323232;}

and the relevant part of the JavaScript:

function changeHandler() {
    $(".orienSel").removeClass( "orienSel" );
    if(this.checked) {
        $("label[for="+$(this).attr("id")+"]").addClass( "orienSel" );
    }
};

An alternate root to the original question, given the label follows the input, you could go with a pure css solution and avoid using JavaScript altogether...:

input[type=checkbox]:checked+label {}

jQuery's .on() method combined with the submit event

I had a problem with the same symtoms. In my case, it turned out that my submit function was missing the "return" statement.

For example:

 $("#id_form").on("submit", function(){
   //Code: Action (like ajax...)
   return false;
 })

How to use .htaccess in WAMP Server?

RewriteEngine on
RewriteBase /basic_test/

RewriteRule ^index.php$ test.php

How to return a custom object from a Spring Data JPA GROUP BY query

@Repository
public interface ExpenseRepo extends JpaRepository<Expense,Long> {
    List<Expense> findByCategoryId(Long categoryId);

    @Query(value = "select category.name,SUM(expense.amount) from expense JOIN category ON expense.category_id=category.id GROUP BY expense.category_id",nativeQuery = true)
    List<?> getAmountByCategory();

}

The above code worked for me.

How can one pull the (private) data of one's own Android app?

Newer versions of Android Studio include the Device File Explorer which I've found to be a handy GUI method of downloading files from my development Nexus 7.

You Must make sure you have enabled USB Debugging on the device

  1. Click View > Tool Windows > Device File Explorer or click the Device File Explorer button in the tool window bar to open the Device File Explorer.
  2. Select a device from the drop down list.
  3. Interact with the device content in the file explorer window. Right-click on a file or directory to create a new file or directory, save the selected file or directory to your machine, upload, delete, or synchronize. Double-click a file to open it in Android Studio.

    Android Studio saves files you open this way in a temporary directory outside of your project. If you make modifications to a file you opened using the Device File Explorer, and would like to save your changes back to the device, you must manually upload the modified version of the file to the device.

file explorer

Full Documentation

What exactly does the .join() method do?

join takes an iterable thing as an argument. Usually it's a list. The problem in your case is that a string is itself iterable, giving out each character in turn. Your code breaks down to this:

"wlfgALGbXOahekxSs".join("595")

which acts the same as this:

"wlfgALGbXOahekxSs".join(["5", "9", "5"])

and so produces your string:

"5wlfgALGbXOahekxSs9wlfgALGbXOahekxSs5"

Strings as iterables is one of the most confusing beginning issues with Python.

Calculate distance in meters when you know longitude and latitude in java

Based on another question on stackoverflow, I got this code.. This calculates the result in meters, not in miles :)

 public static float distFrom(float lat1, float lng1, float lat2, float lng2) {
    double earthRadius = 6371000; //meters
    double dLat = Math.toRadians(lat2-lat1);
    double dLng = Math.toRadians(lng2-lng1);
    double a = Math.sin(dLat/2) * Math.sin(dLat/2) +
               Math.cos(Math.toRadians(lat1)) * Math.cos(Math.toRadians(lat2)) *
               Math.sin(dLng/2) * Math.sin(dLng/2);
    double c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
    float dist = (float) (earthRadius * c);

    return dist;
    }

if (select count(column) from table) > 0 then

Edit:

The oracle tag was not on the question when this answer was offered, and apparently it doesn't work with oracle, but it does work with at least postgres and mysql

No, just use the value directly:

begin
  if (select count(*) from table) > 0 then
     update table
  end if;
end;

Note there is no need for an "else".

Edited

You can simply do it all within the update statement (ie no if construct):

update table
set ...
where ...
and exists (select 'x' from table where ...)

Delete all duplicate rows Excel vba

The duplicate values in any column can be deleted with a simple for loop.

Sub remove()
Dim a As Long
For a = Cells(Rows.Count, 1).End(xlUp).Row To 1 Step -1
If WorksheetFunction.CountIf(Range("A1:A" & a), Cells(a, 1)) > 1 Then Rows(a).Delete
Next
End Sub

Should I use != or <> for not equal in T-SQL?

I preferred using != instead of <> because sometimes I use the <s></s> syntax to write SQL commands. Using != is more handy to avoid syntax errors in this case.

Angularjs dynamic ng-pattern validation

Not taking anything away from Nikos' awesome answer, perhaps you can do this more simply:

<form name="telForm">
  <input name="cb" type='checkbox' data-ng-modal='requireTel'>
  <input name="tel" type="text" ng-model="..." ng-if='requireTel' ng-pattern="phoneNumberPattern" required/>
  <button type="submit" ng-disabled="telForm.$invalid || telForm.$pristine">Submit</button>
</form>

Pay attention to the second input: We can use an ng-if to control rendering and validation in forms. If the requireTel variable is unset, the second input would not only be hidden, but not rendered at all, thus the form will pass validation and the button will become enabled, and you'll get what you need.

React.js: Identifying different inputs with one onChange handler

Deprecated solution

valueLink/checkedLink are deprecated from core React, because it is confusing some users. This answer won't work if you use a recent version of React. But if you like it, you can easily emulate it by creating your own Input component

Old answer content:

What you want to achieve can be much more easily achieved using the 2-way data binding helpers of React.

var Hello = React.createClass({
    mixins: [React.addons.LinkedStateMixin],
    getInitialState: function() {
        return {input1: 0, input2: 0};
    },

    render: function() {
        var total = this.state.input1 + this.state.input2;
        return (
            <div>{total}<br/>
                <input type="text" valueLink={this.linkState('input1')} />;
                <input type="text" valueLink={this.linkState('input2')} />;
            </div>
        );
    }

});

React.renderComponent(<Hello />, document.getElementById('content'));

Easy right?

http://facebook.github.io/react/docs/two-way-binding-helpers.html

You can even implement your own mixin

What tool can decompile a DLL into C++ source code?

There are no decompilers which I know about. W32dasm is good Win32 disassembler.

Groovy: How to check if a string contains any element of an array?

def valid = pointAddress.findAll { a ->
    validPointTypes.any { a.contains(it) }
}

Should do it

Selenium Web Driver & Java. Element is not clickable at point (x, y). Other element would receive the click

Scrolling the page to the near by point mentioned in the exception did the trick for me. Below is code snippet:

$wd_host = 'http://localhost:4444/wd/hub';
$capabilities =
    [
        \WebDriverCapabilityType::BROWSER_NAME => 'chrome',
        \WebDriverCapabilityType::PROXY => [
            'proxyType' => 'manual',
            'httpProxy' => PROXY_DOMAIN.':'.PROXY_PORT,
            'sslProxy' => PROXY_DOMAIN.':'.PROXY_PORT,
            'noProxy' =>  PROXY_EXCEPTION // to run locally
        ],
    ];
$webDriver = \RemoteWebDriver::create($wd_host, $capabilities, 250000, 250000);
...........
...........
// Wait for 3 seconds
$webDriver->wait(3);
// Scrolls the page vertically by 70 pixels 
$webDriver->executeScript("window.scrollTo(0, 70);");

NOTE: I use Facebook php webdriver

NullInjectorError: No provider for AngularFirestore

I had the same issue while adding firebase to my Ionic App. To fix the issue I followed these steps:

npm install @angular/fire firebase --save

In my app/app.module.ts:

...
import { AngularFireModule } from '@angular/fire';
import { environment } from '../environments/environment';
import { AngularFirestoreModule, SETTINGS } from '@angular/fire/firestore';

@NgModule({
  declarations: [AppComponent],
  entryComponents: [],
  imports: [
    BrowserModule, 
    AppRoutingModule,
    AngularFireModule.initializeApp(environment.firebase),
    AngularFirestoreModule
  ],
  providers: [
    { provide: SETTINGS, useValue: {} }
  ],
  bootstrap: [AppComponent]
})

Previously we used FirestoreSettingsToken instead of SETTINGS. But that bug got resolved, now we use SETTINGS. (link)

In my app/services/myService.ts I imported as:

import { AngularFirestore } from "@angular/fire/firestore";

For some reason vscode was importing it as "@angular/fire/firestore/firestore";I After changing it for "@angular/fire/firestore"; the issue got resolved!

Simplest JQuery validation rules example

rules: {
    cname: {
        required: true,
        minlength: 2
    }
},
messages: {
    cname: {
        required: "<li>Please enter a name.</li>",
        minlength: "<li>Your name is not long enough.</li>"
    }
}

I can't install python-ldap

The python-ldap is based on OpenLDAP, so you need to have the development files (headers) in order to compile the Python module. If you're on Ubuntu, the package is called libldap2-dev.

Debian/Ubuntu:

sudo apt-get install libsasl2-dev python-dev libldap2-dev libssl-dev

RedHat/CentOS:

sudo yum install python-devel openldap-devel

When should I use UNSIGNED and SIGNED INT in MySQL?

For negative integer value, SIGNED is used and for non-negative integer value, UNSIGNED is used. It always suggested to use UNSIGNED for id as a PRIMARY KEY.

How to set specific window (frame) size in java swing?

Most layout managers work best with a component's preferredSize, and most GUI's are best off allowing the components they contain to set their own preferredSizes based on their content or properties. To use these layout managers to their best advantage, do call pack() on your top level containers such as your JFrames before making them visible as this will tell these managers to do their actions -- to layout their components.

Often when I've needed to play a more direct role in setting the size of one of my components, I'll override getPreferredSize and have it return a Dimension that is larger than the super.preferredSize (or if not then it returns the super's value).

For example, here's a small drag-a-rectangle app that I created for another question on this site:

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class MoveRect extends JPanel {
   private static final int RECT_W = 90;
   private static final int RECT_H = 70;
   private static final int PREF_W = 600;
   private static final int PREF_H = 300;
   private static final Color DRAW_RECT_COLOR = Color.black;
   private static final Color DRAG_RECT_COLOR = new Color(180, 200, 255);
   private Rectangle rect = new Rectangle(25, 25, RECT_W, RECT_H);
   private boolean dragging = false;
   private int deltaX = 0;
   private int deltaY = 0;

   public MoveRect() {
      MyMouseAdapter myMouseAdapter = new MyMouseAdapter();
      addMouseListener(myMouseAdapter);
      addMouseMotionListener(myMouseAdapter);
   }

   @Override
   protected void paintComponent(Graphics g) {
      super.paintComponent(g);
      if (rect != null) {
         Color c = dragging ? DRAG_RECT_COLOR : DRAW_RECT_COLOR;
         g.setColor(c);
         Graphics2D g2 = (Graphics2D) g;
         g2.draw(rect);
      }
   }

   @Override
   public Dimension getPreferredSize() {
      return new Dimension(PREF_W, PREF_H);
   }

   private class MyMouseAdapter extends MouseAdapter {

      @Override
      public void mousePressed(MouseEvent e) {
         Point mousePoint = e.getPoint();
         if (rect.contains(mousePoint)) {
            dragging = true;
            deltaX = rect.x - mousePoint.x;
            deltaY = rect.y - mousePoint.y;
         }
      }

      @Override
      public void mouseReleased(MouseEvent e) {
         dragging = false;
         repaint();
      }

      @Override
      public void mouseDragged(MouseEvent e) {
         Point p2 = e.getPoint();
         if (dragging) {
            int x = p2.x + deltaX;
            int y = p2.y + deltaY;
            rect = new Rectangle(x, y, RECT_W, RECT_H);
            MoveRect.this.repaint();
         }
      }
   }

   private static void createAndShowGui() {
      MoveRect mainPanel = new MoveRect();

      JFrame frame = new JFrame("MoveRect");
      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      frame.getContentPane().add(mainPanel);
      frame.pack();
      frame.setLocationByPlatform(true);
      frame.setVisible(true);
   }

   public static void main(String[] args) {
      SwingUtilities.invokeLater(new Runnable() {
         public void run() {
            createAndShowGui();
         }
      });
   }
}

Note that my main class is a JPanel, and that I override JPanel's getPreferredSize:

public class MoveRect extends JPanel {
   //.... deleted constants

   private static final int PREF_W = 600;
   private static final int PREF_H = 300;

   //.... deleted fields and constants

   //... deleted methods and constructors

   @Override
   public Dimension getPreferredSize() {
      return new Dimension(PREF_W, PREF_H);
   }

Also note that when I display my GUI, I place it into a JFrame, call pack(); on the JFrame, set its position, and then call setVisible(true); on my JFrame:

   private static void createAndShowGui() {
      MoveRect mainPanel = new MoveRect();

      JFrame frame = new JFrame("MoveRect");
      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      frame.getContentPane().add(mainPanel);
      frame.pack();
      frame.setLocationByPlatform(true);
      frame.setVisible(true);
   }

   public static void main(String[] args) {
      SwingUtilities.invokeLater(new Runnable() {
         public void run() {
            createAndShowGui();
         }
      });
   }
}

How to get a table cell value using jQuery?

$('#mytable tr').each(function() {
    var customerId = $(this).find("td:first").html();    
});

What you are doing is iterating through all the trs in the table, finding the first td in the current tr in the loop, and extracting its inner html.

To select a particular cell, you can reference them with an index:

$('#mytable tr').each(function() {
    var customerId = $(this).find("td").eq(2).html();    
});

In the above code, I will be retrieving the value of the third row (the index is zero-based, so the first cell index would be 0)


Here's how you can do it without jQuery:

var table = document.getElementById('mytable'), 
    rows = table.getElementsByTagName('tr'),
    i, j, cells, customerId;

for (i = 0, j = rows.length; i < j; ++i) {
    cells = rows[i].getElementsByTagName('td');
    if (!cells.length) {
        continue;
    }
    customerId = cells[0].innerHTML;
}

?

jQuery lose focus event

blur event: when the element loses focus.

focusout event: when the element, or any element inside of it, loses focus.

As there is nothing inside the filter element, both blur and focusout will work in this case.

$(function() {
  $('#filter').blur(function() {
    $('#options').hide();
  });
})

jsfiddle with blur: http://jsfiddle.net/yznhb8pc/

$(function() {
  $('#filter').focusout(function() {
    $('#options').hide();
  });
})

jsfiddle with focusout: http://jsfiddle.net/yznhb8pc/1/

Provide password to ssh command inside bash script, Without the usage of public keys and Expect

AFAIK there is no possibility beside from using keys or expect if you are using the command line version ssh. But there are library bindings for the most programming languages like C, python, php, ... . You could write a program in such a language. This way it would be possible to pass the password automatically. But note this is of course a security problem as the password will be stored in plain text in that program

How do I specify new lines on Python, when writing on files?

Most escape characters in string literals from Java are also valid in Python, such as "\r" and "\n".

Passing parameters to JavaScript files

You use Global variables :-D.

Like this:

<script type="text/javascript">
   var obj1 = "somevalue";
   var obj2 = "someothervalue";
</script>
<script type="text/javascript" src="file.js"></script">

The JavaScript code in 'file.js' can access to obj1 and obj2 without problem.

EDIT Just want to add that if 'file.js' wants to check if obj1 and obj2 have even been declared you can use the following function.

function IsDefined($Name) {
    return (window[$Name] != undefined);
}

Hope this helps.

Spring MVC How take the parameter value of a GET HTTP Request in my controller method?

As explained in the documentation, by using an @RequestParam annotation:

public @ResponseBody String byParameter(@RequestParam("foo") String foo) {
    return "Mapped by path + method + presence of query parameter! (MappingController) - foo = "
           + foo;
}

Removing rounded corners from a <select> element in Chrome/Webkit

Inset box-shadow does the trick.

select{
  -webkit-appearance: none;
  box-shadow: inset 0px 0px 0px 4px;
  border-radius: 0px;
  border: none;
  padding:20px 150px 20px 10px;
}

Demo

How to show one layout on top of the other programmatically in my case?

The answer, given by Alexandru is working quite nice. As he said, it is important that this "accessor"-view is added as the last element. Here is some code which did the trick for me:

        ...

        ...

            </LinearLayout>

        </LinearLayout>

    </FrameLayout>

</LinearLayout>

<!-- place a FrameLayout (match_parent) as the last child -->
<FrameLayout
    android:id="@+id/icon_frame_container"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
</FrameLayout>

</TabHost>

in Java:

final MaterialDialog materialDialog = (MaterialDialog) dialogInterface;

FrameLayout frameLayout = (FrameLayout) materialDialog
        .findViewById(R.id.icon_frame_container);

frameLayout.setOnTouchListener(
        new OnSwipeTouchListener(ShowCardActivity.this) {

SQL-Server: Is there a SQL script that I can use to determine the progress of a SQL Server backup or restore process?

For anyone running SQL Server on RDS (AWS), there's a built-in procedure callable in the msdb database which provides comprehensive information for all backup and restore tasks:

exec msdb.dbo.rds_task_status;

This will give a full rundown of each task, its configuration, details about execution (such as completed percentage and total duration), and a task_info column which is immensely helpful when trying to figure out what's wrong with a backup or restore.

Google Drive as FTP Server

I couldn't find a direct GDrive/DropBox solution. I'm also surprised there's no lazy solution for a free ftp host. Windows azure offers a ftp server "FTP connector" that's fairly easy to turn on at: https://portal.azure.com

You can get a free 1 GB account by selecting "View All" machine types during your deployment.

Bootstrap date time picker

Well, here the positioning of the css and script links makes a to of difference. Bootstrap executes in CSS and then Scripts fashion. So if you have even one script written at incorrect place it makes a lot of difference. You can follow the below snippet and change your code accordingly.

_x000D_
_x000D_
<!DOCTYPE html>_x000D_
<html lang="en">_x000D_
<head>_x000D_
    <meta charset="utf-8">_x000D_
    <meta name="viewport" content="width=device-width, initial-scale=1">_x000D_
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">_x000D_
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>_x000D_
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>_x000D_
_x000D_
    <!-- <link rel="stylesheet" type="text/css" href="css/bootstrap-datetimepicker.css"> -->_x000D_
    <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.15.1/moment.min.js"></script>_x000D_
    <link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datetimepicker/4.17.43/css/bootstrap-datetimepicker.min.css"> _x000D_
    <link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datetimepicker/4.17.43/css/bootstrap-datetimepicker-standalone.css"> _x000D_
    <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datetimepicker/4.17.43/js/bootstrap-datetimepicker.min.js"></script>_x000D_
    _x000D_
</head>_x000D_
<body>_x000D_
     <div class="container">_x000D_
          <div class="row">_x000D_
            <div class='col-sm-6'>_x000D_
                <div class="form-group">_x000D_
                    <div class='input-group date' id='datetimepicker1'>_x000D_
                        <input type='text' class="form-control" />_x000D_
                        <span class="input-group-addon">_x000D_
                            <span class="glyphicon glyphicon-calendar"></span>_x000D_
                        </span>_x000D_
                    </div>_x000D_
                </div>_x000D_
            </div>_x000D_
            <script type="text/javascript">_x000D_
                $(function () {_x000D_
                    $('#datetimepicker1').datetimepicker();_x000D_
                });_x000D_
            </script>_x000D_
          </div>_x000D_
       </div>_x000D_
    </body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

Running javascript in Selenium using Python

If you move from iframes, you may get lost in your page, best way to execute some jquery without issue (with selenimum/python/gecko):

# 1) Get back to the main body page
driver.switch_to.default_content()

# 2) Download jquery lib file to your current folder manually & set path here
with open('./_lib/jquery-3.3.1.min.js', 'r') as jquery_js: 
    # 3) Read the jquery from a file
    jquery = jquery_js.read() 
    # 4) Load jquery lib
    driver.execute_script(jquery)
    # 5) Execute your command 
    driver.execute_script('$("#myId").click()')

Android: Scale a Drawable or background image?

Haven't tried to do exactly what you want, but you can scale an ImageView using android:scaleType="fitXY"
and it will be sized to fit into whatever size you give the ImageView.

So you could create a FrameLayout for your layout, put the ImageView inside it, and then whatever other content you need in the FrameLayout as well w/ a transparent background.

<FrameLayout  
android:layout_width="fill_parent" android:layout_height="fill_parent">

  <ImageView 
android:layout_width="fill_parent" android:layout_height="fill_parent"
android:src="@drawable/back" android:scaleType="fitXY" />

  <LinearLayout>your views</LinearLayout>
</FrameLayout>

How to display full (non-truncated) dataframe information in html when converting from pandas dataframe to html?

For those looking to do this in dask. I could not find a similar option in dask but if I simply do this in same notebook for pandas it works for dask too.

import pandas as pd
import dask.dataframe as dd
pd.set_option('display.max_colwidth', -1) # This will set the no truncate for pandas as well as for dask. Not sure how it does for dask though. but it works

train_data = dd.read_csv('./data/train.csv')    
train_data.head(5)

org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'demoRestController'

To me it happened in DogController that autowired DogService that autowired DogRepository. Dog class used to have field name but I changed it to coolName, but didn't change methods in DogRepository: Dog findDogByName(String name). I change that method to Dog findDogByCoolName(String name) and now it works.

What is the best way to find the users home directory in Java?

Others have answered the question before me but a useful program to print out all available properties is:

for (Map.Entry<?,?> e : System.getProperties().entrySet()) {
    System.out.println(String.format("%s = %s", e.getKey(), e.getValue())); 
}

Memory Allocation "Error: cannot allocate vector of size 75.1 Mb"

R has gotten to the point where the OS cannot allocate it another 75.1Mb chunk of RAM. That is the size of memory chunk required to do the next sub-operation. It is not a statement about the amount of contiguous RAM required to complete the entire process. By this point, all your available RAM is exhausted but you need more memory to continue and the OS is unable to make more RAM available to R.

Potential solutions to this are manifold. The obvious one is get hold of a 64-bit machine with more RAM. I forget the details but IIRC on 32-bit Windows, any single process can only use a limited amount of RAM (2GB?) and regardless Windows will retain a chunk of memory for itself, so the RAM available to R will be somewhat less than the 3.4Gb you have. On 64-bit Windows R will be able to use more RAM and the maximum amount of RAM you can fit/install will be increased.

If that is not possible, then consider an alternative approach; perhaps do your simulations in batches with the n per batch much smaller than N. That way you can draw a much smaller number of simulations, do whatever you wanted, collect results, then repeat this process until you have done sufficient simulations. You don't show what N is, but I suspect it is big, so try smaller N a number of times to give you N over-all.

Get a random boolean in python?

You could use the Faker library, it's mainly used for testing, but is capable of providing a variety of fake data.

Install: https://pypi.org/project/Faker/

>>> from faker import Faker
>>> fake = Faker()
>>> fake.pybool()
True

Android: Create a toggle button with image and no text

I know this is a little late, however for anyone interested, I've created a custom component that is basically a toggle image button, the drawable can have states as well as the background

https://gist.github.com/akshaydashrath/9662072

Command not found after npm install in zsh

In my case, Reinstalling node solve the issue. Anyone can install the node via below website.

https://nodejs.org/en/download/

How to rename a file using svn?

You can do it by following 3 steps:

 - svn rm old_file_name
 - svn add new_file_name
 - svn commit

Eclipse fonts and background color

You can install eclipse theme plugin then select default. Please visit here: http://eclipsecolorthemes.org/?view=plugin

python pip on Windows - command 'cl.exe' failed

Refer to this link:

https://www.lfd.uci.edu/~gohlke/pythonlibs/#cytoolz

Download the right whl package for you python version(if you have trouble knowing what version of python you have, just lunch the interpreter )

use pip to install the package, assuming that the file is in downloads folder and you have python 3.6 32 bit :

python -m pip install C:\Users\%USER%\Downloads\cytoolz-0.9.0.1-cp36-cp36m-win32.whl

this is not valid for just this package, but for any package that cannot compile under your own windows installation.

How to show MessageBox on asp.net?

MessageBox doesn't exist in ASP.NET. If you need functionality in the browser, like showing a message box, then you need to opt for javascript. ASP.NET provides you with means to inject javascript which gets rendered and executed when the html sent to the browser's loaded and displayed. You can use the following code in the Page_Load for example:

Type cstype = this.GetType();

// Get a ClientScriptManager reference from the Page class.
ClientScriptManager cs = Page.ClientScript;

// Check to see if the startup script is already registered.
if (!cs.IsStartupScriptRegistered(cstype, "PopupScript"))
{
    String cstext = "alert('Hello World');";
    cs.RegisterStartupScript(cstype, "PopupScript", cstext, true);
}

This sample's taken from MSDN.

How to generate access token using refresh token through google drive API?

If you want to implement that yourself, the OAuth 2.0 flow for Web Server Applications is documented at https://developers.google.com/accounts/docs/OAuth2WebServer, in particular you should check the section about using a refresh token:

https://developers.google.com/accounts/docs/OAuth2WebServer#refresh

Add Variables to Tuple

I'm pretty sure the syntax for this in python is:

user_input1 = raw_input("Enter Name: ")
user_input2 = raw_input("Enter Value: ")
info = (user_input1, user_input2)

once set, tuples cannot be changed.

TensorFlow, "'module' object has no attribute 'placeholder'"

Because you cant use placeholder in tensflow2.0version, so you need to use tensflow1*, or you need to change your code to fix tensflow2.0

Postgres: How to convert a json string to text?

->> works for me.

postgres version:

<postgres.version>11.6</postgres.version>

Query:

select object_details->'valuationDate' as asofJson, object_details->>'valuationDate' as asofText from MyJsonbTable;

Output:

  asofJson       asofText
"2020-06-26"    2020-06-26
"2020-06-25"    2020-06-25
"2020-06-25"    2020-06-25
"2020-06-25"    2020-06-25

How to select data where a field has a min value in MySQL?

Efficient way (with any number of records):

SELECT id, name, MIN(price) FROM (select * from table order by price) as t group by id

Add bottom line to view in SwiftUI / Swift / Objective-C / Xamarin

Please have a look at the below code sample;

Swift 4:

@IBDesignable class DesignableUITextField: UITextField {

    let border = CALayer()

    @IBInspectable var borderColor: UIColor? {
        didSet {
            setup()
        }
    }

    @IBInspectable var borderWidth: CGFloat = 0.5 {
        didSet {
            setup()
        }
    }

    func setup() {
        border.borderColor = self.borderColor?.cgColor

        border.borderWidth = borderWidth
        self.layer.addSublayer(border)
        self.layer.masksToBounds = true
    }

    override func layoutSubviews() {
        super.layoutSubviews()
        border.frame = CGRect(x: 0, y: self.frame.size.height - borderWidth, width:  self.frame.size.width, height: self.frame.size.height)
    }
 }

Writing a dict to txt file and reading it back?

To store Python objects in files, use the pickle module:

import pickle

a = {
  'a': 1,
  'b': 2
}

with open('file.txt', 'wb') as handle:
  pickle.dump(a, handle)

with open('file.txt', 'rb') as handle:
  b = pickle.loads(handle.read())

print a == b # True

Notice that I never set b = a, but instead pickled a to a file and then unpickled it into b.

As for your error:

self.whip = open('deed.txt', 'r').read()

self.whip was a dictionary object. deed.txt contains text, so when you load the contents of deed.txt into self.whip, self.whip becomes the string representation of itself.

You'd probably want to evaluate the string back into a Python object:

self.whip = eval(open('deed.txt', 'r').read())

Notice how eval sounds like evil. That's intentional. Use the pickle module instead.

C# Select elements in list as List of string

List<string> empnames = emplist.Select(e => e.Ename).ToList();

This is an example of Projection in Linq. Followed by a ToList to resolve the IEnumerable<string> into a List<string>.

Alternatively in Linq syntax (head compiled):

var empnamesEnum = from emp in emplist 
                   select emp.Ename;
List<string> empnames = empnamesEnum.ToList();

Projection is basically representing the current type of the enumerable as a new type. You can project to anonymous types, another known type by calling constructors etc, or an enumerable of one of the properties (as in your case).

For example, you can project an enumerable of Employee to an enumerable of Tuple<int, string> like so:

var tuples = emplist.Select(e => new Tuple<int, string>(e.EID, e.Ename));

JSON Java 8 LocalDateTime format in Spring Boot

I found another solution which you can convert it to whatever format you want and apply to all LocalDateTime datatype and you do not have to specify @JsonFormat above every LocalDateTime datatype. first add the dependency :

<dependency>
    <groupId>com.fasterxml.jackson.datatype</groupId>
    <artifactId>jackson-datatype-jsr310</artifactId>
</dependency>

Add the following bean :

@Configuration
public class Java8DateTimeConfiguration {
    /**
     * Customizing
     * http://docs.spring.io/spring-boot/docs/current/reference/html/howto-spring-mvc.html
     *
     * Defining a @Bean of type Jackson2ObjectMapperBuilder will allow you to customize both default ObjectMapper and XmlMapper (used in MappingJackson2HttpMessageConverter and MappingJackson2XmlHttpMessageConverter respectively).
     */
    @Bean
    public Module jsonMapperJava8DateTimeModule() {
        val bean = new SimpleModule();

        bean.addDeserializer (ZonedDateTime.class, new JsonDeserializer<ZonedDateTime>() {
            @Override
            public ZonedDateTime deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException, JsonProcessingException {
                return ZonedDateTime.parse(jsonParser.getValueAsString(), DateTimeFormatter.ISO_ZONED_DATE_TIME);
            }
        });

        bean.addDeserializer(LocalDateTime.class, new JsonDeserializer<LocalDateTime>() {
            @Override
            public LocalDateTime deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException, JsonProcessingException {
                return LocalDateTime.parse(jsonParser.getValueAsString(), DateTimeFormatter.ISO_LOCAL_DATE_TIME);
            }
        });

        bean.addSerializer(ZonedDateTime.class, new JsonSerializer<ZonedDateTime>() {
            @Override
            public void serialize(
                    ZonedDateTime zonedDateTime, JsonGenerator jsonGenerator, SerializerProvider serializerProvider)
                    throws IOException {
                jsonGenerator.writeString(DateTimeFormatter.ISO_ZONED_DATE_TIME.format(zonedDateTime));
            }
        });

        bean.addSerializer(LocalDateTime.class, new JsonSerializer<LocalDateTime>() {
            @Override
            public void serialize(
                    LocalDateTime localDateTime, JsonGenerator jsonGenerator, SerializerProvider serializerProvider)
                    throws IOException {
                jsonGenerator.writeString(DateTimeFormatter.ISO_LOCAL_DATE_TIME.format(localDateTime));
            }
        });

        return bean;
    }
}

in your config file add the following :

@Import(Java8DateTimeConfiguration.class)

This will serialize and de-serialize all properties LocalDateTime and ZonedDateTime as long as you are using objectMapper created by spring.

The format that you got for ZonedDateTime is : "2017-12-27T08:55:17.317+02:00[Asia/Jerusalem]" for LocalDateTime is : "2017-12-27T09:05:30.523"

phpMyAdmin access denied for user 'root'@'localhost' (using password: NO)

found a solution, in my config file I just changed

$cfg['Servers'][$i]['auth_type'] = 'config';

to

$cfg['Servers'][$i]['auth_type'] = 'HTTP';

How do I see if Wi-Fi is connected on Android?

I simply use the following:

SupplicantState supState; 
wifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE);
WifiInfo wifiInfo = wifiManager.getConnectionInfo();
supState = wifiInfo.getSupplicantState();

Which will return one of these states at the time you call getSupplicantState();

ASSOCIATED - Association completed.

ASSOCIATING - Trying to associate with an access point.

COMPLETED - All authentication completed.

DISCONNECTED - This state indicates that client is not associated, but is likely to start looking for an access point.

DORMANT - An Android-added state that is reported when a client issues an explicit DISCONNECT command.

FOUR_WAY_HANDSHAKE - WPA 4-Way Key Handshake in progress.

GROUP_HANDSHAKE - WPA Group Key Handshake in progress.

INACTIVE - Inactive state.

INVALID - A pseudo-state that should normally never be seen.

SCANNING - Scanning for a network.

UNINITIALIZED - No connection.

Why does this code using random strings print "hello world"?

When an instance of java.util.Random is constructed with a specific seed parameter (in this case -229985452 or -147909649), it follows the random number generation algorithm beginning with that seed value.

Every Random constructed with the same seed will generate the same pattern of numbers every time.

Service vs IntentService in the Android platform

Tejas Lagvankar wrote a nice post about this subject. Below are some key differences between Service and IntentService.

When to use?

  • The Service can be used in tasks with no UI, but shouldn't be too long. If you need to perform long tasks, you must use threads within Service.

  • The IntentService can be used in long tasks usually with no communication to Main Thread. If communication is required, can use Main Thread handler or broadcast intents. Another case of use is when callbacks are needed (Intent triggered tasks).

How to trigger?

  • The Service is triggered by calling method startService().

  • The IntentService is triggered using an Intent, it spawns a new worker thread and the method onHandleIntent() is called on this thread.

Triggered From

  • The Service and IntentService may be triggered from any thread, activity or other application component.

Runs On

  • The Service runs in background but it runs on the Main Thread of the application.

  • The IntentService runs on a separate worker thread.

Limitations / Drawbacks

  • The Service may block the Main Thread of the application.

  • The IntentService cannot run tasks in parallel. Hence all the consecutive intents will go into the message queue for the worker thread and will execute sequentially.

When to stop?

  • If you implement a Service, it is your responsibility to stop the service when its work is done, by calling stopSelf() or stopService(). (If you only want to provide binding, you don't need to implement this method).

  • The IntentService stops the service after all start requests have been handled, so you never have to call stopSelf().

Dynamically load JS inside JS

jQuery's $.getScript() is buggy sometimes, so I use my own implementation of it like:

jQuery.loadScript = function (url, callback) {
    jQuery.ajax({
        url: url,
        dataType: 'script',
        success: callback,
        async: true
    });
}

and use it like:

if (typeof someObject == 'undefined') $.loadScript('url_to_someScript.js', function(){
    //Stuff to do after someScript has loaded
});

Find unused code

The truth is that the tool can never give you a 100% certain answer, but coverage tool can give you a pretty good run for the money.

If you count with comprehensive unit test suite, than you can use test coverage tool to see exactly what lines of code were not executed during the test run. You will still need to analyze the code manually: either eliminate what you consider dead code or write test to improve test coverage.

One such tool is NCover, with open source precursor on Sourceforge. Another alternative is PartCover.

Check out this answer on stackoverflow.

jQuery AJAX single file upload

After hours of searching and looking for answer, finally I made it!!!!! Code is below :))))

HTML:

<form id="fileinfo" enctype="multipart/form-data" method="post" name="fileinfo">
    <label>File to stash:</label>
    <input type="file" name="file" required />
</form>
<input type="button" value="Stash the file!"></input>
<div id="output"></div>

jQuery:

$(function(){
    $('#uploadBTN').on('click', function(){ 
        var fd = new FormData($("#fileinfo"));
        //fd.append("CustomField", "This is some extra data");
        $.ajax({
            url: 'upload.php',  
            type: 'POST',
            data: fd,
            success:function(data){
                $('#output').html(data);
            },
            cache: false,
            contentType: false,
            processData: false
        });
    });
});

In the upload.php file you can access the data passed with $_FILES['file'].

Thanks everyone for trying to help:)

I took the answer from here (with some changes) MDN

Read file line by line in PowerShell

Not much documentation on PowerShell loops.

Documentation on loops in PowerShell is plentiful, and you might want to check out the following help topics: about_For, about_ForEach, about_Do, about_While.

foreach($line in Get-Content .\file.txt) {
    if($line -match $regex){
        # Work here
    }
}

Another idiomatic PowerShell solution to your problem is to pipe the lines of the text file to the ForEach-Object cmdlet:

Get-Content .\file.txt | ForEach-Object {
    if($_ -match $regex){
        # Work here
    }
}

Instead of regex matching inside the loop, you could pipe the lines through Where-Object to filter just those you're interested in:

Get-Content .\file.txt | Where-Object {$_ -match $regex} | ForEach-Object {
    # Work here
}

How do I make a dotted/dashed line in Android?

None of these answers worked for me. Most of these answers give you a half-transparent border. To avoid this, you need to wrap your container once again with another container with your preferred color. Here is an example:

This is how it looks

dashed_border_layout.xml

<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:backgroundTint="@color/black"
android:background="@drawable/dashed_border_out">
<LinearLayout
    android:layout_width="150dp"
    android:layout_height="50dp"
    android:padding="5dp"
    android:background="@drawable/dashed_border_in"
    android:orientation="vertical">
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="This is&#10;Dashed Container"
        android:textSize="16sp" />
</LinearLayout>

dashed_border_in.xml

<layer-list xmlns:android="http://schemas.android.com/apk/res/android" >
<item>
    <shape>
        <corners android:radius="10dp" />
        <solid android:color="#ffffff" />
        <stroke
            android:dashGap="5dp"
            android:dashWidth="5dp"
            android:width="3dp"
            android:color="#0000FF" />
        <padding
            android:bottom="5dp"
            android:left="5dp"
            android:right="5dp"
            android:top="5dp" />
    </shape>
</item>

dashed_border_out.xml

<layer-list xmlns:android="http://schemas.android.com/apk/res/android" >
<item>
    <shape>
        <corners android:radius="12dp" />
    </shape>
</item>

Get current url in Angular

other.component.ts

So final correct solution is :

import { Component, OnInit } from '@angular/core';
import { Location } from '@angular/common';
import { Router } from '@angular/router'; 

/* 'router' it must be in small case */

    @Component({
      selector: 'app-other',
      templateUrl: './other.component.html',
      styleUrls: ['./other.component.css']
    })

    export class OtherComponent implements OnInit {

        public href: string = "";
        url: string = "asdf";

        constructor(private router : Router) {} // make variable private so that it would be accessible through out the component

        ngOnInit() {
            this.href = this.router.url;
            console.log(this.router.url);
        }
    }

Loading existing .html file with android WebView

ok, that was my very stupid mistake. I post the answer here just in case someone has the same problem.

The correct path for files stored in assets folder is file:///android_asset/* (with no "s" for assets folder which i was always thinking it must have a "s").

And, mWebView.loadUrl("file:///android_asset/myfile.html"); works under all API levels.

I still not figure out why mWebView.loadUrl("file:///android_res/raw/myfile.html"); works only on API level 8. But it doesn't matter now.

OpenCV Python rotate image by X degrees around specific point

def rotate(image, angle, center = None, scale = 1.0):
    (h, w) = image.shape[:2]

    if center is None:
        center = (w / 2, h / 2)

    # Perform the rotation
    M = cv2.getRotationMatrix2D(center, angle, scale)
    rotated = cv2.warpAffine(image, M, (w, h))

    return rotated

What's the best/easiest GUI Library for Ruby?

I've had some very good experience with Qt, so I would definitely recommend it.

You should be ware of the licensing model though. If you're developing an open source application, you can use the open-source licensed version free of charge. If you're developing a commercial application, you'll have to pay license fees. And you can't develop in the open source one and then switch the license to commercial before you start selling.

P.S. I just had a quick look at shoes. I really like the declarative definitions of the UI elements, so that's definitely worth investigating...

In vb.net, how to get the column names from a datatable

You can loop through the columns collection of the datatable.

VB

Dim dt As New DataTable()
For Each column As DataColumn In dt.Columns
    Console.WriteLine(column.ColumnName)
Next

C#

DataTable dt = new DataTable();
foreach (DataColumn column in dt.Columns)
{
Console.WriteLine(column.ColumnName);
}

Hope this helps!

Is there a splice method for strings?

I solved my problem using this code, is a somewhat replacement for the missing splice.

let str = "I need to remove a character from this";
let pos = str.indexOf("character")

if(pos>-1){
  let result = str.slice(0, pos-2) + str.slice(pos, str.length);
  console.log(result) //I need to remove character from this 
}

I needed to remove a character before/after a certain word, after you get the position the string is split in two and then recomposed by flexibly removing characters using an offset along pos