Programs & Examples On #Lvm

lvm (logical volume manager) is a software that allows disk partitionning by hiding the physical limitations of the underlying disks. It can make logical partitions from separate physical partitions even on separate disks, hide mirroring, allow increasing the size of a logical volume while used and so on

resize2fs: Bad magic number in super-block while trying to open

os: rhel7

After gparted, # xfs_growfs /dev/mapper/rhel-root did the trick on a living system.

$ df -h
Filesystem             Size  Used Avail Use% Mounted on
/dev/mapper/rhel-root   47G   47G   20M 100% /
devtmpfs               1.9G     0  1.9G   0% /dev
tmpfs                  1.9G     0  1.9G   0% /dev/shm
tmpfs                  1.9G  9.3M  1.9G   1% /run
tmpfs                  1.9G     0  1.9G   0% /sys/fs/cgroup
/dev/sda1             1014M  205M  810M  21% /boot
tmpfs                  379M  8.0K  379M   1% /run/user/42
tmpfs                  379M     0  379M   0% /run/user/1000


# lvresize -l +100%FREE /dev/mapper/rhel-root
  Size of logical volume rhel/root changed from <47.00 GiB (12031 extents) to <77.00 GiB (19711 extents).
  Logical volume rhel/root successfully resized.


# xfs_growfs /dev/mapper/rhel-root
meta-data=/dev/mapper/rhel-root  isize=512    agcount=7, agsize=1900032 blks
         =                       sectsz=512   attr=2, projid32bit=1
         =                       crc=1        finobt=0 spinodes=0
data     =                       bsize=4096   blocks=12319744, imaxpct=25
         =                       sunit=0      swidth=0 blks
naming   =version 2              bsize=4096   ascii-ci=0 ftype=1
log      =internal               bsize=4096   blocks=3711, version=2
         =                       sectsz=512   sunit=0 blks, lazy-count=1
realtime =none                   extsz=4096   blocks=0, rtextents=0
data blocks changed from 12319744 to 20184064


# df -h
Filesystem             Size  Used Avail Use% Mounted on
/dev/mapper/rhel-root   77G   47G   31G  62% /
devtmpfs               1.9G     0  1.9G   0% /dev
tmpfs                  1.9G     0  1.9G   0% /dev/shm
tmpfs                  1.9G  9.3M  1.9G   1% /run
tmpfs                  1.9G     0  1.9G   0% /sys/fs/cgroup
/dev/sda1             1014M  205M  810M  21% /boot
tmpfs                  379M  8.0K  379M   1% /run/user/42
tmpfs                  379M     0  379M   0% /run/user/1000

header('HTTP/1.0 404 Not Found'); not doing anything

After writing

header('HTTP/1.0 404 Not Found');

add one more header for any inexisting page on your site. It works, for sure.

header("Location: http://yoursite/nowhere");
die;

Android Min SDK Version vs. Target SDK Version

If you get some compile errors for example:

<uses-sdk
            android:minSdkVersion="10"
            android:targetSdkVersion="15" />

.

private void methodThatRequiresAPI11() {
        BitmapFactory.Options options = new BitmapFactory.Options();
                options.inPreferredConfig = Config.ARGB_8888;  // API Level 1          
                options.inSampleSize = 8;    // API Level 1
                options.inBitmap = bitmap;   // **API Level 11**
        //...
    }

You get compile error:

Field requires API level 11 (current min is 10): android.graphics.BitmapFactory$Options#inBitmap

Since version 17 of Android Development Tools (ADT) there is one new and very useful annotation @TargetApi that can fix this very easily. Add it before the method that is enclosing the problematic declaration:

@TargetApi
private void methodThatRequiresAPI11() {            
  BitmapFactory.Options options = new BitmapFactory.Options();
      options.inPreferredConfig = Config.ARGB_8888;  // API Level 1          
      options.inSampleSize = 8;    // API Level 1

      // This will avoid exception NoSuchFieldError (or NoSuchMethodError) at runtime. 
      if (Integer.valueOf(android.os.Build.VERSION.SDK) >= android.os.Build.VERSION_CODES.HONEYCOMB) {
        options.inBitmap = bitmap;   // **API Level 11**
            //...
      }
    }

No compile errors now and it will run !

EDIT: This will result in runtime error on API level lower than 11. On 11 or higher it will run without problems. So you must be sure you call this method on an execution path guarded by version check. TargetApi just allows you to compile it but you run it on your own risk.

Appending a byte[] to the end of another byte[]

The other provided solutions are great when you want to add only 2 byte arrays, but if you want to keep appending several byte[] chunks to make a single:

byte[] readBytes ; // Your byte array .... //for eg. readBytes = "TestBytes".getBytes();

ByteArrayBuffer mReadBuffer = new ByteArrayBuffer(0 ) ; // Instead of 0, if you know the count of expected number of bytes, nice to input here

mReadBuffer.append(readBytes, 0, readBytes.length); // this copies all bytes from readBytes byte array into mReadBuffer
// Any new entry of readBytes, you can just append here by repeating the same call.

// Finally, if you want the result into byte[] form:
byte[] result = mReadBuffer.buffer();

Hide element by class in pure Javascript

var appBanners = document.getElementsByClassName('appBanner');

for (var i = 0; i < appBanners.length; i ++) {
    appBanners[i].style.display = 'none';
}

JSFiddle.

Ruby String to Date Conversion

What is wrong with Date.parse method?

str = "Tue, 10 Aug 2010 01:20:19 -0400 (EDT)"
date = Date.parse str
=> #<Date: 4910837/2,0,2299161>
puts date
2010-08-10

It seems to work.

The only problem here is time zone. If you want date in UTC time zone, then it is better to use Time object, suppose we have string:

str = "Tue, 10 Aug 2010 01:20:19 +0400"
puts Date.parse str
2010-08-10
puts Date.parse(Time.parse(str).utc.to_s)
2010-08-09

I couldn't find simpler method to convert Time to Date.

How do I get rid of the "cannot empty the clipboard" error?

Good answers by Paul Simon and Steve Homer, I shut down team viewer and that did the trick. Skype or other programs may trigger the same glitch, but in this instance, I recalled the problem occurred when I tried to cut n paste a 2MB file from remote system through windows right click rather than using "File Transfer function in TV. An error message appeared, then the problem with Excel "'Cannot empty clipboard' message.

This problem occurs when you are working on a remote system. After copying and pasting a huge amount of data it shows the error. I have found the solution to this problem.

Go to remote systems task manager and perform the following task

Go to Task Manager > Processes Look for "rdpclip.exe" End that process

Your problem will be solved.

Completely cancel a rebase

If you are "Rebasing", "Already started rebase" which you want to cancel, just comment (#) all commits listed in rebase editor.

As a result you will get a command line message

Nothing to do

What is the difference between UTF-8 and ISO-8859-1?

  • ASCII: 7 bits. 128 code points.

  • ISO-8859-1: 8 bits. 256 code points.

  • UTF-8: 8-32 bits (1-4 bytes). 1,112,064 code points.

Both ISO-8859-1 and UTF-8 are backwards compatible with ASCII, but UTF-8 is not backwards compatible with ISO-8859-1:

#!/usr/bin/env python3

c = chr(0xa9)
print(c)
print(c.encode('utf-8'))
print(c.encode('iso-8859-1'))

Output:

©
b'\xc2\xa9'
b'\xa9'

Does .NET provide an easy way convert bytes to KB, MB, GB, etc.?

I use this for Windows (binary prefixes):

static readonly string[] BinaryPrefix = { "bytes", "KB", "MB", "GB", "TB" }; // , "PB", "EB", "ZB", "YB"
string GetMemoryString(double bytes)
{
    int counter = 0;
    double value = bytes;
    string text = "";
    do
    {
        text = value.ToString("0.0") + " " + BinaryPrefix[counter];
        value /= 1024;
        counter++;
    }
    while (Math.Floor(value) > 0 && counter < BinaryPrefix.Length);
    return text;
}

HTTP 404 Page Not Found in Web Api hosted in IIS 7.5

This is the only answer that worked for me...

I had a similar issue... It seemed like no matter what I did, nothing was getting redirected and my global file was just being ignored. I seriously considered just ending it all before I found this answer. I hope this link helps somebody else.


Adding the following to the web.config file worked for me:

<system.webServer>
  <modules>
    <remove name="UrlRoutingModule-4.0" />
    <add name="UrlRoutingModule-4.0" type="System.Web.Routing.UrlRoutingModule" preCondition="" />
  </modules>
</system.webServer>

system.webServer tag was already there of course but I added the modules tag to it and then the remove & add tags to modules tag.

Callback after all asynchronous forEach callbacks are completed

How about setInterval, to check for complete iteration count, brings guarantee. not sure if it won't overload the scope though but I use it and seems to be the one

_.forEach(actual_JSON, function (key, value) {

     // run any action and push with each iteration 

     array.push(response.id)

});


setInterval(function(){

    if(array.length > 300) {

        callback()

    }

}, 100);

How to SELECT the last 10 rows of an SQL table which has no ID field?

Select from the table, use the ORDER BY __ DESC to sort in reverse order, then limit your results to 10.

SELECT * FROM big_table ORDER BY A DESC LIMIT 10

Convert UTC Epoch to local date

To convert the current epoch time in [ms] to a 24-hour time. You might need to specify the option to disable 12-hour format.

$ node.exe -e "var date = new Date(Date.now()); console.log(date.toLocaleString('en-GB', { hour12:false } ));"

2/7/2018, 19:35:24

or as JS:

var date = new Date(Date.now()); 
console.log(date.toLocaleString('en-GB', { hour12:false } ));
// 2/7/2018, 19:35:24

console.log(date.toLocaleString('en-GB', { hour:'numeric', minute:'numeric', second:'numeric', hour12:false } ));
// 19:35:24

Note: The use of en-GB here, is just a (random) choice of a place using the 24 hour format, it is not your timezone!

How to print a Groovy variable in Jenkins?

The following code worked for me:

echo userInput

How to handle login pop up window using Selenium WebDriver?

Simply switch to alert and use authenticateUsing to set usename and password and then comeback to parent window

Alert Windowalert = driver.switchTo().alert() ;
Windowalert.authenticateUsing(new UserAndPassword(_user_name,_password));
driver.switchTo().defaultContent() ; 

Can an ASP.NET MVC controller return an Image?

if (!System.IO.File.Exists(filePath))
    return SomeHelper.EmptyImageResult(); // preventing JSON GET/POST exception
else
    return new FilePathResult(filePath, contentType);

SomeHelper.EmptyImageResult() should return FileResult with existing image (1x1 transparent, for example).

This is easiest way if you have files stored on local drive. If files are byte[] or stream - then use FileContentResult or FileStreamResult as Dylan suggested.

WebSockets vs. Server-Sent events/EventSource

One thing to note:
I have had issues with websockets and corporate firewalls. (Using HTTPS helps but not always.)

See https://github.com/LearnBoost/socket.io/wiki/Socket.IO-and-firewall-software https://github.com/sockjs/sockjs-client/issues/94

I assume there aren't as many issues with Server-Sent Events. But I don't know.

That said, WebSockets are tons of fun. I have a little web game that uses websockets (via Socket.IO) (http://minibman.com)

UnicodeDecodeError: 'ascii' codec can't decode byte 0xe2 in position 13: ordinal not in range(128)

Use open(fn, 'rb').read().decode('utf-8') instead of just open(fn).read()

Can I pass column name as input parameter in SQL stored Procedure

First Run;

CREATE PROCEDURE sp_First @columnname NVARCHAR(128)--128 = SQL Server Maximum Column Name Length
AS
BEGIN

    DECLARE @query NVARCHAR(MAX)

    SET @query = 'SELECT ' + @columnname + ' FROM Table_1'

    EXEC(@query)

END

Second Run;

EXEC sp_First 'COLUMN_Name'

How to use '-prune' option of 'find' in sh?

Adding to the advice given in other answers (I have no rep to create replies)...

When combining -prune with other expressions, there is a subtle difference in behavior depending on which other expressions are used.

@Laurence Gonsalves' example will find the "*.foo" files that aren't under ".snapshot" directories:-

find . -name .snapshot -prune -o -name '*.foo' -print

However, this slightly different short-hand will, perhaps inadvertently, also list the .snapshot directory (and any nested .snapshot directories):-

find . -name .snapshot -prune -o -name '*.foo'

The reason is (according to the manpage on my system):-

If the given expression does not contain any of the primaries -exec, -ls, -ok, or -print, the given expression is effectively replaced by:

( given_expression ) -print

That is, the second example is the equivalent of entering the following, thereby modifying the grouping of terms:-

find . \( -name .snapshot -prune -o -name '*.foo' \) -print

This has at least been seen on Solaris 5.10. Having used various flavors of *nix for approx 10 years, I've only recently searched for a reason why this occurs.

Property 'value' does not exist on type 'Readonly<{}>'

interface MyProps {
  ...
}

interface MyState {
  value: string
}

class App extends React.Component<MyProps, MyState> {
  ...
}

// Or with hooks, something like

const App = ({}: MyProps) => {
  const [value, setValue] = useState<string>('');
  ...
};

type's are fine too like in @nitzan-tomer's answer, as long as you're consistent.

How do I get current date/time on the Windows command line in a suitable format for usage in a file/folder name?

See Windows Batch File (.bat) to get current date in MMDDYYYY format:

@echo off
For /f "tokens=2-4 delims=/ " %%a in ('date /t') do (set mydate=%%c-%%a-%%b)
For /f "tokens=1-2 delims=/:" %%a in ('time /t') do (set mytime=%%a%%b)
echo %mydate%_%mytime%

If you prefer the time in 24 hour/military format, you can replace the second FOR line with this:

For /f "tokens=1-2 delims=/:" %%a in ("%TIME%") do (set mytime=%%a%%b)

C:> .\date.bat
2008-10-14_0642

If you want the date independently of the region day/month order, you can use "WMIC os GET LocalDateTime" as a source, since it's in ISO order:

@echo off
for /F "usebackq tokens=1,2 delims==" %%i in (`wmic os get LocalDateTime /VALUE 2^>NUL`) do if '.%%i.'=='.LocalDateTime.' set ldt=%%j
set ldt=%ldt:~0,4%-%ldt:~4,2%-%ldt:~6,2% %ldt:~8,2%:%ldt:~10,2%:%ldt:~12,6%
echo Local date is [%ldt%]

C:>test.cmd
Local date is [2012-06-19 10:23:47.048]

"405 method not allowed" in IIS7.5 for "PUT" method

For me this error wouldn't go away and allow PUT methods, whatever i did.. uninstalled webdav, put configuration in web.config to remove webdav from handlers and modules, and set up PUT as an allowed verb on the request filters on iis.. and ensure iis handler mappings handling the request had PUT configured..

My problem was eventually due to bad installation of ASP.NET 4.5 Extensions. Removed everything related to asp.net from server roles and features. restarted. readded the roles and restarted. everything worked with above config.

--- The below will make PUT be accepted, but will send it to the wrong handler. --ignore the below

finally, adding PUT verb as allowed verb on TRACE handler mapping on iis worked.. since i had enabled failed error tracing, and this verb was not allowing the verb.

last time i had the same problem on another server's IIS, it was due to a missing '/' at the end of the URL since it was using a default handler without using the default document probably and now i realize that.. so check IIS handler mappings if nothing else helps.

How can I add new keys to a dictionary?

You can create one:

class myDict(dict):

    def __init__(self):
        self = dict()

    def add(self, key, value):
        self[key] = value

## example

myd = myDict()
myd.add('apples',6)
myd.add('bananas',3)
print(myd)

Gives:

>>> 
{'apples': 6, 'bananas': 3}

SQL Server 2008 Row Insert and Update timestamps

try

CREATE TABLE [dbo].[Names]
(
    [Name] [nvarchar](64) NOT NULL,
    [CreateTS] [smalldatetime] NOT NULL CONSTRAINT CreateTS_DF DEFAULT CURRENT_TIMESTAMP,
    [UpdateTS] [smalldatetime] NOT NULL

)

PS I think a smalldatetime is good enough. You may decide differently.

Can you not do this at the "moment of impact" ?

In Sql Server, this is common:

Update dbo.MyTable 
Set 

ColA = @SomeValue , 
UpdateDS = CURRENT_TIMESTAMP
Where...........

Sql Server has a "timestamp" datatype.

But it may not be what you think.

Here is a reference:

http://msdn.microsoft.com/en-us/library/ms182776(v=sql.90).aspx

Here is a little RowVersion (synonym for timestamp) example:

CREATE TABLE [dbo].[Names]
(
    [Name] [nvarchar](64) NOT NULL,
    RowVers rowversion ,
    [CreateTS] [datetime] NOT NULL CONSTRAINT CreateTS_DF DEFAULT CURRENT_TIMESTAMP,
    [UpdateTS] [datetime] NOT NULL

)


INSERT INTO dbo.Names (Name,UpdateTS)
select 'John' , CURRENT_TIMESTAMP
UNION ALL select 'Mary' , CURRENT_TIMESTAMP
UNION ALL select 'Paul' , CURRENT_TIMESTAMP

select *  ,  ConvertedRowVers = CONVERT(bigint,RowVers) from [dbo].[Names]

Update dbo.Names Set Name = Name

select *  ,  ConvertedRowVers = CONVERT(bigint,RowVers) from [dbo].[Names]

Maybe a complete working example:

DROP TABLE [dbo].[Names]
GO


CREATE TABLE [dbo].[Names]
(
    [Name] [nvarchar](64) NOT NULL,
    RowVers rowversion ,
    [CreateTS] [datetime] NOT NULL CONSTRAINT CreateTS_DF DEFAULT CURRENT_TIMESTAMP,
    [UpdateTS] [datetime] NOT NULL

)

GO

CREATE TRIGGER dbo.trgKeepUpdateDateInSync_ByeByeBye ON dbo.Names
AFTER INSERT, UPDATE
AS

BEGIN

Update dbo.Names Set UpdateTS = CURRENT_TIMESTAMP from dbo.Names myAlias , inserted triggerInsertedTable where 
triggerInsertedTable.Name = myAlias.Name

END


GO






INSERT INTO dbo.Names (Name,UpdateTS)
select 'John' , CURRENT_TIMESTAMP
UNION ALL select 'Mary' , CURRENT_TIMESTAMP
UNION ALL select 'Paul' , CURRENT_TIMESTAMP

select *  ,  ConvertedRowVers = CONVERT(bigint,RowVers) from [dbo].[Names]

Update dbo.Names Set Name = Name , UpdateTS = '03/03/2003' /* notice that even though I set it to 2003, the trigger takes over */

select *  ,  ConvertedRowVers = CONVERT(bigint,RowVers) from [dbo].[Names]

Matching on the "Name" value is probably not wise.

Try this more mainstream example with a SurrogateKey

DROP TABLE [dbo].[Names]
GO


CREATE TABLE [dbo].[Names]
(
    SurrogateKey int not null Primary Key Identity (1001,1),
    [Name] [nvarchar](64) NOT NULL,
    RowVers rowversion ,
    [CreateTS] [datetime] NOT NULL CONSTRAINT CreateTS_DF DEFAULT CURRENT_TIMESTAMP,
    [UpdateTS] [datetime] NOT NULL

)

GO

CREATE TRIGGER dbo.trgKeepUpdateDateInSync_ByeByeBye ON dbo.Names
AFTER UPDATE
AS

BEGIN

   UPDATE dbo.Names
    SET UpdateTS = CURRENT_TIMESTAMP
    From  dbo.Names myAlias
    WHERE exists ( select null from inserted triggerInsertedTable where myAlias.SurrogateKey = triggerInsertedTable.SurrogateKey)

END


GO






INSERT INTO dbo.Names (Name,UpdateTS)
select 'John' , CURRENT_TIMESTAMP
UNION ALL select 'Mary' , CURRENT_TIMESTAMP
UNION ALL select 'Paul' , CURRENT_TIMESTAMP

select *  ,  ConvertedRowVers = CONVERT(bigint,RowVers) from [dbo].[Names]

Update dbo.Names Set Name = Name , UpdateTS = '03/03/2003' /* notice that even though I set it to 2003, the trigger takes over */

select *  ,  ConvertedRowVers = CONVERT(bigint,RowVers) from [dbo].[Names]

Infinite Recursion with Jackson JSON and Hibernate JPA issue

For some reason, in my case, it wasn't working with Set. I had to change it to List and use @JsonIgnore and @ToString.Exclude to get it working.

Replace Set with List:

//before
@OneToMany(mappedBy="client")
private Set<address> addressess;

//after
@OneToMany(mappedBy="client")
private List<address> addressess;

And add @JsonIgnore and @ToString.Exclude annotations:

@ManyToOne
@JoinColumn(name="client_id", nullable = false)
@JsonIgnore
@ToString.Exclude
private Client client;

Using ConfigurationManager to load config from an arbitrary location

In addition to Ishmaeel's answer, the method OpenMappedMachineConfiguration() will always return a Configuration object. So to check to see if it loaded you should check the HasFile property where true means it came from a file.

How to align an image dead center with bootstrap

You could use the following. It supports Bootstrap 3.x above.

<img src="..." alt="..." class="img-responsive center-block" />

How to move from one fragment to another fragment on click of an ImageView in Android?

When you are inside an activity and need to go to a fragment use below

getFragmentManager().beginTransaction().replace(R.id.*TO_BE_REPLACED_LAYOUT_ID*, new tasks()).commit();

But when you are inside a fragment and need to go to a fragment then just add a getActivity(). before, so it would become

getActivity().getFragmentManager().beginTransaction().replace(R.id.*TO_BE_REPLACED_LAYOUT_ID*, new tasks()).commit();

as simple as that.

The *TO_BE_REPLACED_LAYOUT_ID* can be the entire page of activity or a part of it, just make sure to put an id to the layout to be replaced. It is general practice to put the replaceable layout in a FrameLayout .

Parsing PDF files (especially with tables) with PDFBox

Try using TabulaPDF (https://github.com/tabulapdf/tabula) . This is very good library to extract table content from the PDF file. It is very as expected.

Good luck. :)

Edit a commit message in SourceTree Windows (already pushed to remote)

On Version 1.9.6.1. For UnPushed commit.

  1. Click on previously committed description
  2. Click Commit icon
  3. Enter new commit message, and choose "Ammend latest commit" from the Commit options dropdown.
  4. Commit your message.

Why does C# XmlDocument.LoadXml(string) fail when an XML header is included?

I figured it out. Read the MSDN documentation and it says to use .Load instead of LoadXml when reading from strings. Found out this works 100% of time. Oddly enough using StringReader causes problems. I think the main reason is that this is a Unicode encoded string and that could cause problems because StringReader is UTF-8 only.

MemoryStream stream = new MemoryStream();
            byte[] data = body.PayloadEncoding.GetBytes(body.Payload);
            stream.Write(data, 0, data.Length);
            stream.Seek(0, SeekOrigin.Begin);

            XmlTextReader reader = new XmlTextReader(stream);

            // MSDN reccomends we use Load instead of LoadXml when using in memory XML payloads
            bodyDoc.Load(reader);

Difference of two date time in sql server

Check DateDiff out on Books Online.

Is it possible to move/rename files in Git and maintain their history?

I followed this multi-step process to move code to the parent directory and retained history.

Step 0: Created a branch 'history' from 'master' for safekeeping

Step 1: Used git-filter-repo tool to rewrite history. This command below moved folder 'FolderwithContentOfInterest' to one level up and modified the relevant commit history

git filter-repo --path-rename ParentFolder/FolderwithContentOfInterest/:FolderwithContentOfInterest/ --force

Step 2: By this time the GitHub repository lost its remote repository path. Added remote reference

git remote add origin [email protected]:MyCompany/MyRepo.git

Step 3: Pull information on repository

git pull

Step 4: Connect the local lost branch with the origin branch

git branch --set-upstream-to=origin/history history

Step 5: Address merge conflict for the folder structure if prompted

Step 6: Push!!

git push

Note: The modified history and moved folder appear to already be committed. enter code here

Done. Code moves to the parent / desired directory keeping history intact!

Can I add an image to an ASP.NET button?

Assuming a Css class of "image" :

input.image { 
  background: url(/i/bg.png) no-repeat top left; 
  width: /* img-width */; 
  height: /* img-height */ 
}

If you don't know what the image width and height are, you can set this dynamically with javascript.

SQL- Ignore case while searching for a string

You should probably use SQL_Latin1_General_Cp1_CI_AS_KI_WI as your collation. The one you specify in your question is explictly case sensitive.

You can see a list of collations here.

CHECK constraint in MySQL is not working

As mentioned by joanq MariaDB now seems to support CHECK constraints among other goodies:

"Support for CHECK CONSTRAINT (MDEV-7563)."

https://mariadb.com/kb/en/mariadb/mariadb-1021-release-notes/

Capturing standard out and error with Start-Process

To get both stdout and stderr, I use:

Function GetProgramOutput([string]$exe, [string]$arguments)
{
    $process = New-Object -TypeName System.Diagnostics.Process
    $process.StartInfo.FileName = $exe
    $process.StartInfo.Arguments = $arguments

    $process.StartInfo.UseShellExecute = $false
    $process.StartInfo.RedirectStandardOutput = $true
    $process.StartInfo.RedirectStandardError = $true
    $process.Start()

    $output = $process.StandardOutput.ReadToEnd()   
    $err = $process.StandardError.ReadToEnd()

    $process.WaitForExit()

    $output
    $err
}

$exe = "cmd"
$arguments = '/c echo hello 1>&2'   #this writes 'hello' to stderr

$runResult = (GetProgramOutput $exe $arguments)
$stdout = $runResult[-2]
$stderr = $runResult[-1]

[System.Console]::WriteLine("Standard out: " + $stdout)
[System.Console]::WriteLine("Standard error: " + $stderr)

Selenium WebDriver: Wait for complex page with JavaScript to load

I asked my developers to create a JavaScript variable "isProcessing" that I can access (in the "ae" object) that they set when things start running and clear when things are done. I then run it in an accumulator that checks it every 100 ms until it gets five in a row for a total of 500 ms without any changes. If 30 seconds pass, I throw an exception because something should have happened by then. This is in C#.

public static void WaitForDocumentReady(this IWebDriver driver)
{
    Console.WriteLine("Waiting for five instances of document.readyState returning 'complete' at 100ms intervals.");
    IJavaScriptExecutor jse = (IJavaScriptExecutor)driver;
    int i = 0; // Count of (document.readyState === complete) && (ae.isProcessing === false)
    int j = 0; // Count of iterations in the while() loop.
    int k = 0; // Count of times i was reset to 0.
    bool readyState = false;
    while (i < 5)
    {
        System.Threading.Thread.Sleep(100);
        readyState = (bool)jse.ExecuteScript("return ((document.readyState === 'complete') && (ae.isProcessing === false))");
        if (readyState) { i++; }
        else
        {
            i = 0;
            k++;
        }
        j++;
        if (j > 300) { throw new TimeoutException("Timeout waiting for document.readyState to be complete."); }
    }
    j *= 100;
    Console.WriteLine("Waited " + j.ToString() + " milliseconds. There were " + k + " resets.");
}

C convert floating point to int

Good guestion! -- where I have not yet found a satisfying answer for my case, the answer I provide here works for me, but may not be future proof...

If one uses gcc (clang?) and have -Werror and -Wbad-function-cast defined,

int val = (int)pow(10,9);

will result:

error: cast from function call of type 'double' to non-matching type 'int' [-Werror=bad-function-cast]

(for a good reason, overflow and where values are rounded needs to be thought out)

EDIT: 2020-08-30: So, my use case casting the value from function returning double to int, and chose pow() to represent that in place of a private function somewhere. Then I sidestepped thinking pow() more. (See comments more why pow() used below could be problematic...).

After properly thought out (that parameters to pow() are good), int val = pow(10,9); seems to work with gcc 9.2 x86-64 ...

but note:

printf("%d\n", pow(10,4));

may output e.g.

-1121380856

(did for me) where

int i = pow(10,4); printf("%d\n", i);

printed

10000

in one particular case I tried.

How do I call REST API from an android app?

  1. If you want to integrate Retrofit (all steps defined here):

Goto my blog : retrofit with kotlin

  1. Please use android-async-http library.

the link below explains everything step by step.

http://loopj.com/android-async-http/

Here are sample apps:

  1. http://www.techrepublic.com/blog/software-engineer/calling-restful-services-from-your-android-app/

  2. http://blog.strikeiron.com/bid/73189/Integrate-a-REST-API-into-Android-Application-in-less-than-15-minutes

Create a class :

public class HttpUtils {
  private static final String BASE_URL = "http://api.twitter.com/1/";
 
  private static AsyncHttpClient client = new AsyncHttpClient();

  public static void get(String url, RequestParams params, AsyncHttpResponseHandler responseHandler) {
      client.get(getAbsoluteUrl(url), params, responseHandler);
  }

  public static void post(String url, RequestParams params, AsyncHttpResponseHandler responseHandler) {
      client.post(getAbsoluteUrl(url), params, responseHandler);
  }
      
  public static void getByUrl(String url, RequestParams params, AsyncHttpResponseHandler responseHandler) {
      client.get(url, params, responseHandler);
  }

  public static void postByUrl(String url, RequestParams params, AsyncHttpResponseHandler responseHandler) {
      client.post(url, params, responseHandler);
  }

  private static String getAbsoluteUrl(String relativeUrl) {
      return BASE_URL + relativeUrl;
  }
}

Call Method :

    RequestParams rp = new RequestParams();
    rp.add("username", "aaa"); rp.add("password", "aaa@123");
                    
    HttpUtils.post(AppConstant.URL_FEED, rp, new JsonHttpResponseHandler() {
        @Override
        public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
            // If the response is JSONObject instead of expected JSONArray
            Log.d("asd", "---------------- this is response : " + response);
            try {
                JSONObject serverResp = new JSONObject(response.toString());                                                
            } catch (JSONException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }                   
        }
            
        @Override
        public void onSuccess(int statusCode, Header[] headers, JSONArray timeline) {
            // Pull out the first event on the public timeline
                    
        }
    });

Please grant internet permission in your manifest file.

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

you can add compile 'com.loopj.android:android-async-http:1.4.9' for Header[] and compile 'org.json:json:20160212' for JSONObject in build.gradle file if required.

Android Imagebutton change Image OnClick

This misled me a bit - it should be setImageResource instead of setBackgroundResource :) !!

The following works fine :

ImageButton btn = (ImageButton)findViewById(R.id.imageButton1);       
 btn.setImageResource(R.drawable.actions_record);

while when using the setBackgroundResource the actual imagebutton's image stays while the background image is changed which leads to a ugly looking imageButton object

Thanks.

Easiest way to compare arrays in C#

For unit tests, you can use CollectionAssert.AreEqual instead of Assert.AreEqual.

It is probably the easiest way.

How do I use .woff fonts for my website?

After generation of woff files, you have to define font-family, which can be used later in all your css styles. Below is the code to define font families (for normal, bold, bold-italic, italic) typefaces. It is assumed, that there are 4 *.woff files (for mentioned typefaces), placed in fonts subdirectory.

In CSS code:

@font-face {
    font-family: "myfont";
    src: url("fonts/awesome-font.woff") format('woff');
}

@font-face {
    font-family: "myfont";
    src: url("fonts/awesome-font-bold.woff") format('woff');
    font-weight: bold;
}

@font-face {
    font-family: "myfont";
    src: url("fonts/awesome-font-boldoblique.woff") format('woff');
    font-weight: bold;
    font-style: italic;
}

@font-face {
    font-family: "myfont";
    src: url("fonts/awesome-font-oblique.woff") format('woff');
    font-style: italic;
}

After having that definitions, you can just write, for example,

In HTML code:

<div class="mydiv">
    <b>this will be written with awesome-font-bold.woff</b>
    <br/>
    <b><i>this will be written with awesome-font-boldoblique.woff</i></b>
    <br/>
    <i>this will be written with awesome-font-oblique.woff</i>
    <br/>
    this will be written with awesome-font.woff
</div>

In CSS code:

.mydiv {
    font-family: myfont
}

The good tool for generation woff files, which can be included in CSS stylesheets is located here. Not all woff files work correctly under latest Firefox versions, and this generator produces 'correct' fonts.

How do I generate random integers within a specific range in Java?

I use this:

 /**
   * @param min - The minimum.
   * @param max - The maximum.
   * @return A random double between these numbers (inclusive the minimum and maximum).
   */
 public static double getRandom(double min, double max) {
   return (Math.random() * (max + 1 - min)) + min;
 }

You can cast it to an Integer if you want.

C# difference between == and Equals()

There is another dimension to an earlier answer by @BlueMonkMN. The additional dimension is that the answer to the @Drahcir's title question as it is stated also depends on how we arrived at the string value. To illustrate:

string s1 = "test";
string s2 = "test";
string s3 = "test1".Substring(0, 4);
object s4 = s3;
string s5 = "te" + "st";
object s6 = s5;
Console.WriteLine("{0} {1} {2}", object.ReferenceEquals(s1, s2), s1 == s2, s1.Equals(s2));

Console.WriteLine("\n  Case1 - A method changes the value:");
Console.WriteLine("{0} {1} {2}", object.ReferenceEquals(s1, s3), s1 == s3, s1.Equals(s3));
Console.WriteLine("{0} {1} {2}", object.ReferenceEquals(s1, s4), s1 == s4, s1.Equals(s4));

Console.WriteLine("\n  Case2 - Having only literals allows to arrive at a literal:");
Console.WriteLine("{0} {1} {2}", object.ReferenceEquals(s1, s5), s1 == s5, s1.Equals(s5));
Console.WriteLine("{0} {1} {2}", object.ReferenceEquals(s1, s6), s1 == s6, s1.Equals(s6));

The output is:

True True True

  Case1 - A method changes the value:
False True True
False False True

  Case2 - Having only literals allows to arrive at a literal:
True True True
True True True

Check if a value is within a range of numbers

Here is an option with only a single comparison.

// return true if in range, otherwise false
function inRange(x, min, max) {
    return ((x-min)*(x-max) <= 0);
}

console.log(inRange(5, 1, 10));     // true
console.log(inRange(-5, 1, 10));    // false
console.log(inRange(20, 1, 10));    // false

onClick function of an input type="button" not working

When I try:

<input type="button" id="moreFields" onclick="alert('The text will be show!!'); return false;" value="Give me more fields!"  />

It's worked well. So I think the problem is position of moreFields() function. Ensure that function will be define before your input tag.

Pls try:

<script type="text/javascript">
    function moreFields() {
        alert("The text will be show");
    }
</script>

<input type="button" id="moreFields" onclick="moreFields()" value="Give me more fields!"  />

Hope it helped.

jQuery getJSON save result into variable

You can't get value when calling getJSON, only after response.

var myjson;
$.getJSON("http://127.0.0.1:8080/horizon-update", function(json){
    myjson = json;
});

Getting Integer value from a String using javascript/jquery

For parseInt to work, your string should have only numerical data. Something like this:

 str1 = "123.00";
 str2 = "50.00";
 total = parseInt(str1)+parseInt(str2);
 alert(total);

Can you split the string before you start processing them for a total?

How to get the caret column (not pixels) position in a textarea, in characters, from the start?

Updated 5 September 2010

Seeing as everyone seems to get directed here for this issue, I'm adding my answer to a similar question, which contains the same code as this answer but with full background for those who are interested:

IE's document.selection.createRange doesn't include leading or trailing blank lines

To account for trailing line breaks is tricky in IE, and I haven't seen any solution that does this correctly, including any other answers to this question. It is possible, however, using the following function, which will return you the start and end of the selection (which are the same in the case of a caret) within a <textarea> or text <input>.

Note that the textarea must have focus for this function to work properly in IE. If in doubt, call the textarea's focus() method first.

function getInputSelection(el) {
    var start = 0, end = 0, normalizedValue, range,
        textInputRange, len, endRange;

    if (typeof el.selectionStart == "number" && typeof el.selectionEnd == "number") {
        start = el.selectionStart;
        end = el.selectionEnd;
    } else {
        range = document.selection.createRange();

        if (range && range.parentElement() == el) {
            len = el.value.length;
            normalizedValue = el.value.replace(/\r\n/g, "\n");

            // Create a working TextRange that lives only in the input
            textInputRange = el.createTextRange();
            textInputRange.moveToBookmark(range.getBookmark());

            // Check if the start and end of the selection are at the very end
            // of the input, since moveStart/moveEnd doesn't return what we want
            // in those cases
            endRange = el.createTextRange();
            endRange.collapse(false);

            if (textInputRange.compareEndPoints("StartToEnd", endRange) > -1) {
                start = end = len;
            } else {
                start = -textInputRange.moveStart("character", -len);
                start += normalizedValue.slice(0, start).split("\n").length - 1;

                if (textInputRange.compareEndPoints("EndToEnd", endRange) > -1) {
                    end = len;
                } else {
                    end = -textInputRange.moveEnd("character", -len);
                    end += normalizedValue.slice(0, end).split("\n").length - 1;
                }
            }
        }
    }

    return {
        start: start,
        end: end
    };
}

Android: Align button to bottom-right of screen using FrameLayout?

I also ran into this situation and figured out how to do it using FrameLayout. The following output is produced by the code given below.

Some right-bottom aligned text showing up over an image using FrameLayout.

              <FrameLayout
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content" >

                    <ImageView
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:src="@drawable/contactbook_icon"
                        android:layout_gravity="center" />

                    <TextView
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:text="140"
                        android:textSize="12dp"
                        android:textColor="#FFFFFF"
                        android:layout_gravity="bottom|right"
                        android:layout_margin="15dp" />
                </FrameLayout>

Change the margin value to adjust the text position over the image. Removing margin might make the text to go out of the view sometimes.

use std::fill to populate vector with increasing numbers

I've seen the answers with std::generate but you can also "improve" that by using static variables inside the lambda, instead of declaring a counter outside of the function or creating a generator class :

std::vector<int> vec;
std::generate(vec.begin(), vec.end(), [] {
    static int i = 0;
    return i++;
});

I find it a little more concise

how to realize countifs function (excel) in R

Here an example with 100000 rows (occupations are set here from A to Z):

> a = data.frame(sex=sample(c("M", "F"), 100000, replace=T), occupation=sample(LETTERS, 100000, replace=T))
> sum(a$sex == "M" & a$occupation=="A")
[1] 1882

returns the number of males with occupation "A".

EDIT

As I understand from your comment, you want the counts of all possible combinations of sex and occupation. So first create a dataframe with all combinations:

combns = expand.grid(c("M", "F"), LETTERS)

and loop with apply to sum for your criteria and append the results to combns:

combns = cbind (combns, apply(combns, 1, function(x)sum(a$sex==x[1] & a$occupation==x[2])))
colnames(combns) = c("sex", "occupation", "count")

The first rows of your result look as follows:

  sex occupation count
1   M          A  1882
2   F          A  1869
3   M          B  1866
4   F          B  1904
5   M          C  1979
6   F          C  1910

Does this solve your problem?

OR:

Much easier solution suggested by thelatemai:

table(a$sex, a$occupation)


       A    B    C    D    E    F    G    H    I    J    K    L    M    N    O
  F 1869 1904 1910 1907 1894 1940 1964 1907 1918 1892 1962 1933 1886 1960 1972
  M 1882 1866 1979 1904 1895 1845 1946 1905 1999 1994 1933 1950 1876 1856 1911

       P    Q    R    S    T    U    V    W    X    Y    Z
  F 1908 1907 1883 1888 1943 1922 2016 1962 1885 1898 1889
  M 1928 1938 1916 1927 1972 1965 1946 1903 1965 1974 1906

How to join multiple lines of file names into one with custom delimiter?

ls has the option -m to delimit the output with ", " a comma and a space.

ls -m | tr -d ' ' | tr ',' ';'

piping this result to tr to remove either the space or the comma will allow you to pipe the result again to tr to replace the delimiter.

in my example i replace the delimiter , with the delimiter ;

replace ; with whatever one character delimiter you prefer since tr only accounts for the first character in the strings you pass in as arguments.

How to SELECT based on value of another SELECT

You can calculate the total (and from that the desired percentage) by using a subquery in the FROM clause:

SELECT Name,
       SUM(Value) AS "SUM(VALUE)",
       SUM(Value) / totals.total AS "% of Total"
FROM   table1,
       (
           SELECT Name,
                  SUM(Value) AS total
           FROM   table1
           GROUP BY Name
       ) AS totals
WHERE  table1.Name = totals.Name
AND    Year BETWEEN 2000 AND 2001
GROUP BY Name;

Note that the subquery does not have the WHERE clause filtering the years.

Setting individual axis limits with facet_wrap and scales = "free" in ggplot2

I am not sure I understand what you want, but based on what I understood

the x scale seems to be the same, it is the y scale that is not the same, and that is because you specified scales ="free"

you can specify scales = "free_x" to only allow x to be free (in this case it is the same as pred has the same range by definition)

p <- ggplot(plot, aes(x = pred, y = value)) + geom_point(size = 2.5) + theme_bw()
p <- p + facet_wrap(~variable, scales = "free_x")

worked for me, see the picture

enter image description here

I think you were making it too difficult - I do seem to remember one time defining the limits based on a formula with min and max and if faceted I think it used only those values, but I can't find the code

Insert current date into a date column using T-SQL?

UPDATE Table
SET DateColumn=GETDATE()
WHERE UserID=@UserID

If you're inserting into a table, and will always need to put the current date, I would recommend setting GETDATE() as the default value for that column, and don't allow NULLs

What is Python Whitespace and how does it work?

Whitespace is used to denote blocks. In other languages curly brackets ({ and }) are common. When you indent, it becomes a child of the previous line. In addition to the indentation, the parent also has a colon following it.

im_a_parent:
    im_a_child:
        im_a_grandchild
    im_another_child:
        im_another_grand_child

Off the top of my head, def, if, elif, else, try, except, finally, with, for, while, and class all start blocks. To end a block, you simple outdent, and you will have siblings. In the above im_a_child and im_another_child are siblings.

How to unescape HTML character entities in Java?

I have used the Apache Commons StringEscapeUtils.unescapeHtml4() for this:

Unescapes a string containing entity escapes to a string containing the actual Unicode characters corresponding to the escapes. Supports HTML 4.0 entities.

Get request URL in JSP which is forwarded by Servlet

Also you could use

${pageContext.request.requestURI}

npm ERR! code UNABLE_TO_GET_ISSUER_CERT_LOCALLY

In my case, at some point I set my global config to use a cert that was meant for a project.

npm config list

/path/to/global/.npmrc
NODE_EXTRA_CA_CERTS = "./certs/chain.pem"

I opened the file, removed the line and npm install worked again.

The container 'Maven Dependencies' references non existing library - STS

I'm a little late to the party but I'll give my two cents. I just resolved this issue after spending longer than I'd like on it. The above solutions didn't work for me and here's why:

there was a network issue when maven was downloading the required repositories so I actually didn't have the right jars. adding a -U to a maven clean install went and got them for me. So if the above solutions aren't working try this:

  1. Right click on your project -> Choose Run as -> 5 Maven build...
  2. In the Goals field type "clean install -U" and select Run
  3. After that completes right click on your project again and choose Maven -> Update Project and click ok.

Hope it works for you.

How to send a simple email from a Windows batch file?

Max is on he right track with the suggestion to use Windows Scripting for a way to do it without installing any additional executables on the machine. His code will work if you have the IIS SMTP service setup to forward outbound email using the "smart host" setting, or the machine also happens to be running Microsoft Exchange. Otherwise if this is not configured, you will find your emails just piling up in the message queue folder (\inetpub\mailroot\queue). So, unless you can configure this service, you also want to be able to specify the email server you want to use to send the message with. To do that, you can do something like this in your windows script file:

Set objMail = CreateObject("CDO.Message")
Set objConf = CreateObject("CDO.Configuration")
Set objFlds = objConf.Fields
objFlds.Item("http://schemas.microsoft.com/cdo/configuration/sendusing") = 2 'cdoSendUsingPort
objFlds.Item("http://schemas.microsoft.com/cdo/configuration/smtpserver") = "smtp.your-site-url.com" 'your smtp server domain or IP address goes here
objFlds.Item("http://schemas.microsoft.com/cdo/configuration/smtpserverport") = 25 'default port for email
'uncomment next three lines if you need to use SMTP Authorization
'objFlds.Item("http://schemas.microsoft.com/cdo/configuration/sendusername") = "your-username"
'objFlds.Item("http://schemas.microsoft.com/cdo/configuration/sendpassword") = "your-password"
'objFlds.Item("http://schemas.microsoft.com/cdo/configuration/smtpauthenticate") = 1 'cdoBasic
objFlds.Update
objMail.Configuration = objConf
objMail.FromName = "Your Name"
objMail.From = "[email protected]"
objMail.To = "[email protected]"
objMail.Subject = "Email Subject Text"
objMail.TextBody = "The message of the email..."
objMail.Send
Set objFlds = Nothing
Set objConf = Nothing
Set objMail = Nothing

Spring 3.0: Unable to locate Spring NamespaceHandler for XML schema namespace

I ran into a similar error, but refering to Spring Webflow in a newly created Roo project. The solution for me turned out to be (Project) / right-click / Maven / Enable Maven Dependencies (followed by some restarts and republishes to Tomcat).

It appeared that STS or m2Eclipse was failing to push all the spring webflow jars into the web app lib directory. I'm not sure why. But enabling maven dependency handling and then rebuilding seemed to fix the problem; the webflow jars finally get published and thus it can find the schema namespace references.

I investigated this by exploring the tomcat directory that the web app was published to, clicking into WEB-INF/lib/ while it was running and noticing that it was missing webflow jar files.

Nested routes with react router v4 / v5

In react-router-v4 you don't nest <Routes />. Instead, you put them inside another <Component />.


For instance

<Route path='/topics' component={Topics}>
  <Route path='/topics/:topicId' component={Topic} />
</Route>

should become

<Route path='/topics' component={Topics} />

with

const Topics = ({ match }) => (
  <div>
    <h2>Topics</h2>
    <Link to={`${match.url}/exampleTopicId`}>
      Example topic
    </Link>
    <Route path={`${match.path}/:topicId`} component={Topic}/>
  </div>
) 

Here is a basic example straight from the react-router documentation.

How can I get a resource content from a static context?

if you have a context, i mean inside;

public void onReceive(Context context, Intent intent){

}

you can use this code to get resources:

context.getResources().getString(R.string.app_name);

What is callback in Android?

It was discussed before here.

In computer programming, a callback is a piece of executable code that is passed as an argument to other code, which is expected to call back (execute) the argument at some convenient time. The invocation may be immediate as in a synchronous callback or it might happen at later time, as in an asynchronous callback.

Show/Hide Div on Scroll

i have a pretty answer try this code ;)

<div id="DivID">
</div>

$("#DivID").scrollview({ direction: 'y' });
$("#DivID > .ui-scrollbar").addClass("ui-scrollbar-visible");

Repeat table headers in print mode

Chrome and Opera browsers do not support thead {display: table-header-group;} but rest of others support properly..

jQuery validate: How to add a rule for regular expression validation?

You can use the addMethod()

e.g

$.validator.addMethod('postalCode', function (value) { 
    return /^((\d{5}-\d{4})|(\d{5})|([A-Z]\d[A-Z]\s\d[A-Z]\d))$/.test(value); 
}, 'Please enter a valid US or Canadian postal code.');

good article here https://web.archive.org/web/20130609222116/http://www.randallmorey.com/blog/2008/mar/16/extending-jquery-form-validation-plugin/

What are database normal forms and can you give examples?

1NF is the most basic of normal forms - each cell in a table must contain only one piece of information, and there can be no duplicate rows.

2NF and 3NF are all about being dependent on the primary key. Recall that a primary key can be made up of multiple columns. As Chris said in his response:

The data depends on the key [1NF], the whole key [2NF] and nothing but the key [3NF] (so help me Codd).

2NF

Say you have a table containing courses that are taken in a certain semester, and you have the following data:

|-----Primary Key----|               uh oh |
                                           V
CourseID | SemesterID | #Places  | Course Name  |
------------------------------------------------|
IT101    |   2009-1   | 100      | Programming  |
IT101    |   2009-2   | 100      | Programming  |
IT102    |   2009-1   | 200      | Databases    |
IT102    |   2010-1   | 150      | Databases    |
IT103    |   2009-2   | 120      | Web Design   |

This is not in 2NF, because the fourth column does not rely upon the entire key - but only a part of it. The course name is dependent on the Course's ID, but has nothing to do with which semester it's taken in. Thus, as you can see, we have duplicate information - several rows telling us that IT101 is programming, and IT102 is Databases. So we fix that by moving the course name into another table, where CourseID is the ENTIRE key.

Primary Key |

CourseID    |  Course Name |
---------------------------|
IT101       | Programming  |
IT102       | Databases    |
IT103       | Web Design   |

No redundancy!

3NF

Okay, so let's say we also add the name of the teacher of the course, and some details about them, into the RDBMS:

|-----Primary Key----|                           uh oh |
                                                       V
Course  |  Semester  |  #Places   |  TeacherID  | TeacherName  |
---------------------------------------------------------------|
IT101   |   2009-1   |  100       |  332        |  Mr Jones    |
IT101   |   2009-2   |  100       |  332        |  Mr Jones    |
IT102   |   2009-1   |  200       |  495        |  Mr Bentley  |
IT102   |   2010-1   |  150       |  332        |  Mr Jones    |
IT103   |   2009-2   |  120       |  242        |  Mrs Smith   |

Now hopefully it should be obvious that TeacherName is dependent on TeacherID - so this is not in 3NF. To fix this, we do much the same as we did in 2NF - take the TeacherName field out of this table, and put it in its own, which has TeacherID as the key.

 Primary Key |

 TeacherID   | TeacherName  |
 ---------------------------|
 332         |  Mr Jones    |
 495         |  Mr Bentley  |
 242         |  Mrs Smith   |

No redundancy!!

One important thing to remember is that if something is not in 1NF, it is not in 2NF or 3NF either. So each additional Normal Form requires everything that the lower normal forms had, plus some extra conditions, which must all be fulfilled.

Why does Node.js' fs.readFile() return a buffer instead of string?

It is returning a Buffer object.

If you want it in a string, you can convert it with data.toString():

var fs = require("fs");

fs.readFile("test.txt", function (err, data) {
    if (err) throw err;
    console.log(data.toString());
});

Understanding dispatch_async

All of the DISPATCH_QUEUE_PRIORITY_X queues are concurrent queues (meaning they can execute multiple tasks at once), and are FIFO in the sense that tasks within a given queue will begin executing using "first in, first out" order. This is in comparison to the main queue (from dispatch_get_main_queue()), which is a serial queue (tasks will begin executing and finish executing in the order in which they are received).

So, if you send 1000 dispatch_async() blocks to DISPATCH_QUEUE_PRIORITY_DEFAULT, those tasks will start executing in the order you sent them into the queue. Likewise for the HIGH, LOW, and BACKGROUND queues. Anything you send into any of these queues is executed in the background on alternate threads, away from your main application thread. Therefore, these queues are suitable for executing tasks such as background downloading, compression, computation, etc.

Note that the order of execution is FIFO on a per-queue basis. So if you send 1000 dispatch_async() tasks to the four different concurrent queues, evenly splitting them and sending them to BACKGROUND, LOW, DEFAULT and HIGH in order (ie you schedule the last 250 tasks on the HIGH queue), it's very likely that the first tasks you see starting will be on that HIGH queue as the system has taken your implication that those tasks need to get to the CPU as quickly as possible.

Note also that I say "will begin executing in order", but keep in mind that as concurrent queues things won't necessarily FINISH executing in order depending on length of time for each task.

As per Apple:

https://developer.apple.com/library/content/documentation/General/Conceptual/ConcurrencyProgrammingGuide/OperationQueues/OperationQueues.html

A concurrent dispatch queue is useful when you have multiple tasks that can run in parallel. A concurrent queue is still a queue in that it dequeues tasks in a first-in, first-out order; however, a concurrent queue may dequeue additional tasks before any previous tasks finish. The actual number of tasks executed by a concurrent queue at any given moment is variable and can change dynamically as conditions in your application change. Many factors affect the number of tasks executed by the concurrent queues, including the number of available cores, the amount of work being done by other processes, and the number and priority of tasks in other serial dispatch queues.

Basically, if you send those 1000 dispatch_async() blocks to a DEFAULT, HIGH, LOW, or BACKGROUND queue they will all start executing in the order you send them. However, shorter tasks may finish before longer ones. Reasons behind this are if there are available CPU cores or if the current queue tasks are performing computationally non-intensive work (thus making the system think it can dispatch additional tasks in parallel regardless of core count).

The level of concurrency is handled entirely by the system and is based on system load and other internally determined factors. This is the beauty of Grand Central Dispatch (the dispatch_async() system) - you just make your work units as code blocks, set a priority for them (based on the queue you choose) and let the system handle the rest.

So to answer your above question: you are partially correct. You are "asking that code" to perform concurrent tasks on a global concurrent queue at the specified priority level. The code in the block will execute in the background and any additional (similar) code will execute potentially in parallel depending on the system's assessment of available resources.

The "main" queue on the other hand (from dispatch_get_main_queue()) is a serial queue (not concurrent). Tasks sent to the main queue will always execute in order and will always finish in order. These tasks will also be executed on the UI Thread so it's suitable for updating your UI with progress messages, completion notifications, etc.

Set multiple system properties Java command line

If the required properties need to set in system then there is no option than -D But if you need those properties while bootstrapping an application then loading properties through the properties files is a best option. It will not require to change build for a single property.

Java code for getting current time

Try this way, more efficient and compatible:

SimpleDateFormat time_formatter = new SimpleDateFormat("yyyy-MM-dd_HH:mm:ss.SSS");
String current_time_str = time_formatter.format(System.currentTimeMillis());
//Log.i("test", "current_time_str:" + current_time_str);

Empty set literal?

Just to extend the accepted answer:

From version 2.7 and 3.1 python has got set literal {} in form of usage {1,2,3}, but {} itself still used for empty dict.

Python 2.7 (first line is invalid in Python <2.7)

>>> {1,2,3}.__class__
<type 'set'>
>>> {}.__class__
<type 'dict'>

Python 3.x

>>> {1,2,3}.__class__
<class 'set'>
>>> {}.__class__
<class 'dict'>

More here: https://docs.python.org/3/whatsnew/2.7.html#other-language-changes

How to calculate UILabel height dynamically?

Try this

// UILabel *myLabel;

CGSize labelSize = [myLabel.text sizeWithFont:myLabel.font 
                            constrainedToSize:myLabel.frame.size 
                                lineBreakMode:NSLineBreakByWordWrapping];

CGFloat labelHeight = labelSize.height;


int lines = [myLabel.text sizeWithFont:myLabel.font 
                     constrainedToSize:myLabel.frame.size 
                         lineBreakMode:NSLineBreakByWordWrapping].height/16; 
             // '16' is font size

or

int lines = labelHeight/16;

NSLog(@"lines count : %i \n\n",lines);  

or

int lines = [myLabel.text sizeWithFont:myLabel.font 
                     constrainedToSize:myLabel.frame.size 
                         lineBreakMode:UILineBreakModeWordWrap].height /myLabel.font.pointSize; //fetching font size from font

By Using Categories, Just Create the category class named as

UILabel+UILabelDynamicHeight.h

UILabel+UILabelDynamicHeight.m

No more tension about the height calculation. Please review the below implementation.

Updates for iOS7 & Above,iOS 7 below : Dynamically calculate the UILabel height

#define SYSTEM_VERSION_EQUAL_TO(v)                  ([[[UIDevice currentDevice] systemVersion] compare:v options:NSNumericSearch] == NSOrderedSame)
#define SYSTEM_VERSION_GREATER_THAN(v)              ([[[UIDevice currentDevice] systemVersion] compare:v options:NSNumericSearch] == NSOrderedDescending)
#define SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(v)  ([[[UIDevice currentDevice] systemVersion] compare:v options:NSNumericSearch] != NSOrderedAscending)
#define SYSTEM_VERSION_LESS_THAN(v)                 ([[[UIDevice currentDevice] systemVersion] compare:v options:NSNumericSearch] == NSOrderedAscending)
#define SYSTEM_VERSION_LESS_THAN_OR_EQUAL_TO(v)     ([[[UIDevice currentDevice] systemVersion] compare:v options:NSNumericSearch] != NSOrderedDescending)
#define iOS7_0 @"7.0"

UILabel+UILabelDynamicHeight.h

#import <UIKit/UIKit.h>
@interface UILabel (UILabelDynamicHeight)

#pragma mark - Calculate the size the Multi line Label
/*====================================================================*/

    /* Calculate the size of the Multi line Label */

/*====================================================================*/
/**
 *  Returns the size of the Label
 *
 *  @param aLabel To be used to calculte the height
 *
 *  @return size of the Label
 */
 -(CGSize)sizeOfMultiLineLabel;

@end

UILabel+UILabelDynamicHeight.m

#import "UILabel+UILabelDynamicHeight.h"
@implementation UILabel (UILabelDynamicHeight)


#pragma mark - Calculate the size,bounds,frame of the Multi line Label
/*====================================================================*/

/* Calculate the size,bounds,frame of the Multi line Label */

/*====================================================================*/
/**
 *  Returns the size of the Label
 *
 *  @param aLabel To be used to calculte the height
 *
 *  @return size of the Label
 */
-(CGSize)sizeOfMultiLineLabel{

    //Label text
    NSString *aLabelTextString = [self text];

    //Label font
    UIFont *aLabelFont = [self font];

    //Width of the Label
    CGFloat aLabelSizeWidth = self.frame.size.width;


    if (SYSTEM_VERSION_LESS_THAN(iOS7_0)) {
        //version < 7.0

        return [aLabelTextString sizeWithFont:aLabelFont
                            constrainedToSize:CGSizeMake(aLabelSizeWidth, MAXFLOAT)
                                lineBreakMode:NSLineBreakByWordWrapping];
    }
    else if (SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(iOS7_0)) {
        //version >= 7.0

        //Return the calculated size of the Label
        return [aLabelTextString boundingRectWithSize:CGSizeMake(aLabelSizeWidth, MAXFLOAT)
                                              options:NSStringDrawingUsesLineFragmentOrigin
                                           attributes:@{
                                                        NSFontAttributeName : aLabelFont
                                                        }
                                              context:nil].size;

    }

    return [self bounds].size;

}
@end

postgreSQL - psql \i : how to execute script in a given path

Have you tried using Unix style slashes (/ instead of \)?

\ is often an escape or command character, and may be the source of confusion. I have never had issues with this, but I also do not have Windows, so I cannot test it.

Additionally, the permissions may be based on the user running psql, or maybe the user executing the postmaster service, check that both have read to that file in that directory.

For..In loops in JavaScript - key value pairs

If you can use ES6 natively or with Babel (js compiler) then you could do the following:

_x000D_
_x000D_
const test = {a: 1, b: 2, c: 3};_x000D_
_x000D_
for (const [key, value] of Object.entries(test)) {_x000D_
  console.log(key, value);_x000D_
}
_x000D_
_x000D_
_x000D_

Which will print out this output:

a 1
b 2
c 3

The Object.entries() method returns an array of a given object's own enumerable property [key, value] pairs, in the same order as that provided by a for...in loop (the difference being that a for-in loop enumerates properties in the prototype chain as well).

Hope it helps! =)

Handler vs AsyncTask vs Thread

Thread

When you start an app, a process is created to execute the code. To efficiently use computing resource, threads can be started within the process so that multiple tasks can be executed at the time. So threads allow you to build efficient apps by utilizing cpu efficiently without idle time.

In Android, all components execute on a single called main thread. Android system queue tasks and execute them one by one on the main thread. When long running tasks are executed, app become unresponsive.

To prevent this, you can create worker threads and run background or long running tasks.

Handler

Since android uses single thread model, UI components are created non-thread safe meaning only the thread it created should access them that means UI component should be updated on main thread only. As UI component run on the main thread, tasks which run on worker threads can not modify UI components. This is where Handler comes into picture. Handler with the help of Looper can connect to new thread or existing thread and run code it contains on the connected thread.

Handler makes it possible for inter thread communication. Using Handler, background thread can send results to it and the handler which is connected to main thread can update the UI components on the main thread.

AsyncTask

AsyncTask provided by android uses both thread and handler to make running simple tasks in the background and updating results from background thread to main thread easy.

Please see android thread, handler, asynctask and thread pools for examples.

What exactly is node.js used for?

Node.js is used for easily building fast, scalable network applications

MySQL limit from descending order

Let's say we have a table with a column time and you want the last 5 entries, but you want them returned to you in asc order, not desc, this is how you do it:

select * from ( select * from `table` order by `time` desc limit 5 ) t order by `time` asc

How can I scan barcodes on iOS?

For a native iOS 7 bar code scanner take a look at my project on GitHub:

https://github.com/werner77/WECodeScanner

How to get current html page title with javascript

Like this :

jQuery(document).ready(function () {
    var title = jQuery(this).attr('title');
});

works for IE, Firefox and Chrome.

How to avoid "ConcurrentModificationException" while removing elements from `ArrayList` while iterating it?

If you want to modify your List during traversal, then you need to use the Iterator. And then you can use iterator.remove() to remove the elements during traversal.

How to use variables in a command in sed?

This may also can help

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

How to Navigate from one View Controller to another using Swift

SWIFT 3.01

let secondViewController = self.storyboard?.instantiateViewController(withIdentifier: "Conversation_VC") as! Conversation_VC
self.navigationController?.pushViewController(secondViewController, animated: true)

Javascript change font color

Html code

<div id="coloredBy">
    Colored By Santa
</div>

javascript code

document.getElementById("coloredBy").style.color = colorCode; // red or #ffffff

I think this is very easy to use

Compiler warning - suggest parentheses around assignment used as truth value

While that particular idiom is common, even more common is for people to use = when they mean ==. The convention when you really mean the = is to use an extra layer of parentheses:

while ((list = list->next)) { // yes, it's an assignment

Find the min/max element of an array in JavaScript

Using spread operator (ES6)

Math.max(...array);  // the same with "min" => Math.min(...array);

_x000D_
_x000D_
const array = [10, 2, 33, 4, 5];_x000D_
_x000D_
console.log(_x000D_
  Math.max(...array)_x000D_
)
_x000D_
_x000D_
_x000D_

How to discard all changes made to a branch?

git checkout -f

This is suffice for your question. Only thing is, once its done, its done. There is no undo.

Convert digits into words with JavaScript

Cleanest and easiest approach that came to mind:

const numberText = {
  1: 'one',
  2: 'two',
  3: 'three',
  4: 'four',
  5: 'five',
  6: 'six',
  7: 'seven',
  8: 'eight',
  9: 'nine',
  10: 'ten',
  11: 'eleven',
  12: 'twelve',
  13: 'thirteen',
  14: 'fourteen',
  15: 'fifteen',
  16: 'sixteen',
  17: 'seventeen',
  18: 'eighteen',
  19: 'nineteen',
  20: 'twenty',
  30: 'thirty',
  40: 'forty',
  50: 'fifty',
  60: 'sixty',
  70: 'seventy',
  80: 'eighty',
  90: 'ninety',
  100: 'hundred',
  1000: 'thousand',
}

const numberValues = Object.keys(numberText)
  .map((val) => Number(val))
  .sort((a, b) => b - a)

const convertNumberToEnglishText = (n) => {
  if (n === 0) return 'zero'
  if (n < 0) return 'negative ' + convertNumberToEnglishText(-n)

  let num = n
  let text = ''

  for (const numberValue of numberValues) {
    const count = Math.trunc(num / numberValue)

    if (count < 1) continue

    if (numberValue >= 100) text += convertNumberToEnglishText(count) + ' '

    text += numberText[numberValue] + ' '
    num -= count * numberValue
  }

  if (num !== 0) throw Error('Something went wrong!')

  return text.trim()
}

Replace multiple whitespaces with single whitespace in JavaScript string

Something like this:

_x000D_
_x000D_
var s = "  a  b     c  ";_x000D_
_x000D_
console.log(_x000D_
  s.replace(/\s+/g, ' ')_x000D_
)
_x000D_
_x000D_
_x000D_

what does Error "Thread 1:EXC_BAD_INSTRUCTION (code=EXC_I386_INVOP, subcode=0x0)" mean?

This line

secondNumber = Screen.text!.toInt()!

means: Get the Screen object, get the text property and please crash if it doesn't exist, then get the text converted to an integer, and please crash if it doesn't exist.

That's what the ! means: "I am sure this thing exists, so please crash if it doesn't". And crash is what it did.

How to see local history changes in Visual Studio Code?

I built an extension called Checkpoints, an alternative to Local History. Checkpoints has support for viewing history for all files (that has checkpoints) in the tree view, not just the currently active file. There are some other minor differences aswell, but overall they are pretty similar.

SELECT inside a COUNT

You can move the count() inside your sub-select:

SELECT a AS current_a, COUNT(*) AS b,
   ( SELECT COUNT(*) FROM t WHERE a = current_a AND c = 'const' ) as d,
   from t group by a order by b desc

sys.path different in Jupyter and Python - how to import own modules in Jupyter?

The verified solution doesn't work for me, since my notebook is not in my sys.path. This works however;

import os,sys
sys.path.insert(1, os.path.join(os.getcwd()  , '..'))

Why does jQuery or a DOM method such as getElementById not find the element?

The element you were trying to find wasn’t in the DOM when your script ran.

The position of your DOM-reliant script can have a profound effect upon its behavior. Browsers parse HTML documents from top to bottom. Elements are added to the DOM and scripts are (generally) executed as they're encountered. This means that order matters. Typically, scripts can't find elements which appear later in the markup because those elements have yet to be added to the DOM.

Consider the following markup; script #1 fails to find the <div> while script #2 succeeds:

_x000D_
_x000D_
<script>_x000D_
  console.log("script #1: %o", document.getElementById("test")); // null_x000D_
</script>_x000D_
<div id="test">test div</div>_x000D_
<script>_x000D_
  console.log("script #2: %o", document.getElementById("test")); // <div id="test" ..._x000D_
</script>
_x000D_
_x000D_
_x000D_

So, what should you do? You've got a few options:


Option 1: Move your script

Move your script further down the page, just before the closing body tag. Organized in this fashion, the rest of the document is parsed before your script is executed:

_x000D_
_x000D_
<body>_x000D_
  <button id="test">click me</button>_x000D_
  <script>_x000D_
    document.getElementById("test").addEventListener("click", function() {_x000D_
      console.log("clicked: %o", this);_x000D_
    });_x000D_
  </script>_x000D_
</body><!-- closing body tag -->
_x000D_
_x000D_
_x000D_

Note: Placing scripts at the bottom is generally considered a best practice.


Option 2: jQuery's ready()

Defer your script until the DOM has been completely parsed, using $(handler):

_x000D_
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<script>_x000D_
  $(function() {_x000D_
    $("#test").click(function() {_x000D_
      console.log("clicked: %o", this);_x000D_
    });_x000D_
  });_x000D_
</script>_x000D_
<button id="test">click me</button>
_x000D_
_x000D_
_x000D_

Note: You could simply bind to DOMContentLoaded or window.onload but each has its caveats. jQuery's ready() delivers a hybrid solution.


Option 3: Event Delegation

Delegated events have the advantage that they can process events from descendant elements that are added to the document at a later time.

When an element raises an event (provided that it's a bubbling event and nothing stops its propagation), each parent in that element's ancestry receives the event as well. That allows us to attach a handler to an existing element and sample events as they bubble up from its descendants... even those added after the handler is attached. All we have to do is check the event to see whether it was raised by the desired element and, if so, run our code.

jQuery's on() performs that logic for us. We simply provide an event name, a selector for the desired descendant, and an event handler:

_x000D_
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<script>_x000D_
  $(document).on("click", "#test", function(e) {_x000D_
    console.log("clicked: %o",  this);_x000D_
  });_x000D_
</script>_x000D_
<button id="test">click me</button>
_x000D_
_x000D_
_x000D_

Note: Typically, this pattern is reserved for elements which didn't exist at load-time or to avoid attaching a large amount of handlers. It's also worth pointing out that while I've attached a handler to document (for demonstrative purposes), you should select the nearest reliable ancestor.


Option 4: The defer attribute

Use the defer attribute of <script>.

[defer, a Boolean attribute,] is set to indicate to a browser that the script is meant to be executed after the document has been parsed, but before firing DOMContentLoaded.

_x000D_
_x000D_
<script src="https://gh-canon.github.io/misc-demos/log-test-click.js" defer></script>_x000D_
<button id="test">click me</button>
_x000D_
_x000D_
_x000D_

For reference, here's the code from that external script:

document.getElementById("test").addEventListener("click", function(e){
   console.log("clicked: %o", this); 
});

Note: The defer attribute certainly seems like a magic bullet but it's important to be aware of the caveats...
1. defer can only be used for external scripts, i.e.: those having a src attribute.
2. be aware of browser support, i.e.: buggy implementation in IE < 10

C# binary literals

You can always create quasi-literals, constants which contain the value you are after:

const int b001 = 1;
const int b010 = 2;
const int b011 = 3;
// etc ...
Debug.Assert((b001 | b010) == b011);

If you use them often then you can wrap them in a static class for re-use.

However, slightliy off-topic, if you have any semantics associated with the bits (known at compile time) I would suggest using an Enum instead:

enum Flags
{ 
    First = 0,
    Second = 1,
    Third = 2,
    SecondAndThird = 3
}
// later ...
Debug.Assert((Flags.Second | Flags.Third) == Flags.SecondAndThird);

Differences between C++ string == and compare()?

If you just want to check string equality, use the == operator. Determining whether two strings are equal is simpler than finding an ordering (which is what compare() gives,) so it might be better performance-wise in your case to use the equality operator.

Longer answer: The API provides a method to check for string equality and a method to check string ordering. You want string equality, so use the equality operator (so that your expectations and those of the library implementors align.) If performance is important then you might like to test both methods and find the fastest.

What is the "hasClass" function with plain JavaScript?

Element.matches()

Instead of $(element).hasClass('example') in jQuery, you can use element.matches('.example') in plain JavaScript:

if (element.matches('.example')) {
  // Element has example class ...
}

View Browser Compatibility

ImportError: DLL load failed: %1 is not a valid Win32 application

All you have to do is copy the cv2.pyd file from the x86 folder (C:\opencv\build\python\2.7\x86\ for example) to C:\Python27\Lib\site-packages\ , not from the x64 folder.

Hope that help you.

How do I inject a controller into another controller in AngularJS

<div ng-controller="TestCtrl1">
    <div ng-controller="TestCtrl2">
      <!-- your code--> 
    </div> 
</div>

This works best in my case, where TestCtrl2 has it's own directives.

var testCtrl2 = $controller('TestCtrl2')

This gives me an error saying scopeProvider injection error.

   var testCtrl1ViewModel = $scope.$new();
   $controller('TestCtrl1',{$scope : testCtrl1ViewModel });
   testCtrl1ViewModel.myMethod(); 

This doesn't really work if you have directives in 'TestCtrl1', that directive actually have a different scope from this one created here. You end up with two instances of 'TestCtrl1'.

Android: How to change CheckBox size?

Starting with API Level 11 there is another approach exists:

<CheckBox
    ...
    android:scaleX="0.70"
    android:scaleY="0.70"
/>

SQL Server 2008- Get table constraints

Here's a script to get foreign keys:

    SELECT TOP(150)
       t.[name] AS [Table],
       cols.[name] AS [Column],
       t2.[name] AS [Referenced Table],
       c2.[name] AS [Referenced Column],
       constr.[name] AS [Constraint]
  FROM sys.tables t
 INNER JOIN sys.foreign_keys constr ON constr.parent_object_id = t.object_id
 INNER JOIN sys.tables t2 ON t2.object_id = constr.referenced_object_id
 INNER JOIN sys.foreign_key_columns fkc ON fkc.constraint_object_id = constr.object_id
 INNER JOIN sys.columns cols ON cols.object_id = fkc.parent_object_id AND cols.column_id = fkc.parent_column_id
 INNER JOIN sys.columns c2 ON c2.object_id = fkc.referenced_object_id AND c2.column_id = fkc.referenced_column_id
 --WHERE t.[name] IN ('?', '?', ...)
 ORDER BY t.[Name], cols.[name]

Android fastboot waiting for devices

The shortest answer is first run the fastboot command (in my ubuntu case i.e. ./fastboot-linux oem unlock) (here i'm using ubuntu 12.04 and rooting nexus4) then power on your device in fastboot mode (in nexus 4 by pressing vol-down-key and power button)

grunt: command not found when running from terminal

I have been hunting around trying to solve this one for a while and none of the suggested updates to bash seemed to be working. What I discovered was that some point my npm root was modified such that it was pointing to a Users/USER_NAME/.node/node_modules while the actual installation of npm was living at /usr/local/lib/node_modules. You can check this by running npm root and npm root -g (for the global installation). To correct the path you can call npm config set prefix /usr/local.

How to convert a currency string to a double with jQuery or Javascript?

This function should work whichever the locale and currency settings :

function getNumPrice(price, decimalpoint) {
    var p = price.split(decimalpoint);
    for (var i=0;i<p.length;i++) p[i] = p[i].replace(/\D/g,'');
    return p.join('.');
}

This assumes you know the decimal point character (in my case the locale is set from PHP, so I get it with <?php echo cms_function_to_get_decimal_point(); ?>).

Apache Cordova - uninstall globally

Try this for Windows:

    npm uninstall -g cordova

Try this for MAC:

    sudo npm uninstall -g cordova

You can also add Cordova like this:

  1. If You Want To install the previous version of Cordova through the Node Package Manager (npm):

    npm install -g [email protected]
    
  2. If You Want To install the latest version of Cordova:

    npm install -g cordova 
    

Enjoy!

Docker is in volume in use, but there aren't any Docker containers

You should type this command with flag -f (force):

sudo docker volume rm -f <VOLUME NAME>

Angular JS break ForEach

I realise this is old, but an array filter may do what you need:

var arr = [0, 1, 2].filter(function (count) {
    return count < 1;
});

You can then run arr.forEach and other array functions.

I realise that if you intend to cut down on loop operations altogether, this will probably not do what you want. For that you best use while.

count (non-blank) lines-of-code in bash

Script to recursively count all non-blank lines with a certain file extension in the current directory:

#!/usr/bin/env bash
(
echo 0;
for ext in "$@"; do
    for i in $(find . -name "*$ext"); do
        sed '/^\s*$/d' $i | wc -l ## skip blank lines
        #cat $i | wc -l; ## count all lines
        echo +;
    done
done
echo p q;
) | dc;

Sample usage:

./countlines.sh .py .java .html

How to use default Android drawables

Better you copy and move them to your own resources. Some resources might not be available on previous Android versions. Here is a link with all drawables available on each Android version thanks to @fiXedd

session handling in jquery

Assuming you're referring to this plugin, your code should be:

// To Store
$(function() {
    $.session.set("myVar", "value");
});


// To Read
$(function() {
    alert($.session.get("myVar"));
});

Before using a plugin, remember to read its documentation in order to learn how to use it. In this case, an usage example can be found in the README.markdown file, which is displayed on the project page.

Java: Static Class?

Just to swim upstream, static members and classes do not participate in OO and are therefore evil. No, not evil, but seriously, I would recommend a regular class with a singleton pattern for access. This way if you need to override behavior in any cases down the road, it isn't a major retooling. OO is your friend :-)

My $.02

What is context in _.each(list, iterator, [context])?

context is where this refers to in your iterator function. For example:

var person = {};
person.friends = {
  name1: true,
  name2: false,
  name3: true,
  name4: true
};

_.each(['name4', 'name2'], function(name){
  // this refers to the friends property of the person object
  alert(this[name]);
}, person.friends);

How to create a numpy array of arbitrary length strings?

You can do so by creating an array of dtype=object. If you try to assign a long string to a normal numpy array, it truncates the string:

>>> a = numpy.array(['apples', 'foobar', 'cowboy'])
>>> a[2] = 'bananas'
>>> a
array(['apples', 'foobar', 'banana'], 
      dtype='|S6')

But when you use dtype=object, you get an array of python object references. So you can have all the behaviors of python strings:

>>> a = numpy.array(['apples', 'foobar', 'cowboy'], dtype=object)
>>> a
array([apples, foobar, cowboy], dtype=object)
>>> a[2] = 'bananas'
>>> a
array([apples, foobar, bananas], dtype=object)

Indeed, because it's an array of objects, you can assign any kind of python object to the array:

>>> a[2] = {1:2, 3:4}
>>> a
array([apples, foobar, {1: 2, 3: 4}], dtype=object)

However, this undoes a lot of the benefits of using numpy, which is so fast because it works on large contiguous blocks of raw memory. Working with python objects adds a lot of overhead. A simple example:

>>> a = numpy.array(['abba' for _ in range(10000)])
>>> b = numpy.array(['abba' for _ in range(10000)], dtype=object)
>>> %timeit a.copy()
100000 loops, best of 3: 2.51 us per loop
>>> %timeit b.copy()
10000 loops, best of 3: 48.4 us per loop

Background thread with QThread in PyQt

According to the Qt developers, subclassing QThread is incorrect (see http://blog.qt.io/blog/2010/06/17/youre-doing-it-wrong/). But that article is really hard to understand (plus the title is a bit condescending). I found a better blog post that gives a more detailed explanation about why you should use one style of threading over another: http://mayaposch.wordpress.com/2011/11/01/how-to-really-truly-use-qthreads-the-full-explanation/

In my opinion, you should probably never subclass thread with the intent to overload the run method. While that does work, you're basically circumventing how Qt wants you to work. Plus you'll miss out on things like events and proper thread safe signals and slots. Plus as you'll likely see in the above blog post, the "correct" way of threading forces you to write more testable code.

Here's a couple of examples of how to take advantage of QThreads in PyQt (I posted a separate answer below that properly uses QRunnable and incorporates signals/slots, that answer is better if you have a lot of async tasks that you need to load balance).

import sys
from PyQt4 import QtCore
from PyQt4 import QtGui
from PyQt4.QtCore import Qt

# very testable class (hint: you can use mock.Mock for the signals)
class Worker(QtCore.QObject):
    finished = QtCore.pyqtSignal()
    dataReady = QtCore.pyqtSignal(list, dict)

    @QtCore.pyqtSlot()
    def processA(self):
        print "Worker.processA()"
        self.finished.emit()

    @QtCore.pyqtSlot(str, list, list)
    def processB(self, foo, bar=None, baz=None):
        print "Worker.processB()"
        for thing in bar:
            # lots of processing...
            self.dataReady.emit(['dummy', 'data'], {'dummy': ['data']})
        self.finished.emit()


class Thread(QtCore.QThread):
    """Need for PyQt4 <= 4.6 only"""
    def __init__(self, parent=None):
        QtCore.QThread.__init__(self, parent)

     # this class is solely needed for these two methods, there
     # appears to be a bug in PyQt 4.6 that requires you to
     # explicitly call run and start from the subclass in order
     # to get the thread to actually start an event loop

    def start(self):
        QtCore.QThread.start(self)

    def run(self):
        QtCore.QThread.run(self)


app = QtGui.QApplication(sys.argv)

thread = Thread() # no parent!
obj = Worker() # no parent!
obj.moveToThread(thread)

# if you want the thread to stop after the worker is done
# you can always call thread.start() again later
obj.finished.connect(thread.quit)

# one way to do it is to start processing as soon as the thread starts
# this is okay in some cases... but makes it harder to send data to
# the worker object from the main gui thread.  As you can see I'm calling
# processA() which takes no arguments
thread.started.connect(obj.processA)
thread.start()

# another way to do it, which is a bit fancier, allows you to talk back and
# forth with the object in a thread safe way by communicating through signals
# and slots (now that the thread is running I can start calling methods on
# the worker object)
QtCore.QMetaObject.invokeMethod(obj, 'processB', Qt.QueuedConnection,
                                QtCore.Q_ARG(str, "Hello World!"),
                                QtCore.Q_ARG(list, ["args", 0, 1]),
                                QtCore.Q_ARG(list, []))

# that looks a bit scary, but its a totally ok thing to do in Qt,
# we're simply using the system that Signals and Slots are built on top of,
# the QMetaObject, to make it act like we safely emitted a signal for 
# the worker thread to pick up when its event loop resumes (so if its doing
# a bunch of work you can call this method 10 times and it will just queue
# up the calls.  Note: PyQt > 4.6 will not allow you to pass in a None
# instead of an empty list, it has stricter type checking

app.exec_()

# Without this you may get weird QThread messages in the shell on exit
app.deleteLater()        

How to get a random value from dictionary?

One way would be:

import random
d = {'VENEZUELA':'CARACAS', 'CANADA':'OTTAWA'}
random.choice(list(d.values()))

EDIT: The question was changed a couple years after the original post, and now asks for a pair, rather than a single item. The final line should now be:

country, capital = random.choice(list(d.items()))

How to install a certificate in Xcode (preparing for app store submission)

In Xcode 5 this has been moved to:

Xcode>Preferences>Accounts>View Details button>

BasicHttpBinding vs WsHttpBinding vs WebHttpBinding

You're comparing apples to oranges here:

  • webHttpBinding is the REST-style binding, where you basically just hit a URL and get back a truckload of XML or JSON from the web service

  • basicHttpBinding and wsHttpBinding are two SOAP-based bindings which is quite different from REST. SOAP has the advantage of having WSDL and XSD to describe the service, its methods, and the data being passed around in great detail (REST doesn't have anything like that - yet). On the other hand, you can't just browse to a wsHttpBinding endpoint with your browser and look at XML - you have to use a SOAP client, e.g. the WcfTestClient or your own app.

So your first decision must be: REST vs. SOAP (or you can expose both types of endpoints from your service - that's possible, too).

Then, between basicHttpBinding and wsHttpBinding, there differences are as follows:

  • basicHttpBinding is the very basic binding - SOAP 1.1, not much in terms of security, not much else in terms of features - but compatible to just about any SOAP client out there --> great for interoperability, weak on features and security

  • wsHttpBinding is the full-blown binding, which supports a ton of WS-* features and standards - it has lots more security features, you can use sessionful connections, you can use reliable messaging, you can use transactional control - just a lot more stuff, but wsHttpBinding is also a lot *heavier" and adds a lot of overhead to your messages as they travel across the network

For an in-depth comparison (including a table and code examples) between the two check out this codeproject article: Differences between BasicHttpBinding and WsHttpBinding

Responsive width Facebook Page Plugin

This doesn't work too well when you have the plugin placed in a thin column, like a sidebar for example. On medium sized screens these typically run smaller than 280px in width.

.fb-page, 
.fb-page span, 
.fb-page span iframe[style] { 
    width: 100% !important; 
}

This is the code I use to stop the plugin breaking outside of a wrapping container. Unlike the old like box which would tile, this one just overflows, hiding the overflowed content.

TypeError: a bytes-like object is required, not 'str' in python and CSV

I had the same issue with Python3. My code was writing into io.BytesIO().

Replacing with io.StringIO() solved.

MySQL - ignore insert error: duplicate entry

Try creating a duplicate table, preferably a temporary table, without the unique constraint and do your bulk load into that table. Then select only the unique (DISTINCT) items from the temporary table and insert into the target table.

Saving lists to txt file

Assuming your Generic List is of type String:

TextWriter tw = new StreamWriter("SavedList.txt");

foreach (String s in Lists.verbList)
   tw.WriteLine(s);

tw.Close();

Alternatively, with the using keyword:

using(TextWriter tw = new StreamWriter("SavedList.txt"))
{
   foreach (String s in Lists.verbList)
      tw.WriteLine(s);
}

How do I prevent a form from being resized by the user?

Set the highlighted properties. Set MaximimSize and MinimizeSize properties the same size

enter image description here

INSERT INTO vs SELECT INTO

  1. They do different things. Use INSERT when the table exists. Use SELECT INTO when it does not.

  2. Yes. INSERT with no table hints is normally logged. SELECT INTO is minimally logged assuming proper trace flags are set.

  3. In my experience SELECT INTO is most commonly used with intermediate data sets, like #temp tables, or to copy out an entire table like for a backup. INSERT INTO is used when you insert into an existing table with a known structure.

EDIT

To address your edit, they do different things. If you are making a table and want to define the structure use CREATE TABLE and INSERT. Example of an issue that can be created: You have a small table with a varchar field. The largest string in your table now is 12 bytes. Your real data set will need up to 200 bytes. If you do SELECT INTO from your small table to make a new one, the later INSERT will fail with a truncation error because your fields are too small.

Correlation between two vectors?

For correlations you can just use the corr function (statistics toolbox)

corr(A_1(:), A_2(:))

Note that you can also just use

corr(A_1, A_2)

But the linear indexing guarantees that your vectors don't need to be transposed.

Check for special characters in string

_x000D_
_x000D_
var format = /[`!@#$%^&*()_+\-=\[\]{};':"\\|,.<>\/?~]/;
//            ^                                       ^   
document.write(format.test("My @string-with(some%text)") + "<br/>");
document.write(format.test("My string with spaces") + "<br/>");
document.write(format.test("My StringContainingNoSpecialChars"));
_x000D_
_x000D_
_x000D_

What is HTML5 ARIA?

What is ARIA?

ARIA emerged as a way to address the accessibility problem of using a markup language intended for documents, HTML, to build user interfaces (UI). HTML includes a great many features to deal with documents (P, h3,UL,TABLE) but only basic UI elements such as A, INPUT and BUTTON. Windows and other operating systems support APIs that allow (Assistive Technology) AT to access the functionality of UI controls. Internet Explorer and other browsers map the native HTML elements to the accessibility API, but the html controls are not as rich as the controls common on desktop operating systems, and are not enough for modern web applications Custom controls can extend html elements to provide the rich UI needed for modern web applications. Before ARIA, the browser had no way to expose this extra richness to the accessibility API or AT. The classic example of this issue is adding a click handler to an image. It creates what appears to be a clickable button to a mouse user, but is still just an image to a keyboard or AT user.

The solution was to create a set of attributes that allow developers to extend HTML with UI semantics. The ARIA term for a group of HTML elements that have custom functionality and use ARIA attributes to map these functions to accessibility APIs is a “Widget. ARIA also provides a means for authors to document the role of content itself, which in turn, allows AT to construct alternate navigation mechanisms for the content that are much easier to use than reading the full text or only iterating over a list of the links.

It is important to remember that in simple cases, it is much preferred to use native HTML controls and style them rather than using ARIA. That is don’t reinvent wheels, or checkboxes, if you don’t have to.

Fortunately, ARIA markup can be added to existing sites without changing the behavior for mainstream users. This greatly reduces the cost of modifying and testing the website or application.

Recursive directory listing in DOS

dir /s /b /a:d>output.txt will port it to a text file

How do I create documentation with Pydoc?

pydoc is fantastic for generating documentation, but the documentation has to be written in the first place. You must have docstrings in your source code as was mentioned by RocketDonkey in the comments:

"""
This example module shows various types of documentation available for use
with pydoc.  To generate HTML documentation for this module issue the
command:

    pydoc -w foo

"""

class Foo(object):
    """
    Foo encapsulates a name and an age.
    """
    def __init__(self, name, age):
        """
        Construct a new 'Foo' object.

        :param name: The name of foo
        :param age: The ageof foo
        :return: returns nothing
        """
        self.name = name
        self.age = age

def bar(baz):
    """
    Prints baz to the display.
    """
    print baz

if __name__ == '__main__':
    f = Foo('John Doe', 42)
    bar("hello world")

The first docstring provides instructions for creating the documentation with pydoc. There are examples of different types of docstrings so you can see how they look when generated with pydoc.

How do I publish a UDP Port on Docker?

Use the -p flag and add /udp suffix to the port number.

-p 53160:53160/udp

Full command

sudo docker run -p 53160:53160 \
    -p 53160:53160/udp -p 58846:58846 \ 
    -p 8112:8112 -t -i aostanin/deluge /start.sh

If you're running boot2docker on Mac, be sure to forward the same ports on boot2docker to your local machine.

You can also document that your container needs to receive UDP using EXPOSE in The Dockerfile (EXPOSE does not publish the port):

EXPOSE 8285/udp

Here is a link with more Docker Networking info covered in the container docs: https://docs.docker.com/config/containers/container-networking/ (Courtesy of Old Pro in the comments)

Sending emails through SMTP with PHPMailer

Try to send an e-mail through that SMTP server manually/from an interactive mailer (e.g. Mozilla Thunderbird). From the errors, it seems the server won't accept your credentials. Is that SMTP running on the port, or is it SSL+SMTP? You don't seem to be using secure connection in the code you've posted, and I'm not sure if PHPMailer actually supports SSL+SMTP.

(First result of googling your SMTP server's hostname: http://podpora.ebola.cz/idx.php/0/006/article/Strucny-technicky-popis-nastaveni-sluzeb.html seems to say "SMTPs mail sending: secure SSL connection,port: 465" . )

It looks like PHPMailer does support SSL; at least from this. So, you'll need to change this:

define('SMTP_SERVER', 'smtp.ebola.cz');

into this:

define('SMTP_SERVER', 'ssl://smtp.ebola.cz');

CMD: Export all the screen content to a text file

From command prompt Run as Administrator. Example below is to print a list of Services running on your PC run the command below:

net start > c:\netstart.txt

You should see a copy of the text file you just exported with a listing all the PC services running at the root of your C:\ drive.

What is the point of WORKDIR on Dockerfile?

You can think of WORKDIR like a cd inside the container (it affects commands that come later in the Dockerfile, like the RUN command). If you removed WORKDIR in your example above, RUN npm install wouldn't work because you would not be in the /usr/src/app directory inside your container.

I don't see how this would be related to where you put your Dockerfile (since your Dockerfile location on the host machine has nothing to do with the pwd inside the container). You can put the Dockerfile wherever you'd like in your project. However, the first argument to COPY is a relative path, so if you move your Dockerfile you may need to update those COPY commands.

any tool for java object to object mapping?

Another one is Orika - https://github.com/orika-mapper/orika

Orika is a Java Bean mapping framework that recursively copies (among other capabilities) data from one object to another. It can be very useful when developing multi-layered applications.

Orika focuses on automating as much as possible, while providing customization through configuration and extension where needed.

Orika enables the developer to :

  • Map complex and deeply structured objects
  • "Flatten" or "Expand" objects by mapping nested properties to top-level properties, and vice versa
  • Create mappers on-the-fly, and apply customizations to control some or all of the mapping
  • Create converters for complete control over the mapping of a specific set of objects anywhere in the object graph--by type, or even by specific property name
  • Handle proxies or enhanced objects (like those of Hibernate, or the various mock frameworks)
  • Apply bi-directional mapping with one configuration
  • Map to instances of an appropriate concrete class for a target abstract class or interface
  • Handle reverse mappings
  • Handle complex conventions beyond JavaBean specs.

Orika uses byte code generation to create fast mappers with minimal overhead.

Write variable to a file in Ansible

Based on Ramon's answer I run into an error. The problem where spaces in the JSON I tried to write I got it fixed by changing the task in the playbook to look like:

- copy:
    content: "{{ your_json_feed }}"
    dest: "/path/to/destination/file"

As of now I am not sure why this was needed. My best guess is that it had something to do with how variables are replaced in Ansible and the resulting file is parsed.

What is the best way to generate a unique and short file name in Java

Combining other answers, why not use the ms timestamp with a random value appended; repeat until no conflict, which in practice will be almost never.

For example: File-ccyymmdd-hhmmss-mmm-rrrrrr.txt

Pass a simple string from controller to a view MVC3

Why not create a viewmodel with a simple string parameter and then pass that to the view? It has the benefit of being extensible (i.e. you can then add any other things you may want to set in your controller) and it's fairly simple.

public class MyViewModel
{
    public string YourString { get; set; }
}

In the view

@model MyViewModel
@Html.Label(model => model.YourString)

In the controller

public ActionResult Index() 
{
     myViewModel = new MyViewModel();
     myViewModel.YourString = "However you are setting this."
     return View(myViewModel)
}

How do I resize an image using PIL and maintain its aspect ratio?

You can combine PIL's Image.thumbnail with sys.maxsize if your resize limit is only on one dimension (width or height).

For instance, if you want to resize an image so that its height is no more than 100px, while keeping aspect ratio, you can do something like this:

import sys
from PIL import Image

image.thumbnail([sys.maxsize, 100], Image.ANTIALIAS)

Keep in mind that Image.thumbnail will resize the image in place, which is different from Image.resize that instead returns the resized image without changing the original one.

Rails server says port already used, how to kill that process?

If you are on windows machine follow these steps.

c:/project/
cd tmp
c:/project/tmp
cd pids
c:/project/tmp/pids
dir

There you will a file called server.pid

delete it.

c:/project/tmp/pid> del *.pid

Thats it.

EDIT: Please refer this

What is the default value for enum variable?

You can use this snippet :-D

using System;
using System.Reflection;

public static class EnumUtils
{
    public static T GetDefaultValue<T>()
        where T : struct, Enum
    {
        return (T)GetDefaultValue(typeof(T));
    }

    public static object GetDefaultValue(Type enumType)
    {
        var attribute = enumType.GetCustomAttribute<DefaultValueAttribute>(inherit: false);
        if (attribute != null)
            return attribute.Value;

        var innerType = enumType.GetEnumUnderlyingType();
        var zero = Activator.CreateInstance(innerType);
        if (enumType.IsEnumDefined(zero))
            return zero;

        var values = enumType.GetEnumValues();
        return values.GetValue(0);
    }
}

Example:

using System;

public enum Enum1
{
    Foo,
    Bar,
    Baz,
    Quux
}
public enum Enum2
{
    Foo  = 1,
    Bar  = 2,
    Baz  = 3,
    Quux = 0
}
public enum Enum3
{
    Foo  = 1,
    Bar  = 2,
    Baz  = 3,
    Quux = 4
}
[DefaultValue(Enum4.Bar)]
public enum Enum4
{
    Foo  = 1,
    Bar  = 2,
    Baz  = 3,
    Quux = 4
}

public static class Program 
{
    public static void Main() 
    {
        var defaultValue1 = EnumUtils.GetDefaultValue<Enum1>();
        Console.WriteLine(defaultValue1); // Foo

        var defaultValue2 = EnumUtils.GetDefaultValue<Enum2>();
        Console.WriteLine(defaultValue2); // Quux

        var defaultValue3 = EnumUtils.GetDefaultValue<Enum3>();
        Console.WriteLine(defaultValue3); // Foo

        var defaultValue4 = EnumUtils.GetDefaultValue<Enum4>();
        Console.WriteLine(defaultValue4); // Bar
    }
}

Targeting both 32bit and 64bit with Visual Studio in same solution/project

You can generate two solutions differently and merge them afterwards! I did this for VS 2010. and it works. I had 2 different solutions generated by CMake and I merged them

Check if a string contains another string

Use the Instr function

Dim pos As Integer

pos = InStr("find the comma, in the string", ",")

will return 15 in pos

If not found it will return 0

If you need to find the comma with an excel formula you can use the =FIND(",";A1) function.

Notice that if you want to use Instr to find the position of a string case-insensitive use the third parameter of Instr and give it the const vbTextCompare (or just 1 for die-hards).

Dim posOf_A As Integer

posOf_A = InStr(1, "find the comma, in the string", "A", vbTextCompare)

will give you a value of 14.

Note that you have to specify the start position in this case as stated in the specification I linked: The start argument is required if compare is specified.

How to use \n new line in VB msgbox() ...?

The message box must end with a text and not with a variable

PowerShell try/catch/finally

That is very odd.

I went through ItemNotFoundException's base classes and tested the following multiple catches to see what would catch it:

try {
  remove-item C:\nonexistent\file.txt -erroraction stop
}
catch [System.Management.Automation.ItemNotFoundException] {
  write-host 'ItemNotFound'
}
catch [System.Management.Automation.SessionStateException] {
  write-host 'SessionState'
}
catch [System.Management.Automation.RuntimeException] {
  write-host 'RuntimeException'
}
catch [System.SystemException] {
  write-host 'SystemException'
}
catch [System.Exception] {
  write-host 'Exception'
}
catch {
  write-host 'well, darn'
}

As it turns out, the output was 'RuntimeException'. I also tried it with a different exception CommandNotFoundException:

try {
  do-nonexistent-command
}
catch [System.Management.Automation.CommandNotFoundException] {
  write-host 'CommandNotFoundException'
}
catch {
  write-host 'well, darn'
}

That output 'CommandNotFoundException' correctly.

I vaguely remember reading elsewhere (though I couldn't find it again) of problems with this. In such cases where exception filtering didn't work correctly, they would catch the closest Type they could and then use a switch. The following just catches Exception instead of RuntimeException, but is the switch equivalent of my first example that checks all base types of ItemNotFoundException:

try {
  Remove-Item C:\nonexistent\file.txt -ErrorAction Stop
}
catch [System.Exception] {
  switch($_.Exception.GetType().FullName) {
    'System.Management.Automation.ItemNotFoundException' {
      write-host 'ItemNotFound'
    }
    'System.Management.Automation.SessionStateException' {
      write-host 'SessionState'
    }
    'System.Management.Automation.RuntimeException' {
      write-host 'RuntimeException'
    }
    'System.SystemException' {
      write-host 'SystemException'
    }
    'System.Exception' {
      write-host 'Exception'
    }
    default {'well, darn'}
  }
}

This writes 'ItemNotFound', as it should.

Pass Javascript Variable to PHP POST

Your idea of an hidden form element is solid. Something like this

<form action="script.php" method="post">
<input type="hidden" name="total" id="total">
</form>

<script type="text/javascript">
var element = document.getElementById("total");
element.value = getTotalFromSomewhere;
element.form.submit();
</script>

Of course, this will change the location to script.php. If you want to do this invisibly to the user, you'll want to use AJAX. Here's a jQuery example (for brevity). No form or hidden inputs required

$.post("script.php", { total: getTotalFromSomewhere });

How to create a simple checkbox in iOS?

Yeah, no checkbox for you in iOS (-:

Here, this is what I did to create a checkbox:

UIButton *checkbox;
BOOL checkBoxSelected;
checkbox = [[UIButton alloc] initWithFrame:CGRectMake(x,y,20,20)];
// 20x20 is the size of the checkbox that you want
// create 2 images sizes 20x20 , one empty square and
// another of the same square with the checkmark in it
// Create 2 UIImages with these new images, then:

[checkbox setBackgroundImage:[UIImage imageNamed:@"notselectedcheckbox.png"]
                    forState:UIControlStateNormal];
[checkbox setBackgroundImage:[UIImage imageNamed:@"selectedcheckbox.png"]
                    forState:UIControlStateSelected];
[checkbox setBackgroundImage:[UIImage imageNamed:@"selectedcheckbox.png"]
                    forState:UIControlStateHighlighted];
checkbox.adjustsImageWhenHighlighted=YES;
[checkbox addTarget:(nullable id) action:(nonnull SEL) forControlEvents:(UIControlEvents)];
[self.view addSubview:checkbox];

Now in the target method do the following:

-(void)checkboxSelected:(id)sender
{
    checkBoxSelected = !checkBoxSelected; /* Toggle */
    [checkbox setSelected:checkBoxSelected];
}

That's it!

How can I set the Secure flag on an ASP.NET Session Cookie?

Building upon @Mark D's answer I would use web.config transforms to set all the various cookies to Secure. This includes setting anonymousIdentification cookieRequireSSL and httpCookies requireSSL.

To that end you'd setup your web.Release.config as:

<?xml version="1.0"?>
<configuration xmlns:xdt="http://schemas.microsoft.com/XML-Document-Transform">
  <system.web>
    <httpCookies xdt:Transform="SetAttributes(httpOnlyCookies)" httpOnlyCookies="true" />
    <httpCookies xdt:Transform="SetAttributes(requireSSL)" requireSSL="true" />
    <anonymousIdentification xdt:Transform="SetAttributes(cookieRequireSSL)" cookieRequireSSL="true" /> 
  </system.web>
</configuration>

If you're using Roles and Forms Authentication with the ASP.NET Membership Provider (I know, it's ancient) you'll also want to set the roleManager cookieRequireSSL and the forms requireSSL attributes as secure too. If so, your web.release.config might look like this (included above plus new tags for membership API):

<?xml version="1.0"?>
<configuration xmlns:xdt="http://schemas.microsoft.com/XML-Document-Transform">
  <system.web>
    <httpCookies xdt:Transform="SetAttributes(httpOnlyCookies)" httpOnlyCookies="true" />
    <httpCookies xdt:Transform="SetAttributes(requireSSL)" requireSSL="true" />
    <anonymousIdentification xdt:Transform="SetAttributes(cookieRequireSSL)" cookieRequireSSL="true" /> 
    <roleManager xdt:Transform="SetAttributes(cookieRequireSSL)" cookieRequireSSL="true" />
    <authentication>
        <forms xdt:Transform="SetAttributes(requireSSL)" requireSSL="true" />
    </authentication>
  </system.web>
</configuration>

Background on web.config transforms here: http://go.microsoft.com/fwlink/?LinkId=125889

Obviously this goes beyond the original question of the OP but if you don't set them all to secure you can expect that a security scanning tool will notice and you'll see red flags appear on the report. Ask me how I know. :)

Remove an element from a Bash array

This is a quick-and-dirty solution that will work in simple cases but will break if (a) there are regex special characters in $delete, or (b) there are any spaces at all in any items. Starting with:

array+=(pluto)
array+=(pippo)
delete=(pluto)

Delete all entries exactly matching $delete:

array=(`echo $array | fmt -1 | grep -v "^${delete}$" | fmt -999999`)

resulting in echo $array -> pippo, and making sure it's an array: echo $array[1] -> pippo

fmt is a little obscure: fmt -1 wraps at the first column (to put each item on its own line. That's where the problem arises with items in spaces.) fmt -999999 unwraps it back to one line, putting back the spaces between items. There are other ways to do that, such as xargs.

Addendum: If you want to delete just the first match, use sed, as described here:

array=(`echo $array | fmt -1 | sed "0,/^${delete}$/{//d;}" | fmt -999999`)

PHP list of specific files in a directory

You'll be wanting to use glob()

Example:

$files = glob('/path/to/dir/*.xml');

.NET code to send ZPL to Zebra printers

Take a look at this thread: Print ZPL codes to ZEBRA printer using PrintDocument class.

Specifically the OP pick this function from the answers to the thread:

[DllImport("kernel32.dll", SetLastError = true)]
static extern SafeFileHandle CreateFile(string lpFileName, FileAccess dwDesiredAccess,
uint dwShareMode, IntPtr lpSecurityAttributes, FileMode dwCreationDisposition,
uint dwFlagsAndAttributes, IntPtr hTemplateFile);

private void Print()
{
    // Command to be sent to the printer
    string command = "^XA^FO10,10,^AO,30,20^FDFDTesting^FS^FO10,30^BY3^BCN,100,Y,N,N^FDTesting^FS^XZ";

    // Create a buffer with the command
    Byte[] buffer = new byte[command.Length];
    buffer = System.Text.Encoding.ASCII.GetBytes(command);
    // Use the CreateFile external func to connect to the LPT1 port
    SafeFileHandle printer = CreateFile("LPT1:", FileAccess.ReadWrite, 0, IntPtr.Zero, FileMode.Open, 0, IntPtr.Zero);
    // Aqui verifico se a impressora é válida
    if (printer.IsInvalid == true)
    {
        return;
    }

    // Open the filestream to the lpt1 port and send the command
    FileStream lpt1 = new FileStream(printer, FileAccess.ReadWrite);
    lpt1.Write(buffer, 0, buffer.Length);
    // Close the FileStream connection
    lpt1.Close();

}

How to get HttpContext.Current in ASP.NET Core?

Necromancing.
YES YOU CAN, and this is how.
A secret tip for those migrating large junks chunks of code:
The following method is an evil carbuncle of a hack which is actively engaged in carrying out the express work of satan (in the eyes of .NET Core framework developers), but it works:

In public class Startup

add a property

public IConfigurationRoot Configuration { get; }

And then add a singleton IHttpContextAccessor to DI in ConfigureServices.

    // This method gets called by the runtime. Use this method to add services to the container.
    public void ConfigureServices(IServiceCollection services)
    {
        services.AddSingleton<Microsoft.AspNetCore.Http.IHttpContextAccessor, Microsoft.AspNetCore.Http.HttpContextAccessor>();

Then in Configure

    public void Configure(
              IApplicationBuilder app
             ,IHostingEnvironment env
             ,ILoggerFactory loggerFactory
    )
    {

add the DI Parameter IServiceProvider svp, so the method looks like:

    public void Configure(
           IApplicationBuilder app
          ,IHostingEnvironment env
          ,ILoggerFactory loggerFactory
          ,IServiceProvider svp)
    {

Next, create a replacement class for System.Web:

namespace System.Web
{

    namespace Hosting
    {
        public static class HostingEnvironment 
        {
            public static bool m_IsHosted;

            static HostingEnvironment()
            {
                m_IsHosted = false;
            }

            public static bool IsHosted
            {
                get
                {
                    return m_IsHosted;
                }
            }
        }
    }


    public static class HttpContext
    {
        public static IServiceProvider ServiceProvider;

        static HttpContext()
        { }


        public static Microsoft.AspNetCore.Http.HttpContext Current
        {
            get
            {
                // var factory2 = ServiceProvider.GetService<Microsoft.AspNetCore.Http.IHttpContextAccessor>();
                object factory = ServiceProvider.GetService(typeof(Microsoft.AspNetCore.Http.IHttpContextAccessor));

                // Microsoft.AspNetCore.Http.HttpContextAccessor fac =(Microsoft.AspNetCore.Http.HttpContextAccessor)factory;
                Microsoft.AspNetCore.Http.HttpContext context = ((Microsoft.AspNetCore.Http.HttpContextAccessor)factory).HttpContext;
                // context.Response.WriteAsync("Test");

                return context;
            }
        }


    } // End Class HttpContext 


}

Now in Configure, where you added the IServiceProvider svp, save this service provider into the static variable "ServiceProvider" in the just created dummy class System.Web.HttpContext (System.Web.HttpContext.ServiceProvider)

and set HostingEnvironment.IsHosted to true

System.Web.Hosting.HostingEnvironment.m_IsHosted = true;

this is essentially what System.Web did, just that you never saw it (I guess the variable was declared as internal instead of public).

// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory, IServiceProvider svp)
{
    loggerFactory.AddConsole(Configuration.GetSection("Logging"));
    loggerFactory.AddDebug();

    ServiceProvider = svp;
    System.Web.HttpContext.ServiceProvider = svp;
    System.Web.Hosting.HostingEnvironment.m_IsHosted = true;


    app.UseCookieAuthentication(new CookieAuthenticationOptions()
    {
        AuthenticationScheme = "MyCookieMiddlewareInstance",
        LoginPath = new Microsoft.AspNetCore.Http.PathString("/Account/Unauthorized/"),
        AccessDeniedPath = new Microsoft.AspNetCore.Http.PathString("/Account/Forbidden/"),
        AutomaticAuthenticate = true,
        AutomaticChallenge = true,
        CookieSecure = Microsoft.AspNetCore.Http.CookieSecurePolicy.SameAsRequest

       , CookieHttpOnly=false

    });

Like in ASP.NET Web-Forms, you'll get a NullReference when you're trying to access a HttpContext when there is none, such as it used to be in Application_Start in global.asax.

I stress again, this only works if you actually added

services.AddSingleton<Microsoft.AspNetCore.Http.IHttpContextAccessor, Microsoft.AspNetCore.Http.HttpContextAccessor>();

like I wrote you should.
Welcome to the ServiceLocator pattern within the DI pattern ;)
For risks and side effects, ask your resident doctor or pharmacist - or study the sources of .NET Core at github.com/aspnet, and do some testing.


Perhaps a more maintainable method would be adding this helper class

namespace System.Web
{

    public static class HttpContext
    {
        private static Microsoft.AspNetCore.Http.IHttpContextAccessor m_httpContextAccessor;


        public static void Configure(Microsoft.AspNetCore.Http.IHttpContextAccessor httpContextAccessor)
        {
            m_httpContextAccessor = httpContextAccessor;
        }


        public static Microsoft.AspNetCore.Http.HttpContext Current
        {
            get
            {
                return m_httpContextAccessor.HttpContext;
            }
        }


    }


}

And then calling HttpContext.Configure in Startup->Configure

public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory, IServiceProvider svp)
{
    loggerFactory.AddConsole(Configuration.GetSection("Logging"));
    loggerFactory.AddDebug();


    System.Web.HttpContext.Configure(app.ApplicationServices.
        GetRequiredService<Microsoft.AspNetCore.Http.IHttpContextAccessor>()
    );

Sending Arguments To Background Worker?

Check out the DoWorkEventArgs.Argument Property:

...
backgroundWorker1.RunWorkerAsync(yourInt);
...

private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
    // Do not access the form's BackgroundWorker reference directly.
    // Instead, use the reference provided by the sender parameter.
    BackgroundWorker bw = sender as BackgroundWorker;

    // Extract the argument.
    int arg = (int)e.Argument;

    // Start the time-consuming operation.
    e.Result = TimeConsumingOperation(bw, arg);

    // If the operation was canceled by the user, 
    // set the DoWorkEventArgs.Cancel property to true.
    if (bw.CancellationPending)
    {
        e.Cancel = true;
    }
}

PHP + MySQL transactions examples

I think I have figured it out, is it right?:

mysql_query("START TRANSACTION");

$a1 = mysql_query("INSERT INTO rarara (l_id) VALUES('1')");
$a2 = mysql_query("INSERT INTO rarara (l_id) VALUES('2')");

if ($a1 and $a2) {
    mysql_query("COMMIT");
} else {        
    mysql_query("ROLLBACK");
}

what is the difference between ajax and jquery and which one is better?

AJAX is a way of sending information between browser and server without refreshing page. It can be done with or without library like jQuery.

It is easier with the library.

Here is a list of JavaScript libraries/frameworks commonly used in AJAX development.

How do I convert a Python program to a runnable .exe Windows program?

I've used py2exe in the past and have been very happy with it. I didn't particularly enjoy using cx-freeze as much, though

How to display an alert box from C# in ASP.NET?

You can use Message box to show success message. This works great for me.

MessageBox.Show("Data inserted successfully");

Installing tensorflow with anaconda in windows

If you have anaconda version 2.7 installed on your windows, then go to anaconda prompt, type these two commands:

  1. Create a conda environment for tensorflow using conda create -n tensorflow_env tensorflow
  2. activate the tensorflow using conda activate tensorflow_env

If it is activated, then the base will be replaced by tensorflow_env i.e. now it will show (tensorflow_env) C:\Users>

You can now use import tensorflow as tf for using tensorflow in your code.

What is the difference between a deep copy and a shallow copy?

Shallow copying is creating a new object and then copying the non-static fields of the current object to the new object. If a field is a value type --> a bit-by-bit copy of the field is performed; for a reference type --> the reference is copied but the referred object is not; therefore the original object and its clone refer to the same object.

Deep copy is creating a new object and then copying the nonstatic fields of the current object to the new object. If a field is a value type --> a bit-by-bit copy of the field is performed. If a field is a reference type --> a new copy of the referred object is performed. The classes to be cloned must be flagged as [Serializable].

Illegal string offset Warning PHP

i think the only reason for this message is because target Array is actually an array like string etc (JSON -> {"host": "127.0.0.1"}) variable

What does href expression <a href="javascript:;"></a> do?

<a href="javascript:void(0);"></a>

javascript: tells the browser going to write javascript code

pandas dataframe columns scaling with sklearn

As it is being mentioned in pir's comment - the .apply(lambda el: scale.fit_transform(el)) method will produce the following warning:

DeprecationWarning: Passing 1d arrays as data is deprecated in 0.17 and will raise ValueError in 0.19. Reshape your data either using X.reshape(-1, 1) if your data has a single feature or X.reshape(1, -1) if it contains a single sample.

Converting your columns to numpy arrays should do the job (I prefer StandardScaler):

from sklearn.preprocessing import StandardScaler
scale = StandardScaler()

dfTest[['A','B','C']] = scale.fit_transform(dfTest[['A','B','C']].as_matrix())

-- Edit Nov 2018 (Tested for pandas 0.23.4)--

As Rob Murray mentions in the comments, in the current (v0.23.4) version of pandas .as_matrix() returns FutureWarning. Therefore, it should be replaced by .values:

from sklearn.preprocessing import StandardScaler
scaler = StandardScaler()

scaler.fit_transform(dfTest[['A','B']].values)

-- Edit May 2019 (Tested for pandas 0.24.2)--

As joelostblom mentions in the comments, "Since 0.24.0, it is recommended to use .to_numpy() instead of .values."

Updated example:

import pandas as pd
from sklearn.preprocessing import StandardScaler
scaler = StandardScaler()
dfTest = pd.DataFrame({
               'A':[14.00,90.20,90.95,96.27,91.21],
               'B':[103.02,107.26,110.35,114.23,114.68],
               'C':['big','small','big','small','small']
             })
dfTest[['A', 'B']] = scaler.fit_transform(dfTest[['A','B']].to_numpy())
dfTest
      A         B      C
0 -1.995290 -1.571117    big
1  0.436356 -0.603995  small
2  0.460289  0.100818    big
3  0.630058  0.985826  small
4  0.468586  1.088469  small

The request was aborted: Could not create SSL/TLS secure channel

Try this:

ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;

How to specify preference of library path?

This is an old question, but no one seems to have mentioned this.

You were getting lucky that the thing was linking at all.

You needed to change

g++ -g -Wall -o my_binary -L/my/dir -lfoo bar.cpp

to this:

g++ -g -Wall -o my_binary -L/my/dir bar.cpp -lfoo

Your linker keeps track of symbols it needs to resolve. If it reads the library first, it doesn't have any needed symbols, so it ignores the symbols in it. Specify the libraries after the things that need to link to them so that your linker has symbols to find in them.

Also, -lfoo makes it search specifically for a file named libfoo.a or libfoo.so as needed. Not libfoo.so.0. So either ln the name or rename the library as appopriate.

To quote the gcc man page:

-l library
   ...
   It makes a difference where in the command you 
   write this option; the linker searches and processes 
   libraries and object files in the order they are 
   specified.  Thus, foo.o -lz bar.o searches library z 
   after file foo.o but before bar.o.  If bar.o refers 
   to functions in z, those functions may not be loaded.

Adding the file directly to g++'s command line should have worked, unless of course, you put it prior to bar.cpp, causing the linker to ignore it for lacking any needed symbols, because no symbols were needed yet.

Warning: Each child in an array or iterator should have a unique "key" prop. Check the render method of `ListView`

I fixed it by add a property to renderSeparator Component,the code is here:

_renderSeparator(sectionID,rowID){
    return (
        <View style={styles.separatorLine} key={"sectionID_"+sectionID+"_rowID_"+rowID}></View>
    );
}

The key words of this warning is "unique", sectionID + rowID return a unique value in ListView.

java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=1888, result=0, data=null} to activity

 protected void onActivityResult(int requestCode, int resultCode, Intent data) 
    {  
        if (requestCode == CAMERE_REQUEST && resultCode == RESULT_OK && data != null) 
        {  
           Bitmap photo = (Bitmap) data.getExtras().get("data"); 
           imageView.setImageBitmap(photo);
        } 
}

You can check if the resultCode equals RESULT_OK this will only be the case if a picture is taken and selected and everything worked. This if clause here should check every condition.

Change the mouse cursor on mouse over to anchor-like style

Assuming your div has an id="myDiv", add the following to your CSS. The cursor: pointer specifies that the cursor should be the same hand icon that is use for anchors (hyperlinks):

CSS to Add

#myDiv
{
    cursor: pointer;
}

You can simply add the cursor style to your div's HTML like this:

<div style="cursor: pointer">

</div>

EDIT:

If you are determined to use jQuery for this, then add the following line to your $(document).ready() or body onload: (replace myClass with whatever class all of your divs share)

$('.myClass').css('cursor', 'pointer');

Javascript replace all "%20" with a space

If you need to remove white spaces at the end then here is a solution: https://www.geeksforgeeks.org/urlify-given-string-replace-spaces/

_x000D_
_x000D_
const stringQ1 = (string)=>{_x000D_
  //remove white space at the end _x000D_
  const arrString = string.split("")_x000D_
  for(let i = arrString.length -1 ; i>=0 ; i--){_x000D_
    let char = arrString[i];_x000D_
    _x000D_
    if(char.indexOf(" ") >=0){_x000D_
     arrString.splice(i,1)_x000D_
    }else{_x000D_
      break;_x000D_
    }_x000D_
  }_x000D_
_x000D_
  let start =0;_x000D_
  let end = arrString.length -1;_x000D_
  _x000D_
_x000D_
  //add %20_x000D_
  while(start < end){_x000D_
    if(arrString[start].indexOf(' ') >=0){_x000D_
      arrString[start] ="%20"_x000D_
      _x000D_
    }_x000D_
    _x000D_
    start++;_x000D_
  }_x000D_
  _x000D_
  return arrString.join('');_x000D_
}_x000D_
_x000D_
console.log(stringQ1("Mr John Smith   "))
_x000D_
_x000D_
_x000D_

How to hide app title in android?

use

<activity android:name=".ActivityName" 
          android:theme="@android:style/Theme.NoTitleBar">

Open a selected file (image, pdf, ...) programmatically from my Android Application?

Download source code from here (https://deepshikhapuri.wordpress.com/2017/04/24/open-pdf-file-from-sdcard-in-android-programmatically/)

activity_main.xml:

<?xml version=”1.0" encoding=”utf-8"?>
<RelativeLayout xmlns:android=”http://schemas.android.com/apk/res/android&#8221;
xmlns:tools=”http://schemas.android.com/tools&#8221;
android:id=”@+id/activity_main”
android:layout_width=”match_parent”
android:layout_height=”match_parent”
android:background=”#efefef”>

<ListView
android:layout_width=”match_parent”
android:id=”@+id/lv_pdf”
android:divider=”#efefef”
android:layout_marginLeft=”10dp”
android:layout_marginRight=”10dp”
android:layout_marginTop=”10dp”
android:layout_marginBottom=”10dp”
android:dividerHeight=”5dp”
android:layout_height=”wrap_content”>

</ListView>
</RelativeLayout>

MainActivity.java:

package com.pdffilefromsdcard;

import android.Manifest;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Environment;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.Toast;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

public class MainActivity extends AppCompatActivity {

ListView lv_pdf;
public static ArrayList<File> fileList = new ArrayList<File>();
PDFAdapter obj_adapter;
public static int REQUEST_PERMISSIONS = 1;
boolean boolean_permission;
File dir;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
init();

}

private void init() {

lv_pdf = (ListView) findViewById(R.id.lv_pdf);
dir = new File(Environment.getExternalStorageDirectory().getAbsolutePath());
fn_permission();
lv_pdf.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
Intent intent = new Intent(getApplicationContext(), PdfActivity.class);
intent.putExtra(“position”, i);
startActivity(intent);

Log.e(“Position”, i + “”);
}
});
}

public ArrayList<File> getfile(File dir) {
File listFile[] = dir.listFiles();
if (listFile != null && listFile.length > 0) {
for (int i = 0; i < listFile.length; i++) {

if (listFile[i].isDirectory()) {
getfile(listFile[i]);

} else {

boolean booleanpdf = false;
if (listFile[i].getName().endsWith(“.pdf”)) {

for (int j = 0; j < fileList.size(); j++) {
if (fileList.get(j).getName().equals(listFile[i].getName())) {
booleanpdf = true;
} else {

}
}

if (booleanpdf) {
booleanpdf = false;
} else {
fileList.add(listFile[i]);

}
}
}
}
}
return fileList;
}
private void fn_permission() {
if ((ContextCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED)) {

if ((ActivityCompat.shouldShowRequestPermissionRationale(MainActivity.this, android.Manifest.permission.READ_EXTERNAL_STORAGE))) {
} else {
ActivityCompat.requestPermissions(MainActivity.this, new String[]{android.Manifest.permission.READ_EXTERNAL_STORAGE},
REQUEST_PERMISSIONS);

}
} else {
boolean_permission = true;

getfile(dir);

obj_adapter = new PDFAdapter(getApplicationContext(), fileList);
lv_pdf.setAdapter(obj_adapter);

}
}

@Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (requestCode == REQUEST_PERMISSIONS) {

if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {

boolean_permission = true;
getfile(dir);

obj_adapter = new PDFAdapter(getApplicationContext(), fileList);
lv_pdf.setAdapter(obj_adapter);

} else {
Toast.makeText(getApplicationContext(), “Please allow the permission”, Toast.LENGTH_LONG).show();

}
}
}

}

activity_pdf.xml:

<?xml version=”1.0" encoding=”utf-8"?>
<LinearLayout xmlns:android=”http://schemas.android.com/apk/res/android&#8221;
android:layout_width=”match_parent”
android:background=”#ffffff”
android:layout_height=”match_parent”
android:orientation=”vertical”>

<com.github.barteksc.pdfviewer.PDFView
android:id=”@+id/pdfView”
android:layout_margin=”10dp”
android:layout_width=”match_parent”
android:layout_height=”match_parent” />
</LinearLayout>

PdfActivity.java:

package com.pdffilefromsdcard;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;

import com.github.barteksc.pdfviewer.PDFView;
import com.github.barteksc.pdfviewer.listener.OnLoadCompleteListener;
import com.github.barteksc.pdfviewer.listener.OnPageChangeListener;
import com.github.barteksc.pdfviewer.scroll.DefaultScrollHandle;
import com.shockwave.pdfium.PdfDocument;

import java.io.File;
import java.util.List;

public class PdfActivity extends AppCompatActivity implements OnPageChangeListener,OnLoadCompleteListener {

PDFView pdfView;
Integer pageNumber = 0;
String pdfFileName;
String TAG=”PdfActivity”;
int position=-1;

@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_pdf);
init();
}

private void init(){
pdfView= (PDFView)findViewById(R.id.pdfView);
position = getIntent().getIntExtra(“position”,-1);
displayFromSdcard();
}

private void displayFromSdcard() {
pdfFileName = MainActivity.fileList.get(position).getName();

pdfView.fromFile(MainActivity.fileList.get(position))
.defaultPage(pageNumber)
.enableSwipe(true)

.swipeHorizontal(false)
.onPageChange(this)
.enableAnnotationRendering(true)
.onLoad(this)
.scrollHandle(new DefaultScrollHandle(this))
.load();
}
@Override
public void onPageChanged(int page, int pageCount) {
pageNumber = page;
setTitle(String.format(“%s %s / %s”, pdfFileName, page + 1, pageCount));
}
@Override
public void loadComplete(int nbPages) {
PdfDocument.Meta meta = pdfView.getDocumentMeta();
printBookmarksTree(pdfView.getTableOfContents(), “-“);

}

public void printBookmarksTree(List<PdfDocument.Bookmark> tree, String sep) {
for (PdfDocument.Bookmark b : tree) {

Log.e(TAG, String.format(“%s %s, p %d”, sep, b.getTitle(), b.getPageIdx()));

if (b.hasChildren()) {
printBookmarksTree(b.getChildren(), sep + “-“);
}
}
}
}

Thanks!

Comparing two branches in Git?

git diff branch_1..branch_2

That will produce the diff between the tips of the two branches. If you'd prefer to find the diff from their common ancestor to test, you can use three dots instead of two:

git diff branch_1...branch_2

What is the difference between . (dot) and $ (dollar sign)?

My rule is simple (I'm beginner too):

  • do not use . if you want to pass the parameter (call the function), and
  • do not use $ if there is no parameter yet (compose a function)

That is

show $ head [1, 2]

but never:

show . head [1, 2]

How do I get the list of keys in a Dictionary?

List<string> keyList = new List<string>(this.yourDictionary.Keys);

How to use TLS 1.2 in Java 6

After a few hours of playing with the Oracle JDK 1.6, I was able to make it work without any code change. The magic is done by Bouncy Castle to handle SSL and allow JDK 1.6 to run with TLSv1.2 by default. In theory, it could also be applied to older Java versions with eventual adjustments.

  1. Download the latest Java 1.6 version from the Java Archive Oracle website
  2. Uncompress it on your preferred path and set your JAVA_HOME environment variable
  3. Update the JDK with the latest Java Cryptography Extension (JCE) Unlimited Strength Jurisdiction Policy Files 6
  4. Download the Bounce Castle files bcprov-jdk15to18-165.jar and bctls-jdk15to18-165.jar and copy them into your ${JAVA_HOME}/jre/lib/ext folder
  5. Modify the file ${JAVA_HOME}/jre/lib/security/java.security commenting out the providers section and adding some extra lines
    # Original security providers (just comment it)
    # security.provider.1=sun.security.provider.Sun
    # security.provider.2=sun.security.rsa.SunRsaSign
    # security.provider.3=com.sun.net.ssl.internal.ssl.Provider
    # security.provider.4=com.sun.crypto.provider.SunJCE
    # security.provider.5=sun.security.jgss.SunProvider
    # security.provider.6=com.sun.security.sasl.Provider
    # security.provider.7=org.jcp.xml.dsig.internal.dom.XMLDSigRI
    # security.provider.8=sun.security.smartcardio.SunPCSC

    # Add the Bouncy Castle security providers with higher priority
    security.provider.1=org.bouncycastle.jce.provider.BouncyCastleProvider
    security.provider.2=org.bouncycastle.jsse.provider.BouncyCastleJsseProvider
    
    # Original security providers with different priorities
    security.provider.3=sun.security.provider.Sun
    security.provider.4=sun.security.rsa.SunRsaSign
    security.provider.5=com.sun.net.ssl.internal.ssl.Provider
    security.provider.6=com.sun.crypto.provider.SunJCE 
    security.provider.7=sun.security.jgss.SunProvider
    security.provider.8=com.sun.security.sasl.Provider
    security.provider.9=org.jcp.xml.dsig.internal.dom.XMLDSigRI
    security.provider.10=sun.security.smartcardio.SunPCSC

    # Here we are changing the default SSLSocketFactory implementation
    ssl.SocketFactory.provider=org.bouncycastle.jsse.provider.SSLSocketFactoryImpl

Just to make sure it's working let's make a simple Java program to download files from one URL using https.

import java.io.*;
import java.net.*;


public class DownloadWithHttps {

    public static void main(String[] args) {
        try {
            URL url = new URL(args[0]);
            System.out.println("File to Download: " + url);
            String filename = url.getFile();
            File f = new File(filename);
            System.out.println("Output File: " + f.getName());
            BufferedInputStream in = new BufferedInputStream(url.openStream());
            FileOutputStream fileOutputStream = new FileOutputStream(f.getName());
            int bytesRead;
            byte dataBuffer[] = new byte[1024];

            while ((bytesRead = in.read(dataBuffer, 0, 1024)) != -1) {
                fileOutputStream.write(dataBuffer, 0, bytesRead);
            }
            fileOutputStream.close();

        } catch (Exception ex) {
            ex.printStackTrace();
        }

    }
}

Now, just compile the DownloadWithHttps.java program and execute it with your Java 1.6


${JAVA_HOME}/bin/javac DownloadWithHttps.java
${JAVA_HOME}/bin/java DownloadWithHttps https://repo1.maven.org/maven2/org/apache/commons/commons-lang3/3.10/commons-lang3-3.10.jar

Important note for Windows users: This solution was tested in a Linux OS, if you are using Windows, please replace the ${JAVA_HOME} by %JAVA_HOME%.

CSS - How to Style a Selected Radio Buttons Label?

You can add a span to your html and css .

Here's an example from my code ...

HTML ( JSX ):

<input type="radio" name="AMPM" id="radiostyle1" value="AM" checked={this.state.AMPM==="AM"} onChange={this.handleChange}/>  
<label for="radiostyle1"><span></span> am  </label>

<input type="radio" name="AMPM" id="radiostyle2" value="PM" checked={this.state.AMPM==="PM"} onChange={this.handleChange}/>
<label for="radiostyle2"><span></span> pm  </label>

CSS to make standard radio button vanish on screen and superimpose custom button image:

input[type="radio"] {  
    opacity:0;                                      
}

input[type="radio"] + label {
    font-size:1em;
    text-transform: uppercase;
    color: white ;  
    cursor: pointer;
    margin:auto 15px auto auto;                    
}

input[type="radio"] + label span {
    display:inline-block;
    width:30px;
    height:10px;
    margin:1px 0px 0 -30px;                       
    cursor:pointer;
    border-radius: 20%;
}


input[type="radio"] + label span {
    background-color: #FFFFFF 
}


input[type="radio"]:checked + label span{
     background-color: #660006;  
}

How to get the children of the $(this) selector?

Without knowing the ID of the DIV I think you could select the IMG like this:

$("#"+$(this).attr("id")+" img:first")

Getting vertical gridlines to appear in line plot in matplotlib

Short answer (read below for more info):

ax.grid(axis='both', which='both')

enter image description here

What you do is correct and it should work.

However, since the X axis in your example is a DateTime axis the Major tick-marks (most probably) are appearing only at the both ends of the X axis. The other visible tick-marks are Minor tick-marks.

The ax.grid() method, by default, draws grid lines on Major tick-marks. Therefore, nothing appears in your plot.

Use the code below to highlight the tick-marks. Majors will be Blue while Minors are Red.

ax.tick_params(which='both', width=3)
ax.tick_params(which='major', length=20, color='b')
ax.tick_params(which='minor', length=10, color='r')

Now to force the grid lines to be appear also on the Minor tick-marks, pass the which='minor' to the method:

ax.grid(b=True, which='minor', axis='x', color='#000000', linestyle='--')

or simply use which='both' to draw both Major and Minor grid lines. And this a more elegant grid line:

ax.grid(b=True, which='minor', axis='both', color='#888888', linestyle='--')
ax.grid(b=True, which='major', axis='both', color='#000000', linestyle='-')

Generator expressions vs. list comprehensions

Python 3.7:

List comprehensions are faster.

enter image description here

Generators are more memory efficient. enter image description here

As all others have said, if you're looking to scale infinite data, you'll need a generator eventually. For relatively static small and medium-sized jobs where speed is necessary, a list comprehension is best.

Reducing the gap between a bullet and text in a list item

ul li:before {
    content: "";
    margin-left: "your negative value";
}

How to parse this string in Java?

 String result;
 String str = "/usr/local/apache2/resumes/dir1/dir2/dir3/dir4";
 String regex ="(dir)+[\\d]";
 Matcher matcher = Pattern.compile( regex ).matcher( str);
  while (matcher.find( ))
  {
  result = matcher.group();     
  System.out.println(result);                 
}

output-- dir1 dir2 dir3 dir4

Mockito: Inject real objects into private @Autowired fields

Use @Spy annotation

@RunWith(MockitoJUnitRunner.class)
public class DemoTest {
    @Spy
    private SomeService service = new RealServiceImpl();

    @InjectMocks
    private Demo demo;

    /* ... */
}

Mockito will consider all fields having @Mock or @Spy annotation as potential candidates to be injected into the instance annotated with @InjectMocks annotation. In the above case 'RealServiceImpl' instance will get injected into the 'demo'

For more details refer

Mockito-home

@Spy

@Mock

Trim spaces from start and end of string

Here is my current code, the 2nd line works if I comment the 3rd line, but don't work if I leave it how it is.

var page_title = $(this).val().replace(/[^a-zA-Z0-9\s]/g, '');
page_title = page_title.replace(/^\s\s*/, '').replace(/\s\s*$/, '');
page_title = page_title.replace(/([\s]+)/g, '-');

How to make "if not true condition"?

On Unix systems that supports it (not macOS it seems):

if getent passwd "$username" >/dev/null; then
    printf 'User %s exists\n' "$username"
else
    printf 'User %s does not exist\n' "$username"
fi 

This has the advantage that it will query any directory service that may be in use (YP/NIS or LDAP etc.) and the local password database file.


The issue with grep -q "$username" /etc/passwd is that it will give a false positive when there is no such user, but something else matches the pattern. This could happen if there is a partial or exact match somewhere else in the file.

For example, in my passwd file, there is a line saying

build:*:21:21:base and xenocara build:/var/empty:/bin/ksh

This would provoke a valid match on things like cara and enoc etc., even though there are no such users on my system.

For a grep solution to be correct, you will need to properly parse the /etc/passwd file:

if cut -d ':' -f 1 /etc/passwd | grep -qxF "$username"; then
    # found
else
    # not found
fi

... or any other similar test against the first of the :-delimited fields.

Gradle's dependency cache may be corrupt (this sometimes occurs after a network connection timeout.)

Try the next step to "Refresh" your IDE (android studio)

1. Let Gradle rebuild your auto-genrated files by click Build | Rebuild
2. Also try Choose File | Invalidate Caches/Restart.

How to install node.js as windows service?

I'm not addressing the question directly, but providing an alternative that might also meet your requirement in a more node.js fashion way.

Functionally the requirements are:

  1. Have the logic (app) running in the background
  2. Be able to start/stop the logic
  3. Automatically start the logic when system boots up

These requirements can be satisfied by using a process manager (PM) and making the process manager start on system startup. Two good PMs that are Windows-friendly are:

To make the PM start automatically, the most simple way is to create a scheduled task with a "At Startup" trigger:

enter image description here

'int' object has no attribute '__getitem__'

you can also covert int to str first and assign index to it then again convert it to int like this:

int(str(x)[n]) //where x is an integer value

How to exit when back button is pressed?

Add this code in the activity from where you want to exit from the app on pressing back button:

@Override
public void onBackPressed() {
    super.onBackPressed();
    exitFromApp();
}

private void exitFromApp() {
    Intent intent = new Intent(Intent.ACTION_MAIN);
    intent.addCategory(Intent.CATEGORY_HOME);
    startActivity(intent);
}

need to test if sql query was successful

You can use this to check if there are any results ($result) from a query:

if (mysqli_num_rows($result) != 0)
 {
  //results found
 } else {
  // results not found
 }

Excel- compare two cell from different sheet, if true copy value from other cell

In your destination field you want to use VLOOKUP like so:

=VLOOKUP(Sheet1!A1:A100,Sheet2!A1:F100,6,FALSE)

VLOOKUP Arguments:

  1. The set fields you want to lookup.
  2. The table range you want to lookup up your value against. The first column of your defined table should be the column you want compared against your lookup field. The table range should also contain the value you want to display (Column F).
  3. This defines what field you want to display upon a match.
  4. FALSE tells VLOOKUP to do an exact match.

In javascript, how do you search an array for a substring match

ref: In javascript, how do you search an array for a substring match

The solution given here is generic unlike the solution 4556343#4556343, which requires a previous parse to identify a string with which to join(), that is not a component of any of the array strings.
Also, in that code /!id-[^!]*/ is more correctly, /![^!]*id-[^!]*/ to suit the question parameters:

  1. "search an array ..." (of strings or numbers and not functions, arrays, objects, etc.)
  2. "for only part of the string to match " (match can be anywhere)
  3. "return the ... matched ... element" (singular, not ALL, as in "... the ... elementS")
  4. "with the full string" (include the quotes)

... NetScape / FireFox solutions (see below for a JSON solution):

javascript:         /* "one-liner" statement solution */
   alert(
      ["x'!x'\"id-2",'\' "id-1 "',   "item","thing","id-3-text","class" ] .
         toSource() . match( new RegExp( 
            '[^\\\\]("([^"]|\\\\")*' + 'id-' + '([^"]|\\\\")*[^\\\\]")' ) ) [1]
   );

or

javascript:
   ID = 'id-' ;
   QS = '([^"]|\\\\")*' ;           /* only strings with escaped double quotes */
   RE = '[^\\\\]("' +QS+ ID +QS+ '[^\\\\]")' ;/* escaper of escaper of escaper */
   RE = new RegExp( RE ) ;
   RA = ["x'!x'\"id-2",'\' "id-1 "',   "item","thing","id-3-text","class" ] ;
   alert(RA.toSource().match(RE)[1]) ;

displays "x'!x'\"id-2".
Perhaps raiding the array to find ALL matches is 'cleaner'.

/* literally (? backslash star escape quotes it!) not true, it has this one v  */
javascript:                            /* purely functional - it has no ... =! */
   RA = ["x'!x'\"id-2",'\' "id-1 "',   "item","thing","id-3-text","class" ] ;
   function findInRA(ra,id){
      ra.unshift(void 0) ;                                     /* cheat the [" */
      return ra . toSource() . match( new RegExp(
             '[^\\\\]"' + '([^"]|\\\\")*' + id + '([^"]|\\\\")*' + '[^\\\\]"' ,
             'g' ) ) ;
   }
   alert( findInRA( RA, 'id-' ) . join('\n\n') ) ;

displays:

     "x'!x'\"id-2"

     "' \"id-1 \""

     "id-3-text"

Using, JSON.stringify():

javascript:                             /* needs prefix cleaning */
   RA = ["x'!x'\"id-2",'\' "id-1 "',   "item","thing","id-3-text","class" ] ;
   function findInRA(ra,id){
      return JSON.stringify( ra ) . match( new RegExp(
             '[^\\\\]"([^"]|\\\\")*' + id + '([^"]|\\\\")*[^\\\\]"' ,
             'g' ) ) ;
   }
   alert( findInRA( RA, 'id-' ) . join('\n\n') ) ;

displays:

    ["x'!x'\"id-2"

    ,"' \"id-1 \""

    ,"id-3-text"

wrinkles:

  • The "unescaped" global RegExp is /[^\]"([^"]|\")*id-([^"]|\")*[^\]"/g with the \ to be found literally. In order for ([^"]|\")* to match strings with all "'s escaped as \", the \ itself must be escaped as ([^"]|\\")*. When this is referenced as a string to be concatenated with id-, each \ must again be escaped, hence ([^"]|\\\\")*!
  • A search ID that has a \, *, ", ..., must also be escaped via .toSource() or JSON or ... .
  • null search results should return '' (or "" as in an EMPTY string which contains NO "!) or [] (for all search).
  • If the search results are to be incorporated into the program code for further processing, then eval() is necessary, like eval('['+findInRA(RA,ID).join(',')+']').

--------------------------------------------------------------------------------

Digression:
Raids and escapes? Is this code conflicted?
The semiotics, syntax and semantics of /* it has no ... =! */ emphatically elucidates the escaping of quoted literals conflict.

Does "no =" mean:

  • "no '=' sign" as in javascript:alert('\x3D') (Not! Run it and see that there is!),
  • "no javascript statement with the assignment operator",
  • "no equal" as in "nothing identical in any other code" (previous code solutions demonstrate there are functional equivalents),
  • ...

Quoting on another level can also be done with the immediate mode javascript protocol URI's below. (// commentaries end on a new line (aka nl, ctrl-J, LineFeed, ASCII decimal 10, octal 12, hex A) which requires quoting since inserting a nl, by pressing the Return key, invokes the URI.)

javascript:/* a comment */  alert('visible')                                ;
javascript:// a comment ;   alert(  'not'  ) this is all comment             %0A;
javascript:// a comment %0A alert('visible but  %\0A  is wrong ')   // X     %0A
javascript:// a comment %0A alert('visible but %'+'0A is a pain to type')   ;

Note: Cut and paste any of the javascript: lines as an immediate mode URI (at least, at most?, in FireFox) to use first javascript: as a URI scheme or protocol and the rest as JS labels.

Case insensitive access for generic dictionary

There's no way to specify a StringComparer at the point where you try to get a value. If you think about it, "foo".GetHashCode() and "FOO".GetHashCode() are totally different so there's no reasonable way you could implement a case-insensitive get on a case-sensitive hash map.

You can, however, create a case-insensitive dictionary in the first place using:-

var comparer = StringComparer.OrdinalIgnoreCase;
var caseInsensitiveDictionary = new Dictionary<string, int>(comparer);

Or create a new case-insensitive dictionary with the contents of an existing case-sensitive dictionary (if you're sure there are no case collisions):-

var oldDictionary = ...;
var comparer = StringComparer.OrdinalIgnoreCase;
var newDictionary = new Dictionary<string, int>(oldDictionary, comparer);

This new dictionary then uses the GetHashCode() implementation on StringComparer.OrdinalIgnoreCase so comparer.GetHashCode("foo") and comparer.GetHashcode("FOO") give you the same value.

Alternately, if there are only a few elements in the dictionary, and/or you only need to lookup once or twice, you can treat the original dictionary as an IEnumerable<KeyValuePair<TKey, TValue>> and just iterate over it:-

var myKey = ...;
var myDictionary = ...;
var comparer = StringComparer.OrdinalIgnoreCase;
var value = myDictionary.FirstOrDefault(x => String.Equals(x.Key, myKey, comparer)).Value;

Or if you prefer, without the LINQ:-

var myKey = ...;
var myDictionary = ...;
var comparer = StringComparer.OrdinalIgnoreCase;
int? value;
foreach (var element in myDictionary)
{
  if (String.Equals(element.Key, myKey, comparer))
  {
    value = element.Value;
    break;
  }
}

This saves you the cost of creating a new data structure, but in return the cost of a lookup is O(n) instead of O(1).

Golang read request body

I could use the GetBody from Request package.

Look this comment in source code from request.go in net/http:

GetBody defines an optional func to return a new copy of Body. It is used for client requests when a redirect requires reading the body more than once. Use of GetBody still requires setting Body. For server requests it is unused."

GetBody func() (io.ReadCloser, error)

This way you can get the body request without make it empty.

Sample:

getBody := request.GetBody
copyBody, err := getBody()
if err != nil {
    // Do something return err
}
http.DefaultClient.Do(request)

How to update MySql timestamp column to current timestamp on PHP?

Use this query:

UPDATE `table` SET date_date=now();

Sample code can be:

<?php
$con = mysql_connect("localhost","peter","abc123");
if (!$con)
  {
  die('Could not connect: ' . mysql_error());
  }

mysql_select_db("my_db", $con);

mysql_query("UPDATE `table` SET date_date=now()");

mysql_close($con);
?>

Convert json to a C# array?

Old question but worth adding an answer if using .NET Core 3.0 or later. JSON serialization/deserialization is built into the framework (System.Text.Json), so you don't have to use third party libraries any more. Here's an example based off the top answer given by @Icarus

using System;
using System.Collections.Generic;

namespace ConsoleApp
{
    class Program
    {
        static void Main(string[] args)
        {
            var json = "[{\"Name\":\"John Smith\", \"Age\":35}, {\"Name\":\"Pablo Perez\", \"Age\":34}]";

            // use the built in Json deserializer to convert the string to a list of Person objects
            var people = System.Text.Json.JsonSerializer.Deserialize<List<Person>>(json);

            foreach (var person in people)
            {
                Console.WriteLine(person.Name + " is " + person.Age + " years old.");
            }
        }

        public class Person
        {
            public int Age { get; set; }
            public string Name { get; set; }
        }
    }
}