Programs & Examples On #Word boundaries

get user timezone

On server-side it will be not as accurate as with JavaScript. Meanwhile, sometimes it is required to solve such task. Just to share the possible solution in this case I write this answer.

If you need to determine user's time zone it could be done via Geo-IP services. Some of them providing timezone. For example, this one (http://smart-ip.net/geoip-api) could help:

<?php
$ip     = $_SERVER['REMOTE_ADDR']; // means we got user's IP address 
$json   = file_get_contents( 'http://smart-ip.net/geoip-json/' . $ip); // this one service we gonna use to obtain timezone by IP
// maybe it's good to add some checks (if/else you've got an answer and if json could be decoded, etc.)
$ipData = json_decode( $json, true);

if ($ipData['timezone']) {
    $tz = new DateTimeZone( $ipData['timezone']);
    $now = new DateTime( 'now', $tz); // DateTime object corellated to user's timezone
} else {
   // we can't determine a timezone - do something else...
}

Shell script to delete directories older than n days

find supports -delete operation, so:

find /base/dir/* -ctime +10 -delete;

I think there's a catch that the files need to be 10+ days older too. Haven't tried, someone may confirm in comments.

The most voted solution here is missing -maxdepth 0 so it will call rm -rf for every subdirectory, after deleting it. That doesn't make sense, so I suggest:

find /base/dir/* -maxdepth 0  -type d -ctime +10 -exec rm -rf {} \;

The -delete solution above doesn't use -maxdepth 0 because find would complain the dir is not empty. Instead, it implies -depth and deletes from the bottom up.

How to parse XML using shellscript?

Do you have xml_grep installed? It's a perl based utility standard on some distributions (it came pre-installed on my CentOS system). Rather than giving it a regular expression, you give it an xpath expression.

Python re.sub(): how to substitute all 'u' or 'U's with 'you'

Firstly, why doesn't your solution work. You mix up a lot of concepts. Mostly character class with other ones. In the first character class you use | which stems from alternation. In character classes you don't need the pipe. Just list all characters (and character ranges) you want:

[Uu]

Or simply write u if you use the case-insensitive modifier. If you write a pipe there, the character class will actually match pipes in your subject string.

Now in the second character class you use the comma to separate your characters for some odd reason. That does also nothing but include commas into the matchable characters. s and W are probably supposed to be the built-in character classes. Then escape them! Otherwise they will just match literal s and literal W. But then \W already includes everything else you listed there, so a \W alone (without square brackets) would have been enough. And the last part (^a-zA-Z) also doesn't work, because it will simply include ^, (, ) and all letters into the character class. The negation syntax only works for entire character classes like [^a-zA-Z].

What you actually want is to assert that there is no letter in front or after your u. You can use lookarounds for that. The advantage is that they won't be included in the match and thus won't be removed:

r'(?<![a-zA-Z])[uU](?![a-zA-Z])'

Note that I used a raw string. Is generally good practice for regular expressions, to avoid problems with escape sequences.

These are negative lookarounds that make sure that there is no letter character before or after your u. This is an important difference to asserting that there is a non-letter character around (which is similar to what you did), because the latter approach won't work at the beginning or end of the string.

Of course, you can remove the spaces around you from the replacement string.

If you don't want to replace u that are next to digits, you can easily include the digits into the character classes:

r'(?<![a-zA-Z0-9])[uU](?![a-zA-Z0-9])'

And if for some reason an adjacent underscore would also disqualify your u for replacement, you could include that as well. But then the character class coincides with the built-in \w:

r'(?<!\w)[uU](?!\w)'

Which is, in this case, equivalent to EarlGray's r'\b[uU]\b'.

As mentioned above you can shorten all of these, by using the case-insensitive modifier. Taking the first expression as an example:

re.sub(r'(?<![a-z])u(?![a-z])', 'you', text, flags=re.I)

or

re.sub(r'(?<![a-z])u(?![a-z])', 'you', text, flags=re.IGNORECASE)

depending on your preference.

I suggest that you do some reading through the tutorial I linked several times in this answer. The explanations are very comprehensive and should give you a good headstart on regular expressions, which you will probably encounter again sooner or later.

How do I format a String in an email so Outlook will print the line breaks?

I had the same issue, and found a solution. Try this: %0D%0A to add a line break.

Align button to the right

The bootstrap 4.0.0 file you are getting from cdn doesn't have a pull-right (or pull-left) class. The v4 is in alpha, so there are many issues like that.

There are 2 options:

1) Reverse to bootstrap 3.3.7

2) Write your own CSS.

Is a view faster than a simple query?

There is no practical different and if you read BOL you will find that ever your plain old SQL SELECT * FROM X does take advantage of plan caching etc.

How to set width of a div in percent in JavaScript?

Also you can use .prop() and it should be better because

Since jQuery 1.6, these properties can no longer be set with the .attr() method. They do not have corresponding attributes and are only properties.

$(elem).prop('width', '100%');
$(elem).prop('height', '100%');

How can I use an ES6 import in Node.js?

I don't know if this will work for your case, but I am running an Express.js server with this:

nodemon --inspect ./index.js --exec babel-node --presets es2015,stage-2

This gives me the ability to import and use spread operator even though I'm only using Node.js version 8.

You'll need to install babel-cli, babel-preset-es2015, and babel-preset-stage-2 to do what I'm doing.

how to overlap two div in css?

add to second div bottomDiv

and add this to css.

 .bottomDiv{
       position:relative;
       bottom:150px;
       left:150px;
    }

http://jsfiddle.net/aw8RD/1/

How to use google maps without api key

Note : This answer is now out-of-date. You are now required to have an API key to use google maps. Read More


you need to change your API from V2 to V3, Since Google Map Version 3 don't required API Key

Check this out..

write your script as

<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script>

Karma: Running a single test file from command line

This option is no longer supported in recent versions of karma:

see https://github.com/karma-runner/karma/issues/1731#issuecomment-174227054

The files array can be redefined using the CLI as such:

karma start --files=Array("test/Spec/services/myServiceSpec.js")

or escaped:

karma start --files=Array\(\"test/Spec/services/myServiceSpec.js\"\)

References

How do I properly set the permgen size?

Don't put the environment configuration in catalina.bat/catalina.sh. Instead you should create a new file in CATALINA_BASE\bin\setenv.bat to keep your customizations separate of tomcat installation.

Disabling radio buttons with jQuery

You should use classes to make it more simple, instead of the attribute name, or any other jQuery selector.

Android Studio - Gradle sync project failed

In my case NDK location was the issue.

go to File->Project Structure->SDK Location and add NDK location

Android emulator not able to access the internet

Updating my WIFI adapter to resolve DNS on 8.8.8.8 solved the issue for me. It started to happen after an Apple update which messed up the DNS address.

enter image description here

How to connect SQLite with Java?

Hey i have posted a video tutorial on youtube about this, you can check that and you can find here the sample code :

http://myfundatimemachine.blogspot.in/2012/06/database-connection-to-java-application.html

Quick way to list all files in Amazon S3 bucket?

For Python's boto3 after having used aws configure:

import boto3
s3 = boto3.resource('s3')

bucket = s3.Bucket('name')
for obj in bucket.objects.all():
    print(obj.key)

How set the android:gravity to TextView from Java side in Android

You should use textView.setGravity(Gravity.CENTER_HORIZONTAL);.

Remember that using

LinearLayout.LayoutParams layoutParams =new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
layoutParams2.gravity = Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL;

won't work. This will set the gravity for the widget and not for it's text.

Capturing mobile phone traffic on Wireshark

Similarly to making your PC a wireless access point, but can be much easier, is using reverse tethering. If you happen to have an HTC phone they have a nice reverse-tethering option called "Internet pass-through", under the network/mobile network sharing settings. It routes all your traffic through your PC and you can just run Wireshark there.

update listview dynamically with adapter

I created a method just for that. I use it any time I need to manually update a ListView. Hopefully this gives you an idea of how to implement your own

public static void UpdateListView(List<SomeObject> SomeObjects, ListView ListVw)
{    
    if(ListVw != null)
    {
        final YourAdapter adapter = (YourAdapter) ListVw.getAdapter();

        //You'll have to create this method in your adapter class. It's a simple setter.
        adapter.SetList(SomeObjects);

        adapter.notifyDataSetChanged();
    }
}

I'm using an adapter that inherites from BaseAdapter. Should work for any other type of adapter.

When or Why to use a "SET DEFINE OFF" in Oracle Database

Here is the example:

SQL> set define off;
SQL> select * from dual where dummy='&var';

no rows selected

SQL> set define on
SQL> /
Enter value for var: X
old   1: select * from dual where dummy='&var'
new   1: select * from dual where dummy='X'

D
-
X

With set define off, it took a row with &var value, prompted a user to enter a value for it and replaced &var with the entered value (in this case, X).

How do you make a deep copy of an object?

1)

public static Object deepClone(Object object) {
   try {
     ByteArrayOutputStream baos = new ByteArrayOutputStream();
     ObjectOutputStream oos = new ObjectOutputStream(baos);
     oos.writeObject(object);
     ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());
     ObjectInputStream ois = new ObjectInputStream(bais);
     return ois.readObject();
   }
   catch (Exception e) {
     e.printStackTrace();
     return null;
   }
 }

2)

    // (1) create a MyPerson object named Al
    MyAddress address = new MyAddress("Vishrantwadi ", "Pune", "India");
    MyPerson al = new MyPerson("Al", "Arun", address);

    // (2) make a deep clone of Al
    MyPerson neighbor = (MyPerson)deepClone(al);

Here your MyPerson and MyAddress class must implement serilazable interface

Creating a folder if it does not exists - "Item already exists"

I was not even concentrating, here is how to do it

$DOCDIR = [Environment]::GetFolderPath("MyDocuments")
$TARGETDIR = '$DOCDIR\MatchedLog'
if(!(Test-Path -Path $TARGETDIR )){
    New-Item -ItemType directory -Path $TARGETDIR
}

SQL Query to add a new column after an existing column in SQL Server 2005

Microsoft SQL (AFAIK) does not allow you to alter the table and add a column after a specific column. Your best bet is using Sql Server Management Studio, or play around with either dropping and re-adding the table, or creating a new table and moving the data over manually. neither are very graceful.

MySQL does however:

ALTER TABLE mytable
ADD COLUMN  new_column <type>
AFTER       existing_column

npm install error - unable to get local issuer certificate

Use the command

npm config set strict-ssl false

Powershell: A positional parameter cannot be found that accepts argument "xxx"

I had to use

powershell.AddCommand("Get-ADPermission");
powershell.AddParameter("Identity", "complete id path with OU in it");

to get past this error

The create-react-app imports restriction outside of src directory

Remove it using Craco:

module.exports = {
  webpack: {
    configure: webpackConfig => {
      const scopePluginIndex = webpackConfig.resolve.plugins.findIndex(
        ({ constructor }) => constructor && constructor.name === 'ModuleScopePlugin'
      );

      webpackConfig.resolve.plugins.splice(scopePluginIndex, 1);
      return webpackConfig;
    }
  }
};

WebForms UnobtrusiveValidationMode requires a ScriptResourceMapping for jquery

I think this is the best solution for this type error. So please add below line. Also it work my code when I am using MSVS 2015.

<configuration>
<appSettings>
<add key="ValidationSettings:UnobtrusiveValidationMode" value="None" />
</appSettings>
</configuration>

How to import keras from tf.keras in Tensorflow?

Use the keras module from tensorflow like this:

import tensorflow as tf

Import classes

from tensorflow.python.keras.layers import Input, Dense

or use directly

dense = tf.keras.layers.Dense(...)

EDIT Tensorflow 2

from tensorflow.keras.layers import Input, Dense

and the rest stays the same.

Scheduling recurring task in Android

I realize this is an old question and has been answered but this could help someone. In your activity

private ScheduledExecutorService scheduleTaskExecutor;

In onCreate

  scheduleTaskExecutor = Executors.newScheduledThreadPool(5);

    //Schedule a task to run every 5 seconds (or however long you want)
    scheduleTaskExecutor.scheduleAtFixedRate(new Runnable() {
        @Override
        public void run() {
            // Do stuff here!

            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    // Do stuff to update UI here!
                    Toast.makeText(MainActivity.this, "Its been 5 seconds", Toast.LENGTH_SHORT).show();
                }
            });

        }
    }, 0, 5, TimeUnit.SECONDS); // or .MINUTES, .HOURS etc.

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

Try wih :

SELECT * FROM sys.dm_exec_requests where command like '%BACKUP%'

SELECT command, percent_complete, start_time FROM sys.dm_exec_requests where command like '%BACKUP%'

SELECT command, percent_complete,total_elapsed_time, estimated_completion_time, start_time
  FROM sys.dm_exec_requests
  WHERE command IN ('RESTORE DATABASE','BACKUP DATABASE')

Redirect using AngularJS

It is hard to say without knowing your code. My best guess is that the onchange event is not firing when you change your textbox value from JavaScript code.

There are two ways for this to work; the first is to call onchange by yourself, and the second is to wait for the textbox to lose focus.

Check this question; same issue, different framework.

How to access shared folder without giving username and password

I found one way to access the shared folder without giving the username and password.

We need to change the share folder protect settings in the machine where the folder has been shared.

Go to Control Panel > Network and sharing center > Change advanced sharing settings > Enable Turn Off password protect sharing option.

By doing the above settings we can access the shared folder without any username/password.

Undefined reference to sqrt (or other mathematical functions)

Here are my observation, firstly you need to include the header math.h as sqrt() function declared in math.h header file. For e.g

#include <math.h>

secondly, if you read manual page of sqrt you will notice this line Link with -lm.

#include <math.h> /* header file you need to include */

double sqrt(double x); /* prototype of sqrt() function */

Link with -lm. /* Library linking instruction */

But application still says undefined reference to sqrt. Do you see any problem here?

Compiler error is correct as you haven't linked your program with library lm & linker is unable to find reference of sqrt(), you need to link it explicitly. For e.g

gcc -Wall -Wextra -Werror -pedantic test.c -lm

Telling gcc directly to link a library statically

It is possible of course, use -l: instead of -l. For example -l:libXYZ.a to link with libXYZ.a. Notice the lib written out, as opposed to -lXYZ which would auto expand to libXYZ.

How can I read the client's machine/computer name from the browser?

You can do it with IE 'sometimes' as I have done this for an internal application on an intranet which is IE only. Try the following:

function GetComputerName() {
    try {
        var network = new ActiveXObject('WScript.Network');
        // Show a pop up if it works
        alert(network.computerName);
    }
    catch (e) { }
}

It may or may not require some specific security setting setup in IE as well to allow the browser to access the ActiveX object.

Here is a link to some more info on WScript: More Information

Binding Combobox Using Dictionary as the Datasource

SortedDictionary<string, int> userCache = new SortedDictionary<string, int>
{
  {"a", 1},
  {"b", 2},
  {"c", 3}
};
comboBox1.DataSource = new BindingSource(userCache, null);
comboBox1.DisplayMember = "Key";
comboBox1.ValueMember = "Value";

But why are you setting the ValueMember to "Value", shouldn't it be bound to "Key" (and DisplayMember to "Value" as well)?

RecyclerView expand/collapse items

I am surprised that there's no concise answer yet, although such an expand/collapse animation is very easy to achieve with just 2 lines of code:

(recycler.itemAnimator as SimpleItemAnimator).supportsChangeAnimations = false // called once

together with

notifyItemChanged(position) // in adapter, whenever a child view in item's recycler gets hidden/shown

So for me, the explanations in the link below were really useful: https://medium.com/@nikola.jakshic/how-to-expand-collapse-items-in-recyclerview-49a648a403a6

Can not find module “@angular-devkit/build-angular”

This worked for me: Type npm audit fix in the commandline. Afterwards I was able to use ng serve --open again.

How to get last inserted id?

There are all sorts of ways to get the Last Inserted ID but the easiest way I have found is by simply retrieving it from the TableAdapter in the DataSet like so:

<Your DataTable Class> tblData = new <Your DataTable Class>();
<Your Table Adapter Class> tblAdpt = new <Your Table Adapter Class>();

/*** Initialize and update Table Data Here ***/

/*** Make sure to call the EndEdit() method ***/
/*** of any Binding Sources before update ***/
<YourBindingSource>.EndEdit();

//Update the Dataset
tblAdpt.Update(tblData);

//Get the New ID from the Table Adapter
long newID = tblAdpt.Adapter.InsertCommand.LastInsertedId;

Hope this Helps ...

What's the fastest way to delete a large folder in Windows?

Try Shift + Delete. Did 24.000 files in 2 minutes for me.

Android emulator-5554 offline

Simply delete and created gear avd again.It will work.

Python: call a function from string name

You can use a dictionary too.

def install():
    print "In install"

methods = {'install': install}

method_name = 'install' # set by the command line options
if method_name in methods:
    methods[method_name]() # + argument list of course
else:
    raise Exception("Method %s not implemented" % method_name)

How to do 3 table JOIN in UPDATE query?

For PostgreSQL example:

UPDATE TableA AS a
SET param_from_table_a=FALSE -- param FROM TableA
FROM TableB AS b
WHERE b.id=a.param_id AND a.amount <> 0; 

What is the javascript filename naming convention?

One possible naming convention is to use something similar to the naming scheme jQuery uses. It's not universally adopted but it is pretty common.

product-name.plugin-ver.sion.filetype.js

where the product-name + plugin pair can also represent a namespace and a module. The version and filetype are usually optional.

filetype can be something relative to how the content of the file is. Often seen are:

  • min for minified files
  • custom for custom built or modified files

Examples:

  • jquery-1.4.2.min.js
  • jquery.plugin-0.1.js
  • myapp.invoice.js

How to get a complete list of ticker symbols from Yahoo Finance?

There is a nice C# wrapper for the Yahoo.Finance API at http://code.google.com/p/yahoo-finance-managed/ that will get you there. Unfortunately there is no direct way to download the ticker list but the following creates the list by iterating through the alphabetical groups:

        AlphabeticIDIndexDownload dl1 = new AlphabeticIDIndexDownload();
        dl1.Settings.TopIndex = null;
        Response<AlphabeticIDIndexResult> resp1 = dl1.Download();

        writeStream.WriteLine("Id|Isin|Name|Exchange|Type|Industry");

        foreach (var alphabeticalIndex in resp1.Result.Items)
        {
            AlphabeticalTopIndex topIndex = (AlphabeticalTopIndex) alphabeticalIndex;
            dl1.Settings.TopIndex = topIndex;
            Response<AlphabeticIDIndexResult> resp2 = dl1.Download();

            foreach (var index in resp2.Result.Items)
            {
                IDSearchDownload dl2 = new IDSearchDownload();
                Response<IDSearchResult> resp3 = dl2.Download(index);


                int i = 0;
                foreach (var item in resp3.Result.Items)
                {
                    writeStream.WriteLine(item.ID + "|" + item.ISIN + "|" + item.Name + "|" + item.Exchange + "|" + item.Type + "|" + item.Industry);
                }

            }
        }

It gave me a list of about 75,000 securities in about 4 mins.

is there something like isset of php in javascript/jQuery?

If you want to check if a property exists: hasOwnProperty is the way to go

And since most objects are properties of some other object (eventually leading to the window object) this can work well for checking if values have been declared.

Why can't Python find shared objects that are in directories in sys.path?

For me what works here is to using a version manager such as pyenv, which I strongly recommend to get your project environments and package versions well managed and separate from that of the operative system.

I had this same error after an OS update, but was easily fixed with pyenv install 3.7-dev (the version I use).

python ignore certificate validation urllib2

For those who uses an opener, you can achieve the same thing based on Enno Gröper's great answer:

import urllib2, ssl

ctx = ssl.create_default_context()
ctx.check_hostname = False
ctx.verify_mode = ssl.CERT_NONE

opener = urllib2.build_opener(urllib2.HTTPSHandler(context=ctx), your_first_handler, your_second_handler[...])
opener.addheaders = [('Referer', 'http://example.org/blah.html')]

content = opener.open("https://localhost/").read()

And then use it as before.

According to build_opener and HTTPSHandler, a HTTPSHandler is added if ssl module exists, here we just specify our own instead of the default one.

How to declare array of zeros in python (or an array of a certain size)

Depending on what you're actually going to do with the data after it's collected, collections.defaultdict(int) might be useful.

Regular expression to detect semi-colon terminated C++ for & while loops

This is the kind of thing you really shouldn't do with a regular expression. Just parse the string one character at a time, keeping track of opening/closing parentheses.

If this is all you're looking for, you definitely don't need a full-blown C++ grammar lexer/parser. If you want practice, you can write a little recursive-decent parser, but even that's a bit much for just matching parentheses.

Creating and Naming Worksheet in Excel VBA

http://www.mrexcel.com/td0097.html

Dim WS as Worksheet
Set WS = Sheets.Add

You don't have to know where it's located, or what it's name is, you just refer to it as WS.
If you still want to do this the "old fashioned" way, try this:

Sheets.Add.Name = "Test"

What is the color code for transparency in CSS?

jus add two zeroes (00) before your color code you will get the transparent of that color

How to remove a column from an existing table?

This can also be done through the SSMS GUI. The nice thing about this method is it warns you if there are any relationships on that column and can also automatically delete those as well.

  1. Put table in Design view (right click on table) like so:

enter image description here

  1. Right click on column in table's Design view and click "Delete Column"

enter image description here

As I stated before, if there are any relationships that would also need to be deleted, it will ask you at this point if you would like to delete those as well. You will likely need to do so to delete the column.

Unable to get provider com.google.firebase.provider.FirebaseInitProvider

you should be sure

to add this line at your manifest

https://developer.android.com/studio/run/index.html#instant-run

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.android.multidex.myapplication">
    <application
        ...
        android:name="android.support.multidex.MultiDexApplication">
        ...
    </application>
</manifest>

Java, How to get number of messages in a topic in apache kafka

It is not java, but may be useful

./bin/kafka-run-class.sh kafka.tools.GetOffsetShell 
  --broker-list <broker>:  <port> 
  --topic <topic-name> --time -1 --offsets 1 
  | awk -F  ":" '{sum += $3} END {print sum}'

How to set Spinner Default by its Value instead of Position?

this is how i did it:

String[] listAges = getResources().getStringArray(R.array.ages);

        // Creating adapter for spinner
        ArrayAdapter<String> dataAdapter =
                new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, listAges);

        // Drop down layout style - list view with radio button
        dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);

        // attaching data adapter to spinner
        spinner_age.getBackground().setColorFilter(ContextCompat.getColor(this, R.color.spinner_icon), PorterDuff.Mode.SRC_ATOP);
        spinner_age.setAdapter(dataAdapter);
        spinner_age.setSelection(0);
        spinner_age.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                String item = parent.getItemAtPosition(position).toString();

                if(position > 0){
                    // get spinner value
                    Toast.makeText(parent.getContext(), "Age..." + item, Toast.LENGTH_SHORT).show();
                }else{
                    // show toast select gender
                    Toast.makeText(parent.getContext(), "none" + item, Toast.LENGTH_SHORT).show();
                }
            }
            @Override
            public void onNothingSelected(AdapterView<?> parent) {
            }
        });

How to create hyperlink to call phone number on mobile devices?

- doesnt make matter but + sign is important when mobile user is in roaming
this is the standard format

<a href="tel:+4917640206387">+49 (0)176 - 402 063 87</a>

You can read more about it in the spec, see Make Telephone Numbers "Click-to-Call".

Variable declaration in a header file

If you declare it like

int x;

in a header file which is then included in multiple places, you'll end up with multiple instances of x (and potentially compile or link problems).

The correct way to approach this is to have the header file say

extern int x; /* declared in foo.c */

and then in foo.c you can say

int x; /* exported in foo.h */

THen you can include your header file in as many places as you like.

httpd Server not started: (13)Permission denied: make_sock: could not bind to address [::]:88

I had similar error while trying to start httpd service for openstack train installation in RHEL 7.5 too.

-- Unit httpd.service has begun starting up.
Jan 31 10:11:16 controller httpd[1631]: (13)Permission denied: AH00072: make_sock: could not bind to address 10.0.0.11:5000
Jan 31 10:11:16 controller httpd[1631]: no listening sockets available, shutting down
Jan 31 10:11:16 controller httpd[1631]: AH00015: Unable to open logs
Jan 31 10:11:16 controller systemd[1]: httpd.service: main process exited, code=exited, status=1/FAILURE
Jan 31 10:11:16 controller kill[1632]: kill: cannot find process ""
Jan 31 10:11:16 controller systemd[1]: httpd.service: control process exited, code=exited status=1
Jan 31 10:11:16 controller systemd[1]: Failed to start The Apache HTTP Server.
-- Subject: Unit httpd.service has failed

Solution: It got resolved by disabling SElinux.

How do I check if a string contains a specific word?

Look at strpos():

<?php
    $mystring = 'abc';
    $findme   = 'a';
    $pos = strpos($mystring, $findme);

    // Note our use of ===. Simply, == would not work as expected
    // because the position of 'a' was the 0th (first) character.
    if ($pos === false) {
        echo "The string '$findme' was not found in the string '$mystring'.";
    }
    else {
        echo "The string '$findme' was found in the string '$mystring',";
        echo " and exists at position $pos.";
    }
?>

What are the best practices for SQLite on Android?

My understanding of SQLiteDatabase APIs is that in case you have a multi threaded application, you cannot afford to have more than a 1 SQLiteDatabase object pointing to a single database.

The object definitely can be created but the inserts/updates fail if different threads/processes (too) start using different SQLiteDatabase objects (like how we use in JDBC Connection).

The only solution here is to stick with 1 SQLiteDatabase objects and whenever a startTransaction() is used in more than 1 thread, Android manages the locking across different threads and allows only 1 thread at a time to have exclusive update access.

Also you can do "Reads" from the database and use the same SQLiteDatabase object in a different thread (while another thread writes) and there would never be database corruption i.e "read thread" wouldn't read the data from the database till the "write thread" commits the data although both use the same SQLiteDatabase object.

This is different from how connection object is in JDBC where if you pass around (use the same) the connection object between read and write threads then we would likely be printing uncommitted data too.

In my enterprise application, I try to use conditional checks so that the UI Thread never have to wait, while the BG thread holds the SQLiteDatabase object (exclusively). I try to predict UI Actions and defer BG thread from running for 'x' seconds. Also one can maintain PriorityQueue to manage handing out SQLiteDatabase Connection objects so that the UI Thread gets it first.

How to use mouseover and mouseout in Angular 6

If your interested , then go with directive property . Code might looks bit tough , but itshows all the property of Angular 6 . Here am adding a sample code

import { Directive, OnInit, ElementRef, Renderer2 ,HostListener,HostBinding,Input} from '@angular/core';
import { MockNgModuleResolver } from '@angular/compiler/testing';
//import { Event } from '@angular/router';

@Directive({
  selector: '[appBetterHighlight]'
})
export class BetterHighlightDirective implements OnInit {
   defaultcolor :string = 'black'
   Highlightedcolor : string = 'red'
    @HostBinding('style.color') color : string = this.defaultcolor;

  constructor(private elm : ElementRef , private render:Renderer2) { }
ngOnInit()
{}
@HostListener('mouseenter') mouseover(event :Event)
{

  this.color= this.Highlightedcolor ;
}
@HostListener('mouseleave') mouseleave(event: Event)
{

  this.color = this.defaultcolor;
}
}

Just use the selector name 'appBetterHighlight' anywhere in the template to access this property .

GCD to perform task in main thread

For the asynchronous dispatch case you describe above, you shouldn't need to check if you're on the main thread. As Bavarious indicates, this will simply be queued up to be run on the main thread.

However, if you attempt to do the above using a dispatch_sync() and your callback is on the main thread, your application will deadlock at that point. I describe this in my answer here, because this behavior surprised me when moving some code from -performSelectorOnMainThread:. As I mention there, I created a helper function:

void runOnMainQueueWithoutDeadlocking(void (^block)(void))
{
    if ([NSThread isMainThread])
    {
        block();
    }
    else
    {
        dispatch_sync(dispatch_get_main_queue(), block);
    }
}

which will run a block synchronously on the main thread if the method you're in isn't currently on the main thread, and just executes the block inline if it is. You can employ syntax like the following to use this:

runOnMainQueueWithoutDeadlocking(^{
    //Do stuff
});

Bogus foreign key constraint fail

Disable foreign key checking

SET FOREIGN_KEY_CHECKS=0

What does it mean by select 1 from table?

SELECT 1 FROM TABLE_NAME means, "Return 1 from the table". It is pretty unremarkable on its own, so normally it will be used with WHERE and often EXISTS (as @gbn notes, this is not necessarily best practice, it is, however, common enough to be noted, even if it isn't really meaningful (that said, I will use it because others use it and it is "more obvious" immediately. Of course, that might be a viscous chicken vs. egg issue, but I don't generally dwell)).

 SELECT * FROM TABLE1 T1 WHERE EXISTS (
     SELECT 1 FROM TABLE2 T2 WHERE T1.ID= T2.ID
 );

Basically, the above will return everything from table 1 which has a corresponding ID from table 2. (This is a contrived example, obviously, but I believe it conveys the idea. Personally, I would probably do the above as SELECT * FROM TABLE1 T1 WHERE ID IN (SELECT ID FROM TABLE2); as I view that as FAR more explicit to the reader unless there were a circumstantially compelling reason not to).

EDIT

There actually is one case which I forgot about until just now. In the case where you are trying to determine existence of a value in the database from an outside language, sometimes SELECT 1 FROM TABLE_NAME will be used. This does not offer significant benefit over selecting an individual column, but, depending on implementation, it may offer substantial gains over doing a SELECT *, simply because it is often the case that the more columns that the DB returns to a language, the larger the data structure, which in turn mean that more time will be taken.

Java resource as file

Try this:

ClassLoader.getResourceAsStream ("some/pkg/resource.properties");

There are more methods available, e.g. see here: http://www.javaworld.com/javaworld/javaqa/2003-08/01-qa-0808-property.html

'\r': command not found - .bashrc / .bash_profile

For those who don't have dos2unix installed (and don't want to install it):

Remove trailing \r character that causes this error:

sed -i 's/\r$//' filename


Explanation:

Option -i is for in-place editing, we delete the trailing \r directly in the input file. Thus be careful to type the pattern correctly.

How to open .dll files to see what is written inside?

you are better off with a decompiler like redgates .net reflector or jetbrains resharper decompiler. there are open source ones also like

http://www.jetbrains.com/decompiler/

http://ilspy.net/

Read response headers from API response - Angular 5 + TypeScript

Angular 7 Service:

    this.http.post(environment.urlRest + '/my-operation',body, { headers: headers, observe: 'response'});
    
Component:
    this.myService.myfunction().subscribe(
          (res: HttpResponse) => {
              console.log(res.headers.get('x-token'));
                }  ,
        error =>{
        }) 
    

<> And Not In VB.NET

The C# and VB.NET compilers often generate different IL for operations that are apparently equivalent in both languages. It just so happens that C# does the "expected" thing when you write stringvar == null, but VB.NET does not. To get the same effect in VB.NET you have to force true reference equality with the Is operator.

What is the difference between __str__ and __repr__?

  1. __str__ must return string object whereas __repr__ can return any python expression.
  2. If __str__ implementation is missing then __repr__ function is used as fallback. There is no fallback if __repr__ function implementation is missing.
  3. If __repr__ function is returning String representation of the object, we can skip implementation of __str__ function.

Source: https://www.journaldev.com/22460/python-str-repr-functions

How do I find the location of my Python site-packages directory?

You should try this command to determine pip's install location

Python 2

pip show six | grep "Location:" | cut -d " " -f2

Python 3

pip3 show six | grep "Location:" | cut -d " " -f2

A long bigger than Long.MAX_VALUE

That method can't return true. That's the point of Long.MAX_VALUE. It would be really confusing if its name were... false. Then it should be just called Long.SOME_FAIRLY_LARGE_VALUE and have literally zero reasonable uses. Just use Android's isUserAGoat, or you may roll your own function that always returns false.

Note that a long in memory takes a fixed number of bytes. From Oracle:

long: The long data type is a 64-bit signed two's complement integer. It has a minimum value of -9,223,372,036,854,775,808 and a maximum value of 9,223,372,036,854,775,807 (inclusive). Use this data type when you need a range of values wider than those provided by int.

As you may know from basic computer science or discrete math, there are 2^64 possible values for a long, since it is 64 bits. And as you know from discrete math or number theory or common sense, if there's only finitely many possibilities, one of them has to be the largest. That would be Long.MAX_VALUE. So you are asking something similar to "is there an integer that's >0 and < 1?" Mathematically nonsensical.

If you actually need this for something for real then use BigInteger class.

Python basics printing 1 to 100

Because the condition is never true. i.e. count !=100 never executes when you put count=count+3 or count =count+9. try this out..while count<100

How do I create a round cornered UILabel on the iPhone?

Works perfect in Swift 2.0

    @IBOutlet var theImage: UIImageView! //you can replace this with any UIObject eg: label etc


    override func viewDidLoad() {
        super.viewDidLoad()
//Make sure the width and height are same
        self.theImage.layer.cornerRadius = self.theImage.frame.size.width / 2
        self.theImage.layer.borderWidth = 2.0
        self.theImage.layer.borderColor = UIColor.whiteColor().CGColor
        self.theImage.clipsToBounds = true

    }

How to send an email using PHP?

<?php
include "db_conn.php";//connection file
require "PHPMailerAutoload.php";// it will be in PHPMailer
require "class.smtp.php";// it will be in PHPMailer
require "class.phpmailer.php";// it will be in PHPMailer


$response = array();
$params = json_decode(file_get_contents("php://input"));

if(!empty($params->email_id)){

    $email_id = $params->email_id;
    $flag=false;
    echo "something";
    if(!filter_var($email_id, FILTER_VALIDATE_EMAIL))
    {
        $response['ERROR']='EMAIL address format error'; 
        echo json_encode($response,JSON_UNESCAPED_SLASHES);
        return;
    }
    $sql="SELECT * from sales where email_id ='$email_id' ";

    $result = mysqli_query($conn,$sql);
    $count = mysqli_num_rows($result);

    $to = "[email protected]";
    $subject = "DEMO Subject";
    $messageBody ="demo message .";

    if($count ==0){
        $response["valid"] = false;
        $response["message"] = "User is not registered yet";
        echo json_encode($response);
        return;
    }

    else {

        $mail = new PHPMailer();
        $mail->IsSMTP();
        $mail->SMTPAuth = true; // authentication enabled
        $mail->IsHTML(true); 
        $mail->SMTPSecure = 'ssl';//turn on to send html email
        // $mail->Host = "ssl://smtp.zoho.com";
        $mail->Host = "p3plcpnl0749.prod.phx3.secureserver.net";//you can use gmail 
        $mail->Port = 465;
        $mail->Username = "[email protected]";
        $mail->Password = "demopassword";
        $mail->SetFrom("[email protected]", "Any demo alert");
        $mail->Subject = $subject;

        $mail->Body = $messageBody;
        $mail->AddAddress($to);
        echo "yes";

        if(!$mail->send()) {
           echo "Mailer Error: " . $mail->ErrorInfo;
       } 
       else {
           echo "Message has been sent successfully";
      }
    }

}
else{
    $response["valid"] = false;
    $response["message"] = "Required field(s) missing";
    echo json_encode($response);
}


?>

The above code is working for me.

Saving response from Requests to file

As Peter already pointed out:

In [1]: import requests

In [2]: r = requests.get('https://api.github.com/events')

In [3]: type(r)
Out[3]: requests.models.Response

In [4]: type(r.content)
Out[4]: str

You may also want to check r.text.

Also: https://2.python-requests.org/en/latest/user/quickstart/

How do I include the string header?

I don't hear about "apstring".If you want to use string with c++ ,you can do like this:

#include<string>
using namespace std;
int main()
{
   string str;
   cin>>str;
   cout<<str;
   ...
   return 0;
}

I hope this can avail

SELECT query with CASE condition and SUM()

To get each sum in a separate column:

Select SUM(IF(CPaymentType='Check', CAmount, 0)) as PaymentAmountCheck,
       SUM(IF(CPaymentType='Cash', CAmount, 0)) as PaymentAmountCash
from TableOrderPayment
where CPaymentType IN ('Check','Cash') 
and CDate<=SYSDATETIME() 
and CStatus='Active';

Upgrading Node.js to latest version

sudo npm install n -g sudo n 0.12.2

or

sudo npm install -g n sudo n latest

or

sudo npm cache clean -f sudo npm install -g n sudo n latest

These work well. But for UX term terminal node -v did not show latest version so I have closed and reopened new terminal. I found v10.1.0, output of node-v after installation by sudo n latest

I keep getting "Uncaught SyntaxError: Unexpected token o"

Looks like jQuery takes a guess about the datatype. It does the JSON parsing even though you're not calling getJSON()-- then when you try to call JSON.parse() on an object, you're getting the error.

Further explanation can be found in Aditya Mittal's answer.

CSS - How to Style a Selected Radio Buttons Label?

As there is currently no CSS solution to style a parent, I use a simple jQuery one here to add a class to a label with checked input inside it.

$(document).on("change","input", function(){
 $("label").removeClass("checkedlabel");
 if($(this).is(":checked")) $(this).closest("label").addClass("checkedlabel");
});

Don't forget to give the pre-checked input's label the class checkedlabel too

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

Facebook Login -> Settings -> Valid OAuth redirect URIs -> insert the domains of your redirect url, remember you should add 'https' or http. eg: if your redirect url is https://xxx.xxx.com/path/callback.do, you only need to enter https://xxx.xxx.com/, it's ok for me.

image processing to improve tesseract OCR accuracy

The Tesseract documentation contains some good details on how to improve the OCR quality via image processing steps.

To some degree, Tesseract automatically applies them. It is also possible to tell Tesseract to write an intermediate image for inspection, i.e. to check how well the internal image processing works (search for tessedit_write_images in the above reference).

More importantly, the new neural network system in Tesseract 4 yields much better OCR results - in general and especially for images with some noise. It is enabled with --oem 1, e.g. as in:

$ tesseract --oem 1 -l deu page.png result pdf

(this example selects the german language)

Thus, it makes sense to test first how far you get with the new Tesseract LSTM mode before applying some custom pre-processing image processing steps.

'names' attribute must be the same length as the vector

Depending on what you're doing in the loop, the fact that the %in% operator returns a vector might be an issue; consider a simple example:

c1 <- c("one","two","three","more","more")
c2 <- c("seven","five","three")

if(c1%in%c2) {
    print("hello")
}

then the following warning is issued:

Warning message:
In if (c1 %in% c2) { :
  the condition has length > 1 and only the first element will be used

if something in your if statement is dependent on a specific number of elements, and they don't match, then it is possible to obtain the error you see

Where can I find the default timeout settings for all browsers?

firstly I don't think there is just one solution to your problem....

As you know each browser is vastly differant.

But lets see if we can get any closer to the answer you need....

I think IE Might be easy...

Check this link http://support.microsoft.com/kb/181050

For Firefox try this:

Open Firefox, and in the address bar, type "about:config" (without quotes). From there, scroll down to the Network.http.keep-alive and make sure that is set to "true". If it is not, double click it, and it will go from false to true. Now, go one below that to network.http.keep-alive.timeout -- and change that number by double clicking it. if you put in, say, 500 there, you should be good. let us know if this helps at all

Getting 400 bad request error in Jquery Ajax POST

Yes. You need to stringify the JSON data orlse 400 bad request error occurs as it cannot identify the data.

400 Bad Request

Bad Request. Your browser sent a request that this server could not understand.

Plus you need to add content type and datatype as well. If not you will encounter 415 error which says Unsupported Media Type.

415 Unsupported Media Type

Try this.

var newData =   {
                  "subject:title":"Test Name",
                  "subject:description":"Creating test subject to check POST method API",
                  "sub:tags": ["facebook:work", "facebook:likes"],
                  "sampleSize" : 10,
                  "values": ["science", "machine-learning"]
                  };

var dataJson = JSON.stringify(newData);

$.ajax({
  type: 'POST',
  url: "http://localhost:8080/project/server/rest/subjects",
  data: dataJson,
  error: function(e) {
    console.log(e);
  },
  dataType: "json",
  contentType: "application/json"
});

With this way you can modify the data you need with ease. It wont confuse you as it is defined outside the ajax block.

How to read one single line of csv data in Python?

you could get just the first row like:

with open('some.csv', newline='') as f:
  csv_reader = csv.reader(f)
  csv_headings = next(csv_reader)
  first_line = next(csv_reader)

Saving utf-8 texts with json.dumps as UTF8, not as \u escape sequence

Use codecs if possible,

with codecs.open('file_path', 'a+', 'utf-8') as fp:
    fp.write(json.dumps(res, ensure_ascii=False))

How to center-justify the last line of text in CSS?

There doesn't appear to be a way. You can fake it by using justify and then wrapping the last line of text in a span and setting just that to text align center. It works ok for small blocks of text but is not a useful approach to large quantities of text or dynamic text.

I suggest finding somebody at Adobe who's involved in their W3C work and nagging them to bring up right/left/center justification in their next meeting. If anyone's gonna be able to push for basic typography features in CSS it'd be Adobe.

Smooth scroll without the use of jQuery

You can use a for loop with window.scrollTo and setTimeout to scroll smoothly with plain Javascript. To scroll to an element with my scrollToSmoothly function: scrollToSmoothly(elem.offsetTop) (assuming elem is a DOM element). You can use this to scroll smoothly to any y-position in the document.

function scrollToSmoothly(pos, time){
/*Time is only applicable for scrolling upwards*/
/*Code written by hev1*/
/*pos is the y-position to scroll to (in pixels)*/
     if(isNaN(pos)){
      throw "Position must be a number";
     }
     if(pos<0){
     throw "Position can not be negative";
     }
    var currentPos = window.scrollY||window.screenTop;
    if(currentPos<pos){
    var t = 10;
       for(let i = currentPos; i <= pos; i+=10){
       t+=10;
        setTimeout(function(){
        window.scrollTo(0, i);
        }, t/2);
      }
    } else {
    time = time || 2;
       var i = currentPos;
       var x;
      x = setInterval(function(){
         window.scrollTo(0, i);
         i -= 10;
         if(i<=pos){
          clearInterval(x);
         }
     }, time);
      }
}

Demo:

_x000D_
_x000D_
<button onClick="scrollToDiv()">Scroll To Element</button>_x000D_
<div style="margin: 1000px 0px; text-align: center;">Div element<p/>_x000D_
<button onClick="scrollToSmoothly(Number(0))">Scroll back to top</button>_x000D_
</div>_x000D_
<script>_x000D_
function scrollToSmoothly(pos, time){_x000D_
/*Time is only applicable for scrolling upwards*/_x000D_
/*Code written by hev1*/_x000D_
/*pos is the y-position to scroll to (in pixels)*/_x000D_
     if(isNaN(pos)){_x000D_
      throw "Position must be a number";_x000D_
     }_x000D_
     if(pos<0){_x000D_
     throw "Position can not be negative";_x000D_
     }_x000D_
    var currentPos = window.scrollY||window.screenTop;_x000D_
    if(currentPos<pos){_x000D_
    var t = 10;_x000D_
       for(let i = currentPos; i <= pos; i+=10){_x000D_
       t+=10;_x000D_
        setTimeout(function(){_x000D_
       window.scrollTo(0, i);_x000D_
        }, t/2);_x000D_
      }_x000D_
    } else {_x000D_
    time = time || 2;_x000D_
       var i = currentPos;_x000D_
       var x;_x000D_
      x = setInterval(function(){_x000D_
         window.scrollTo(0, i);_x000D_
         i -= 10;_x000D_
         if(i<=pos){_x000D_
          clearInterval(x);_x000D_
         }_x000D_
     }, time);_x000D_
      }_x000D_
}_x000D_
function scrollToDiv(){_x000D_
  var elem = document.querySelector("div");_x000D_
  scrollToSmoothly(elem.offsetTop);_x000D_
}_x000D_
</script>
_x000D_
_x000D_
_x000D_

Set Encoding of File to UTF8 With BOM in Sublime Text 3

Into Preferences > Settings - Users
File : Preferences.sublime-settings

Write this :

"show_encoding" : true,

It's explain on the release note date 17 December 2013. Build 3059. Official site Sublime Text 3

Daylight saving time and time zone best practices

  • Never, ever store local time without its UTC offset (or a reference to the time zone)—examples of how not to do it include FAT32 and struct tm in C.¹
  • Understand that a time zone is a combination of
    • a set of UTC offsets (e.g. +0100 in winter, +0200 in summer)
    • rules for when the switchover happens (which may change over time: for example, in the 1990s the EU harmonized the switchover as being on the last Sundays in March and October, at 02:00 standard time/03:00 DST; previously this differed between member states).

¹ Some implementations of struct tm do store the UTC offset, but this has not made it into the standard.

Delete/Reset all entries in Core Data?

You can delete the SQLite file - but I choose to do it by purging the tables individually with a functions:

- (void) deleteAllObjects: (NSString *) entityDescription  {
    NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
    NSEntityDescription *entity = [NSEntityDescription entityForName:entityDescription inManagedObjectContext:_managedObjectContext];
    [fetchRequest setEntity:entity];

    NSError *error;
    NSArray *items = [_managedObjectContext executeFetchRequest:fetchRequest error:&error];
    [fetchRequest release];


    for (NSManagedObject *managedObject in items) {
        [_managedObjectContext deleteObject:managedObject];
        DLog(@"%@ object deleted",entityDescription);
    }
    if (![_managedObjectContext save:&error]) {
        DLog(@"Error deleting %@ - error:%@",entityDescription,error);
    }

}

The reason I chose to do it table by table is that it makes me confirm as I am doing the programming that deleting the contents of the table is sensible and there is not data that I would rather keep.

Doing it this will is much slower than just deleting the file and I will change to a file delete if I this method takes too long.

How do you stretch an image to fill a <div> while keeping the image's aspect-ratio?

Update 2016:

Modern browser behave much better. All you should need to do is to set the image width to 100% (demo)

.container img {
   width: 100%;
}

Since you don't know the aspect ratio, you'll have to use some scripting. Here is how I would do it with jQuery (demo):

CSS

.container {
    width: 40%;
    height: 40%;
    background: #444;
    margin: 0 auto;
}
.container img.wide {
    max-width: 100%;
    max-height: 100%;
    height: auto;
}
.container img.tall {
    max-height: 100%;
    max-width: 100%;
    width: auto;
}?

HTML

<div class="container">
 <img src="http://i48.tinypic.com/wrltuc.jpg" />
</div>
<br />
<br />
<div class="container">
 <img src="http://i47.tinypic.com/i1bek8.jpg" />
</div>

Script

$(window).load(function(){
 $('.container').find('img').each(function(){
  var imgClass = (this.width/this.height > 1) ? 'wide' : 'tall';
  $(this).addClass(imgClass);
 })
})

How to interactively (visually) resolve conflicts in SourceTree / git

I'm using SourceTree along with TortoiseMerge/Diff, which is very easy and convinient diff/merge tool.

If you'd like to use it as well, then:

  1. Get standalone version of TortoiseMerge/Diff (quite old, since it doesn't ship standalone since version 1.6.7 of TortosieSVN, that is since July 2011). Links and details in this answer.

  2. Unzip TortoiseIDiff.exe and TortoiseMerge.exe to any folder (c:\Program Files (x86)\Atlassian\SourceTree\extras\ in my case).

  3. In SourceTree open Tools > Options > Diff > External Diff / Merge. Select TortoiseMerge in both dropdown lists.

  4. Hit OK and point SourceTree to your location of TortoiseIDiff.exe and TortoiseMerge.exe.

After that, you can select Resolve Conflicts > Launch External Merge Tool from context menu on each conflicted file in your local repository. This will open up TortoiseMerge, where you can easily deal with all the conflicts, you have. Once finished, simply close TortoiseMerge (you don't even need to save changes, this will probably be done automatically) and after few seconds SourceTree should handle that gracefully.

The only problem is, that it automatically creates backup copy, even though proper option is unchecked.

XML shape drawable not rendering desired color

In drawable I use this xml code to define the border and background:

<shape xmlns:android="http://schemas.android.com/apk/res/android"> 
  <stroke android:width="4dp" android:color="#D8FDFB" /> 
  <padding android:left="7dp" android:top="7dp" 
    android:right="7dp" android:bottom="7dp" /> 
  <corners android:radius="4dp" /> 
  <solid android:color="#f0600000"/> 
</shape> 

Image, saved to sdcard, doesn't appear in Android's Gallery app

This will aslo solve your problem if your image in gallery are not showing instead they might showing a 404 type bitmap in midle. please add a the tags that are in my code with your image because there must some meta data in order to show image in gallery.

      String resultPath = getExternalFilesDir(Environment.DIRECTORY_PICTURES)+ 
      getString(R.string.directory) + System.currentTimeMillis() + ".jpg";

       new File(resultPath).getParentFile().mkdir();

        try {
            OutputStream fileOutputStream = new FileOutputStream(resultPath);
            savedBitmap.compress(CompressFormat.JPEG, 100, fileOutputStream);
            fileOutputStream.flush();
            fileOutputStream.close();
        } catch (IOException e2) {
            e2.printStackTrace();
        }
        savedBitmap.recycle();

        File file = new File(resultPath);
        ContentValues values = new ContentValues();
        values.put(MediaStore.Images.Media.TITLE, "Photo");
        values.put(MediaStore.Images.Media.DESCRIPTION, "Edited");
        values.put(MediaStore.Images.Media.MIME_TYPE, "image/jpeg");
        values.put(MediaStore.Images.Media.DATE_TAKEN, System.currentTimeMillis ());
        values.put(MediaStore.Images.Media.DATE_ADDED, System.currentTimeMillis());
        values.put(MediaStore.Images.ImageColumns.BUCKET_ID, file.toString().toLowerCase(Locale.US).hashCode());
        values.put(MediaStore.Images.ImageColumns.BUCKET_DISPLAY_NAME, file.getName().toLowerCase(Locale.US));
        values.put("_data", resultPath);

        ContentResolver cr = getContentResolver();
        cr.insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);




        return  resultPath;

Hibernate table not mapped error in HQL query

The exception message says:

Books is not mapped [SELECT COUNT(*) FROM Books]; nested exception is org.hibernate.hql.ast.QuerySyntaxException: Books is not mapped [SELECT COUNT(*) FROM Books]

Books is not mapped. That is, that there is no mapped type called Books.

And indeed, there isn't. Your mapped type is called Book. It's mapped to a table called Books, but the type is called Book. When you write HQL (or JPQL) queries, you use the names of the types, not the tables.

So, change your query to:

select count(*) from Book

Although I think it may need to be

select count(b) from Book b

If HQL doesn't support the * notation.

json call with C#

Its just a sample of how to post Json data and get Json data to/from a Rest API in BIDS 2008 using System.Net.WebRequest and without using newtonsoft. This is just a sample code and definitely can be fine tuned (well tested and it works and serves my test purpose like a charm). Its just to give you an Idea. I wanted this thread but couldn't find hence posting this.These were my major sources from where I pulled this. Link 1 and Link 2

Code that works(unit tested)

           //Get Example
            var httpWebRequest = (System.Net.HttpWebRequest)System.Net.WebRequest.Create("https://abc.def.org/testAPI/api/TestFile");
            httpWebRequest.ContentType = "application/json";
            httpWebRequest.Method = "GET";

            var username = "usernameForYourApi";
            var password = "passwordForYourApi";

            var bytes = Encoding.UTF8.GetBytes(username + ":" + password);
            httpWebRequest.Headers.Add("Authorization", "Basic " + Convert.ToBase64String(bytes));
            var httpResponse = (System.Net.HttpWebResponse)httpWebRequest.GetResponse();
            using (StreamReader streamReader = new StreamReader(httpResponse.GetResponseStream()))
            {
                string result = streamReader.ReadToEnd();
                Dts.Events.FireInformation(3, "result from readng stream", result, "", 0, ref fireagain);
            }


            //Post Example
            var httpWebRequestPost = (System.Net.HttpWebRequest)System.Net.WebRequest.Create("https://abc.def.org/testAPI/api/TestFile");
            httpWebRequestPost.ContentType = "application/json";
            httpWebRequestPost.Method = "POST";
            bytes = Encoding.UTF8.GetBytes(username + ":" + password);
            httpWebRequestPost.Headers.Add("Authorization", "Basic " + Convert.ToBase64String(bytes));

            //POST DATA newtonsoft didnt worked with BIDS 2008 in this test package
            //json https://stackoverflow.com/questions/6201529/how-do-i-turn-a-c-sharp-object-into-a-json-string-in-net
            // fill File model with some test data
            CSharpComplexClass fileModel = new CSharpComplexClass();
            fileModel.CarrierID = 2;
            fileModel.InvoiceFileDate = DateTime.Now;
            fileModel.EntryMethodID = EntryMethod.Manual;
            fileModel.InvoiceFileStatusID = FileStatus.NeedsReview;
            fileModel.CreateUserID = "37f18f01-da45-4d7c-a586-97a0277440ef";
            string json = new JavaScriptSerializer().Serialize(fileModel);
            Dts.Events.FireInformation(3, "reached json", json, "", 0, ref fireagain);
            byte[] byteArray = Encoding.UTF8.GetBytes(json);
            httpWebRequestPost.ContentLength = byteArray.Length;
            // Get the request stream.  
            Stream dataStream = httpWebRequestPost.GetRequestStream();
            // Write the data to the request stream.  
            dataStream.Write(byteArray, 0, byteArray.Length);
            // Close the Stream object.  
            dataStream.Close();
            // Get the response.  
            WebResponse response = httpWebRequestPost.GetResponse();
            // Display the status.  
            //Console.WriteLine(((HttpWebResponse)response).StatusDescription);
            Dts.Events.FireInformation(3, "Display the status", ((HttpWebResponse)response).StatusDescription, "", 0, ref fireagain);
            // Get the stream containing content returned by the server.  
            dataStream = response.GetResponseStream();
            // Open the stream using a StreamReader for easy access.  
            StreamReader reader = new StreamReader(dataStream);
            // Read the content.  
            string responseFromServer = reader.ReadToEnd();
            Dts.Events.FireInformation(3, "responseFromServer ", responseFromServer, "", 0, ref fireagain);

References in my test script task inside BIDS 2008(having SP1 and 3.5 framework) enter image description here

How to return HTTP 500 from ASP.NET Core RC2 Web Api?

How about creating a custom ObjectResult class that represents an Internal Server Error like the one for OkObjectResult? You can put a simple method in your own base class so that you can easily generate the InternalServerError and return it just like you do Ok() or BadRequest().

[Route("api/[controller]")]
[ApiController]
public class MyController : MyControllerBase
{
    [HttpGet]
    [Route("{key}")]
    public IActionResult Get(int key)
    {
        try
        {
            //do something that fails
        }
        catch (Exception e)
        {
            LogException(e);
            return InternalServerError();
        }
    }
}

public class MyControllerBase : ControllerBase
{
    public InternalServerErrorObjectResult InternalServerError()
    {
        return new InternalServerErrorObjectResult();
    }

    public InternalServerErrorObjectResult InternalServerError(object value)
    {
        return new InternalServerErrorObjectResult(value);
    }
}

public class InternalServerErrorObjectResult : ObjectResult
{
    public InternalServerErrorObjectResult(object value) : base(value)
    {
        StatusCode = StatusCodes.Status500InternalServerError;
    }

    public InternalServerErrorObjectResult() : this(null)
    {
        StatusCode = StatusCodes.Status500InternalServerError;
    }
}

Git Symlinks in Windows

2020 Answer

  1. Enable "Developer mode" in Windows 10 -- gives mklink permissions
  2. Ensure symlinks are enabled in git
    • git config --global core.symlinks true
    • or check the checkbox when installing msysgit

Switching branches will force the recreation of missing symlinks.

Be careful, support for Symlinks in git on Windows is relatively new. There are some bugs that still affect some git clients. Notably, symlinks with relative (..) paths are mangled in some programs because of a fixed regression in libgit2. GitKraken is affected by this, for instance.

How do I update a formula with Homebrew?

You can't use brew install to upgrade an installed formula. If you want upgrade all of outdated formulas, you can use the command below.

brew outdated | xargs brew upgrade

How to convert unsigned long to string

Try using sprintf:

unsigned long x=1000000;
char buffer[21];
sprintf(buffer,"%lu", x);

Edit:

Notice that you have to allocate a buffer in advance, and have no idea how long the numbers will actually be when you do so. I'm assuming 32bit longs, which can produce numbers as big as 10 digits.

See Carl Smotricz's answer for a better explanation of the issues involved.

Remove substring from the string

here's what I'd do

2.2.1 :015 > class String; def remove!(start_index, end_index) (end_index - start_index + 1).times{ self.slice! start_index }; self end; end;
2.2.1 :016 >   "idliketodeleteHEREallthewaytoHEREplease".remove! 14, 32
 => "idliketodeleteplease" 
2.2.1 :017 > ":)".remove! 1,1
 => ":" 
2.2.1 :018 > "ohnoe!".remove! 2,4
 => "oh!" 

Formatted on multiple lines:

class String
    def remove!(start_index, end_index)
        (end_index - start_index + 1).times{ self.slice! start_index }
        self
    end 
end

How to run a C# console application with the console hidden

Add this to your class to import the DLL file:

[DllImport("user32.dll")] 
static extern bool ShowWindow(IntPtr hWnd, int nCmdShow); 

[DllImport("kernel32.dll")] 
static extern IntPtr GetConsoleWindow();

const int SW_HIDE = 0;
const int SW_SHOW = 5;

And then if you want to hide it use this command:

 var handle = GetConsoleWindow();
 ShowWindow(handle, SW_HIDE);

And if you want to show the console:

var handle = GetConsoleWindow();
ShowWindow(handle, SW_SHOW);

How to make an executable JAR file?

In Eclipse you can do it simply as follows :

Right click on your Java Project and select Export.

Select Java -> Runnable JAR file -> Next.

Select the Launch Configuration and choose project file as your Main class

Select the Destination folder where you would like to save it and click Finish.

How to specify preference of library path?

As an alternative, you can use the environment variables LIBRARY_PATH and CPLUS_INCLUDE_PATH, which respectively indicate where to look for libraries and where to look for headers (CPATH will also do the job), without specifying the -L and -I options.

Edit: CPATH includes header with -I and CPLUS_INCLUDE_PATH with -isystem.

Bluetooth pairing without user confirmation

Well, this should really be broken into 2 parts:

  1. Can you pair 2 Bluetooth devices without going through a Bluetooth pairing handshake? No, you can't. That's baked into the protocol so there is no way around this.
  2. Can you perform the handshake without a user interface? Yes, you can: that's just code.

I'm not sure how you do it in Windows land, but in *nix land there are functions buried in the Bluez stack that let you receive notifications about when a new device appears, and send it the pairing code (clearly there have to be these functions: those are what the user interface use). Given sufficient time and experience I'm sure you could figure out how to write your own version of the Bluetooth Settings app that somehow:

  • Detected a new device had arrived
  • Looked at the name/bluetooth mac address and checked some internal database for the pairing code to use.
  • Sent the pairing code and completed the operation

All without having to pop up a user interface.

If you go ahead and write the code I'd LOVE to get my hands on it.

JPanel vs JFrame in Java

JFrame is the window; it can have one or more JPanel instances inside it. JPanel is not the window.

You need a Swing tutorial:

http://docs.oracle.com/javase/tutorial/uiswing/

/etc/apt/sources.list" E212: Can't open file for writing

change the permission for the other user for that type setfacl -m u:username:rw filename

Bootstrap: How to center align content inside column?

You can do this by adding a div i.e. centerBlock. And give this property in CSS to center the image or any content. Here is the code:

<div class="container">
    <div class="row">
        <div class="col-sm-4 col-md-4 col-lg-4">
            <div class="centerBlock">
                <img class="img-responsive" src="img/some-image.png" title="This image needs to be centered">
            </div>
        </div>
        <div class="col-sm-8 col-md-8 col-lg-8">
            Some content not important at this moment
        </div>
    </div>
</div>


// CSS

.centerBlock {
  display: table;
  margin: auto;
}

Format Date output in JSF

If you use OmniFaces you can also use it's EL functions like of:formatDate() to format Date objects. You would use it like this:

<h:outputText value="#{of:formatDate(someBean.dateField, 'dd.MM.yyyy HH:mm')}" />

This way you can not only use it for output but also to pass it on to other JSF components.

How to stop (and restart) the Rails Server?

Now in rails 5 yu can do:

rails restart

This print by rails --tasks

Restart app by touching tmp/restart.txt

I think that is usefully if you run rails as a demon

Reset Excel to default borders

Just go to Home> Cell Style > Normal

khir

Java Multithreading concept and join() method

I came across the join() while learning about race condition and I will clear the doubts I was having. So let us take this small example

Thread t2 = new Thread(
             new Runnable() {
                 public void run () {
                     //do something
                 }
              }
);
Thread t1 = new Thread(
             new Runnable() {
                 public void run () {
                     //do something
                 }
              }
);
t2.start(); //Line 11
t1.start(); //Line 12
t2.join();  //Line 13
t1.join();  //Line 14
System.out.print("<Want to print something that was being modified by t2 and t1>")

My AIM
Three threads are running namely t1, t2 and the main thread. I want to print something after the t1 and t2 has finished. The printing operation is on my main thread therefore for the expected answer I need to let t1 and t2 finish and then print my output.

So t1.join() just makes the main thread wait, till the t1 thread completes before going to the next line in program.

Here is the definition as per GeeksforGeeks:

java.lang.Thread class provides the join() method which allows one thread to wait until another thread completes its execution.

Here is one question that might solve your doubt

Q-> Will t1 thread get the time slice to run by the thread scheduler, when the program is processing the t2.join() at Line 13?

ANS-> Yes it will be eligible to get the time slice to run as we have already made it eligible by running the line t1.start() at Line 11.
t2.join() only applies the condition when the JVM will go to next line, that is Line 14.
It might be also possible that t1 might get finished processing at Line 13.

Using .otf fonts on web browsers

You can implement your OTF font using @font-face like:

@font-face {
    font-family: GraublauWeb;
    src: url("path/GraublauWeb.otf") format("opentype");
}

@font-face {
    font-family: GraublauWeb;
    font-weight: bold;
    src: url("path/GraublauWebBold.otf") format("opentype");
}

// Edit: OTF now works in most browsers, see comments

However if you want to support a wide variety of browsers i would recommend you to switch to WOFF and TTF font types. WOFF type is implemented by every major desktop browser, while the TTF type is a fallback for older Safari, Android and iOS browsers. If your font is a free font, you could convert your font using for example a transfonter.

@font-face {
    font-family: GraublauWeb;
    src: url("path/GraublauWebBold.woff") format("woff"), url("path/GraublauWebBold.ttf")  format("truetype");
}

If you want to support nearly every browser that is still out there (not necessary anymore IMHO), you should add some more font-types like:

@font-face {
    font-family: GraublauWeb;
    src: url("webfont.eot"); /* IE9 Compat Modes */
    src: url("webfont.eot?#iefix") format("embedded-opentype"), /* IE6-IE8 */
         url("webfont.woff") format("woff"), /* Modern Browsers */
         url("webfont.ttf")  format("truetype"), /* Safari, Android, iOS */
         url("webfont.svg#svgFontName") format("svg"); /* Legacy iOS */
}

You can read more about why all these types are implemented and their hacks here. To get a detailed view of which file-types are supported by which browsers, see:

@font-face Browser Support

EOT Browser Support

WOFF Browser Support

TTF Browser Support

SVG-Fonts Browser Support

hope this helps

How to stop IIS asking authentication for default website on localhost

This is most likely a NT file permissions problem. IUSR_ needs to have file system permissions to read whatever file you're requesting (like /inetpub/wwwroot/index.htm).

If you still have trouble, check the IIS logs, typically at \windows\system32\logfiles\W3SVC*.

How to define a variable in a Dockerfile?

To answer your question:

In my Dockerfile, I would like to define variables that I can use later in the Dockerfile.

You can define a variable with:

ARG myvalue=3

Spaces around the equal character are not allowed.

And use it later with:

RUN echo $myvalue > /test

How to declare std::unique_ptr and what is the use of it?

There is no difference in working in both the concepts of assignment to unique_ptr.

int* intPtr = new int(3);
unique_ptr<int> uptr (intPtr);

is similar to

unique_ptr<int> uptr (new int(3));

Here unique_ptr automatically deletes the space occupied by uptr.


how pointers, declared in this way will be different from the pointers declared in a "normal" way.

If you create an integer in heap space (using new keyword or malloc), then you will have to clear that memory on your own (using delete or free respectively).

In the below code,

int* heapInt = new int(5);//initialize int in heap memory
.
.//use heapInt
.
delete heapInt;

Here, you will have to delete heapInt, when it is done using. If it is not deleted, then memory leakage occurs.

In order to avoid such memory leaks unique_ptr is used, where unique_ptr automatically deletes the space occupied by heapInt when it goes out of scope. So, you need not do delete or free for unique_ptr.

How can I generate a list of files with their absolute path in Linux?

This worked for me. But it didn't list in alphabetical order.

find "$(pwd)" -maxdepth 1

This command lists alphabetically as well as lists hidden files too.

ls -d -1 "$PWD/".*; ls -d -1 "$PWD/"*;

Deserialize a JSON array in C#

This code is working fine for me,

var a = serializer.Deserialize<List<Entity>>(json);

Simple way to query connected USB devices info in Python?

When I run your code, I get the following output for example.

<usb.Device object at 0xef38c0>
Device: 001
  idVendor: 7531 (0x1d6b)
  idProduct: 1 (0x0001)
Manufacturer: 3
Serial: 1
Product: 2

Noteworthy are that a) I have usb.Device objects whereas you have usb.legacy.Device objects, and b) I have device filenames.

Each usb.Bus has a dirname field and each usb.Device has the filename. As you can see, the filename is something like 001, and so is the dirname. You can combine these to get the bus file. For dirname=001 and filname=001, it should be something like /dev/bus/usb/001/001.

You should first, though figure out what this "usb.legacy" situation is. I'm running the latest version and I don't even have a legacy sub-module.

Finally, you should use the idVendor and idProduct fields to uniquely identify the device when it's plugged in.

Go to particular revision

Before executing this command keep in mind that it will leave you in detached head status

Use git checkout <sha1> to check out a particular commit.

Where <sha1> is the commit unique number that you can obtain with git log

Here are some options after you are in detached head status:

  • Copy the files or make the changes that you need to a folder outside your git folder, checkout the branch were you need them git checkout <existingBranch> and replace files
  • Create a new local branch git checkout -b <new_branch_name> <sha1>

console.log(result) returns [object Object]. How do I get result.name?

Try adding JSON.stringify(result) to convert the JS Object into a JSON string.

From your code I can see you are logging the result in error which is called if the AJAX request fails, so I'm not sure how you'd go about accessing the id/name/etc. then (you are checking for success inside the error condition!).

Note that if you use Chrome's console you should be able to browse through the object without having to stringify the JSON, which makes it easier to debug.

How to emulate a do-while loop in Python?

Why don't you just do

for s in l :
    print s
print "done"

?

What Content-Type value should I send for my XML sitemap?

both are fine.

text/xxx means that in case the program does not understand xxx it makes sense to show the file to the user as plain text. application/xxx means that it is pointless to show it.

Please note that those content-types were originally defined for E-Mail attachment before they got later used in Web world.

Using Spring RestTemplate in generic method with generic parameter

As the code below shows it, it works.

public <T> ResponseWrapper<T> makeRequest(URI uri, final Class<T> clazz) {
   ResponseEntity<ResponseWrapper<T>> response = template.exchange(
        uri,
        HttpMethod.POST,
        null,
        new ParameterizedTypeReference<ResponseWrapper<T>>() {
            public Type getType() {
                return new MyParameterizedTypeImpl((ParameterizedType) super.getType(), new Type[] {clazz});
        }
    });
    return response;
}

public class MyParameterizedTypeImpl implements ParameterizedType {
    private ParameterizedType delegate;
    private Type[] actualTypeArguments;

    MyParameterizedTypeImpl(ParameterizedType delegate, Type[] actualTypeArguments) {
        this.delegate = delegate;
        this.actualTypeArguments = actualTypeArguments;
    }

    @Override
    public Type[] getActualTypeArguments() {
        return actualTypeArguments;
    }

    @Override
    public Type getRawType() {
        return delegate.getRawType();
    }

    @Override
    public Type getOwnerType() {
        return delegate.getOwnerType();
    }

}

get number of columns of a particular row in given excel using Java

/** Count max number of nonempty cells in sheet rows */
private int getColumnsCount(XSSFSheet xssfSheet) {
    int result = 0;
    Iterator<Row> rowIterator = xssfSheet.iterator();
    while (rowIterator.hasNext()) {
        Row row = rowIterator.next();
        List<Cell> cells = new ArrayList<>();
        Iterator<Cell> cellIterator = row.cellIterator();
        while (cellIterator.hasNext()) {
            cells.add(cellIterator.next());
        }
        for (int i = cells.size(); i >= 0; i--) {
            Cell cell = cells.get(i-1);
            if (cell.toString().trim().isEmpty()) {
                cells.remove(i-1);
            } else {
                result = cells.size() > result ? cells.size() : result;
                break;
            }
        }
    }
    return result;
}

NVIDIA-SMI has failed because it couldn't communicate with the NVIDIA driver

My system version: ubuntu 20.04 LTS.

  • I solved this by generate a new MOK and enroll it into shim.

  • Without disable of Secure Boot, although it also really works for me.

  • Simply execute this command and follow what it suggests:

    sudo update-secureboot-policy --enroll-key
    

According to ubuntu's wiki: How can I do non-automated signing of drivers

Linux configure/make, --prefix?

Do configure --help and see what other options are available.

It is very common to provide different options to override different locations. By standard, --prefix overrides all of them, so you need to override config location after specifying the prefix. This course of actions usually works for every automake-based project.

The worse case scenario is when you need to modify the configure script, or even worse, generated makefiles and config.h headers. But yeah, for Xfce you can try something like this:

./configure --prefix=/home/me/somefolder/mybuild/output/target --sysconfdir=/etc 

I believe that should do it.

How to set value to form control in Reactive Forms in Angular

Use patchValue() method which helps to update even subset of controls.

setValue(){
  this.editqueForm.patchValue({user: this.question.user, questioning: this.question.questioning})
}


From Angular docs setValue() method:

Error When strict checks fail, such as setting the value of a control that doesn't exist or if you excluding the value of a control.

In your case, object missing options and questionType control value so setValue() will fail to update.

Android Failed to install HelloWorld.apk on device (null) Error

Restarting the device works for me. Using adb install can get the apk installed, but it's annoying to use it everytime you launch the app when debugging within eclipse.

Trying to embed newline in a variable in bash

The trivial solution is to put those newlines where you want them.

var="a
b
c"

Yes, that's an assignment wrapped over multiple lines.

However, you will need to double-quote the value when interpolating it, otherwise the shell will split it on whitespace, effectively turning each newline into a single space (and also expand any wildcards).

echo "$p"

Generally, you should double-quote all variable interpolations unless you specifically desire the behavior described above.

Why does git status show branch is up-to-date when changes exist upstream?

While these are all viable answers, I decided to give my way of checking if local repo is in line with the remote, whithout fetching or pulling. In order to see where my branches are I use simply:

git remote show origin

What it does is return all the current tracked branches and most importantly - the info whether they are up to date, ahead or behind the remote origin ones. After the above command, this is an example of what is returned:

  * remote origin
  Fetch URL: https://github.com/xxxx/xxxx.git
  Push  URL: https://github.com/xxxx/xxxx.git
  HEAD branch: master
  Remote branches:
    master      tracked
    no-payments tracked
  Local branches configured for 'git pull':
    master      merges with remote master
    no-payments merges with remote no-payments
  Local refs configured for 'git push':
    master      pushes to master      (local out of date)
    no-payments pushes to no-payments (local out of date)

Hope this helps someone.

reading and parsing a TSV file, then manipulating it for saving as CSV (*efficiently*)

You should use the csv module to read the tab-separated value file. Do not read it into memory in one go. Each row you read has all the information you need to write rows to the output CSV file, after all. Keep the output file open throughout.

import csv

with open('sample.txt', newline='') as tsvin, open('new.csv', 'w', newline='') as csvout:
    tsvin = csv.reader(tsvin, delimiter='\t')
    csvout = csv.writer(csvout)

    for row in tsvin:
        count = int(row[4])
        if count > 0:
            csvout.writerows([row[2:4] for _ in range(count)])

or, using the itertools module to do the repeating with itertools.repeat():

from itertools import repeat
import csv

with open('sample.txt', newline='') as tsvin, open('new.csv', 'w', newline='') as csvout:
    tsvin = csv.reader(tsvin, delimiter='\t')
    csvout = csv.writer(csvout)

    for row in tsvin:
        count = int(row[4])
        if count > 0:
            csvout.writerows(repeat(row[2:4], count))

Simple If/Else Razor Syntax

Just use this for the closing tag:

  @:</tr>

And leave your if/else as is.

Seems like the if statement doesn't wanna' work.

It works fine. You're working in 2 language-spaces here, it seems only proper not to split open/close sandwiches over the border.

PHP PDO returning single row

how about using limit 0,1 for mysql optimisation

and about your code:

$DBH = new PDO( "connection string goes here" );

$STH - $DBH -> prepare( "select figure from table1" );

$STH -> execute();

$result = $STH ->fetch(PDO::FETCH_ASSOC)

echo $result["figure"];

$DBH = null;

Convert xlsx to csv in Linux with command line

In bash, I used this libreoffice command to convert all my xlsx files in the current directory:

for i   in *.xlsx; do  libreoffice --headless --convert-to csv "$i" ; done

It takes care of spaces in the filename.

Tried again some years later, and it didn't work. This thread gives some tips, but the quickiest solution was to run as root (or running a sudo libreoffice). Not elegant, but quick.

Use the command scalc.exe in Windows

Set a path variable with spaces in the path in a Windows .cmd file or batch file

Try this;

  1. create a variable as below

    SET "SolutionDir=C:\Test projects\Automation tests\bin\Debug"**
    
  2. Then replace the path with variable. Make sure to add quotes for starts and end

    vstest.console.exe "%SolutionDir%\Automation.Specs.dll"
    

How to upload a file and JSON data in Postman?

If you need like Upload file in multipart using form data and send json data(Dto object) in same POST Request

Get yor JSON object as String in Controller and make it Deserialize by adding this line

ContactDto contactDto  = new ObjectMapper().readValue(yourJSONString, ContactDto.class);

How to load assemblies in PowerShell?

[System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SqlServer.Smo") worked for me.

How to change the default port of mysql from 3306 to 3360

You need to edit your my.cnf file and make sure you have the port set as in the following line:

port = 3360

Then restart your MySQL service and you should be good to go. There is no query you can run to make this change because the port is not a dynamic variable (q.v. here for MySQL documentation showing a table of all system variables).

phpexcel to download

FOR XLSX USE

SET IN $xlsName name from XLSX with extension. Example: $xlsName = 'teste.xlsx';

$objPHPExcel = new PHPExcel();

$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
header('Content-Type: application/vnd.ms-excel');
header('Content-Disposition: attachment;filename="'.$xlsName.'"');
header('Cache-Control: max-age=0');
$objWriter->save('php://output');

FOR XLS USE

SET IN $xlsName name from XLS with extension. Example: $xlsName = 'teste.xls';

$objPHPExcel = new PHPExcel();

$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
header('Content-Type: application/vnd.ms-excel');
header('Content-Disposition: attachment;filename="'.$xlsName.'"');
header('Cache-Control: max-age=0');
$objWriter->save('php://output');

Is there a way to force npm to generate package-lock.json?

By default, package-lock.json is updated whenever you run npm install. However, this can be disabled globally by setting package-lock=false in ~/.npmrc.

When the global package-lock=false setting is active, you can still force a project’s package-lock.json file to be updated by running:

npm install --package-lock

This command is the only surefire way of forcing a package-lock.json update.

GridView sorting: SortDirection always Ascending

This is another way of solving the issue:

protected void grdHeader_OnSorting(object sender, GridViewSortEventArgs e)
{
    List<V_ReportPeriodStatusEntity> items = GetPeriodStatusesForScreenSelection();
    items.Sort = e.SortExpression + " " + ConvertSortDirectionToSql(e);
    grdHeader.DataSource = items;
    grdHeader.DataBind();
}

private string ConvertSortDirectionToSql(GridViewSortEventArgs e)
{
    ViewState[e.SortExpression] = ViewState[e.SortExpression] ?? "ASC";
    ViewState[e.SortExpression] = (ViewState[e.SortExpression].ToString() == "ASC") ? "DESC" : "ASC";
    return ViewState[e.SortExpression].ToString();
}

Adding maven nexus repo to my pom.xml

If you don't want or you cannot modify the settings.xml file, you can create a new one in your root project, and call maven passing it as a parameter with the -s parameter:

$ mvn COMMAND ... -s settings.xml

Is it a good practice to place C++ definitions in header files?

I personally do this in my header files:

// class-declaration

// inline-method-declarations

I don't like mixing the code for the methods in with the class as I find it a pain to look things up quickly.

I would not put ALL of the methods in the header file. The compiler will (normally) not be able to inline virtual methods and will (likely) only inline small methods without loops (totally depends on the compiler).

Doing the methods in the class is valid... but from a readablilty point of view I don't like it. Putting the methods in the header does mean that, when possible, they will get inlined.

How do I UPDATE from a SELECT in SQL Server?

There is even a shorter method and it might be surprising for you:

Sample data set:

CREATE TABLE #SOURCE ([ID] INT, [Desc] VARCHAR(10));
CREATE TABLE #DEST   ([ID] INT, [Desc] VARCHAR(10));

INSERT INTO #SOURCE VALUES(1,'Desc_1'), (2, 'Desc_2'), (3, 'Desc_3');
INSERT INTO #DEST   VALUES(1,'Desc_4'), (2, 'Desc_5'), (3, 'Desc_6');

Code:

UPDATE #DEST
SET #DEST.[Desc] = #SOURCE.[Desc]
FROM #SOURCE
WHERE #DEST.[ID] = #SOURCE.[ID];

How to decrypt the password generated by wordpress

This is one of the proposed solutions found in the article Jacob mentioned, and it worked great as a manual way to change the password without having to use the email reset.

  1. In the DB table wp_users, add a key, like abc123 to the user_activation column.
  2. Visit yoursite.com/wp-login.php?action=rp&key=abc123&login=yourusername
  3. You will be prompted to enter a new password.

How to enter a series of numbers automatically in Excel

=IF(B1<>"",COUNTA($B$1:B1)&".","")

Using formula

  1. Paste the above formula in column A or where you need to have the serial no
  2. When the second column (For Example, when B column is filled the serial no will be automatically generated in column A).

What does += mean in Python?

+= is the in-place addition operator.

It's the same as doing cnt = cnt + 1. For example:

>>> cnt = 0
>>> cnt += 2
>>> print cnt
2
>>> cnt += 42
>>> print cnt
44

The operator is often used in a similar fashion to the ++ operator in C-ish languages, to increment a variable by one in a loop (i += 1)

There are similar operator for subtraction/multiplication/division/power and others:

i -= 1 # same as i = i - 1
i *= 2 # i = i * 2
i /= 3 # i = i / 3
i **= 4 # i = i ** 4

The += operator also works on strings, for example:

>>> s = "Hi"
>>> s += " there"
>>> print s
Hi there

People tend to recommend against doing this for performance reason, but for the most scripts this really isn't an issue. To quote from the "Sequence Types" docs:

  1. If s and t are both strings, some Python implementations such as CPython can usually perform an in-place optimization for assignments of the form s=s+t or s+=t. When applicable, this optimization makes quadratic run-time much less likely. This optimization is both version and implementation dependent. For performance sensitive code, it is preferable to use the str.join() method which assures consistent linear concatenation performance across versions and implementations.

The str.join() method refers to doing the following:

mysentence = []
for x in range(100):
    mysentence.append("test")
" ".join(mysentence)

..instead of the more obvious:

mysentence = ""
for x in range(100):
    mysentence += " test"

The problem with the later is (aside from the leading-space), depending on the Python implementation, the Python interpreter will have to make a new copy of the string in memory every time you append (because strings are immutable), which will get progressively slower the longer the string to append is.. Whereas appending to a list then joining it together into a string is a consistent speed (regardless of implementation)

If you're doing basic string manipulation, don't worry about it. If you see a loop which is basically just appending to a string, consider constructing an array, then "".join()'ing it.

ng-model for `<input type="file"/>` (with directive DEMO)

For multiple files input using lodash or underscore:

.directive("fileread", [function () {
    return {
        scope: {
            fileread: "="
        },
        link: function (scope, element, attributes) {
            element.bind("change", function (changeEvent) {
                return _.map(changeEvent.target.files, function(file){
                  scope.fileread = [];
                  var reader = new FileReader();
                  reader.onload = function (loadEvent) {
                      scope.$apply(function () {
                          scope.fileread.push(loadEvent.target.result);
                      });
                  }
                  reader.readAsDataURL(file);
                });
            });
        }
    }
}]);

How to add additional fields to form before submit?

Try this:

$('#form').submit(function(eventObj) {
    $(this).append('<input type="hidden" name="field_name" value="value" /> ');
    return true;
});

Arrays in cookies PHP

recently i've created this code for my client, i'm using array for cookie in this code, actually this code gets recently viewed pages by user using cookies, hope it helps you...!

function curPageURL() { // get url
return 'http' . ((
!empty($_SERVER['HTTPS']) &&
$_SERVER['HTTPS'] !== 'off' ||
$_SERVER['SERVER_PORT'] == 443
) ? 's' : '') . '://' . $_SERVER['SERVER_NAME'] . (
$_SERVER['SERVER_PORT'] == 80 ? '' :  $_SERVER['SERVER_PORT']
) . $_SERVER['REQUEST_URI'];
}

$currentPage = curPageURL(); // call function
$counter = $_COOKIE['_counter']; // set counter variable

if(!$_COOKIE['_PAGES']){ // if _Pages cookie
$default = 1; // set default value to 1
setcookie("_counter",$default,time()+7200); // set counter cookie
setcookie("_PAGES[$default]",$currentPage, time()+3600); // set cookie  
}
else{ // if ! _Pages cookie 
$default = $counter+1; // set default value to +1
setcookie("_counter",$default,time()+7200); // set counter cookie
}


if(@in_array($currentPage, @$_COOKIE['_PAGES'])){ // if same url found
}
else{ // if new url found
setcookie("_PAGES[$default]",$currentPage, time()+3600); // set cookie  
}


if($_COOKIE['_PAGES']){
foreach ($_COOKIE['_PAGES'] as $value){
    echo "<a href='{$value}'>{$value}</a>";
} 
}

Moment js date time comparison

moment(d).isAfter(ahead30now); // true

http://momentjs.com/docs/#/query/is-after/

if (moment(d).isAfter(ahead30now)) {
    // allow input time
    console.log('UTC TIME DB', d.format());
} else {

}

What does this symbol mean in IntelliJ? (red circle on bottom-left corner of file name, with 'J' in it)

First mark the directory as the source root. Then go to the pom excel and right click on it. select add as maven project .

Referring to a Column Alias in a WHERE Clause

If you don't want to list all your columns in CTE, another way to do this would be to use outer apply:

select
    s.logcount, s.logUserID, s.maxlogtm,
    a.daysdiff
from statslogsummary as s
    outer apply (select datediff(day, s.maxlogtm, getdate()) as daysdiff) as a
where a.daysdiff > 120

.htaccess redirect www to non-www with SSL/HTTPS

To enforce non-www and https in a single request, you can use the following Rule in your htaccess :

RewriteEngine on

RewriteCond %{HTTP_HOST} ^www\. [OR]
RewriteCond %{HTTPS} off
RewriteCond %{HTTP_HOST} ^(?:www\.)?(.+)$
RewriteRule ^ https://%1%{REQUEST_URI} [NE,L,R]

This redirects http://www.example.com/ or https://www.example.com/ to ssl non-www https://example.com/ .

I am using R Temp Redirect flag for testing purpose and to avoid browser caching. If you want to make the redirect permanent , just change the R flag to R=301 .

How do you round a floating point number in Perl?

If you decide to use printf or sprintf, note that they use the Round half to even method.

foreach my $i ( 0.5, 1.5, 2.5, 3.5 ) {
    printf "$i -> %.0f\n", $i;
}
__END__
0.5 -> 0
1.5 -> 2
2.5 -> 2
3.5 -> 4

Getting the size of an array in an object

Javascript arrays have a length property. Use it like this:

st.itemb.length

Room - Schema export directory is not provided to the annotation processor so we cannot export the schema

I use .kts Gradle files (Kotlin Gradle DSL) and the kotlin-kapt plugin but I still get a script compilation error when I use Ivanov Maksim's answer.

Unresolved reference: kapt

For me this was the only thing which worked:

android {
    defaultConfig {
        javaCompileOptions {
            annotationProcessorOptions {
                arguments = mapOf("room.schemaLocation" to "$projectDir/schemas")
            }
        }
    }
}

Load RSA public key from file

Once you have your key stored in a PEM file, you can read it back easily using PemObject and PemReader classes provided by BouncyCastle, as shown in this this tutorial.

Create a PemFile class that encapsulates file handling:

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;

import org.bouncycastle.util.io.pem.PemObject;
import org.bouncycastle.util.io.pem.PemReader;

public class PemFile {

    private PemObject pemObject;

    public PemFile(String filename) throws FileNotFoundException, IOException {
        PemReader pemReader = new PemReader(new InputStreamReader(
                new FileInputStream(filename)));
        try {
            this.pemObject = pemReader.readPemObject();
        } finally {
            pemReader.close();
        }
    }

    public PemObject getPemObject() {
        return pemObject;
    }
}

Then instantiate private and public keys as usual:

import java.io.FileNotFoundException;
import java.io.IOException;
import java.security.KeyFactory;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.Security;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;

import org.apache.log4j.Logger;
import org.bouncycastle.jce.provider.BouncyCastleProvider;

public class Main {

    protected final static Logger LOGGER = Logger.getLogger(Main.class);

    public final static String RESOURCES_DIR = "src/main/resources/rsa-sample/";

    public static void main(String[] args) throws FileNotFoundException,
            IOException, NoSuchAlgorithmException, NoSuchProviderException {
        Security.addProvider(new BouncyCastleProvider());
        LOGGER.info("BouncyCastle provider added.");

        KeyFactory factory = KeyFactory.getInstance("RSA", "BC");
        try {
            PrivateKey priv = generatePrivateKey(factory, RESOURCES_DIR
                    + "id_rsa");
            LOGGER.info(String.format("Instantiated private key: %s", priv));

            PublicKey pub = generatePublicKey(factory, RESOURCES_DIR
                    + "id_rsa.pub");
            LOGGER.info(String.format("Instantiated public key: %s", pub));
        } catch (InvalidKeySpecException e) {
            e.printStackTrace();
        }
    }

    private static PrivateKey generatePrivateKey(KeyFactory factory,
            String filename) throws InvalidKeySpecException,
            FileNotFoundException, IOException {
        PemFile pemFile = new PemFile(filename);
        byte[] content = pemFile.getPemObject().getContent();
        PKCS8EncodedKeySpec privKeySpec = new PKCS8EncodedKeySpec(content);
        return factory.generatePrivate(privKeySpec);
    }

    private static PublicKey generatePublicKey(KeyFactory factory,
            String filename) throws InvalidKeySpecException,
            FileNotFoundException, IOException {
        PemFile pemFile = new PemFile(filename);
        byte[] content = pemFile.getPemObject().getContent();
        X509EncodedKeySpec pubKeySpec = new X509EncodedKeySpec(content);
        return factory.generatePublic(pubKeySpec);
    }
}

Hope this helps.

X-Frame-Options on apache

What did it for me was the following, I've added the following directive in both the http <VirtualHost *:80> and https <VirtualHost *:443> virtual host blocks:

ServerName your-app.com
ServerAlias www.your-app.com

Header always unset X-Frame-Options
Header set X-Frame-Options "SAMEORIGIN"

The reasoning behind this? Well by default if set, the server does not reset the X-Frame-Options header so we need to first always remove the default value, in my case it was DENY, and then with the next rule we set it to the desired value, in my case SAMEORIGIN. Of course you can use the Header set X-Frame-Options ALLOW-FROM ... rule as well.

java.lang.UnsupportedClassVersionError

The code was most likely compiled with a later JDK (without using cross-compilation options) and is being run on an earlier JRE. While upgrading the JRE is one solution, it would be better to use the cross-compilation options to ensure the code will run on whatever JRE is intended as the minimum version for the app.

When do you use Java's @Override annotation and why?

It does allow you (well, the compiler) to catch when you've used the wrong spelling on a method name you are overriding.

How do I use a delimiter with Scanner.useDelimiter in Java?

With Scanner the default delimiters are the whitespace characters.

But Scanner can define where a token starts and ends based on a set of delimiter, wich could be specified in two ways:

  1. Using the Scanner method: useDelimiter(String pattern)
  2. Using the Scanner method : useDelimiter(Pattern pattern) where Pattern is a regular expression that specifies the delimiter set.

So useDelimiter() methods are used to tokenize the Scanner input, and behave like StringTokenizer class, take a look at these tutorials for further information:

And here is an Example:

public static void main(String[] args) {

    // Initialize Scanner object
    Scanner scan = new Scanner("Anna Mills/Female/18");
    // initialize the string delimiter
    scan.useDelimiter("/");
    // Printing the tokenized Strings
    while(scan.hasNext()){
        System.out.println(scan.next());
    }
    // closing the scanner stream
    scan.close();
}

Prints this output:

Anna Mills
Female
18

Measuring text height to be drawn on Canvas ( Android )

If anyone still has problem, this is my code.

I have a custom view which is square (width = height) and I want to assign a character to it. onDraw() shows how to get height of character, although I'm not using it. Character will be displayed in the middle of view.

public class SideBarPointer extends View {

    private static final String TAG = "SideBarPointer";

    private Context context;
    private String label = "";
    private int width;
    private int height;

    public SideBarPointer(Context context) {
        super(context);
        this.context = context;
        init();
    }

    public SideBarPointer(Context context, AttributeSet attrs) {
        super(context, attrs);
        this.context = context;
        init();
    }

    public SideBarPointer(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        this.context = context;
        init();
    }

    private void init() {
//        setBackgroundColor(0x64FF0000);
    }

    @Override
    public void onMeasure(int widthMeasureSpec, int heightMeasureSpec){
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);

        height = this.getMeasuredHeight();
        width = this.getMeasuredWidth();

        setMeasuredDimension(width, width);
    }

    protected void onDraw(Canvas canvas) {
        float mDensity = context.getResources().getDisplayMetrics().density;
        float mScaledDensity = context.getResources().getDisplayMetrics().scaledDensity;

        Paint previewPaint = new Paint();
        previewPaint.setColor(0x0C2727);
        previewPaint.setAlpha(200);
        previewPaint.setAntiAlias(true);

        Paint previewTextPaint = new Paint();
        previewTextPaint.setColor(Color.WHITE);
        previewTextPaint.setAntiAlias(true);
        previewTextPaint.setTextSize(90 * mScaledDensity);
        previewTextPaint.setShadowLayer(5, 1, 2, Color.argb(255, 87, 87, 87));

        float previewTextWidth = previewTextPaint.measureText(label);
//        float previewTextHeight = previewTextPaint.descent() - previewTextPaint.ascent();
        RectF previewRect = new RectF(0, 0, width, width);

        canvas.drawRoundRect(previewRect, 5 * mDensity, 5 * mDensity, previewPaint);
        canvas.drawText(label, (width - previewTextWidth)/2, previewRect.top - previewTextPaint.ascent(), previewTextPaint);

        super.onDraw(canvas);
    }

    public void setLabel(String label) {
        this.label = label;
        Log.e(TAG, "Label: " + label);

        this.invalidate();
    }
}

How to center the elements in ConstraintLayout

There is a simpler way. If you set layout constraints as follows and your EditText is fixed sized, it will get centered in the constraint layout:

app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintBottom_toBottomOf="parent"

The left/right pair centers the view horizontally and top/bottom pair centers it vertically. This is because when you set the left, right or top,bottom constraints bigger than the view it self, the view gets centered between the two constraints i.e the bias is set to 50%. You can also move view up/down or right/left by setting the bias your self. Play with it a bit and you will see how it affects the views position.

How to call a PHP function on the click of a button

Here is an example which you could use:

<html>
    <body>
        <form action="btnclick.php" method="get">
            <input type="submit" name="on" value="on">
            <input type="submit" name="off" value="off">
        </form>
    </body>
</html>
<?php
    if(isset($_GET['on'])) {
        onFunc();
    }
    if(isset($_GET['off'])) {
        offFunc();
    }

    function onFunc(){
        echo "Button on Clicked";
    }
    function offFunc(){
        echo "Button off clicked";
    }
?>

How to customize <input type="file">?

Here is a quick pure CSS workaround (works on chrome and has a FireFox fallback included), including the file name,a label and an custom upload button, does what it should - no need of JavaScript at all!

Note: ? This works on Chrome and has a FireFox fallback - anyways, I would not use it on a real world website - if browser compatibility is a thing to you (what it should be). So it's more kind of experimental.

_x000D_
_x000D_
.fileUploadInput {_x000D_
  display: grid;_x000D_
  grid-gap: 10px;_x000D_
  position: relative;_x000D_
  z-index: 1; }_x000D_
  _x000D_
  .fileUploadInput label {_x000D_
    display: flex;_x000D_
    align-items: center;_x000D_
    color: setColor(primary, 0.5);_x000D_
    background: setColor(white);_x000D_
    transition: .4s ease;_x000D_
    font-family: arial, sans-serif;_x000D_
    font-size: .75em;_x000D_
    font-weight: regular; }_x000D_
    _x000D_
  .fileUploadInput input {_x000D_
    position: relative;_x000D_
    z-index: 1;_x000D_
    padding: 0 gap(m);_x000D_
    width: 100%;_x000D_
    height: 50px;_x000D_
    border: 1px solid #323262;_x000D_
    border-radius: 3px;_x000D_
    font-family: arial, sans-serif;_x000D_
    font-size: 1rem;_x000D_
    font-weight: regular; }_x000D_
    .fileUploadInput input[type="file"] {_x000D_
      padding: 0 gap(m); }_x000D_
      .fileUploadInput input[type="file"]::-webkit-file-upload-button {_x000D_
        visibility: hidden;_x000D_
        margin-left: 10px;_x000D_
        padding: 0;_x000D_
        height: 50px;_x000D_
        width: 0; }_x000D_
        _x000D_
  .fileUploadInput button {_x000D_
    position: absolute;_x000D_
    right: 0;_x000D_
    bottom: 0;_x000D_
    width: 50px;_x000D_
    height: 50px;_x000D_
    line-height: 0;_x000D_
    user-select: none;_x000D_
    color: white;_x000D_
    background-color: #323262;_x000D_
    border-radius: 0 3px 3px 0;_x000D_
    font-family: arial, sans-serif;_x000D_
    font-size: 1rem;_x000D_
    font-weight: 800; }_x000D_
    .fileUploadInput button svg {_x000D_
      width: auto;_x000D_
      height: 50%; }_x000D_
_x000D_
* {_x000D_
  margin: 0px;_x000D_
  padding: 0px;_x000D_
  box-sizing: border-box;_x000D_
  border: 0px;_x000D_
  outline: 0;_x000D_
  background-repeat: no-repeat;_x000D_
  appearance: none;_x000D_
  border-radius: 0;_x000D_
  vertical-align: middle;_x000D_
  font-weight: inherit;_x000D_
  font-style: inherit;_x000D_
  font-family: inherit;_x000D_
  text-decoration: none;_x000D_
  list-style: none;_x000D_
  user-select: text;_x000D_
  line-height: 1.333em; }_x000D_
_x000D_
body {_x000D_
  display: flex;_x000D_
  align-items: center;_x000D_
  justify-content: center;_x000D_
  width: 100%;_x000D_
  height: 100vh;_x000D_
  background: rgba(66, 50, 98, 0.05); }_x000D_
_x000D_
.container {_x000D_
  padding: 25px;_x000D_
  box-shadow: 0 0 20px rgba(66, 50, 98, 0.35);_x000D_
  border: 1px solid #eaeaea;_x000D_
  border-radius: 3px;_x000D_
  background: white; }_x000D_
_x000D_
@-moz-document url-prefix() {_x000D_
.fileUploadInput button{_x000D_
    display: none_x000D_
}_x000D_
}
_x000D_
<!-- Author: Ali Soueidan-->_x000D_
<!-- Author URI: https//: www.alisoueidan.com-->_x000D_
_x000D_
<div class="container">_x000D_
    <div class="fileUploadInput">_x000D_
    <label>? Upload File</label>_x000D_
    <input type="file" />_x000D_
    <button>+</button></div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

How do I get Maven to use the correct repositories?

I think what you have missed here is this:

https://maven.apache.org/settings.html#Servers

The repositories for download and deployment are defined by the repositories and distributionManagement elements of the POM. However, certain settings such as username and password should not be distributed along with the pom.xml. This type of information should exist on the build server in the settings.xml.

This is the prefered way of using custom repos. So probably what is happening is that the url of this repo is in settings.xml of the build server.

Once you get hold of the url and credentials, you can put them in your machine here: ~/.m2/settings.xml like this:

<settings ...> 

        .
        .
        .
        <servers>
            <server>
              <id>internal-repository-group</id>
              <username>YOUR-USERNAME-HERE</username>
              <password>YOUR-PASSWORD-HERE</password>
            </server>
        </servers>
</settings>

EDIT:

You then need to refer this repository into project POM. The id internal-repository-group can be used in every project. You can setup multiple repos and credentials setting using different IDs in settings xml.

The advantage of this approach is that project can be shared without worrying about the credentials and don't have to mention the credentials in every project.

Following is a sample pom of a project using "internal-repository-group"

<repositories>
    <repository>
        <id>internal-repository-group</id>
        <name>repo-name</name>
        <url>http://project.com/yourrepourl/</url>
        <layout>default</layout>
        <releases>
            <enabled>true</enabled>
            <updatePolicy>never</updatePolicy>
        </releases>
        <snapshots>
            <enabled>true</enabled>
            <updatePolicy>never</updatePolicy>
        </snapshots>
    </repository>
</repositories>

Is there a standard function to check for null, undefined, or blank variables in JavaScript?

For everyone coming here for having similar question, the following works great and I have it in my library the last years:

(function(g3, $, window, document, undefined){
   g3.utils = g3.utils || {};
/********************************Function type()********************************
* Returns a lowercase string representation of an object's constructor.
* @module {g3.utils}
* @function {g3.utils.type}
* @public
* @param {Type} 'obj' is any type native, host or custom.
* @return {String} Returns a lowercase string representing the object's 
* constructor which is different from word 'object' if they are not custom.
* @reference http://perfectionkills.com/instanceof-considered-harmful-or-how-to-write-a-robust-isarray/
* http://stackoverflow.com/questions/3215046/differentiating-between-arrays-and-hashes-in-javascript
* http://javascript.info/tutorial/type-detection
*******************************************************************************/
g3.utils.type = function (obj){
   if(obj === null)
      return 'null';
   else if(typeof obj === 'undefined')
      return 'undefined';
   return Object.prototype.toString.call(obj).match(/^\[object\s(.*)\]$/)[1].toLowerCase();
};
}(window.g3 = window.g3 || {}, jQuery, window, document));

SQL to Query text in access with an apostrophe in it

You escape ' by doubling it, so:

Select * from tblStudents where name like 'Daniel O''Neal' 

Note that if you're accepting "Daniel O'Neal" from user input, the broken quotation is a serious security issue. You should always sanitize the string or use parametrized queries.

Cassandra port usage - how are the ports used?

8080 - JMX (remote)

8888 - Remote debugger (removed in 0.6.0)

7000 - Used internal by Cassandra
(7001 - Obsolete, removed in 0.6.0. Used for membership communication, aka gossip)

9160 - Thrift client API

Cassandra FAQ What ports does Cassandra use?

TypeError: 'dict' object is not callable

it's number_map[int(x)], you tried to actually call the map with one argument

MySQL: #1075 - Incorrect table definition; autoincrement vs another key?

You can make the id the primary key, and set member_id to NOT NULL UNIQUE. (Which you've done.) Columns that are NOT NULL UNIQUE can be the target of foreign key references, just like a primary key can. (I'm pretty sure that's true of all SQL platforms.)

At the conceptual level, there's no difference between PRIMARY KEY and NOT NULL UNIQUE. At the physical level, this is a MySQL issue; other SQL platforms will let you use a sequence without making it the primary key.

But if performance is really important, you should think twice about widening your table by four bytes per row for that tiny visual convenience. In addition, if you switch to INNODB in order to enforce foreign key constraints, MySQL will use your primary key in a clustered index. Since you're not using your primary key, I imagine that could hurt performance.

jquery change div text

Put the title in its own span.

<span id="dialog_title_span">'+dialog_title+'</span>
$('#dialog_title_span').text("new dialog title");

How do you render primitives as wireframes in OpenGL?

If you are using the fixed pipeline (OpenGL < 3.3) or the compatibility profile you can use

//Turn on wireframe mode
glPolygonMode(GL_FRONT_AND_BACK, GL_LINE);

//Draw the scene with polygons as lines (wireframe)
renderScene();

//Turn off wireframe mode
glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);

In this case you can change the line width by calling glLineWidth

Otherwise you need to change the polygon mode inside your draw method (glDrawElements, glDrawArrays, etc) and you may end up with some rough results because your vertex data is for triangles and you are outputting lines. For best results consider using a Geometry shader or creating new data for the wireframe.

Is it possible to run JavaFX applications on iOS, Android or Windows Phone 8?

Yes you can run JavaFX application on iOS, android, desktop, RaspberryPI (no windows8 mobile yet).

Work in Action :

We did it! JavaFX8 multimedia project on iPad, Android, Windows and Mac!

JavaFX Everywhere

Ensemble8 Javafx8 Android Demo

My Sample JavaFX application Running on Raspberry Pi

My Sample Application Running on Android

JavaFX on iOS and Android

Dev Resources :

Android :

Building and deploying JavaFX Applications on Android

iOS :

NetBeans support for JavaFX for iOS is out!

Develop a JavaFX + iOS app with RoboVM + e(fx)clipse tools in 10 minutes

If you are going to develop serious applications here is some more info

Misc :

At present for JavaFX Oracle priority list is Desktop (Mac,windows,linux) and Embedded (Raspberry Pi, beagle Board etc) .For iOS/android oracle done most of the hardwork and opnesourced javafxports of these platforms as part of OpenJFX ,but there is no JVM from oracle for ios/android.Community is putting all together by filling missing piece(JVM) for ios/android,Community made good progress in running JavaFX on ios (RoboVM) / android(DalvikVM). If you want you can also contribute to the community by sponsoring (Become a RoboVM sponsor) or start developing apps and report issues.

Edit 06/23/2014 :

Johan Vos created a website for javafx ports JavaFX on Mobile and Tablets,check this for updated info ..

Is it possible to run .APK/Android apps on iPad/iPhone devices?

Apple users can download your .apk file, however they cannot run it. It is a different file format than iPhone apps (.ipa)

Use VBA to Clear Immediate Window?

Thanks ProfoundlyOblivious,

No SendKeys, check
No VBA Extensibility, check
No 3rd Party Executables, check
One minor problem:

Localised Office versions use another caption for the immediate window. In Dutch it is named "Direct".
I have added one line to get the localised caption in case FindWindowExA fails. For those who use both the English and Dutch version of MS-Office.

+1 for you for doing most of the work!

Option Explicit

Private Declare PtrSafe Function FindWindowA Lib "user32" (ByVal lpClassName As String, ByVal lpWindowName As String) As LongPtr
Private Declare PtrSafe Function FindWindowExA Lib "user32" (ByVal hWnd1 As LongPtr, ByVal hWnd2 As LongPtr, ByVal lpsz1 As String, ByVal lpsz2 As String) As LongPtr
Private Declare PtrSafe Function PostMessageA Lib "user32" (ByVal hwnd As LongPtr, ByVal wMsg As Long, ByVal wParam As LongPtr, ByVal lParam As LongPtr) As Long
Private Declare PtrSafe Sub keybd_event Lib "user32" (ByVal bVk As Byte, ByVal bScan As Byte, ByVal dwFlags As Long, ByVal dwExtraInfo As LongPtr)

Private Const WM_ACTIVATE As Long = &H6
Private Const KEYEVENTF_KEYUP = &H2
Private Const VK_CONTROL = &H11

Public Sub ClearImmediateWindow()
    Dim hwndVBE As LongPtr
    Dim hwndImmediate As LongPtr
    
    hwndVBE = FindWindowA("wndclass_desked_gsk", vbNullString)
    hwndImmediate = FindWindowExA(hwndVBE, ByVal 0&, "VbaWindow", "Immediate") ' English caption
    If hwndImmediate = 0 Then hwndImmediate = FindWindowExA(hwndVBE, ByVal 0&, "VbaWindow", "Direct") ' Dutch caption
    PostMessageA hwndImmediate, WM_ACTIVATE, 1, 0&
    
    keybd_event VK_CONTROL, 0, 0, 0
    keybd_event vbKeyA, 0, 0, 0
    keybd_event vbKeyA, 0, KEYEVENTF_KEYUP, 0
    keybd_event VK_CONTROL, 0, KEYEVENTF_KEYUP, 0
   
    keybd_event vbKeyDelete, 0, 0, 0
    keybd_event vbKeyDelete, 0, KEYEVENTF_KEYUP, 0
End Sub

Selection with .loc in python

This is using dataframes from the pandas package. The "index" part can be either a single index, a list of indices, or a list of booleans. This can be read about in the documentation: https://pandas.pydata.org/pandas-docs/stable/indexing.html

So the index part specifies a subset of the rows to pull out, and the (optional) column_name specifies the column you want to work with from that subset of the dataframe. So if you want to update the 'class' column but only in rows where the class is currently set as 'versicolor', you might do something like what you list in the question:

iris_data.loc[iris_data['class'] == 'versicolor', 'class'] = 'Iris-versicolor'

Submit a form in a popup, and then close the popup

The Solution on top won't work because a submit redirects the page to the endpoint of form and wait for response to redirect. I see that this is an old Question but Most Asked and even i came to know the answer.Still here is my solution what i am implementing. I tried to keep it secure with Nonce but if you don't care then not required.

Method 1: You need to Pop up the form.

document.getElementById('edit_info_button').addEventListener('click',function(){
        window.open('{% url "updateuserinfo" %}','newwindow', 'width=400,height=600,scrollbars=no');
    });

Then you have the form open.

Submit the form normally.

Then return an HTTPResponse in render to a template(HTML file) With a STRICT Content Security Policy. A Variable that contains the following script. Nonce contains a Base64 128bits or larger randomly generated string for every request made to server.

<script nonce="{{nonce}}">window.close()</script>

Method 2:

Or you can redirect to another Page which is suppose to close ... Which already Contains the window.close() script. This will close the pop up window.

Method 3:

Otherwise the simplest will be Use a Ajax call if you are comfortable with one.Use then() and check your condition to the httpresponse from the server.Close the window when success.

Extracting specific selected columns to new DataFrame as a copy

If you want to have a new data frame then:

import pandas as pd
old = pd.DataFrame({'A' : [4,5], 'B' : [10,20], 'C' : [100,50], 'D' : [-30,-50]})
new=  old[['A', 'C', 'D']]

Regex: Remove lines containing "help", etc

If you're on Windows, try findstr. Third-party tools are not needed:

findstr /V /L "searchstring" inputfile.txt > outputfile.txt

It supports regex's too! Just read the tool's help findstr /?.

P.S. If you want to work with big, huge files (like 400 MB log files) a text editor is not very memory-efficient, so, as someone already pointed out, command-line tools are the way to go. But there's no grep on Windows, so...

I just ran this on a 1 GB log file, and it literally took 3 seconds.

Group dataframe and get sum AND count?

Just in case you were wondering how to rename columns during aggregation, here's how for

pandas >= 0.25: Named Aggregation

df.groupby('Company Name')['Amount'].agg(MySum='sum', MyCount='count')

Or,

df.groupby('Company Name').agg(MySum=('Amount', 'sum'), MyCount=('Amount', 'count'))

                       MySum  MyCount
Company Name                       
Vifor Pharma UK Ltd  4207.93        5

sql - insert into multiple tables in one query

I had the same problem. I solve it with a for loop.

Example:

If I want to write in 2 identical tables, using a loop

for x = 0 to 1

 if x = 0 then TableToWrite = "Table1"
 if x = 1 then TableToWrite = "Table2"
  Sql = "INSERT INTO " & TableToWrite & " VALUES ('1','2','3')"
NEXT

either

ArrTable = ("Table1", "Table2")

for xArrTable = 0 to Ubound(ArrTable)
 Sql = "INSERT INTO " & ArrTable(xArrTable) & " VALUES ('1','2','3')"
NEXT

If you have a small query I don't know if this is the best solution, but if you your query is very big and it is inside a dynamical script with if/else/case conditions this is a good solution.

How to use z-index in svg elements?

You can use use.

<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 160 120">
    <g>
        <g id="one">
            <circle fill="green" cx="100" cy="105" r="20" />
        </g>
        <g id="two">
            <circle fill="orange" cx="100" cy="95" r="20" />
        </g>
    </g>
    <use xlink:href="#one" />
</svg>

The green circle appears on top.
jsFiddle

Maintain aspect ratio of div but fill screen width and height in CSS?

Use the new CSS viewport units vw and vh (viewport width / viewport height)

FIDDLE

Resize vertically and horizontally and you'll see that the element will always fill the maximum viewport size without breaking the ratio and without scrollbars!

(PURE) CSS

div
{
    width: 100vw; 
    height: 56.25vw; /* height:width ratio = 9/16 = .5625  */
    background: pink;
    max-height: 100vh;
    max-width: 177.78vh; /* 16/9 = 1.778 */
    margin: auto;
    position: absolute;
    top:0;bottom:0; /* vertical center */
    left:0;right:0; /* horizontal center */
}

_x000D_
_x000D_
* {_x000D_
  margin: 0;_x000D_
  padding: 0;_x000D_
}_x000D_
div {_x000D_
  width: 100vw;_x000D_
  height: 56.25vw;_x000D_
  /* 100/56.25 = 1.778 */_x000D_
  background: pink;_x000D_
  max-height: 100vh;_x000D_
  max-width: 177.78vh;_x000D_
  /* 16/9 = 1.778 */_x000D_
  margin: auto;_x000D_
  position: absolute;_x000D_
  top: 0;_x000D_
  bottom: 0;_x000D_
  /* vertical center */_x000D_
  left: 0;_x000D_
  right: 0;_x000D_
  /* horizontal center */_x000D_
}
_x000D_
<div></div>
_x000D_
_x000D_
_x000D_

If you want to use a maximum of say 90% width and height of the viewport: FIDDLE

_x000D_
_x000D_
* {_x000D_
  margin: 0;_x000D_
  padding: 0;_x000D_
}_x000D_
div {_x000D_
  width: 90vw;_x000D_
  /* 90% of viewport vidth */_x000D_
  height: 50.625vw;_x000D_
  /* ratio = 9/16 * 90 = 50.625 */_x000D_
  background: pink;_x000D_
  max-height: 90vh;_x000D_
  max-width: 160vh;_x000D_
  /* 16/9 * 90 = 160 */_x000D_
  margin: auto;_x000D_
  position: absolute;_x000D_
  top: 0;_x000D_
  bottom: 0;_x000D_
  left: 0;_x000D_
  right: 0;_x000D_
}
_x000D_
<div></div>
_x000D_
_x000D_
_x000D_

Also, browser support is pretty good too: IE9+, FF, Chrome, Safari- caniuse

In Android, how do I set margins in dp programmatically?

In Kotlin it will look like this:

val layoutParams = (yourView?.layoutParams as? MarginLayoutParams)
layoutParams?.setMargins(40, 40, 40, 40)
yourView?.layoutParams = layoutParams

How to dynamically change header based on AngularJS partial view?

I just discovered a nice way to set your page title if you're using routing:

JavaScript:

var myApp = angular.module('myApp', ['ngResource'])

myApp.config(
    ['$routeProvider', function($routeProvider) {
        $routeProvider.when('/', {
            title: 'Home',
            templateUrl: '/Assets/Views/Home.html',
            controller: 'HomeController'
        });
        $routeProvider.when('/Product/:id', {
            title: 'Product',
            templateUrl: '/Assets/Views/Product.html',
            controller: 'ProductController'
        });
    }]);

myApp.run(['$rootScope', function($rootScope) {
    $rootScope.$on('$routeChangeSuccess', function (event, current, previous) {
        $rootScope.title = current.$$route.title;
    });
}]);

HTML:

<!DOCTYPE html>
<html ng-app="myApp">
<head>
    <title ng-bind="'myApp &mdash; ' + title">myApp</title>
...

Edit: using the ng-bind attribute instead of curlies {{}} so they don't show on load

What is a web service endpoint?

Updated answer, from Peter in comments :

This is de "old terminology", use directally the WSDL2 "endepoint" definition (WSDL2 translated "port" to "endpoint").


Maybe you find an answer in this document : http://www.w3.org/TR/wsdl.html

A WSDL document defines services as collections of network endpoints, or ports. In WSDL, the abstract definition of endpoints and messages is separated from their concrete network deployment or data format bindings. This allows the reuse of abstract definitions: messages, which are abstract descriptions of the data being exchanged, and port types which are abstract collections of operations. The concrete protocol and data format specifications for a particular port type constitutes a reusable binding. A port is defined by associating a network address with a reusable binding, and a collection of ports define a service. Hence, a WSDL document uses the following elements in the definition of network services:

  • Types– a container for data type definitions using some type system (such as XSD).
  • Message– an abstract, typed definition of the data being communicated.
  • Operation– an abstract description of an action supported by the service.
  • Port Type–an abstract set of operations supported by one or more endpoints.
  • Binding– a concrete protocol and data format specification for a particular port type.
  • Port– a single endpoint defined as a combination of a binding and a network address.
  • Service– a collection of related endpoints.

http://www.ehow.com/info_12212371_definition-service-endpoint.html

The endpoint is a connection point where HTML files or active server pages are exposed. Endpoints provide information needed to address a Web service endpoint. The endpoint provides a reference or specification that is used to define a group or family of message addressing properties and give end-to-end message characteristics, such as references for the source and destination of endpoints, and the identity of messages to allow for uniform addressing of "independent" messages. The endpoint can be a PC, PDA, or point-of-sale terminal.

Cosine Similarity between 2 Number Lists

I don't suppose performance matters much here, but I can't resist. The zip() function completely recopies both vectors (more of a matrix transpose, actually) just to get the data in "Pythonic" order. It would be interesting to time the nuts-and-bolts implementation:

import math
def cosine_similarity(v1,v2):
    "compute cosine similarity of v1 to v2: (v1 dot v2)/{||v1||*||v2||)"
    sumxx, sumxy, sumyy = 0, 0, 0
    for i in range(len(v1)):
        x = v1[i]; y = v2[i]
        sumxx += x*x
        sumyy += y*y
        sumxy += x*y
    return sumxy/math.sqrt(sumxx*sumyy)

v1,v2 = [3, 45, 7, 2], [2, 54, 13, 15]
print(v1, v2, cosine_similarity(v1,v2))

Output: [3, 45, 7, 2] [2, 54, 13, 15] 0.972284251712

That goes through the C-like noise of extracting elements one-at-a-time, but does no bulk array copying and gets everything important done in a single for loop, and uses a single square root.

ETA: Updated print call to be a function. (The original was Python 2.7, not 3.3. The current runs under Python 2.7 with a from __future__ import print_function statement.) The output is the same, either way.

CPYthon 2.7.3 on 3.0GHz Core 2 Duo:

>>> timeit.timeit("cosine_similarity(v1,v2)",setup="from __main__ import cosine_similarity, v1, v2")
2.4261788514654654
>>> timeit.timeit("cosine_measure(v1,v2)",setup="from __main__ import cosine_measure, v1, v2")
8.794677709375264

So, the unpythonic way is about 3.6 times faster in this case.

SQL Server Creating a temp table for this query

DECLARE #MyTempTable TABLE (SiteName varchar(50), BillingMonth varchar(10), Consumption float)

INSERT INTO #MyTempTable (SiteName, BillingMonth, Consumption)
SELECT  tblMEP_Sites.Name AS SiteName, convert(varchar(10),BillingMonth ,101) AS BillingMonth, SUM(Consumption) AS Consumption
FROM tblMEP_Projects.......  --your joining statements

Here, # - use this to create table inside tempdb
@ - use this to create table as variable.

How do you cast a List of supertypes to a List of subtypes?

class MyClass {
  String field;

  MyClass(String field) {
    this.field = field;
  }
}

@Test
public void testTypeCast() {
  List<Object> objectList = Arrays.asList(new MyClass("1"), new MyClass("2"));

  Class<MyClass> clazz = MyClass.class;
  List<MyClass> myClassList = objectList.stream()
      .map(clazz::cast)
      .collect(Collectors.toList());

  assertEquals(objectList.size(), myClassList.size());
  assertEquals(objectList, myClassList);
}

This test shows how to cast List<Object> to List<MyClass>. But you need to take an attention to that objectList must contain instances of the same type as MyClass. And this example can be considered when List<T> is used. For this purpose get field Class<T> clazz in constructor and use it instead of MyClass.class.

How can I perform an inspect element in Chrome on my Galaxy S3 Android device?

Update: 8-20-2015

Please note the instructions have changed since this question was asked 2 yrs ago.

So on Newer versions of Android and Chrome for Android. You need to use this.

https://developers.google.com/web/tools/setup/remote-debugging/remote-debugging?hl=en

Original Answer:

I have the S3 and it works fine. I have found that a common mistake is not enabling USB Debugging in Chrome mobile. Not only do you have to enable USB debugging on the device itself under developer options but you have to go to the Chrome Browser on your phone and enable it in the settings there too.

Try this with the SDK

  1. Chrome for Mobile - Settings > Developer Tools > [x] Enable USB Web debugging
  2. Device - Settings > Developer options > [x] USB debugging
  3. Connect Device to Computer
  4. Enable port forwarding on your computer by doing the following command below

    C:\adb forward tcp:9222 localabstract:chrome_devtools_remote

Go to http://localhost:9222 in Chrome on your Computer

TroubleShooting:

If you get command not found when trying to run ADB, make sure Platform-Tools is in your path or just use the whole path to your SDK and run it

C:\path-to-SDK\platform-tools\adb forward tcp:9222 localabstract:chrome_devtools_remote

If you get "device not found", then run adb kill-server and then try again.