Programs & Examples On #Reportbuilder

ReportBuilder can refer to either the Microsoft Report Builder tool for SQL Server Reporting Services (SSRS) reports, or to the Digital Metaphors Corporation reporting solution for Delphi developers on the Window platform. Always use an appropriate companion tag.

Scope 'session' is not active for the current thread; IllegalStateException: No thread-bound request found

If anyone else stuck on same point, following solved my problem.

In web.xml

 <listener>
            <listener-class>
                    org.springframework.web.context.request.RequestContextListener 
            </listener-class>
  </listener>

In Session component

@Component
@Scope(value = "session",  proxyMode = ScopedProxyMode.TARGET_CLASS)

In pom.xml

    <dependency>
        <groupId>cglib</groupId>
        <artifactId>cglib</artifactId>
        <version>3.1</version>
    </dependency>

Looking to understand the iOS UIViewController lifecycle

The methods viewWillLayoutSubviews and viewDidLayoutSubviews aren't mentioned in the diagrams, but these are called between viewWillAppear and viewDidAppear. They can be called multiple times.

Add Favicon to Website

  1. This is not done in PHP. It's part of the <head> tags in a HTML page.
  2. That icon is called a favicon. According to Wikipedia:

    A favicon (short for favorites icon), also known as a shortcut icon, website icon, URL icon, or bookmark icon is a 16×16 or 32×32 pixel square icon associated with a particular website or webpage.

  3. Adding it is easy. Just add an .ico image file that is either 16x16 pixels or 32x32 pixels. Then, in the web pages, add <link rel="shortcut icon" href="favicon.ico" type="image/x-icon"> to the <head> element.
  4. You can easily generate favicons here.

How to write a UTF-8 file with Java?

Try this

Writer out = new BufferedWriter(new OutputStreamWriter(
    new FileOutputStream("outfilename"), "UTF-8"));
try {
    out.write(aString);
} finally {
    out.close();
}

How to store the hostname in a variable in a .bat file?

I'm using the environment variable COMPUTERNAME:

copy "C:\Program Files\Windows Resource Kits\Tools\" %SYSTEMROOT%\system32
srvcheck \\%COMPUTERNAME% > c:\shares.txt
echo %COMPUTERNAME%

How to open Visual Studio Code from the command line on OSX?

I had this issue because of VS Code Insiders. The path variable was there but I needed to rename the code-insiders.cmd inside to code.cmd .

Maybe this is useful to someone.

Java Replace Line In Text File

If replacement is of different length:

  1. Read file until you find the string you want to replace.
  2. Read into memory the part after text you want to replace, all of it.
  3. Truncate the file at start of the part you want to replace.
  4. Write replacement.
  5. Write rest of the file from step 2.

If replacement is of same length:

  1. Read file until you find the string you want to replace.
  2. Set file position to start of the part you want to replace.
  3. Write replacement, overwriting part of file.

This is the best you can get, with constraints of your question. However, at least the example in question is replacing string of same length, So the second way should work.

Also be aware: Java strings are Unicode text, while text files are bytes with some encoding. If encoding is UTF8, and your text is not Latin1 (or plain 7-bit ASCII), you have to check length of encoded byte array, not length of Java string.

AttributeError: Module Pip has no attribute 'main'

Pip 10.0.* doesn't support main.

You have to downgrade to pip 9.0.3.

Gradle error: Minimum supported Gradle version is 3.3. Current version is 3.2

Error Message: Gradle sync failed: Minimum supported Gradle version is 4.9. Current version is 4.1-milestone-1. If using the gradle wrapper, try editing the distributionUrl in SampleProj/app/gradle/wrapper/gradle-wrapper.properties to gradle-4.9-all.zip

I am using Android studio IDE version 3.2 beta 2.

Solution: When we open gradle-wrapper.properties file in IDE it shows correct distributionUrl. but originally it has not been updated. So change the distributionUrl property manually.

Example : open a gradle-wrapper.properties file in notepad or any other editor. /Project/app/gradle/wrapper/gradle-wrapper.properties and change distributionUrl property to like this

distributionUrl=https\://services.gradle.org/distributions/gradle-4.9-all.zip

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

I just found an easy solution for myself. Had an margin-top of 15px

HTML

<h2 id="Anchor">Anchor</h2>

CSS

h2{margin-top:-60px; padding-top:75px;}

Jenkins fails when running "service start jenkins"

In my case, the issue was of unsupported java version

Check the file /etc/init.d/jenkins to find out which java versions are supported.

To find which java versions are supported, run

grep -m 1 "JAVA_ALLOWED_VERSIONS" /etc/init.d/jenkins

The output will be like this(your's might be different)

JAVA_ALLOWED_VERSIONS=( "1.8" "11" )

In my case version 1.8 and 11 are supported. I will be going with version 11.

Install the supported version of jre using command

For ubuntu/debian

sudo apt install openjdk-11-jre 

For centOS use

sudo yum install java-11-openjdk-devel

Find the path to newly installed jre

For ubuntu/debian path is

/usr/lib/jvm/java-11-openjdk-amd64/bin/java

You can find the path on centOS under /usr/lib/jvm/

Modify the file /etc/init.d/jenkins At line number 28, replace the JAVA=`type -p java` with JAVA='/usr/lib/jvm/java-11-openjdk-amd64/bin/java'

Now run command to reload the systemctl daemon

sudo systemctl daemon-reload

Start the jenkins service

sudo systemctl start jenkins

Full Screen Theme for AppCompat

Based on the answer by @nebyan, I found that the action bar is still not hiding.

The following code works for me:

<style name="AppFullScreenTheme" parent="Theme.AppCompat.Light.NoActionBar">
    <item name="android:windowNoTitle">true</item>
    <item name="android:windowActionBar">false</item>
    <item name="android:windowFullscreen">true</item>
    <item name="android:windowContentOverlay">@null</item>
</style>

and of course dont forgot to edit your AndroidManifest file.

<activity
    android:name="YOUR_ACTIVITY_NAME"
    android:theme="@style/AppFullScreenTheme" 
/>

In Python, how do I iterate over a dictionary in sorted key order?

sorted returns a list, hence your error when you try to iterate over it, but because you can't order a dict you will have to deal with a list.

I have no idea what the larger context of your code is, but you could try adding an iterator to the resulting list. like this maybe?:

return iter(sorted(dict.iteritems()))

of course you will be getting back tuples now because sorted turned your dict into a list of tuples

ex: say your dict was: {'a':1,'c':3,'b':2} sorted turns it into a list:

[('a',1),('b',2),('c',3)]

so when you actually iterate over the list you get back (in this example) a tuple composed of a string and an integer, but at least you will be able to iterate over it.

Why does CSS not support negative padding?

This could help, by the way:

The box-sizing CSS property is used to alter the default CSS box model used to calculate widths and heights of elements.

http://www.w3.org/TR/css3-ui/#box-sizing
https://developer.mozilla.org/En/CSS/Box-sizing

Passing parameters to addTarget:action:forControlEvents

Target-Action allows three different forms of action selector:

- (void)action
- (void)action:(id)sender
- (void)action:(id)sender forEvent:(UIEvent *)event

Convert a character digit to the corresponding integer in C

As per other replies, this is fine:

char c = '5';
int x = c - '0';

Also, for error checking, you may wish to check isdigit(c) is true first. Note that you cannot completely portably do the same for letters, for example:

char c = 'b';
int x = c - 'a'; // x is now not necessarily 1

The standard guarantees that the char values for the digits '0' to '9' are contiguous, but makes no guarantees for other characters like letters of the alphabet.

document.getElementById(id).focus() is not working for firefox or chrome

Add a control, where you want to set focus then change its property like below

<asp:TextBox ID="txtDummy" runat="server" Text="" Width="2" ReadOnly="true" BorderStyle="None" BackColor="Transparent"></asp:TextBox>

In the codebehind, just call like below txtDummy.Focus()

this method is working in all browser.

Pointer vs. Reference

I really think you will benefit from establishing the following function calling coding guidelines:

  1. As in all other places, always be const-correct.

    • Note: This means, among other things, that only out-values (see item 3) and values passed by value (see item 4) can lack the const specifier.
  2. Only pass a value by pointer if the value 0/NULL is a valid input in the current context.

    • Rationale 1: As a caller, you see that whatever you pass in must be in a usable state.

    • Rationale 2: As called, you know that whatever comes in is in a usable state. Hence, no NULL-check or error handling needs to be done for that value.

    • Rationale 3: Rationales 1 and 2 will be compiler enforced. Always catch errors at compile time if you can.

  3. If a function argument is an out-value, then pass it by reference.

    • Rationale: We don't want to break item 2...
  4. Choose "pass by value" over "pass by const reference" only if the value is a POD (Plain old Datastructure) or small enough (memory-wise) or in other ways cheap enough (time-wise) to copy.

    • Rationale: Avoid unnecessary copies.
    • Note: small enough and cheap enough are not absolute measurables.

How to use NSJSONSerialization

Your root json object is not a dictionary but an array:

[{"id": "1", "name":"Aaa"}, {"id": "2", "name":"Bbb"}]

This might give you a clear picture of how to handle it:

NSError *e = nil;
NSArray *jsonArray = [NSJSONSerialization JSONObjectWithData: data options: NSJSONReadingMutableContainers error: &e];

if (!jsonArray) {
  NSLog(@"Error parsing JSON: %@", e);
} else {
   for(NSDictionary *item in jsonArray) {
      NSLog(@"Item: %@", item);
   }
}

AES Encrypt and Decrypt

You can just copy & paste these methods (Swift 4+):

    class func encryptMessage(message: String, encryptionKey: String, iv: String) -> String? {
        if let aes = try? AES(key: encryptionKey, iv: iv),
            let encrypted = try? aes.encrypt(Array<UInt8>(message.utf8)) {
            return encrypted.toHexString()
        }
        return nil
    }

    class func decryptMessage(encryptedMessage: String, encryptionKey: String, iv: String) -> String? {
        if let aes = try? AES(key: encryptionKey, iv: iv),
            let decrypted = try? aes.decrypt(Array<UInt8>(hex: encryptedMessage)) {
            return String(data: Data(bytes: decrypted), encoding: .utf8)
        }
        return nil
    }

Example:

let encryptMessage = encryptMessage(message: "Hello World!", encryptionKey: "mykeymykeymykey1", iv: "myivmyivmyivmyiv")    
// Output of encryptMessage is: 649849a5e700d540f72c4429498bf9f4

let decryptedMessage = decryptMessage(encryptedMessage: encryptMessage, encryptionKey: "mykeymykeymykey1", iv: "myivmyivmyivmyiv")
// Output of decryptedMessage is: Hello World!

Don't forget encryptionKey & iv should be 16 bytes.


How to close a window using jQuery

For IE: window.close(); and self.close(); should work fine.

If you want just open the IE browser and type

javascript:self.close() and hit enter, it should ask you for a prompt.

Note: this method doesn't work for Chrome or Firefox.

How to insert date values into table

Since dob is DATE data type, you need to convert the literal to DATE using TO_DATE and the proper format model. The syntax is:

TO_DATE('<date_literal>', '<format_model>')

For example,

SQL> CREATE TABLE t(dob DATE);

Table created.

SQL> INSERT INTO t(dob) VALUES(TO_DATE('17/12/2015', 'DD/MM/YYYY'));

1 row created.

SQL> COMMIT;

Commit complete.

SQL> SELECT * FROM t;

DOB
----------
17/12/2015

A DATE data type contains both date and time elements. If you are not concerned about the time portion, then you could also use the ANSI Date literal which uses a fixed format 'YYYY-MM-DD' and is NLS independent.

For example,

SQL> INSERT INTO t(dob) VALUES(DATE '2015-12-17');

1 row created.

Cannot push to Git repository on Bitbucket

I had this issue and I thought I was crazy. I have been using SSH for 20 years. and git over SSH since 2012... but why couldn't I fetch my bitbucket repository on my home computer?

well, I have two bitbucket accounts and had 4 SSH keys loaded inside my agent. even if my .ssh/config was configured to use the right key. when ssh was initializing the connection, it was using them in order loaded into the agent. so I was getting logged into my personal bitbucket account.

then getting a Forbidden error trying to fetch the repo. makes sense.

I unloaded the key from the agent

ssh-add -d ~/.ssh/personal_rsa

then I could fetch the repos.

... Later I found out I can force it to use the specified identity only

 Host bitbucket.org-user2
     HostName bitbucket.org
     User git
     IdentityFile ~/.ssh/user2
     IdentitiesOnly yes

I didn't know about that last option IdentitiesOnly

from the bitbucket documentation itself

https://blog.developer.atlassian.com/different-ssh-keys-multiple-bitbucket-accounts/

Import cycle not allowed

Here is an illustration of your first import cycle problem.

                  project/controllers/account
                     ^                    \    
                    /                      \
                   /                        \ 
                  /                         \/
         project/components/mux <--- project/controllers/base

As you can see with my bad ASCII chart is that you are creating an import cycle when project/components/mux imports project/controllers/account. Since Go does not support circular dependencies you get the import cycle not allowed error during compile time.

What does servletcontext.getRealPath("/") mean and when should I use it

A web application's context path is the directory that contains the web application's WEB-INF directory. It can be thought of as the 'home' of the web app. Often, when writing web applications, it can be important to get the actual location of this directory in the file system, since this allows you to do things such as read from files or write to files.

This location can be obtained via the ServletContext object's getRealPath() method. This method can be passed a String parameter set to File.separator to get the path using the operating system's file separator ("/" for UNIX, "\" for Windows).

Android activity life cycle - what are all these methods for?

I run some logs as per answers above and here is the output:

Starting Activity

On Activity Load (First Time)
————————————————————————————————————————————————
D/IndividualChatActivity: onCreate: 
D/IndividualChatActivity: onStart: 
D/IndividualChatActivity: onResume: 
D/IndividualChatActivity: onPostResume: 

Reload After BackPressed
————————————————————————————————————————————————
D/IndividualChatActivity: onCreate: 
D/IndividualChatActivity: onStart: 
D/IndividualChatActivity: onResume: 
D/IndividualChatActivity: onPostResume: 

OnMaximize(Circle Button)
————————————————————————————————————————————————
D/IndividualChatActivity: onRestart: 
D/IndividualChatActivity: onStart: 
D/IndividualChatActivity: onResume: 
D/IndividualChatActivity: onPostResume: 

OnMaximize(Square Button)
————————————————————————————————————————————————
D/IndividualChatActivity: onRestart: 
D/IndividualChatActivity: onStart: 
D/IndividualChatActivity: onResume: 
D/IndividualChatActivity: onPostResume: 

Stopping The Activity

On BackPressed
————————————————————————————————————————————————
D/IndividualChatActivity: onPause:
D/IndividualChatActivity: onStop: 
D/IndividualChatActivity: onDestroy: 

OnMinimize (Circle Button)
————————————————————————————————————————————————
D/IndividualChatActivity: onPause: 
D/IndividualChatActivity: onStop: 

OnMinimize (Square Button)
————————————————————————————————————————————————
D/IndividualChatActivity: onPause: 
D/IndividualChatActivity: onStop: 

Going To Another Activity
————————————————————————————————————————————————
D/IndividualChatActivity: onPause:
D/IndividualChatActivity: onStop: 

Close The App
————————————————————————————————————————————————
D/IndividualChatActivity: onDestroy: 

In my personal opinion only two are required onStart and onStop.

onResume seems to be in every instance of getting back, and onPause in every instance of leaving (except for closing the app).

Move_uploaded_file() function is not working

always set folder directory properly for image otherwise image will not be upload check my code for image upload if you issue still there let me know will help you

if (move_uploaded_file($_FILES['profile_picture']['tmp_name'],'../images/manager/'. 
    $_FILES["profile_picture"]['name'])) {
      echo "Uploaded";
} else {
      echo "File not uploaded";
}

Replacing accented characters php

So I found this on php.net page for preg_replace function

// replace accented chars

$string = "Zacarías Ferreíra"; // my definition for string variable
$accents = '/&([A-Za-z]{1,2})(grave|acute|circ|cedil|uml|lig);/';

$string_encoded = htmlentities($string,ENT_NOQUOTES,'UTF-8');

$string = preg_replace($accents,'$1',$string_encoded);

If you have encoding issues you may get someting like this "Zacarías Ferreíra", just decode the string and use said code above

$string = utf8_decode("Zacarías Ferreíra");

Is Xamarin free in Visual Studio 2015?

Seems like now it's free for small teams and students, according to Scott Hanselman post https://twitter.com/shanselman/status/715568774418595840

https://visualstudio.microsoft.com/vs/pricing/

Visual Studio Community
FREE

A free, full-featured and extensible IDE for Windows users to create Android and iOS apps with Xamarin, as well as Windows apps, web apps, and cloud services.

  • Students
  • OSS development
  • Small teams

and

Xamarin Studio Community FREE

A free, full-featured IDE for Mac users to create Android and iOS apps using Xamarin.

  • Students
  • OSS development
  • Small teams

Where does error CS0433 "Type 'X' already exists in both A.dll and B.dll " come from?

This happened to me because of an error in my Web.Config

<add assembly="System.Web.Abstractions, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
<add assembly="System.Web.Helpers, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
<add assembly="System.Web.Routing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
<add assembly="System.Web.Mvc, Version=5.1.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
<add assembly="System.Web.WebPages, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>

The Sytem.Web.Helpers was pointed at 1.0.0.0 instead of 3.0.0.0 (MVC 3 is being used on this project).

Because IIS couldn't find the reference in the local folder it looked in the GAC and found two different versions. After pointing it at the correct reference IIS found the local dll and used that instead of searching the GAC.

How to debug heap corruption errors?

What type of allocation functions are you using? I recently hit a similar error using the Heap* style allocation functions.

It turned out that I was mistakenly creating the heap with the HEAP_NO_SERIALIZE option. This essentially makes the Heap functions run without thread safety. It's a performance improvement if used properly but shouldn't ever be used if you are using HeapAlloc in a multi-threaded program [1]. I only mention this because your post mentions you have a multi-threaded app. If you are using HEAP_NO_SERIALIZE anywhere, delete that and it will likely fix your problem.

[1] There are certain situations where this is legal, but it requires you to serialize calls to Heap* and is typically not the case for multi-threaded programs.

javascript - Create Simple Dynamic Array

var arr = [];
while(mynumber--) {
    arr[mynumber] = String(mynumber+1);
}

Is either GET or POST more secure than the other?

You should also be aware that if your sites contains link to other external sites you dont control using GET will put that data in the refeerer header on the external sites when they press the links on your site. So transfering login data through GET methods is ALWAYS a big issue. Since that might expose login credentials for easy access by just checking the logs or looking in Google analytics (or similar).

How to convert Seconds to HH:MM:SS using T-SQL

DECLARE @Seconds INT = 86200;
SELECT 
CONVERT(VARCHAR(15), 
CAST(CONVERT(VARCHAR(12), @Seconds / 60 / 60 % 24)
+':'+ CONVERT(VARCHAR(2), @Seconds / 60 % 60)
+':'+ CONVERT(VARCHAR(2), @Seconds % 60) AS TIME), 100) AS [HH:MM:SS (AM/PM)]

enter image description here

How to insert a new key value pair in array in php?

foreach($test_package_data as $key=>$data ) {

   $category_detail_arr = $test_package_data[$key]['category_detail'];

   foreach( $category_detail_arr as $i=>$value ) {
     $test_package_data[$key]['category_detail'][$i]['count'] = $some_value;////<----Here
   }

}

Update only specific fields in a models.Model

To update a subset of fields, you can use update_fields:

survey.save(update_fields=["active"]) 

The update_fields argument was added in Django 1.5. In earlier versions, you could use the update() method instead:

Survey.objects.filter(pk=survey.pk).update(active=True)

How to split a string with angularJS

You may want to wrap that functionality up into a filter, this way you don't have to put the mySplit function in all of your controllers. For example

angular.module('myModule', [])
    .filter('split', function() {
        return function(input, splitChar, splitIndex) {
            // do some bounds checking here to ensure it has that index
            return input.split(splitChar)[splitIndex];
        }
    });

From here, you can use a filter as you originally intended

{{test | split:',':0}}
{{test | split:',':0}}

More info at http://docs.angularjs.org/guide/filter (thanks ross)

Plunkr @ http://plnkr.co/edit/NA4UeL

EF Code First "Invalid column name 'Discriminator'" but no inheritance

Old Q, but for posterity...it also also happens (.NET Core 2.1) if you have a self-referencing navigation property ("Parent" or "Children" of the same type) but the Id property name isn't what EF expects. That is, I had an "Id" property on my class called WorkflowBase, and it had an array of related child steps, which were also of type WorkflowBase, and it kept trying to associate them with a non-existent "WorkflowBaseId" (the name i suppose it prefers as a natural/conventional default). I had to explicitly configure it using HasMany(), WithOne(), and HasConstraintName() to tell it how to traverse. But I spent a few hours thinking the problem was in 'locally' mapping the object's primary key, which i attempted to fix a bunch of different ways but which was probably always working.

How to use OpenSSL to encrypt/decrypt files?

Encrypt:

openssl enc -in infile.txt -out encrypted.dat -e -aes256 -k symmetrickey

Decrypt:

openssl enc -in encrypted.dat -out outfile.txt -d -aes256 -k symmetrickey

For details, see the openssl(1) docs.

How to perform string interpolation in TypeScript?

In JavaScript you can use template literals:

let value = 100;
console.log(`The size is ${ value }`);

Hashing a file in Python

TL;DR use buffers to not use tons of memory.

We get to the crux of your problem, I believe, when we consider the memory implications of working with very large files. We don't want this bad boy to churn through 2 gigs of ram for a 2 gigabyte file so, as pasztorpisti points out, we gotta deal with those bigger files in chunks!

import sys
import hashlib

# BUF_SIZE is totally arbitrary, change for your app!
BUF_SIZE = 65536  # lets read stuff in 64kb chunks!

md5 = hashlib.md5()
sha1 = hashlib.sha1()

with open(sys.argv[1], 'rb') as f:
    while True:
        data = f.read(BUF_SIZE)
        if not data:
            break
        md5.update(data)
        sha1.update(data)

print("MD5: {0}".format(md5.hexdigest()))
print("SHA1: {0}".format(sha1.hexdigest()))

What we've done is we're updating our hashes of this bad boy in 64kb chunks as we go along with hashlib's handy dandy update method. This way we use a lot less memory than the 2gb it would take to hash the guy all at once!

You can test this with:

$ mkfile 2g bigfile
$ python hashes.py bigfile
MD5: a981130cf2b7e09f4686dc273cf7187e
SHA1: 91d50642dd930e9542c39d36f0516d45f4e1af0d
$ md5 bigfile
MD5 (bigfile) = a981130cf2b7e09f4686dc273cf7187e
$ shasum bigfile
91d50642dd930e9542c39d36f0516d45f4e1af0d  bigfile

Hope that helps!

Also all of this is outlined in the linked question on the right hand side: Get MD5 hash of big files in Python


Addendum!

In general when writing python it helps to get into the habit of following pep-8. For example, in python variables are typically underscore separated not camelCased. But that's just style and no one really cares about those things except people who have to read bad style... which might be you reading this code years from now.

pass **kwargs argument to another function with **kwargs

Because a dictionary is a single value. You need to use keyword expansion if you want to pass it as a group of keyword arguments.

What is ADT? (Abstract Data Type)

Actually Abstract Data Types is:

  • Concepts or theoretical model that defines a data type logically
  • Specifies set of data and set of operations that can be performed on that data
  • Does not mention anything about how operations will be implemented
  • "Existing as an idea but not having a physical idea"

For example, lets see specifications of some Abstract Data Types,

  1. List Abstract Data Type: initialize(), get(), insert(), remove(), etc.
  2. Stack Abstract Data Type: push(), pop(), peek(), isEmpty(), isNull(), etc.
  3. Queue Abstract Data Type: enqueue(), dequeue(), size(), peek(), etc.

How to iterate object in JavaScript?

There's this way too (new to EcmaScript5):

dictionary.data.forEach(function(item){
    console.log(item.name + ' ' + item.id);
});

Same approach for images

Select Specific Columns from Spark DataFrame

Problem was to select columns of on dataframe after joining with other dataframe.

I tried below and select the columns of salaryDf from the joined dataframe.

Hope this will help

        val empDf=spark.read.option("header","true").csv("/data/tech.txt")

        val salaryDf=spark.read.option("header","true").csv("/data/salary.txt")

        val joinData= empDf.join(salaryDf,empDf.col("first") === salaryDf.col("first") and  empDf.col("last") === salaryDf.col("last"))

      //**below will select the colums of salaryDf only**

     val finalDF=joinData.select(salaryDf.columns map  salaryDf.col:_*)

//same way we can select the columns of empDf
joinData.select(empDf.columns map  empDf.col:_*)

How do I import an SQL file using the command line in MySQL?

I kept running into the problem where the database wasn't created.

I fixed it like this

mysql -u root -e "CREATE DATABASE db_name"
mysql db_name --force < import_script.sql

Adobe Reader Command Line Reference

You can find something about this in the Adobe Developer FAQ. (It's a PDF document rather than a web page, which I guess is unsurprising in this particular case.)

The FAQ notes that the use of the command line switches is unsupported.

To open a file it's:

AcroRd32.exe <filename>

The following switches are available:

  • /n - Launch a new instance of Reader even if one is already open
  • /s - Don't show the splash screen
  • /o - Don't show the open file dialog
  • /h - Open as a minimized window
  • /p <filename> - Open and go straight to the print dialog
  • /t <filename> <printername> <drivername> <portname> - Print the file the specified printer.

Styling text input caret

If you are using a webkit browser you can change the color of the caret by following the next CSS snippet. I'm not sure if It's possible to change the format with CSS.

input,
textarea {
    font-size: 24px;
    padding: 10px;
    
    color: red;
    text-shadow: 0px 0px 0px #000;
    -webkit-text-fill-color: transparent;
}

input::-webkit-input-placeholder,
textarea::-webkit-input-placeholder {
    color:
    text-shadow: none;
    -webkit-text-fill-color: initial;
}

Here is an example: http://jsfiddle.net/8k1k0awb/

Load HTML File Contents to Div [without the use of iframes]

    document.getElementById("id").innerHTML='<object type="text/html" data="x.html"></object>';

CSS: how do I create a gap between rows in a table?

If you stick with the design using tables the best idea will be to give an empty row with no content and specified height between each rows in the table.

You can use div to avoid this complexity. Just give a margin to each div.

What is the Eclipse shortcut for "public static void main(String args[])"?

To get public static void main(String[] args) line in eclipse without typing the whole line type "main" and press Ctrl + space then, you will get the option for the main method select it.

enter image description here

sqlite3.ProgrammingError: Incorrect number of bindings supplied. The current statement uses 1, and there are 74 supplied

You need to pass in a sequence, but you forgot the comma to make your parameters a tuple:

cursor.execute('INSERT INTO images VALUES(?)', (img,))

Without the comma, (img) is just a grouped expression, not a tuple, and thus the img string is treated as the input sequence. If that string is 74 characters long, then Python sees that as 74 separate bind values, each one character long.

>>> len(img)
74
>>> len((img,))
1

If you find it easier to read, you can also use a list literal:

cursor.execute('INSERT INTO images VALUES(?)', [img])

Limiting Python input strings to certain characters and lengths

We can use assert here.

def _input(inp_str:str):
    try:
        assert len(inp_str)<=15,print('More than 15 characters present')
        assert all('a'<=i<='z' for i in inp_str),print('Characters other than "a"-"z" are found')
        return inp_str
    except Exception as e:
        pass

_input('abcd')
#abcd
_input('abc d')
#Characters other than "a"-"z" are found
_input('abcdefghijklmnopqrst')
#More than 15 characters present

jQuery override default validation error message display (Css) Popup/Tooltip like

Unfortunately I can't comment with my newbie reputation, but I have a solution for the issue of the screen going blank, or at least this is what worked for me. Instead of setting the wrapper class inside of the errorPlacement function, set it immediately when you're setting the wrapper type.

$('#myForm').validate({
    errorElement: "div",
    wrapper: "div class=\"message\"",
    errorPlacement: function(error, element) {
        offset = element.offset();
        error.insertBefore(element);
        //error.addClass('message');  // add a class to the wrapper
        error.css('position', 'absolute');
        error.css('left', offset.left + element.outerWidth() + 5);
        error.css('top', offset.top - 3);
    }

});

I'm assuming doing it this way allows the validator to know which div elements to remove, instead of all of them. Worked for me but I'm not entirely sure why, so if someone could elaborate that might help others out a ton.

Getting Git to work with a proxy server - fails with "Request timed out"

If you have tsocks or proxychains installed and configured, you can

$ tsocks git clone <you_repository>

or

$ proxychains git clone <you_repository>

to make it shorter, I created a symbol link /usr/bin/p for proxychains, so I can use it like this

p git clone <you_repository>

and I can use it to proxy any command,

p <cmd-need-be-proxied>

by the way, proxychains is not updated for a long time, you may wanna try proxychians-ng

"Actual or formal argument lists differs in length"

You try to instantiate an object of the Friends class like this:

Friends f = new Friends(friendsName, friendsAge);

The class does not have a constructor that takes parameters. You should either add the constructor, or create the object using the constructor that does exist and then use the set-methods. For example, instead of the above:

Friends f = new Friends();
f.setName(friendsName);
f.setAge(friendsAge);

Sleep function in Windows, using C

Use:

#include <windows.h>

Sleep(sometime_in_millisecs); // Note uppercase S

And here's a small example that compiles with MinGW and does what it says on the tin:

#include <windows.h>
#include <stdio.h>

int main() {
    printf( "starting to sleep...\n" );
    Sleep(3000); // Sleep three seconds
    printf("sleep ended\n");
}

libz.so.1: cannot open shared object file

After checking to which package does the libz.so.1 belongs (http://packages.ubuntu.com/lucid/i386/zlib1g/filelist) you should try to install zlib1g:

sudo apt-get install zlib1g

As pointed by @E-rich, it may be required to add a :i386 suffix to the package name for the package manager correctly identify it:

sudo apt-get install zlib1g:i386


EDIT (for CentOS or other distro that makes use of yum):

If someone using CentOS (or any other distro that makes use of yum) that may end up reading this question, @syslogic proposed the following solution in the comments:

yum install zlib.i686

or, for 32-bit binaries:

yum install zlib.i386

What tool to use to draw file tree diagram

Why could you not just make a file structure on the Windows file system and populate it with your desired names, then use a screen grabber like HyperSnap (or the ubiquitous Alt-PrtScr) to capture a section of the Explorer window.

I did this when 'demoing' an internet application which would have collapsible sections, I just had to create files that looked like my desired entries.

HyperSnap gives JPGs at least (probably others but I've never bothered to investigate).

Or you could screen capture the icons +/- from Explorer and use them within MS Word Draw itself to do your picture, but I've never been able to get MS Word Draw to behave itself properly.

IE and Edge fix for object-fit: cover;

You can use this js code. Just change .post-thumb img with your img.

$('.post-thumb img').each(function(){           // Note: {.post-thumb img} is css selector of the image tag
    var t = $(this),
        s = 'url(' + t.attr('src') + ')',
        p = t.parent(),
        d = $('<div></div>');
    t.hide();
    p.append(d);
    d.css({
        'height'                : 260,          // Note: You can change it for your needs
        'background-size'       : 'cover',
        'background-repeat'     : 'no-repeat',
        'background-position'   : 'center',
        'background-image'      : s
    });
});

How can I inspect element in chrome when right click is disabled?

ALTERNATE WAY:
enter image description here


Click Developer Tools to inspect element. You may also use keyboard shortcuts, such as CtrlL+Shift+I, F12 (or Fn+F12), etc.

JavaScript: clone a function

This answer is for people who see cloning a function as the answer to their desired usage, but who many not actually need to clone a function, because what they really want is simply to be able to attach different properties to the same function, but only declare that function one time.

Do this by creating a function-creating function:

function createFunction(param1, param2) {
   function doSomething() {
      console.log('in the function!');
   }
   // Assign properties to `doSomething` if desired, perhaps based
   // on the arguments passed into `param1` and `param2`. Or,
   // even return a different function from among a group of them.
   return doSomething;
};

let a = createFunction();
a.something = 1;
let b = createFunction();
b.something = 2; // does not overwrite a.something
console.log(a.something);
a();
b();

This is not exactly the same as you have outlined, however, it depends on how you want to use the function you're wishing to clone. This also uses more memory because it actually creates multiple copies of the function, once per invocation. However, this technique may solve some people's use case without the need for a complicated clone function.

AttributeError: 'str' object has no attribute 'append'

myList[1] is an element of myList and it's type is string.

myList[1] is str, you can not append to it. myList is a list, you should have been appending to it.

>>> myList = [1, 'from form', [1,2]]
>>> myList[1]
'from form'
>>> myList[2]
[1, 2]
>>> myList[2].append('t')
>>> myList
[1, 'from form', [1, 2, 't']]
>>> myList[1].append('t')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'str' object has no attribute 'append'
>>> 

Auto populate columns in one sheet from another sheet

Use the 'EntireColumn' property, that's what it is there for. C# snippet, but should give you a good indication of how to do this:

string rangeQuery = "A1:A1";

Range range = workSheet.get_Range(rangeQuery, Type.Missing);

range = range.EntireColumn;

What exactly is Spring Framework for?

Spring is a good alternative to Enterprise JavaBeans (EJB) technology. It also has web framework and web services framework component.

Show a number to two decimal places

Alternatively,

$padded = sprintf('%0.2f', $unpadded); // 520 -> 520.00

phpMyAdmin - The MySQL Extension is Missing

I had a similar issue, but it didn't help to add extension=mysql.so in my php.ini. It turned out that the mysql.so file was not in my extension folder nor anywhere else on my machine. Solved this by downloading the php source and building the extension manually and then copying it into the extension folder.

How to use a global array in C#?

Your class shoud look something like this:

class Something {     int[] array; //global array, replace type of course     void function1() {        array = new int[10]; //let say you declare it here that will be 10 integers in size     }     void function2() {        array[0] = 12; //assing value at index 0 to 12.     } } 

That way you array will be accessible in both functions. However, you must be careful with global stuff, as you can quickly overwrite something.

How to combine class and ID in CSS selector?

use: tag.id ; tag#classin the tag variables in your css.

Get absolute path to workspace directory in Jenkins Pipeline plugin

Note: this solution works only if the slaves have the same directory structure as the master. pwd() will return the workspace directory on the master due to JENKINS-33511.

I used to do it using pwd() functionality of pipeline plugin. So, if you need to get a workspace on slave, you may do smth like this:

node('label'){
    //now you are on slave labeled with 'label'
    def workspace = pwd()
    //${workspace} will now contain an absolute path to job workspace on slave 
}

Pad left or right with string.format (not padleft or padright) with arbitrary string

Edit: I misunderstood your question, I thought you were asking how to pad with spaces.

What you are asking is not possible using the string.Format alignment component; string.Format always pads with whitespace. See the Alignment Component section of MSDN: Composite Formatting.

According to Reflector, this is the code that runs inside StringBuilder.AppendFormat(IFormatProvider, string, object[]) which is called by string.Format:

int repeatCount = num6 - str2.Length;
if (!flag && (repeatCount > 0))
{
    this.Append(' ', repeatCount);
}
this.Append(str2);
if (flag && (repeatCount > 0))
{
    this.Append(' ', repeatCount);
}

As you can see, blanks are hard coded to be filled with whitespace.

Find all special characters in a column in SQL Server 2008

Select * from TableName Where ColumnName LIKE '%[^A-Za-z0-9, ]%'

This will give you all the row which contains any special character.

Compiling a C++ program with gcc

By default, gcc selects the language based on the file extension, but you can force gcc to select a different language backend with the -x option thus:

gcc -x c++

More options are detailed in the gcc man page under "Options controlling the kind of output". See e.g. http://linux.die.net/man/1/gcc (search on the page for the text -x language).

This facility is very useful in cases where gcc can't guess the language using a file extension, for example if you're generating code and feeding it to gcc via stdin.

How to git ignore subfolders / subdirectories?

You can use .gitignore in the top level to ignore all directories in the project with the same name. For example:

Debug/
Release/

This should update immediately so it's visible when you do git status. Ensure that these directories are not already added to git, as that will override the ignores.

Getting "file not found" in Bridging Header when importing Objective-C frameworks into Swift project

This happened to me after adding/renaming current configurations and it makes sense.

Every configuration makes use of Configurations Set generated by cocoapods so these things needs to match.

So if you add/rename configurations, these will need to use the right configuration sets, and for that running pod install will do it.

jQuery scroll to element

I wrote a general purpose function that scrolls to either a jQuery object, a CSS selector, or a numeric value.

Example usage:

// scroll to "#target-element":
$.scrollTo("#target-element");

// scroll to 80 pixels above first element with class ".invalid":
$.scrollTo(".invalid", -80);

// scroll a container with id "#my-container" to 300 pixels from its top:
$.scrollTo(300, 0, "slow", "#my-container");

The function's code:

/**
* Scrolls the container to the target position minus the offset
*
* @param target    - the destination to scroll to, can be a jQuery object
*                    jQuery selector, or numeric position
* @param offset    - the offset in pixels from the target position, e.g.
*                    pass -80 to scroll to 80 pixels above the target
* @param speed     - the scroll speed in milliseconds, or one of the
*                    strings "fast" or "slow". default: 500
* @param container - a jQuery object or selector for the container to
*                    be scrolled. default: "html, body"
*/
jQuery.scrollTo = function (target, offset, speed, container) {

    if (isNaN(target)) {

        if (!(target instanceof jQuery))
            target = $(target);

        target = parseInt(target.offset().top);
    }

    container = container || "html, body";
    if (!(container instanceof jQuery))
        container = $(container);

    speed = speed || 500;
    offset = offset || 0;

    container.animate({
        scrollTop: target + offset
    }, speed);
};

How to change MySQL data directory?

For one of the environment I changed mysql data directory to new location but during restart of mysql server, it was taking time. So I checked the port, and found that other process was listening on mysql port. So I killed the process and restarted mysql server and it worked well.

I followed below steps for changing data directory which worked excellent. change mysql data directory in Linux

Create the perfect JPA entity

The JPA 2.0 Specification states that:

  • The entity class must have a no-arg constructor. It may have other constructors as well. The no-arg constructor must be public or protected.
  • The entity class must a be top-level class. An enum or interface must not be designated as an entity.
  • The entity class must not be final. No methods or persistent instance variables of the entity class may be final.
  • If an entity instance is to be passed by value as a detached object (e.g., through a remote interface), the entity class must implement the Serializable interface.
  • Both abstract and concrete classes can be entities. Entities may extend non-entity classes as well as entity classes, and non-entity classes may extend entity classes.

The specification contains no requirements about the implementation of equals and hashCode methods for entities, only for primary key classes and map keys as far as I know.

Finding CN of users in Active Directory

Most common AD default design is to have a container, cn=users just after the root of the domain. Thus a DN might be:

cn=admin,cn=users,DC=domain,DC=company,DC=com

Also, you might have sufficient rights in an LDAP bind to connect anonymously, and query for (cn=admin). If so, you should get the full DN back in that query.

CSS: center element within a <div> element

I have found another solution

<style type="text/css">
    .container {
        width:600px; //set how much you want
        overflow: hidden; 
        position: relative;
     }
     .containerSecond{
        position: absolute; 
        top:0px; 
        left:-500%; 
        width:1100%;
     }
     .content{
        width: 800px; //your content size 
        margin:0 auto;
     }           
</style>

and in body

<div class="container">
   <div class="containerSecond">
       <div class="content"></div>
   </div>
</div>

This will center your content div whenever your container is bigger or smaller. In this case your content should be bigger than 1100% of container to not be centered, but in that case you can make with of containerSecond bigger, and it will work

How to get names of enum entries?

I wrote an EnumUtil class which is making a type check by the enum value:

export class EnumUtils {
  /**
   * Returns the enum keys
   * @param enumObj enum object
   * @param enumType the enum type
   */
  static getEnumKeys(enumObj: any, enumType: EnumType): any[] {
    return EnumUtils.getEnumValues(enumObj, enumType).map(value => enumObj[value]);
  }

  /**
   * Returns the enum values
   * @param enumObj enum object
   * @param enumType the enum type
   */
  static getEnumValues(enumObj: any, enumType: EnumType): any[] {
    return Object.keys(enumObj).filter(key => typeof enumObj[key] === enumType);
  }
}

export enum EnumType {
  Number = 'number',
  String = 'string'
}

How to use it:

enum NumberValueEnum{
  A= 0,
  B= 1
}

enum StringValueEnum{
  A= 'A',
  B= 'B'
}

EnumUtils.getEnumKeys(NumberValueEnum, EnumType.Number);
EnumUtils.getEnumValues(NumberValueEnum, EnumType.Number);

EnumUtils.getEnumKeys(StringValueEnum, EnumType.String);
EnumUtils.getEnumValues(StringValueEnum, EnumType.String);

Result for NumberValueEnum keys: ["A", "B"]

Result for NumberValueEnum values: [0, 1]

Result for StringValueEnumkeys: ["A", "B"]

Result for StringValueEnumvalues: ["A", "B"]

How to get Current Timestamp from Carbon in Laravel 5

It may be a little late, but you could use the helper function time() to get the current timestamp. I tried this function and it did the job, no need for classes :).

You can find this in the official documentation at https://laravel.com/docs/5.0/templates

Regards.

How do I access (read, write) Google Sheets spreadsheets with Python?

Take a look at gspread port for api v4 - pygsheets. It should be very easy to use rather than the google client.

Sample example

import pygsheets

gc = pygsheets.authorize()

# Open spreadsheet and then workseet
sh = gc.open('my new ssheet')
wks = sh.sheet1

# Update a cell with value (just to let him know values is updated ;) )
wks.update_cell('A1', "Hey yank this numpy array")

# update the sheet with array
wks.update_cells('A2', my_nparray.to_list())

# share the sheet with your friend
sh.share("[email protected]")

See the docs here.

Author here.

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

A "floating point number" is how computers usually represent numbers that are not integers -- basically, a number with a decimal point. In C++ you declare them with float instead of int. A floating point exception is an error that occurs when you try to do something impossible with a floating point number, such as divide by zero.

Format in kotlin string templates

Since String.format is only an extension function (see here) which internally calls java.lang.String.format you could write your own extension function using Java's DecimalFormat if you need more flexibility:

fun Double.format(fracDigits: Int): String {
    val df = DecimalFormat()
    df.setMaximumFractionDigits(fracDigits)
    return df.format(this)
}

println(3.14159.format(2)) // 3.14

How to justify a single flexbox item (override justify-content)

To expand on Pavlo's answer https://stackoverflow.com/a/34063808/1069914, you can have multiple child items justify-content: flex-start in their behavior but have the last item justify-content: flex-end

_x000D_
_x000D_
.container {
  height: 100px;
  border: solid 10px skyblue;
  display: flex;
  justify-content: flex-end;
}

.container > *:not(:last-child) {
    margin-right: 0;
    margin-left: 0;
}

/* set the second to last-child */
.container > :nth-last-child(2) {
    margin-right: auto;
    margin-left: 0;
}

.block {
  width: 50px;
  background: tomato;
  border: 1px solid black;
}
_x000D_
<div class="container">
    <div class="block"></div>
    <div class="block"></div>
    <div class="block"></div>
    <div class="block" style="width:150px">I should be at the end of the flex container (i.e. justify-content: flex-end)</div>
</div>
_x000D_
_x000D_
_x000D_

How to extract numbers from a string and get an array of ints?

for rational numbers use this one: (([0-9]+.[0-9]*)|([0-9]*.[0-9]+)|([0-9]+))

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

you should do import Map from './Map' React is just telling you it doesn't know where variable you are importing is.

convert a char* to std::string

I need to use std::string to store data retrieved by fgets().

Why using fgets() when you are programming C++? Why not std::getline()?

How to get all columns' names for all the tables in MySQL?

To list all the fields from a table in MySQL:

select * 
  from information_schema.columns 
 where table_schema = 'your_DB_name' 
   and table_name = 'Your_tablename'

Why does cURL return error "(23) Failed writing body"?

In my case, I was doing: curl <blabla> | jq | grep <blibli>

With jq . it worked: curl <blabla> | jq . | grep <blibli>

Do fragments really need an empty constructor?

Yes, as you can see the support-package instantiates the fragments too (when they get destroyed and re-opened). Your Fragment subclasses need a public empty constructor as this is what's being called by the framework.

Copy filtered data to another sheet using VBA

Best way of doing it

Below code is to copy the visible data in DBExtract sheet, and paste it into duplicateRecords sheet, with only filtered values. Range selected by me is the maximum range that can be occupied by my data. You can change it as per your need.

  Sub selectVisibleRange()

    Dim DbExtract, DuplicateRecords As Worksheet
    Set DbExtract = ThisWorkbook.Sheets("Export Worksheet")
    Set DuplicateRecords = ThisWorkbook.Sheets("DuplicateRecords")

    DbExtract.Range("A1:BF9999").SpecialCells(xlCellTypeVisible).Copy
    DuplicateRecords.Cells(1, 1).PasteSpecial


    End Sub

strange error in my Animation Drawable

Looks like whatever is in your Animation Drawable definition is too much memory to decode and sequence. The idea is that it loads up all the items and make them in an array and swaps them in and out of the scene according to the timing specified for each frame.

If this all can't fit into memory, it's probably better to either do this on your own with some sort of handler or better yet just encode a movie with the specified frames at the corresponding images and play the animation through a video codec.

How can I count the rows with data in an Excel sheet?

With formulas, what you can do is:

  • in a new column (say col D - cell D2), add =COUNTA(A2:C2)
  • drag this formula till the end of your data (say cell D4 in our example)
  • add a last formula to sum it up (e.g in cell D5): =SUM(D2:D4)

Apache Name Virtual Host with SSL

You MUST add below part to enable NameVirtualHost functionality with given IP.

NameVirtualHost IP_Address:443

Best way to store chat messages in a database?

There's nothing wrong with saving the whole history in the database, they are prepared for that kind of tasks.

Actually you can find here in Stack Overflow a link to an example schema for a chat: example

If you are still worried for the size, you could apply some optimizations to group messages, like adding a buffer to your application that you only push after some time (like 1 minute or so); that way you would avoid having only 1 line messages

live output from subprocess command

TLDR for Python 3:

import subprocess
import sys
with open('test.log', 'wb') as f: 
    process = subprocess.Popen(your_command, stdout=subprocess.PIPE)
    for c in iter(lambda: process.stdout.read(1), b''): 
        sys.stdout.buffer.write(c)
        f.buffer.write(c)

You have two ways of doing this, either by creating an iterator from the read or readline functions and do:

import subprocess
import sys
with open('test.log', 'w') as f:  # replace 'w' with 'wb' for Python 3
    process = subprocess.Popen(your_command, stdout=subprocess.PIPE)
    for c in iter(lambda: process.stdout.read(1), ''):  # replace '' with b'' for Python 3
        sys.stdout.write(c)
        f.write(c)

or

import subprocess
import sys
with open('test.log', 'w') as f:  # replace 'w' with 'wb' for Python 3
    process = subprocess.Popen(your_command, stdout=subprocess.PIPE)
    for line in iter(process.stdout.readline, ''):  # replace '' with b'' for Python 3
        sys.stdout.write(line)
        f.write(line)

Or you can create a reader and a writer file. Pass the writer to the Popen and read from the reader

import io
import time
import subprocess
import sys

filename = 'test.log'
with io.open(filename, 'wb') as writer, io.open(filename, 'rb', 1) as reader:
    process = subprocess.Popen(command, stdout=writer)
    while process.poll() is None:
        sys.stdout.write(reader.read())
        time.sleep(0.5)
    # Read the remaining
    sys.stdout.write(reader.read())

This way you will have the data written in the test.log as well as on the standard output.

The only advantage of the file approach is that your code doesn't block. So you can do whatever you want in the meantime and read whenever you want from the reader in a non-blocking way. When you use PIPE, read and readline functions will block until either one character is written to the pipe or a line is written to the pipe respectively.

How can labels/legends be added for all chart types in chart.js (chartjs.org)?

Strangely, I didn't find anything about legends and labels in the Chart.js documentation. It seems like you can't do it with chart.js alone.

I used https://github.com/bebraw/Chart.js.legend which is extremely light, to generate the legends.

Functions are not valid as a React child. This may happen if you return a Component instead of from render

What would be wrong with doing;

<div className="" key={index}>
   {i.title}
</div>

[/*Use IIFE */]

{(function () {
     if (child.children && child.children.length !== 0) {
     let menu = createMenu(child.children);
     console.log("nested menu", menu);
     return menu;
   }
 })()}

Installing Java 7 (Oracle) in Debian via apt-get

Managed to get answer after do some google..

echo "deb http://ppa.launchpad.net/webupd8team/java/ubuntu precise main" | tee -a /etc/apt/sources.list
echo "deb-src http://ppa.launchpad.net/webupd8team/java/ubuntu precise main" | tee -a /etc/apt/sources.list
apt-key adv --keyserver hkp://keyserver.ubuntu.com:80 --recv-keys EEA14886
apt-get update
# Java 7
apt-get install oracle-java7-installer
# For Java 8 command is:
apt-get install oracle-java8-installer

How do you create optional arguments in php?

Give the optional argument a default value.

function date ($format, $timestamp='') {
}

Check if string contains only letters in javascript

With /^[a-zA-Z]/ you only check the first character:

  • ^: Assert position at the beginning of the string
  • [a-zA-Z]: Match a single character present in the list below:
    • a-z: A character in the range between "a" and "z"
    • A-Z: A character in the range between "A" and "Z"

If you want to check if all characters are letters, use this instead:

/^[a-zA-Z]+$/.test(str);
  • ^: Assert position at the beginning of the string
  • [a-zA-Z]: Match a single character present in the list below:
    • +: Between one and unlimited times, as many as possible, giving back as needed (greedy)
    • a-z: A character in the range between "a" and "z"
    • A-Z: A character in the range between "A" and "Z"
  • $: Assert position at the end of the string (or before the line break at the end of the string, if any)

Or, using the case-insensitive flag i, you could simplify it to

/^[a-z]+$/i.test(str);

Or, since you only want to test, and not match, you could check for the opposite, and negate it:

!/[^a-z]/i.test(str);

How to query SOLR for empty fields?

According to SolrQuerySyntax, you can use q=-id:[* TO *].

Convert String to Type in C#

If you really want to get the type by name you may use the following:

System.AppDomain.CurrentDomain.GetAssemblies().SelectMany(x => x.GetTypes()).First(x => x.Name == "theassembly");

Note that you can improve the performance of this drastically the more information you have about the type you're trying to load.

Setting Curl's Timeout in PHP

Your code sets the timeout to 1000 seconds. For milliseconds, use CURLOPT_TIMEOUT_MS.

Expression must be a modifiable lvalue

The assignment operator has lower precedence than &&, so your condition is equivalent to:

if ((match == 0 && k) = m)

But the left-hand side of this is an rvalue, namely the boolean resulting from the evaluation of the sub­expression match == 0 && k, so you cannot assign to it.

By contrast, comparison has higher precedence, so match == 0 && k == m is equivalent to:

if ((match == 0) && (k == m))

Reverse engineering from an APK file to a project

Not really. There are a number of dex disassembler/decompiler suites out there such as smali, or dex2jar that will generate semi-humanreadable output (in the case of dex2jar, you can get java code through the use of something like JD-GUI but the process is not perfect and it is very unlikely that you'll be able to 100% recreate your source code. However, it could potentially give you a place to start rebuilding your source tree.

How can multiple rows be concatenated into one in Oracle without creating a stored procedure?

Easy:

SELECT question_id, wm_concat(element_id) as elements
FROM   questions
GROUP BY question_id;

Pesonally tested on 10g ;-)

From http://www.oracle-base.com/articles/10g/StringAggregationTechniques.php

HTML list-style-type dash

For anyone having this problem today, the solution is simply:

list-style: "- "

How to update maven repository in Eclipse?

You can right-click on your project then Maven > Update Project..., then select Force Update of Snapshots/Releases checkbox then click OK.

Python: Find a substring in a string and returning the index of the substring

Not directly answering the question but I got a similar question recently where I was asked to count the number of times a sub-string is repeated in a given string. Here is the function I wrote:

def count_substring(string, sub_string):
    cnt = 0
    len_ss = len(sub_string)
    for i in range(len(string) - len_ss + 1):
        if string[i:i+len_ss] == sub_string:
            cnt += 1
    return cnt

The find() function probably returns the index of the fist occurrence only. Storing the index in place of just counting, can give us the distinct set of indices the sub-string gets repeated within the string.

Disclaimer: I am 'extremly' new to Python programming.

user authentication libraries for node.js?

Also have a look at everyauth if you want third party/social network login integration.

PostgreSQL: Drop PostgreSQL database through command line

You can run the dropdb command from the command line:

dropdb 'database name'

Note that you have to be a superuser or the database owner to be able to drop it.

You can also check the pg_stat_activity view to see what type of activity is currently taking place against your database, including all idle processes.

SELECT * FROM pg_stat_activity WHERE datname='database name';

Note that from PostgreSQL v13 on, you can disconnect the users automatically with

DROP DATABASE dbname FORCE;

or

dropdb -f dbname

How to convert enum names to string in c

I found a C preprocessor trick that is doing the same job without declaring a dedicated array string (Source: http://userpage.fu-berlin.de/~ram/pub/pub_jf47ht81Ht/c_preprocessor_applications_en).

Sequential enums

Following the invention of Stefan Ram, sequential enums (without explicitely stating the index, e.g. enum {foo=-1, foo1 = 1}) can be realized like this genius trick:

#include <stdio.h>

#define NAMES C(RED)C(GREEN)C(BLUE)
#define C(x) x,
enum color { NAMES TOP };
#undef C

#define C(x) #x,    
const char * const color_name[] = { NAMES };

This gives the following result:

int main( void )  { 
    printf( "The color is %s.\n", color_name[ RED ]);  
    printf( "There are %d colors.\n", TOP ); 
}

The color is RED.
There are 3 colors.

Non-Sequential enums

Since I wanted to map error codes definitions to are array string, so that I can append the raw error definition to the error code (e.g. "The error is 3 (LC_FT_DEVICE_NOT_OPENED)."), I extended the code in that way that you can easily determine the required index for the respective enum values:

#define LOOPN(n,a) LOOP##n(a)
#define LOOPF ,
#define LOOP2(a) a LOOPF a LOOPF
#define LOOP3(a) a LOOPF a LOOPF a LOOPF
#define LOOP4(a) a LOOPF a LOOPF a LOOPF a LOOPF
#define LOOP5(a) a LOOPF a LOOPF a LOOPF a LOOPF a LOOPF
#define LOOP6(a) a LOOPF a LOOPF a LOOPF a LOOPF a LOOPF a LOOPF
#define LOOP7(a) a LOOPF a LOOPF a LOOPF a LOOPF a LOOPF a LOOPF a LOOPF
#define LOOP8(a) a LOOPF a LOOPF a LOOPF a LOOPF a LOOPF a LOOPF a LOOPF a LOOPF
#define LOOP9(a) a LOOPF a LOOPF a LOOPF a LOOPF a LOOPF a LOOPF a LOOPF a LOOPF a LOOPF


#define LC_ERRORS_NAMES \
    Cn(LC_RESPONSE_PLUGIN_OK, -10) \
    Cw(8) \
    Cn(LC_RESPONSE_GENERIC_ERROR, -1) \
    Cn(LC_FT_OK, 0) \
    Ci(LC_FT_INVALID_HANDLE) \
    Ci(LC_FT_DEVICE_NOT_FOUND) \
    Ci(LC_FT_DEVICE_NOT_OPENED) \
    Ci(LC_FT_IO_ERROR) \
    Ci(LC_FT_INSUFFICIENT_RESOURCES) \
    Ci(LC_FT_INVALID_PARAMETER) \
    Ci(LC_FT_INVALID_BAUD_RATE) \
    Ci(LC_FT_DEVICE_NOT_OPENED_FOR_ERASE) \
    Ci(LC_FT_DEVICE_NOT_OPENED_FOR_WRITE) \
    Ci(LC_FT_FAILED_TO_WRITE_DEVICE) \
    Ci(LC_FT_EEPROM_READ_FAILED) \
    Ci(LC_FT_EEPROM_WRITE_FAILED) \
    Ci(LC_FT_EEPROM_ERASE_FAILED) \
    Ci(LC_FT_EEPROM_NOT_PRESENT) \
    Ci(LC_FT_EEPROM_NOT_PROGRAMMED) \
    Ci(LC_FT_INVALID_ARGS) \
    Ci(LC_FT_NOT_SUPPORTED) \
    Ci(LC_FT_OTHER_ERROR) \
    Ci(LC_FT_DEVICE_LIST_NOT_READY)


#define Cn(x,y) x=y,
#define Ci(x) x,
#define Cw(x)
enum LC_errors { LC_ERRORS_NAMES TOP };
#undef Cn
#undef Ci
#undef Cw
#define Cn(x,y) #x,
#define Ci(x) #x,
#define Cw(x) LOOPN(x,"")
static const char* __LC_errors__strings[] = { LC_ERRORS_NAMES };
static const char** LC_errors__strings = &__LC_errors__strings[10];

In this example, the C preprocessor will generate the following code:

enum LC_errors { LC_RESPONSE_PLUGIN_OK=-10,  LC_RESPONSE_GENERIC_ERROR=-1, LC_FT_OK=0, LC_FT_INVALID_HANDLE, LC_FT_DEVICE_NOT_FOUND, LC_FT_DEVICE_NOT_OPENED, LC_FT_IO_ERROR, LC_FT_INSUFFICIENT_RESOURCES, LC_FT_INVALID_PARAMETER, LC_FT_INVALID_BAUD_RATE, LC_FT_DEVICE_NOT_OPENED_FOR_ERASE, LC_FT_DEVICE_NOT_OPENED_FOR_WRITE, LC_FT_FAILED_TO_WRITE_DEVICE, LC_FT_EEPROM_READ_FAILED, LC_FT_EEPROM_WRITE_FAILED, LC_FT_EEPROM_ERASE_FAILED, LC_FT_EEPROM_NOT_PRESENT, LC_FT_EEPROM_NOT_PROGRAMMED, LC_FT_INVALID_ARGS, LC_FT_NOT_SUPPORTED, LC_FT_OTHER_ERROR, LC_FT_DEVICE_LIST_NOT_READY, TOP };

static const char* __LC_errors__strings[] = { "LC_RESPONSE_PLUGIN_OK", "" , "" , "" , "" , "" , "" , "" , "" "LC_RESPONSE_GENERIC_ERROR", "LC_FT_OK", "LC_FT_INVALID_HANDLE", "LC_FT_DEVICE_NOT_FOUND", "LC_FT_DEVICE_NOT_OPENED", "LC_FT_IO_ERROR", "LC_FT_INSUFFICIENT_RESOURCES", "LC_FT_INVALID_PARAMETER", "LC_FT_INVALID_BAUD_RATE", "LC_FT_DEVICE_NOT_OPENED_FOR_ERASE", "LC_FT_DEVICE_NOT_OPENED_FOR_WRITE", "LC_FT_FAILED_TO_WRITE_DEVICE", "LC_FT_EEPROM_READ_FAILED", "LC_FT_EEPROM_WRITE_FAILED", "LC_FT_EEPROM_ERASE_FAILED", "LC_FT_EEPROM_NOT_PRESENT", "LC_FT_EEPROM_NOT_PROGRAMMED", "LC_FT_INVALID_ARGS", "LC_FT_NOT_SUPPORTED", "LC_FT_OTHER_ERROR", "LC_FT_DEVICE_LIST_NOT_READY", };

This results to the following implementation capabilities:

LC_errors__strings[-1] ==> LC_errors__strings[LC_RESPONSE_GENERIC_ERROR] ==> "LC_RESPONSE_GENERIC_ERROR"

How to select only the first rows for each unique value of a column?

to get every unique value from your customer table, use

SELECT DISTINCT CName FROM customertable;

more in-depth of w3schools: https://www.w3schools.com/sql/sql_distinct.asp

How to create separate AngularJS controller files?

Not so graceful, but the very much simple in implementation solution - using global variable.

In the "first" file:


window.myApp = angular.module("myApp", [])
....

in the "second" , "third", etc:


myApp.controller('MyController', function($scope) {
    .... 
    }); 

How to install SignTool.exe for Windows 10

As per the comments in the question... On Windows 10 Signtool.exe and other SDK tools have been moved into "%programfiles(x86)%\Windows Kits\".

Typical path to signtool on Windows 10.

  • 32 bit = "c:\Program Files (x86)\Windows Kits\10\bin\x86\signtool.exe"
  • 64 bit = "c:\Program Files (x86)\Windows Kits\10\bin\x64\signtool.exe"

Tools for SDK 8.0 and 8.1 also reside in the "Windows Kits" folder.

Detect Safari using jQuery

Using a mix of feature detection and Useragent string:

    var is_opera = !!window.opera || navigator.userAgent.indexOf(' OPR/') >= 0;
    var is_Edge = navigator.userAgent.indexOf("Edge") > -1;
    var is_chrome = !!window.chrome && !is_opera && !is_Edge;
    var is_explorer= typeof document !== 'undefined' && !!document.documentMode && !is_Edge;
    var is_firefox = typeof window.InstallTrigger !== 'undefined';
    var is_safari = /^((?!chrome|android).)*safari/i.test(navigator.userAgent);

Usage:
if (is_safari) alert('Safari');

Or for Safari only, use this :

if ( /^((?!chrome|android).)*safari/i.test(navigator.userAgent)) {alert('Its Safari');}

Calling the base class constructor from the derived class constructor

The base-class constructor is already automatically called by your derived-class constructor. In C++, if the base class has a default constructor (takes no arguments, can be auto-generated by the compiler!), and the derived-class constructor does not invoke another base-class constructor in its initialisation list, the default constructor will be called. I.e. your code is equivalent to:

class PetStore: public Farm
{
public :
    PetStore()
    : Farm()     // <---- Call base-class constructor in initialision list
    {
     idF=0;
    };
private:
    int idF;
    string nameF;
}

How do I programmatically set the value of a select box element using JavaScript?

The easiest way if you need to:
1) Click a button which defines select option
2) Go to another page, where select option is
3) Have that option value selected on another page

1) your button links (say, on home page)

<a onclick="location.href='contact.php?option=1';" style="cursor:pointer;">Sales</a>
<a onclick="location.href='contact.php?option=2';" style="cursor:pointer;">IT</a>

(where contact.php is your page with select options. Note the page url has ?option=1 or 2)

2) put this code on your second page (my case contact.php)

<?
if (isset($_GET['option']) && $_GET['option'] != "") {
$pg = $_GET['option'];              
} ?>

3) make the option value selected, depending on the button clicked

<select>
<option value="Sales" <? if ($pg == '1') { echo "selected"; } ?> >Sales</option>
<option value="IT" <? if ($pg == '2') { echo "selected"; } ?> >IT</option>
</select>

.. and so on.
So this is an easy way of passing the value to another page (with select option list) through GET in url. No forms, no IDs.. just 3 steps and it works perfect.

py2exe - generate single executable file

I've been able to create a single exe file with all resources embeded into the exe. I'm building on windows. so that will explain some of the os.system calls i'm using.

First I tried converting all my images into bitmats and then all my data files into text strings. but this caused the final exe to be very very large.

After googleing for a week i figured out how to alter py2exe script to meet my needs.

here is the patch link on sourceforge i submitted, please post comments so we can get it included in the next distribution.

http://sourceforge.net/tracker/index.php?func=detail&aid=3334760&group_id=15583&atid=315583

this explanes all the changes made, i've simply added a new option to the setup line. here is my setup.py.

i'll try to comment it as best I can. Please know that my setup.py is complex do to the fact that i'm access the images by filename. so I must store a list to keep track of them.

this is from a want-to-b screen saver I was trying to make.

I use exec to generate my setup at run time, its easyer to cut and paste like that.

exec "setup(console=[{'script': 'launcher.py', 'icon_resources': [(0, 'ICON.ico')],\
      'file_resources': [%s], 'other_resources': [(u'INDEX', 1, resource_string[:-1])]}],\
      options={'py2exe': py2exe_options},\
      zipfile = None )" % (bitmap_string[:-1])

breakdown

script = py script i want to turn to an exe

icon_resources = the icon for the exe

file_resources = files I want to embed into the exe

other_resources = a string to embed into the exe, in this case a file list.

options = py2exe options for creating everything into one exe file

bitmap_strings = a list of files to include

Please note that file_resources is not a valid option untill you edit your py2exe.py file as described in the link above.

first time i've tried to post code on this site, if I get it wrong don't flame me.

from distutils.core import setup
import py2exe #@UnusedImport
import os

#delete the old build drive
os.system("rmdir /s /q dist")

#setup my option for single file output
py2exe_options = dict( ascii=True,  # Exclude encodings
                       excludes=['_ssl',  # Exclude _ssl
                                 'pyreadline', 'difflib', 'doctest', 'locale',
                                 'optparse', 'pickle', 'calendar', 'pbd', 'unittest', 'inspect'],  # Exclude standard library
                       dll_excludes=['msvcr71.dll', 'w9xpopen.exe',
                                     'API-MS-Win-Core-LocalRegistry-L1-1-0.dll',
                                     'API-MS-Win-Core-ProcessThreads-L1-1-0.dll',
                                     'API-MS-Win-Security-Base-L1-1-0.dll',
                                     'KERNELBASE.dll',
                                     'POWRPROF.dll',
                                     ],
                       #compressed=None,  # Compress library.zip
                       bundle_files = 1,
                       optimize = 2                        
                       )

#storage for the images
bitmap_string = '' 
resource_string = ''
index = 0

print "compile image list"                          

for image_name in os.listdir('images/'):
    if image_name.endswith('.jpg'):
        bitmap_string += "( " + str(index+1) + "," + "'" + 'images/' + image_name + "'),"
        resource_string += image_name + " "
        index += 1

print "Starting build\n"

exec "setup(console=[{'script': 'launcher.py', 'icon_resources': [(0, 'ICON.ico')],\
      'file_resources': [%s], 'other_resources': [(u'INDEX', 1, resource_string[:-1])]}],\
      options={'py2exe': py2exe_options},\
      zipfile = None )" % (bitmap_string[:-1])

print "Removing Trash"
os.system("rmdir /s /q build")
os.system("del /q *.pyc")
print "Build Complete"

ok, thats it for the setup.py now the magic needed access the images. I developed this app without py2exe in mind then added it later. so you'll see access for both situations. if the image folder can't be found it tries to pull the images from the exe resources. the code will explain it. this is part of my sprite class and it uses a directx. but you can use any api you want or just access the raw data. doesn't matter.

def init(self):
    frame = self.env.frame
    use_resource_builtin = True
    if os.path.isdir(SPRITES_FOLDER):
        use_resource_builtin = False
    else:
        image_list = LoadResource(0, u'INDEX', 1).split(' ')

    for (model, file) in SPRITES.items():
        texture = POINTER(IDirect3DTexture9)()
        if use_resource_builtin: 
            data = LoadResource(0, win32con.RT_RCDATA, image_list.index(file)+1) #windll.kernel32.FindResourceW(hmod,typersc,idrsc)               
            d3dxdll.D3DXCreateTextureFromFileInMemory(frame.device,   #Pointer to an IDirect3DDevice9 interface
                                              data,                #Pointer to the file in memory
                                              len(data),           #Size of the file in memory
                                              byref(texture))      #ppTexture
        else:
            d3dxdll.D3DXCreateTextureFromFileA(frame.device, #@UndefinedVariable
                                               SPRITES_FOLDER + file,
                                               byref(texture))            
        self.model_sprites[model] = texture
    #else:
    #    raise Exception("'sprites' folder is not present!")

Any questions fell free to ask.

open_basedir restriction in effect. File(/) is not within the allowed path(s):

I uploaded my codeigniter project on Directadmin panel. I was getting same error. error

Then I change in php settings.

open_basedir = session.save_path = ./temp/

Then it worked for me.

Get index of a key/value pair in a C# dictionary based on the value

In your comment to max's answer, you say that what you really wanted to get is the key in, and not the index of, the KeyValuePair that contains a certain value. You could edit your question to make it more clear.

It is worth pointing out (EricM has touched upon this in his answer) that a value might appear more than once in the dictionary, in which case one would have to think which key he would like to get: e.g. the first that comes up, the last, all of them?

If you are sure that each key has a unique value, you could have another dictionary, with the values from the first acting as keys and the previous keys acting as values. Otherwise, this second dictionary idea (suggested by Jon Skeet) will not work, as you would again have to think which of all the possible keys to use as value in the new dictionary.

If you were asking about the index, though, EricM's answer would be OK. Then you could get the KeyValuePair in question by using:

yourDictionary.ElementAt(theIndexYouFound);

provided that you do not add/remove things in yourDictionary.

PS: I know it's been almost 7 years now, but what the heck. I thought it best to formulate my answer as addressing the OP, but of course by now one can say it is an answer for just about anyone else but the OP. Fully aware of that, thank you.

List all employee's names and their managers by manager name using an inner join

No, the correct join is:

inner join Employees m on e.mgr = m.EmpID;

You need to match the ManagerID for the current employee with the EmployeeID of the manager. Not with the ManagerID of the manager.

update
As noted by Andrey Gordeev:
You'd also need to add m.Ename to your SELECT query in order to get the name of the Manager in your result. Otherwise you'd only get the managerID.

How to change font size in Eclipse for Java text editors?

The Eclipse-Fonts extension will add toolbar buttons and keyboard shortcuts for changing font size. You can then use AutoHotkey to make Ctrl + mousewheel zoom.

Under menu Help ? Install New Software... in the menu, paste the update URL (http://eclipse-fonts.googlecode.com/svn/trunk/FontsUpdate/) into the Works with: text box and press Enter. Expand the tree and select FontsFeature as in the following image:

Eclipse extension installation screen capture

Complete the installation and restart Eclipse. Then you should see the A toolbar buttons (circled in red in the following image) and be able to use the keyboard shortcuts Ctrl + - and Ctrl + = to zoom (although you may have to unbind those keys from Eclipse first).

Eclipse screen capture with the font size toolbar buttons circled

To get Ctrl + mouse wheel zooming, you can use AutoHotkey with the following script:

; Ctrl + mouse wheel zooming in Eclipse.
; Requires Eclipse-Fonts (https://code.google.com/p/eclipse-fonts/).
; Thank you for the unique window class, SWT/Eclipse.
;
#IfWinActive ahk_class SWT_Window0
    ^WheelUp:: Send ^{=}
    ^WheelDown:: Send ^-
#IfWinActive

Vue.js dynamic images not working

Vue.js uses vue-loader, a loader for WebPack which is set up to rewrite/convert paths at compile time, in order to allow you to not worry about static paths that would differ between deployments (local, dev, one hosting platform or the other), by allowing you to use relative local filesystem paths. It also adds other benefits like asset caching and versioning (you can probably see this by checking the actual src URL being generated).

So having a src that would normally be handled by vue-loader/WebPack set to a dynamic expression, evaluated at runtime, will circumvent this mechanism and the dynamic URL generated will be invalid in the context of the actual deployment (unless it's fully qualified, that's an exception).

If instead, you would use a require function call in the dynamic expression, vue-loader/WebPack will see it and apply the usual magic.

For example, this wouldn't work:

<img alt="Logo" :src="logo" />
computed: {
    logo() {
        return this.colorMode === 'dark'
               ? './assets/logo-dark.png'
               : './assets/logo-white.png';
    }
}

While this would work:

<img alt="Logo" :src="logo" />
computed: {
    logo() {
        return this.colorMode === 'dark'
               ? require('./assets/logo-dark.png')
               : require('./assets/logo-white.png');
    }
}

I just found out about this myself. Took me an hour but... you live, you learn, right?

MySQL JDBC Driver 5.1.33 - Time Zone Issue

I solved this issue without any single code change. just goto system time setting and set the time zone. In my case the default time zone was UTC which I changed to my local time zone. After I did restart all services, everything worked for me.

jQuery val is undefined?

I just ran across this myself yesterday on a project I was working on. I'm my specific case, it was not exactly what the input was named, but how the ID was named.

<input id="user_info[1][last_name]" ..... />
var last_name = $("#user_info[1][last_name]").val() // returned undefined

Removing the brackets solved the issue:

<input id="user_info1_last_name" ..... />
var last_name = $("#user_info1_last_name").val() // returned "MyLastNameValue"

Anyway, probably a no brainer for some people, but in case this helps anyone else... there you go!

:-) - Drew

How to get height of <div> in px dimension

For those looking for a plain JS solution:

let el = document.querySelector("#myElementId");

// including the element's border
let width = el.offsetWidth;
let height = el.offsetHeight;

// not including the element's border:
let width = el.clientWidth;
let height = el.clientHeight;

Check out this article for more details.

SQL : BETWEEN vs <= and >=

I have a slight preference for BETWEEN because it makes it instantly clear to the reader that you are checking one field for a range. This is especially true if you have similar field names in your table.

If, say, our table has both a transactiondate and a transitiondate, if I read

transactiondate between ...

I know immediately that both ends of the test are against this one field.

If I read

transactiondate>='2009-04-17' and transactiondate<='2009-04-22'

I have to take an extra moment to make sure the two fields are the same.

Also, as a query gets edited over time, a sloppy programmer might separate the two fields. I've seen plenty of queries that say something like

where transactiondate>='2009-04-17'
  and salestype='A'
  and customernumber=customer.idnumber
  and transactiondate<='2009-04-22'

If they try this with a BETWEEN, of course, it will be a syntax error and promptly fixed.

Facebook API: Get fans of / people who like a page

I created small tool called luster for downloading list of "likers" and "followers" of your Facebook page.

After download and unpack archive for your platform you can run it from terminal as

luster fans my-page-name

Where my-page-name is string identifier of your Facebook page.

You will be asked for email and password to your Facebook account. Note that this account need to have one of available page roles. Even Analyst is enough.

After while you should receive output similar to following

TIME,KIND,ID,NAME,LINK
1581665652,Like,111111111,John Doe,https://www.facebook.com/111111111
1581663355,Like,222222222,Kal Peterson,https://www.facebook.com/222222222
1581661970,Follow,333333333,Nikol Kus,https://www.facebook.com/333333333

This tool is based on reading table which can be found in Settings -> People and Other Pages section of your Facebook page.

Be aware that there is some limit up to 7k results from Facebook side. I tested it on two pages with more than 20k of fans and didn't get more then 7k results.

See https://github.com/zladovan/luster for details.

Check if a string is palindrome

Reverse the string and check if original string and reverse are same or not

How to draw in JPanel? (Swing/graphics Java)

When working with graphical user interfaces, you need to remember that drawing on a pane is done in the Java AWT/Swing event queue. You can't just use the Graphics object outside the paint()/paintComponent()/etc. methods.

However, you can use a technique called "Frame buffering". Basically, you need to have a BufferedImage and draw directly on it (see it's createGraphics() method; that graphics context you can keep and reuse for multiple operations on a same BufferedImage instance, no need to recreate it all the time, only when creating a new instance). Then, in your JPanel's paintComponent(), you simply need to draw the BufferedImage instance unto the JPanel. Using this technique, you can perform zoom, translation and rotation operations quite easily through affine transformations.

Any way to select without causing locking in MySQL?

Use

SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED.

Version 5.0 Docs are here.

Version 5.1 Docs are here.

Python how to plot graph sine wave

This is another option

#!/usr/bin/env python

import numpy as np
import matplotlib
matplotlib.use('TKAgg') #use matplotlib backend TkAgg (optional)
import matplotlib.pyplot as plt

sample_rate = 200 # sampling frequency in Hz (atleast 2 times f)
t = np.linspace(0,5,sample_rate)    #time axis
f = 100 #Signal frequency in Hz
sig = np.sin(2*np.pi*f*(t/sample_rate))
plt.plot(t,sig)
plt.xlabel("Time")
plt.ylabel("Amplitude")
plt.tight_layout() 
plt.show()

Python error message io.UnsupportedOperation: not readable

There are few modes to open file (read, write etc..)

If you want to read from file you should type file = open("File.txt","r"), if write than file = open("File.txt","w"). You need to give the right permission regarding your usage.

more modes:

  • r. Opens a file for reading only.
  • rb. Opens a file for reading only in binary format.
  • r+ Opens a file for both reading and writing.
  • rb+ Opens a file for both reading and writing in binary format.
  • w. Opens a file for writing only.
  • you can find more modes in here

Instantiating a generic type

No, and the fact that you want to seems like a bad idea. Do you really need a default constructor like this?

One-liner if statements, how to convert this if-else-statement

return (expression) ? value1 : value2;

If value1 and value2 are actually true and false like in your example, you may as well just

return expression;

How can I disable a button in a jQuery dialog from a function?

If you create a dialog providing id's for the buttons,

$("#dialog").dialog({ buttons: [ {
 id: "dialogSave",
 text: "Save",
 click: function() { $(this).dialog("close"); }
},
{
 id: "dialogCancel",
 text: "Cancel",
 click: function() { $(this).dialog("close"); 
}
}]});       

we can disable button with the following code:

$("#dialogSave").button("option", "disabled", true);

enable/disable zoom in Android WebView

I've looked at the source code for WebView and I concluded that there is no elegant way to accomplish what you are asking.

What I ended up doing was subclassing WebView and overriding OnTouchEvent. In OnTouchEvent for ACTION_DOWN, I check how many pointers there are using MotionEvent.getPointerCount(). If there is more than one pointer, I call setSupportZoom(true), otherwise I call setSupportZoom(false). I then call the super.OnTouchEvent().

This will effectively disable zooming when scrolling (thus disabling the zoom controls) and enable zooming when the user is about to pinch zoom. Not a nice way of doing it, but it has worked well for me so far.

Note that getPointerCount() was introduced in 2.1 so you'll have to do some extra stuff if you support 1.6.

Create boolean column in MySQL with false as default value?

If you are making the boolean column as not null then the default 'default' value is false; you don't have to explicitly specify it.

Error Code: 1005. Can't create table '...' (errno: 150)

My problem was not listed, it was something so silly ..... The table that has the FK as PK was a composite PK that was declared like this: primary key (CNPJ, CEP) I wanted the CEP field to be FK in another table and I was stuck in this error, the moral of the story just inverted the code above for Primary key (CEP, CNPJ) and it worked. Get tip their friends.

MVC3 EditorFor readOnly

The EditorFor html helper does not have overloads that take HTML attributes. In this case, you need to use something more specific like TextBoxFor:

<div class="editor-field">
    @Html.TextBoxFor(model => model.userName, new 
        { disabled = "disabled", @readonly = "readonly" })
</div>

You can still use EditorFor, but you will need to have a TextBoxFor in a custom EditorTemplate:

public class MyModel
{
    [UIHint("userName")]
    public string userName { ;get; set; }
}

Then, in your Views/Shared/EditorTemplates folder, create a file userName.cshtml. In that file, put this:

@model string
@Html.TextBoxFor(m => m, new { disabled = "disabled", @readonly = "readonly" })

Change Circle color of radio button

  1. Declare custom style in your styles.xml file.

    <style name="MyRadioButton" parent="Theme.AppCompat.Light">  
      <item name="colorControlNormal">@color/indigo</item>
      <item name="colorControlActivated">@color/pink</item>
    </style>  
    
  2. Apply this style to your RadioButton via android:theme attribute.

    <RadioButton  
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:checked="true"
        android:text="Radio Button"
        android:theme="@style/MyRadioButton"/>
    

    only if your activity extends AppCompatActivity

"unrecognized import path" with go get

I installed Go with brew on OSX 10.11, and found I had to set GOROOT to:

/usr/local/Cellar/go/1.5.1/libexec

(Of course replace the version in this path with go version you have)

Brew uses symlinks, which were fooling the gotool. So follow the links home.

If a DOM Element is removed, are its listeners also removed from memory?

Don't hesitate to watch heap to see memory leaks in event handlers keeping a reference to the element with a closure and the element keeping a reference to the event handler.

Garbage collector do not like circular references.

Usual memory leak case: admit an object has a ref to an element. That element has a ref to the handler. And the handler has a ref to the object. The object has refs to a lot of other objects. This object was part of a collection you think you have thrown away by unreferencing it from your collection. => the whole object and all it refers will remain in memory till page exit. => you have to think about a complete killing method for your object class or trust a mvc framework for example.

Moreover, don't hesitate to use the Retaining tree part of Chrome dev tools.

How Can I Truncate A String In jQuery?

  function truncateString(str, length) {
     return str.length > length ? str.substring(0, length - 3) + '...' : str
  }

JavaFX and OpenJDK

Try obuildfactory.

There is need to modify these scripts (contains error and don't exactly do the "thing" required), i will upload mine scripts forked from obuildfactory in next few days. and so i will also update my answer accordingly.

Until then enjoy, sir :)

PATH issue with pytest 'ImportError: No module named YadaYadaYada'

I'm not sure why py.test does not add the current directory in the PYTHONPATH itself, but here's a workaround (to be executed from the root of your repository):

python -m pytest tests/

It works because Python adds the current directory in the PYTHONPATH for you.

In JPA 2, using a CriteriaQuery, how to count results

I've sorted this out using the cb.createQuery() (without the result type parameter):

public class Blah() {

    CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder();
    CriteriaQuery query = criteriaBuilder.createQuery();
    Root<Entity> root;
    Predicate whereClause;
    EntityManager entityManager;
    Class<Entity> domainClass;

    ... Methods to create where clause ...

    public Blah(EntityManager entityManager, Class<Entity> domainClass) {
        this.entityManager = entityManager;
        this.domainClass = domainClass;
        criteriaBuilder = entityManager.getCriteriaBuilder();
        query = criteriaBuilder.createQuery();
        whereClause = criteriaBuilder.equal(criteriaBuilder.literal(1), 1);
        root = query.from(domainClass);
    }

    public CriteriaQuery<Entity> getQuery() {
        query.select(root);
        query.where(whereClause);
        return query;
    }

    public CriteriaQuery<Long> getQueryForCount() {
        query.select(criteriaBuilder.count(root));
        query.where(whereClause);
        return query;
    }

    public List<Entity> list() {
        TypedQuery<Entity> q = this.entityManager.createQuery(this.getQuery());
        return q.getResultList();
    }

    public Long count() {
        TypedQuery<Long> q = this.entityManager.createQuery(this.getQueryForCount());
        return q.getSingleResult();
    }
}

Hope it helps :)

Squash the first two commits in Git?

If you simply want to squash all commits into a single, initial commit, just reset the repository and amend the first commit:

git reset hash-of-first-commit
git add -A
git commit --amend

Git reset will leave the working tree intact, so everything is still there. So just add the files using git add commands, and amend the first commit with these changes. Compared to rebase -i you'll lose the ability to merge the git comments though.

Identifying Exception Type in a handler Catch Block

Alternatively:

var exception = err as Web2PDFException; 

if ( excecption != null ) 
{ 
     Web2PDFException wex = exception; 
     .... 
}

What is the right way to POST multipart/form-data using curl?

On Windows 10, curl 7.28.1 within powershell, I found the following to work for me:

$filePath = "c:\temp\dir with spaces\myfile.wav"
$curlPath = ("myfilename=@" + $filePath)
curl -v -F $curlPath URL

How to get the first line of a file in a bash script?

head takes the first lines from a file, and the -n parameter can be used to specify how many lines should be extracted:

line=$(head -n 1 filename)

What's the best way to get the current URL in Spring MVC?

Well there are two methods to access this data easier, but the interface doesn't offer the possibility to get the whole URL with one call. You have to build it manually:

public static String makeUrl(HttpServletRequest request)
{
    return request.getRequestURL().toString() + "?" + request.getQueryString();
}

I don't know about a way to do this with any Spring MVC facilities.

If you want to access the current Request without passing it everywhere you will have to add a listener in the web.xml:

<listener>
    <listener-class>org.springframework.web.context.request.RequestContextListener</listener-class>
</listener>

And then use this to get the request bound to the current Thread:

((ServletRequestAttributes) RequestContextHolder.currentRequestAttributes()).getRequest()

How to auto-reload files in Node.js?

For people using Vagrant and PHPStorm, file watcher is a faster approach

  • disable immediate sync of the files so you run the command only on save then create a scope for the *.js files and working directories and add this command

    vagrant ssh -c "/var/www/gadelkareem.com/forever.sh restart"

where forever.sh is like

#!/bin/bash

cd /var/www/gadelkareem.com/ && forever $1 -l /var/www/gadelkareem.com/.tmp/log/forever.log -a app.js

Converting JSON to XML in Java

If you want to replace any node value you can do like this

JSONObject json = new JSONObject(str);
String xml = XML.toString(json);
xml.replace("old value", "new value");

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

Use Add/Remove programs from the Control Panel.

Get JSONArray without array name?

JSONArray has a constructor which takes a String source (presumed to be an array).

So something like this

JSONArray array = new JSONArray(yourJSONArrayAsString);

How can I make robocopy silent in the command line except for progress?

A workaround, if you want it to be absolutely silent, is to redirect the output to a file (and optionally delete it later).

Robocopy src dest > output.log
del output.log

Can't compare naive and aware datetime.now() <= challenge.datetime_end

Just:

dt = datetimeObject.strftime(format) # format = your datetime format ex) '%Y %d %m'
dt = datetime.datetime.strptime(dt,format)

So do this:

start_time = challenge.datetime_start.strftime('%Y %d %m %H %M %S')
start_time = datetime.datetime.strptime(start_time,'%Y %d %m %H %M %S')

end_time = challenge.datetime_end.strftime('%Y %d %m %H %M %S')
end_time = datetime.datetime.strptime(end_time,'%Y %d %m %H %M %S')

and then use start_time and end_time

Take the content of a list and append it to another list

Take a look at itertools.chain for a fast way to treat many small lists as a single big list (or at least as a single big iterable) without copying the smaller lists:

>>> import itertools
>>> p = ['a', 'b', 'c']
>>> q = ['d', 'e', 'f']
>>> r = ['g', 'h', 'i']
>>> for x in itertools.chain(p, q, r):
        print x.upper()

Using jQuery to build table rows from AJAX response(json)

I do following to get JSON response from Ajax and parse without using parseJson:

$.ajax({
  dataType: 'json', <----
  type: 'GET',
  url: 'get/allworldbankaccounts.json',
  data: $("body form:first").serialize(),

If you are using dataType as Text then you need $.parseJSON(response)

AngularJS - value attribute for select

If you use the track by option, the value attribute is correctly written, e.g.:

<div ng-init="a = [{label: 'one', value: 15}, {label: 'two', value: 20}]">
    <select ng-model="foo" ng-options="x for x in a track by x.value"/>
</div>

produces:

<select>
    <option value="" selected="selected"></option>
    <option value="15">one</option>
    <option value="20">two</option>
</select>

What's the meaning of exception code "EXC_I386_GPFLT"?

You can often get information from the header files. For example:

$ cd /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.9.sdk
$ find usr -name \*.h -exec fgrep -l EXC_I386_GPFLT {} \;
usr/include/mach/i386/exception.h
^C
$ more usr/include/mach/i386/exception.h
....
#define EXC_I386_GPFLT          13      /* general protection fault     */

OK, so it's a general protection fault (as its name suggests anyway). Googling "i386 general protection fault" yields many hits, but this looks interesting:

Memory protection is also implemented using the segment descriptors. First, the processor checks whether a value loaded in a segment register references a valid descriptor. Then it checks that every linear address calculated actually lies within the segment. Also, the type of access (read, write, or execute) is checked against the information in the segment descriptor. Whenever one of these checks fails, exception (interrupt) 13 (hex 0D) is raised. This exception is called a General Protection Fault (GPF).

That 13 matches what we saw in the header files, so it looks like the same thing. However from the application programmer's point-of-view, it just means we're referencing memory we shouldn't be, and it's doesn't really matter how it's implemented on the hardware.

Combine two ActiveRecord::Relation objects

Brute force it:

first_name_relation = User.where(:first_name => 'Tobias') # ActiveRecord::Relation
last_name_relation  = User.where(:last_name  => 'Fünke') # ActiveRecord::Relation

all_name_relations = User.none
first_name_relation.each do |ar|
  all_name_relations.new(ar)
end
last_name_relation.each do |ar|
  all_name_relations.new(ar)
end

Slide up/down effect with ng-show and ng-animate

update for Angular 1.2+ (v1.2.6 at the time of this post):

.stuff-to-show {
  position: relative;
  height: 100px;
  -webkit-transition: top linear 1.5s;
  transition: top linear 1.5s;
  top: 0;
}
.stuff-to-show.ng-hide {
  top: -100px;
}
.stuff-to-show.ng-hide-add,
.stuff-to-show.ng-hide-remove {
  display: block!important;
}

(plunker)

Delayed function calls

It sounds like the control of the creation of both these objects and their interdependence needs to controlled externally, rather than between the classes themselves.

Cleaning `Inf` values from an R dataframe

Option 1

Use the fact that a data.frame is a list of columns, then use do.call to recreate a data.frame.

do.call(data.frame,lapply(DT, function(x) replace(x, is.infinite(x),NA)))

Option 2 -- data.table

You could use data.table and set. This avoids some internal copying.

DT <- data.table(dat)
invisible(lapply(names(DT),function(.name) set(DT, which(is.infinite(DT[[.name]])), j = .name,value =NA)))

Or using column numbers (possibly faster if there are a lot of columns):

for (j in 1:ncol(DT)) set(DT, which(is.infinite(DT[[j]])), j, NA)

Timings

# some `big(ish)` data
dat <- data.frame(a = rep(c(1,Inf), 1e6), b = rep(c(Inf,2), 1e6), 
                  c = rep(c('a','b'),1e6),d = rep(c(1,Inf), 1e6),  
                  e = rep(c(Inf,2), 1e6))
# create data.table
library(data.table)
DT <- data.table(dat)

# replace (@mnel)
system.time(na_dat <- do.call(data.frame,lapply(dat, function(x) replace(x, is.infinite(x),NA))))
## user  system elapsed 
#  0.52    0.01    0.53 

# is.na (@dwin)
system.time(is.na(dat) <- sapply(dat, is.infinite))
# user  system elapsed 
# 32.96    0.07   33.12 

# modified is.na
system.time(is.na(dat) <- do.call(cbind,lapply(dat, is.infinite)))
#  user  system elapsed 
# 1.22    0.38    1.60 


# data.table (@mnel)
system.time(invisible(lapply(names(DT),function(.name) set(DT, which(is.infinite(DT[[.name]])), j = .name,value =NA))))
# user  system elapsed 
# 0.29    0.02    0.31 

data.table is the quickest. Using sapply slows things down noticeably.

Writing to a new file if it doesn't exist, and appending to a file if it does

Using the pathlib module (python's object-oriented filesystem paths)

Just for kicks, this is perhaps the latest pythonic version of the solution.

from pathlib import Path 

path = Path(f'{player}.txt')
path.touch()  # default exists_ok=True
with path.open('a') as highscore:
   highscore.write(f'Username:{player}')

C# List<string> to string with delimiter

You can use String.Join. If you have a List<string> then you can call ToArray first:

List<string> names = new List<string>() { "John", "Anna", "Monica" };
var result = String.Join(", ", names.ToArray());

In .NET 4 you don't need the ToArray anymore, since there is an overload of String.Join that takes an IEnumerable<string>.

Results:


John, Anna, Monica

Chart won't update in Excel (2007)

Just activate the sheet where the chart is:

Sheets(1).Activate

and your problem disappears.

I had the same problem and none of the things you mentioned in question worked for me until I just activated sheet. The accepted answer didn't work for me neither.

Alternatively you can make:

ActiveCell.Activate

Formatting floats in a numpy array

You can use round function. Here some example

numpy.round([2.15295647e+01, 8.12531501e+00, 3.97113829e+00, 1.00777250e+01],2)
array([ 21.53,   8.13,   3.97,  10.08])

IF you want change just display representation, I would not recommended to alter printing format globally, as it suggested above. I would format my output in place.

>>a=np.array([2.15295647e+01, 8.12531501e+00, 3.97113829e+00, 1.00777250e+01])
>>> print([ "{:0.2f}".format(x) for x in a ])
['21.53', '8.13', '3.97', '10.08']

converting string to long in python

Well, longs can't hold anything but integers.

One option is to use a float: float('234.89')

The other option is to truncate or round. Converting from a float to a long will truncate for you: long(float('234.89'))

>>> long(float('1.1'))
1L
>>> long(float('1.9'))
1L
>>> long(round(float('1.1')))
1L
>>> long(round(float('1.9')))
2L

cordova run with ios error .. Error code 65 for command: xcodebuild with args:

I had the same problem. In my case cordova platform update ios helped. The reason was in outdated version.

To add server using sp_addlinkedserver

I got it. It worked fine

Thank you for your help:

EXEC sp_addlinkedserver @server='Servername'

EXEC sp_addlinkedsrvlogin 'Servername', 'false', NULL, 'username', 'password@123'

Array slices in C#

Arrays are enumerable, so your foo already is an IEnumerable<byte> itself. Simply use LINQ sequence methods like Take() to get what you want out of it (don't forget to include the Linq namespace with using System.Linq;):

byte[] foo = new byte[4096];

var bar = foo.Take(41);

If you really need an array from any IEnumerable<byte> value, you could use the ToArray() method for that. That does not seem to be the case here.

Java Regex Replace with Capturing Group

Java 9 offers a Matcher.replaceAll() that accepts a replacement function:

resultString = regexMatcher.replaceAll(
        m -> String.valueOf(Integer.parseInt(m.group()) * 3));

React Hooks useState() with Object

You can pass new value like this

  setExampleState({...exampleState,  masterField2: {
        fieldOne: "c",
        fieldTwo: {
           fieldTwoOne: "d",
           fieldTwoTwo: "e"
           }
        },
   }})

DATEDIFF function in Oracle

Just subtract the two dates:

select date '2000-01-02' - date '2000-01-01' as dateDiff
from dual;

The result will be the difference in days.

More details are in the manual:
https://docs.oracle.com/cd/E11882_01/server.112/e41084/sql_elements001.htm#i48042

Why should I prefer to use member initialization lists?

Syntax:

  class Sample
  {
     public:
         int Sam_x;
         int Sam_y;

     Sample(): Sam_x(1), Sam_y(2)     /* Classname: Initialization List */
     {
           // Constructor body
     }
  };

Need of Initialization list:

 class Sample
 {
     public:
         int Sam_x;
         int Sam_y;

     Sample()     */* Object and variables are created - i.e.:declaration of variables */*
     { // Constructor body starts 

         Sam_x = 1;      */* Defining a value to the variable */* 
         Sam_y = 2;

     } // Constructor body ends
  };

in the above program, When the class’s constructor is executed, Sam_x and Sam_y are created. Then in constructor body, those member data variables are defined.

Use cases:

  1. Const and Reference variables in a Class

In C, variables must be defined during creation. the same way in C++, we must initialize the Const and Reference variable during object creation by using Initialization list. if we do initialization after object creation (Inside constructor body), we will get compile time error.

  1. Member objects of Sample1 (base) class which do not have default constructor

     class Sample1 
     {
         int i;
         public:
         Sample1 (int temp)
         {
            i = temp;
         }
     };
    
      // Class Sample2 contains object of Sample1 
     class Sample2
     {
      Sample1  a;
      public:
      Sample2 (int x): a(x)      /* Initializer list must be used */
      {
    
      }
     };
    

While creating object for derived class which will internally calls derived class constructor and calls base class constructor (default). if base class does not have default constructor, user will get compile time error. To avoid, we must have either

 1. Default constructor of Sample1 class
 2. Initialization list in Sample2 class which will call the parametric constructor of Sample1 class (as per above program)
  1. Class constructor’s parameter name and Data member of a Class are same:

     class Sample3 {
        int i;         /* Member variable name : i */  
        public:
        Sample3 (int i)    /* Local variable name : i */ 
        {
            i = i;
            print(i);   /* Local variable: Prints the correct value which we passed in constructor */
        }
        int getI() const 
        { 
             print(i);    /*global variable: Garbage value is assigned to i. the expected value should be which we passed in constructor*/
             return i; 
        }
     };
    

As we all know, local variable having highest priority then global variable if both variables are having same name. In this case, the program consider "i" value {both left and right side variable. i.e: i = i} as local variable in Sample3() constructor and Class member variable(i) got override. To avoid, we must use either

  1. Initialization list 
  2. this operator.

Where to find Application Loader app in Mac?

For anyone finding this now (23/09/2019) Application Loader has been removed from Xcode.

If you have built the application in Xcode you should be able to follow these instructions to upload your and distribute your project Upload an app

I am not sure what to do if you have been given a .ipa file, for example when building an Expo project, I'll update this post when i have an answer.

In the mean time more info can be found here. Developer Apple - Whats new

How to use a typescript enum value in an Angular2 ngSwitch statement

Angular4 - Using Enum in HTML Template ngSwitch / ngSwitchCase

Solution here: https://stackoverflow.com/a/42464835/802196

credit: @snorkpete

In your component, you have

enum MyEnum{
  First,
  Second
}

Then in your component, you bring in the Enum type via a member 'MyEnum', and create another member for your enum variable 'myEnumVar' :

export class MyComponent{
  MyEnum = MyEnum;
  myEnumVar:MyEnum = MyEnum.Second
  ...
}

You can now use myEnumVar and MyEnum in your .html template. Eg, Using Enums in ngSwitch:

<div [ngSwitch]="myEnumVar">
  <div *ngSwitchCase="MyEnum.First"><app-first-component></app-first-component></div>
  <div *ngSwitchCase="MyEnum.Second"><app-second-component></app-second-component></div>
  <div *ngSwitchDefault>MyEnumVar {{myEnumVar}} is not handled.</div>
</div>

Maven: repository element was not specified in the POM inside distributionManagement?

The ID of the two repos are both localSnap; that's probably not what you want and it might confuse Maven.

If that's not it: There might be more repository elements in your POM. Search the output of mvn help:effective-pom for repository to make sure the number and place of them is what you expect.

How to allow remote access to my WAMP server for Mobile(Android)

I assume you are using windows. Open the command prompt and type ipconfig and find out your local address (on your pc) it should look something like 192.168.1.13 or 192.168.0.5 where the end digit is the one that changes. It should be next to IPv4 Address.

If your WAMP does not use virtual hosts the next step is to enter that IP address on your phones browser ie http://192.168.1.13 If you have a virtual host then you will need root to edit the hosts file.

If you want to test the responsiveness / mobile design of your website you can change your user agent in chrome or other browsers to mimic a mobile.

See http://googlesystem.blogspot.co.uk/2011/12/changing-user-agent-new-google-chrome.html.

Edit: Chrome dev tools now has a mobile debug tool where you can change the size of the viewport, spoof user agents, connections (4G, 3G etc).

If you get forbidden access then see this question WAMP error: Forbidden You don't have permission to access /phpmyadmin/ on this server. Basically, change the occurrances of deny,allow to allow,deny in the httpd.conf file. You can access this by the WAMP menu.

To eliminate possible causes of the issue for now set your config file to

<Directory />
    Options FollowSymLinks
    AllowOverride All
    Order allow,deny
    Allow from all
    <RequireAll>
        Require all granted
    </RequireAll>
</Directory>

As thatis working for my windows PC, if you have the directory config block as well change that also to allow all.

Config file that fixed the problem:

https://gist.github.com/samvaughton/6790739

Problem was that the /www apache directory config block still had deny set as default and only allowed from localhost.

Adding Permissions in AndroidManifest.xml in Android Studio?

You can add manually in the manifest file within manifest tag by:

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

This permission is required to be able to access the camera device.

Access Control Request Headers, is added to header in AJAX request with jQuery

This code below works for me. I always use only single quotes, and it works fine. I suggest you should use only single quotes or only double quotes, but not mixed up.

$.ajax({
    url: 'YourRestEndPoint',
    headers: {
        'Authorization':'Basic xxxxxxxxxxxxx',
        'X-CSRF-TOKEN':'xxxxxxxxxxxxxxxxxxxx',
        'Content-Type':'application/json'
    },
    method: 'POST',
    dataType: 'json',
    data: YourData,
    success: function(data){
      console.log('succes: '+data);
    }
  });

Importing class from another file

Your problem is basically that you never specified the right path to the file.

Try instead, from your main script:

from folder.file import Klasa

Or, with from folder import file:

from folder import file
k = file.Klasa()

Or again:

import folder.file as myModule
k = myModule.Klasa()

How to capture the browser window close event?

My Issue: The 'onbeforeunload' event would only be triggered if there were odd number of submits(clicks). I had a combination of solutions from similar threads in SO to have my solution work. well my code will speak.

<!--The definition of event and initializing the trigger flag--->


$(document).ready(function() {
  updatefgallowPrompt(true);
  window.onbeforeunload = WarnUser; 
}

function WarnUser() {
  var allowPrompt = getfgallowPrompt();
  if(allowPrompt) {
    saveIndexedDataAlert();
    return null;
  } else {
    updatefgallowPrompt(true);
    event.stopPropagation
  }
}

<!--The method responsible for deciding weather the unload event is triggered from submit or not--->
function saveIndexedDataAlert() {
  var allowPrompt = getfgallowPrompt();
  var lenIndexedDocs = parseInt($('#sortable3 > li').size()) + parseInt($('#sortable3 > ul').size());

  if(allowPrompt && $.trim(lenIndexedDocs) > 0) {
    event.returnValue = "Your message";
  } else {
    event.returnValue = "   ";
    updatefgallowPrompt(true);
  }
}

<!---Function responsible to reset the trigger flag---->
$(document).click(function(event) {  
  $('a').live('click', function() { updatefgallowPrompt(false); });
});

<!--getter and setter for the flag---->
function updatefgallowPrompt (allowPrompt){ //exit msg dfds
  $('body').data('allowPrompt', allowPrompt);   
}   

function getfgallowPrompt(){        
  return $('body').data('allowPrompt'); 
}

How to check if a variable is not null?

There is another possible scenario I have just come across.

I did an ajax call and got data back as null, in a string format. I had to check it like this:

if(value != 'null'){}

So, null was a string which read "null" rather than really being null.

EDIT: It should be understood that I'm not selling this as the way it should be done. I had a scenario where this was the only way it could be done. I'm not sure why... perhaps the guy who wrote the back-end was presenting the data incorrectly, but regardless, this is real life. It's frustrating to see this down-voted by someone who understands that it's not quite right, and then up-voted by someone it actually helps.

How to get first and last element in an array in java?

Getting first and last elements in an array in Java

int[] a = new int[]{1, 8, 5, 9, 4};

First Element: a[0]

Last Element: a[a.length-1]

How can I remove Nan from list Python/NumPy

if you check for the element type

type(countries[1])

the result will be <class float> so you can use the following code:

[i for i in countries if type(i) is not float]

Structure of a PDF file?

Extracting text from PDF is a hard problem because PDF has such a layout-oriented structure. You can see the docs and source code of my barely-successful attempt on CPAN (my implementation is in Perl). The PDF data structure is very cool and well designed, but it's easier to write than read.

How to resolve the error on 'react-native start'

I found the regexp.source changed from node v12.11.0, maybe the new v8 engine caused. see more on https://github.com/nodejs/node/releases/tag/v12.11.0.

D:\code\react-native>nvm use 12.10.0
Now using node v12.10.0 (64-bit)

D:\code\react-native>node
Welcome to Node.js v12.10.0.
Type ".help" for more information.
> /node_modules[/\\]react[/\\]dist[/\\].*/.source
'node_modules[\\/\\\\]react[\\/\\\\]dist[\\/\\\\].*'
> /node_modules[/\\]react[/\\]dist[/\\].*/.source.replace(/\//g, path.sep)
'node_modules[\\\\\\\\]react[\\\\\\\\]dist[\\\\\\\\].*'
>
(To exit, press ^C again or ^D or type .exit)
>

D:\code\react-native>nvm use 12.11.0
Now using node v12.11.0 (64-bit)

D:\code\react-native>node
Welcome to Node.js v12.11.0.
Type ".help" for more information.
> /node_modules[/\\]react[/\\]dist[/\\].*/.source
'node_modules[/\\\\]react[/\\\\]dist[/\\\\].*'
> /node_modules[/\\]react[/\\]dist[/\\].*/.source.replace(/\//g, path.sep)
'node_modules[\\\\\\]react[\\\\\\]dist[\\\\\\].*'
>
(To exit, press ^C again or ^D or type .exit)
>

D:\code\react-native>nvm use 12.13.0
Now using node v12.13.0 (64-bit)

D:\code\react-native>node
Welcome to Node.js v12.13.0.
Type ".help" for more information.
> /node_modules[/\\]react[/\\]dist[/\\].*/.source
'node_modules[/\\\\]react[/\\\\]dist[/\\\\].*'
> /node_modules[/\\]react[/\\]dist[/\\].*/.source.replace(/\//g, path.sep)
'node_modules[\\\\\\]react[\\\\\\]dist[\\\\\\].*'
>
(To exit, press ^C again or ^D or type .exit)
>

D:\code\react-native>nvm use 13.3.0
Now using node v13.3.0 (64-bit)

D:\code\react-native>node
Welcome to Node.js v13.3.0.
Type ".help" for more information.
> /node_modules[/\\]react[/\\]dist[/\\].*/.source
'node_modules[/\\\\]react[/\\\\]dist[/\\\\].*'
> /node_modules[/\\]react[/\\]dist[/\\].*/.source.replace(/\//g, path.sep)
'node_modules[\\\\\\]react[\\\\\\]dist[\\\\\\].*'
>

Error:Conflict with dependency 'com.google.code.findbugs:jsr305'

delete espresso dependencies in gradle file works for me.

delete those lines in app gradle file:

androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
    exclude group: 'com.android.support', module: 'support-annotations'
})