Programs & Examples On #Modulino

My kubernetes pods keep crashing with "CrashLoopBackOff" but I can't find any log

In your yaml file, add command and args lines:

...
containers:
      - name: api
        image: localhost:5000/image-name 
        command: [ "sleep" ]
        args: [ "infinity" ]
...

Works for me.

How to uninstall / completely remove Oracle 11g (client)?

Do everything suggested by ziesemer.

You may also want to remove from the registry:

HKEY_LOCAL_MACHINE\SOFTWARE\ODBC\ODBCINST.INI\<any Ora* drivers> keys     

HKEY_LOCAL_MACHINE\SOFTWARE\ODBC\ODBCINST.INI\ODBC Drivers<any Ora* driver> values

So they no longer appear in the "ODBC Drivers that are installed on your system" in ODBC Data Source Administrator

Removing multiple files from a Git repo that have already been deleted from disk

git ls-files --deleted -z | xargs -0 git rm --cached

This will remove all deleted files that were previous tracked by git, as well as handle the case where your filenames have spaces in them.

Depending on your POSIX variant, you may need to use xargs -0 -r: this will cause xargs to gracefully exit when piped null content.

EDIT: --cached and --deleted flags are used in tandem to safeguard against accidentally deleting files that have not already been deleted.

Android Studio 3.0 Flavor Dimension Issue

If you want not to use dimensions you should use this line

android { 
compileSdkVersion 24

...
flavorDimensions "default"
...
}

but if you want ti use dimensions you should declare your dimension name first and then use this name after THIS example is from the documentations:

android {
...
buildTypes {
debug {...}
release {...}
}

  // Specifies the flavor dimensions you want to use. The order in which you
  // list each dimension determines its priority, from highest to lowest,
  // when Gradle merges variant sources and configurations. You must assign
  // each product flavor you configure to one of the flavor dimensions.
  flavorDimensions "api", "mode"

  productFlavors {
    demo {
  // Assigns this product flavor to the "mode" flavor dimension.
  dimension "mode"
  ...
}

full {
  dimension "mode"
  ...
}

// Configurations in the "api" product flavors override those in "mode"
// flavors and the defaultConfig block. Gradle determines the priority
// between flavor dimensions based on the order in which they appear next
// to the flavorDimensions property above--the first dimension has a higher
// priority than the second, and so on.
minApi24 {
  dimension "api"
  minSdkVersion 24
  // To ensure the target device receives the version of the app with
  // the highest compatible API level, assign version codes in increasing
  // value with API level. To learn more about assigning version codes to
  // support app updates and uploading to Google Play, read Multiple APK Support
  versionCode 30000 + android.defaultConfig.versionCode
  versionNameSuffix "-minApi24"
  ...
}

minApi23 {
  dimension "api"
  minSdkVersion 23
  versionCode 20000  + android.defaultConfig.versionCode
  versionNameSuffix "-minApi23"
  ...
}

minApi21 {
  dimension "api"
  minSdkVersion 21
  versionCode 10000  + android.defaultConfig.versionCode
  versionNameSuffix "-minApi21"
  ...
    }
  }
}
...

Trying to get Laravel 5 email to work

My .env file configuration is like this for laravel 5.1

MAIL_DRIVER=smtp
MAIL_HOST=smtp.gmail.com
MAIL_PORT=587
[email protected]
MAIL_PASSWORD=****************
MAIL_ENCRYPTION=tls

here most important thing is that I created gmail application specific password(16 digit).

I need to reveal one more thing since no luck for any of configuration. That is, whenever I changed .env file need to run this command

php artisan config:cache

And this is most most most important because without this command laravel executes previous settings from it's cache. It's required me more than 10 hours to figure out.

How to install pywin32 module in windows 7

You can install pywin32 wheel packages from PYPI with PIP by pointing to this package: https://pypi.python.org/pypi/pypiwin32 No need to worry about first downloading the package, just use pip:

pip install pypiwin32

Currently I think this is "the easiest" way to get in working :) Hope this helps.

How to make PopUp window in java

Hmm it has been a little while but from what I remember...
If you want a custom window you can just make a new frame and make it show up just like you would with the main window. Java also has a great dialog library that you can check out here:

How to Make Dialogs

That may be able to give you the functionality you are looking for with a whole lot less effort.

Object[] possibilities = {"ham", "spam", "yam"};
String s = (String)JOptionPane.showInputDialog(
                    frame,
                    "Complete the sentence:\n"
                    + "\"Green eggs and...\"",
                    "Customized Dialog",
                    JOptionPane.PLAIN_MESSAGE,
                    icon,
                    possibilities,
                    "ham");

//If a string was returned, say so.
if ((s != null) && (s.length() > 0)) {
    setLabel("Green eggs and... " + s + "!");
    return;
}

//If you're here, the return value was null/empty.
setLabel("Come on, finish the sentence!");

If you do not care to limit the user's choices, you can either use a form of the showInputDialog method that takes fewer arguments or specify null for the array of objects. In the Java look and feel, substituting null for possibilities results in a dialog that has a text field and looks like this:

App can't be opened because it is from an unidentified developer

Try looking into Gatekeeper. I am not sure of too much Mac stuff, but I heard that you can enable it in there.

How to check if a value exists in an object using JavaScript

The simple answer to this is given below.

This is working because every JavaScript type has a “constructor” property on it prototype”.

let array = []
array.constructor === Array
// => true


let data = {}
data.constructor === Object
// => true

sql searching multiple words in a string

In SQL Server 2005+ with Full-Text indexing switched on, I'd do the following:

SELECT *
  FROM T
 WHERE CONTAINS(C, '"David" OR "Robi" OR "Moses"');

If you wanted your search to bring back results where the result is prefixed with David, Robi or Moses you could do:

SELECT *
  FROM T
 WHERE CONTAINS(C, '"David*" OR "Robi*" OR "Moses*"');

What is 0x10 in decimal?

0x means the number is hexadecimal, or base 16.

0x10 is 16.

event.returnValue is deprecated. Please use the standard event.preventDefault() instead

I saw this warning on many websites. Also, I saw that YUI 3 library also gives the same warning. It's a warning generated from the library (whether is it jQuery or YUI).

How to check for palindrome using Python logic

The awesome part of python is the things you can do with it. You don't have to use indexes for strings.

The following will work (using slices)

def palindrome(n):
    return n == n[::-1]

What it does is simply reverses n, and checks if they are equal. n[::-1] reverses n (the -1 means to decrement)

"2) My for loop (in in range (999, 100, -1), is this a bad way to do it in Python?"

Regarding the above, you want to use xrange instead of range (because range will create an actual list, while xrange is a fast generator)

My opinions on question 3

I learned C before Python, and I just read the docs, and played around with it using the console. (and by doing Project Euler problems as well :)

Angular 2.0 and Modal Dialog

Check ASUI dialog which create at runtime. There is no need of hide and show logic. Simply service will create a component at runtime using AOT ASUI NPM

Modifying a file inside a jar

Not sure if this help, but you can edit without extracting:

  1. Open the jar file from vi editor
  2. Select the file you want to edit from the list
  3. Press enter to open the file do the changers and save it pretty simple

Check the blog post for more details http://vinurip.blogspot.com/2015/04/how-to-edit-contents-of-jar-file-on-mac.html

Add UIPickerView & a Button in Action sheet - How?

For those guys who are tying to find the DatePickerDoneClick function... here is the simple code to dismiss the Action Sheet. Obviously aac should be an ivar (the one which goes in your implmentation .h file)


- (void)DatePickerDoneClick:(id)sender{
    [aac dismissWithClickedButtonIndex:0 animated:YES];
}

De-obfuscate Javascript code to make it readable again

I have tried both of online jsbeautifier(jsbeautifier, jsnice), these tools gave me beautiful js code,

but couldn't copy for very large js (must be bug, when i copy, copied buffer contains only one character '-').

I found that only working solution was prettyjs:

http://www.thaoh.net/prettyjs/

How to apply filters to *ngFor?

I've created a plunker based off of the answers here and elsewhere.

Additionally I had to add an @Input, @ViewChild, and ElementRef of the <input> and create and subscribe() to an observable of it.

Angular2 Search Filter: PLUNKR (UPDATE: plunker no longer works)

Jquery click event not working after append method

Use on :

$('#registered_participants').on('click', '.new_participant_form', function() {

So that the click is delegated to any element in #registered_participants having the class new_participant_form, even if it's added after you bound the event handler.

Regex to match only letters

Pattern pattern = Pattern.compile("^[a-zA-Z]+$");

if (pattern.matcher("a").find()) {

   ...do something ......
}

Mathematical functions in Swift

To be perfectly precise, Darwin is enough. No need to import the whole Cocoa framework.

import Darwin

Of course, if you need elements from Cocoa or Foundation or other higher level frameworks, you can import them instead

Rock, Paper, Scissors Game Java

I would recommend making Rock, Paper and Scissors objects. The objects would have the logic of both translating to/from Strings and also "knowing" what beats what. The Java enum is perfect for this.

public enum Type{

  ROCK, PAPER, SCISSOR;

  public static Type parseType(String value){
     //if /else logic here to return either ROCK, PAPER or SCISSOR

     //if value is not either, you can return null
  }
}

The parseType method can return null if the String is not a valid type. And you code can check if the value is null and if so, print "invalid try again" and loop back to re-read the Scanner.

Type person=null;

 while(person==null){
      System.out.println("Enter your play: "); 
      person= Type.parseType(scan.next());
      if(person ==null){
         System.out.println("invalid try again");
      }
 }

Furthermore, your type enum can determine what beats what by having each Type object know:

public enum Type{

    //...

    //each type will implement this method differently
    public abstract boolean beats(Type other);


}

each type will implement this method differently to see what beats what:

ROCK{

   @Override
   public boolean beats(Type other){            
        return other ==  SCISSOR;

   }
}

 ...

Then in your code

 Type person, computer;
   if (person.equals(computer)) 
   System.out.println("It's a tie!");
  }else if(person.beats(computer)){
     System.out.println(person+ " beats " + computer + "You win!!"); 
  }else{
     System.out.println(computer + " beats " + person+ "You lose!!");
  }

Which port(s) does XMPP use?

According to Extensible Messaging and Presence Protocol (Wikipedia), the standard TCP port for the server is 5222.

The client would presumably use the same ports as the messaging protocol, but can also use http (port 80) and https (port 443) for message delivery. These have the advantage of working for users behind firewalls, so your network admin should not need to get involved.

SQLite error 'attempt to write a readonly database' during insert?

I got the same error from IIS under windows 7. To fix this error i had to add full control permissions to IUSR account for sqlite database file. You don't need to change permissions if you use sqlite under webmatrix instead of IIS.

How can I get a file's size in C++?

It is also possible to find that out using the fopen(),fseek() and ftell() function.

int get_file_size(std::string filename) // path to file
{
    FILE *p_file = NULL;
    p_file = fopen(filename.c_str(),"rb");
    fseek(p_file,0,SEEK_END);
    int size = ftell(p_file);
    fclose(p_file);
    return size;
}

How to split elements of a list?

I had to split a list for feature extraction in two parts lt,lc:

ltexts = ((df4.ix[0:,[3,7]]).values).tolist()
random.shuffle(ltexts)

featsets = [(act_features((lt)),lc) 
              for lc, lt in ltexts]

def act_features(atext):
  features = {}
  for word in nltk.word_tokenize(atext):
     features['cont({})'.format(word.lower())]=True
  return features

How can I check a C# variable is an empty string "" or null?

if (string.IsNullOrEmpty(myString)) {
   //
}

Eliminating NAs from a ggplot

Not sure if you have solved the problem. For this issue, you can use the "filter" function in the dplyr package. The idea is to filter the observations/rows whose values of the variable of your interest is not NA. Next, you make the graph with these filtered observations. You can find my codes below, and note that all the name of the data frame and variable is copied from the prompt of your question. Also, I assume you know the pipe operators.

library(tidyverse) 

MyDate %>%
   filter(!is.na(the_variable)) %>%
     ggplot(aes(x= the_variable, fill=the_variable)) + 
        geom_bar(stat="bin") 

You should be able to remove the annoying NAs on your plot. Hope this works :)

Oracle find a constraint

maybe this can help..

SELECT constraint_name, constraint_type, column_name
from user_constraints natural join user_cons_columns
where table_name = "my_table_name";

HTML input field hint

the best way to give a hint is placeholder like this:

<input.... placeholder="hint".../>

Hive: how to show all partitions of a table?

CLI has some limit when ouput is displayed. I suggest to export output into local file:

$hive -e 'show partitions table;' > partitions

How can I load storyboard programmatically from class?

In your storyboard go to the Attributes inspector and set the view controller's Identifier. You can then present that view controller using the following code.

UIStoryboard *sb = [UIStoryboard storyboardWithName:@"MainStoryboard" bundle:nil];
UIViewController *vc = [sb instantiateViewControllerWithIdentifier:@"myViewController"];
vc.modalTransitionStyle = UIModalTransitionStyleFlipHorizontal;
[self presentViewController:vc animated:YES completion:NULL];

Reading images in python

If you just want to read an image in Python using the specified libraries only, I will go with matplotlib

In matplotlib :

import matplotlib.image
read_img = matplotlib.image.imread('your_image.png')

Installing TensorFlow on Windows (Python 3.6.x)

For someone w/ TF 1.3:

Current TensorFlow 1.3 support Python 3.6, and then you need cuDNN 6 (cudnn64_6.dll)

Based on Tensorflow on windows - ImportError: DLL load failed: The specified module could not be found and this: https://github.com/tensorflow/tensorflow/issues/7705

How prevent CPU usage 100% because of worker process in iis

Diagnosing

In terms of diagnosing what App Pool is causing trouble, you can:

  1. Select the server
  2. Go to IIS > Worker Processes

Server Settings

This should bring up a menu like this so you can determine which App Pool is running amok.

Worker Processes

From there you can simply restart the the app pool and 9 times out of 10 that will fix any immediate issues you're having.

Treating

Unless you run some sort of controversial business, this is probably not a DDOS attack. It's likely that some code is just hanging because it couldn't get through to another server or got stuck in a loop or mis-allocated resources or your app pool just hasn't been recycled in a while.

You can deal with this problem programmatically without having to manually identify, log in, and recycle the app pool. Just configure the CPU property on your App Pool. You can have it kill (and automatically restart) your process anytime you reach a CPU threshold for a certain amount of time.

In your case, if you want it to restart at 80%, you can right click on the app pool and go to Advanced Settings and apply the following configurations:

App Pool Advanced Settings

NOTE: As kraken101 pointed out, different IIS GUIs have treated this differently over time. While the config value is always in 1/1000 of a %, sometimes the GUI takes the whole percent.

You can add this to your config section like this:

<applicationPools>
   <add name="DefaultAppPool">
     <cpu limit="80000" action="KillW3wp" resetInterval="00:01:00" />
   </add>
</applicationPools>

Alternatively, you could script it with Powershell's WebAdministration Module like this:
(*make sure web-scripting-tools is enabled)

Import-Module WebAdministration

$appPoolName = "DefaultAppPool"
$appPool = Get-Item "IIS:\AppPools\$appPoolName"
$appPool.cpu.limit = 80000
$appPool.cpu.action = "KillW3wp"
$appPool.cpu.resetInterval = "00:01:00"
$appPool | Set-Item

Preventing

The steps above will help fix some things once they've broken, but won't really solve any underlying issues you have.

Here are some resources on doing performance monitoring:

Mock MVC - Add Request Parameter to test

When i analyzed your code. I have also faced the same problem but my problem is if i give value for both first and last name means it is working fine. but when i give only one value means it says 400. anyway use the .andDo(print()) method to find out the error

public void testGetUserByName() throws Exception {
    String firstName = "Jack";
    String lastName = "s";       
    this.userClientObject = client.createClient();
    mockMvc.perform(get("/byName")
            .sessionAttr("userClientObject", this.userClientObject)
            .param("firstName", firstName)
            .param("lastName", lastName)               
    ).andDo(print())
     .andExpect(status().isOk())
            .andExpect(content().contentType("application/json"))
            .andExpect(jsonPath("$[0].id").exists())
            .andExpect(jsonPath("$[0].fn").value("Marge"));
}

If your problem is org.springframework.web.bind.missingservletrequestparameterexception you have to change your code to

@RequestMapping(value = "/byName", method = RequestMethod.GET)
    @ResponseStatus(HttpStatus.OK)
    public
    @ResponseBody
    String getUserByName(
        @RequestParam( value="firstName",required = false) String firstName,
        @RequestParam(value="lastName",required = false) String lastName, 
        @ModelAttribute("userClientObject") UserClient userClient)
    {

        return client.getUserByName(userClient, firstName, lastName);
    }

How to scale Docker containers in production

Update: 2019-03-11

First of all thanks for those who have upvoted this answer over the years.

Please be aware that this question was asked in August 2013, when Docker was still a very new technology. Since then: Kubernetes was launched on June 2014, Docker swarm was integrated into the Docker engine in Feb 2015, Amazon launched it's container solution, ECS, in April 2015 and Google launched GKE in August 2015. It's fair to say the production container landscape has changed substantially.


The short answer is that you'd have to write your own logic to do this.

I would expect this kind of feature to emerge from the following projects, built on top of docker, and designed to support applications in production:

Update 1

Another related project I recently discovered:

Update 2

The latest release Openstack contains support for managing Docker containers:

Update 3

System for managing Docker instances

And a presentation on how to use tools like Packer, Docker and Serf to deliver an immutable server infrastructure pattern

Update 4

A neat article on how to wire together docker containers using serf:

Update 5

Run Docker on Mesos using the Marathon framework

Mesosphere Docker Developer Tutorial

Update 6

Run Docker on Tsuru as it supports docker-cluster and segregated scheduler deploy

Update 7

Docker-based environments orchestration

maestro-ng

Update 8

decking.io

Update 9

Google kubernetes

Update 10

Redhat have refactored their openshift PAAS to integrate Docker

Update 11

A Docker NodeJS lib wrapping the Docker command line and managing it from a json file.

Update 12

Amazon's new container service enables scaling in the cluster.

Update 13

Strictly speaking Flocker does not "scale" applications, but it is designed to fufil a related function of making stateful containers (running databases services?) portable across multiple docker hosts:

https://clusterhq.com/

Update 14

A project to create portable templates that describe Docker applications:

http://panamax.io/

Update 15

The Docker project is now addressing orchestration natively (See announcement)

Update 16

Spotify Helios

See also:

Update 17

The Openstack project now has a new "container as a service" project called Magnum:

Shows a lot of promise, enables the easy setup of Docker orchestration frameworks like Kubernetes and Docker swarm.

Update 18

Rancher is a project that is maturing rapidly

http://rancher.com/

Nice UI and strong focus on hyrbrid Docker infrastructures

Update 19

The Lattice project is an offshoot of Cloud Foundry for managing container clusters.

Update 20

Docker recently bought Tutum:

https://www.docker.com/tutum

Update 21

Package manager for applications deployed on Kubernetes.

http://helm.sh/

Update 22

Vamp is an open source and self-hosted platform for managing (micro)service oriented architectures that rely on container technology.

http://vamp.io/

Update 23

A Distributed, Highly Available, Datacenter-Aware Scheduler

From the guys that gave us Vagrant and other powerful tools.

Update 24

Container hosting solution for AWS, open source and based on Kubernetes

https://supergiant.io/

Update 25

Apache Mesos based container hosted located in Germany

https://sloppy.io/features/#features

And Docker Inc. also provide a container hosting service called Docker cloud

https://cloud.docker.com/

Update 26

Jelastic is a hosted PAAS service that scales containers automatically.

Home does not contain an export named Home

Use

import Home from './layouts/Home'

rather than

import { Home } from './layouts/Home'

Remove {} from Home

Bash command line and input limit

There is a buffer limit of something like 1024. The read will simply hang mid paste or input. To solve this use the -e option.

http://linuxcommand.org/lc3_man_pages/readh.html

-e use Readline to obtain the line in an interactive shell

Change your read to read -e and annoying line input hang goes away.

How to add Python to Windows registry

I had the same issue while trying to install bots on a Windows Server. Took me a while to find a solution, but this is what worked for me:

  1. Open Command Prompt as Administrator
  2. Copy this: reg add HKLM\SOFTWARE\Python\PythonCore\2.7\InstallPath /ve /t REG_SZ /d "C:\Python27" /f and tailor for your specifications.
  3. Right click and paste the tailored version into Command Prompt and hit Enter!

Anyway, I hope that this can help someone in the future.

Ruby on Rails - Import Data from a CSV file

require 'csv'    

csv_text = File.read('...')
csv = CSV.parse(csv_text, :headers => true)
csv.each do |row|
  Moulding.create!(row.to_hash)
end

How to get the function name from within that function?

You could use Function.name:

In most implementations of JavaScript, once you have your constructor's reference in scope, you can get its string name from its name property (e.g. Function.name, or Object.constructor.name

You could use Function.callee:

The native arguments.caller method has been deprecated, but most browsers support Function.caller, which will return the actual invoking object (its body of code): https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/caller?redirectlocale=en-US&redirectslug=JavaScript%2FReference%2FGlobal_Objects%2FFunction%2Fcaller

You could create a source map:

If what you need is the literal function signature (the "name" of it) and not the object itself, you might have to resort to something a little more customized, like creating an array reference of the API string values you'll need to access frequently. You can map them together using Object.keys() and your array of strings, or look into Mozilla's source maps library on GitHub, for bigger projects: https://github.com/mozilla/source-map

Twitter bootstrap 3 two columns full height

I wrote a simple CSS compatible with Bootstrap to create full width and height tables:

Fiddle : https://jsfiddle.net/uasbfc5e/4/

The principle is :

  • add the "tablefull" on a main DIV
  • then implicitly, the DIV below will create rows
  • and then DIV below the rows will be cells
  • You can use the class "tableheader" for headers or similar

The HTML :

<div class="tablefull">
    <div class="tableheader">
        <div class="col-xs-4">Header A</div>
        <div class="col-xs-4">B</div>
        <div class="col-xs-4">C</div>
    </div>
    <div>
        <div class="col-xs-6">Content 50% width auto height</div>
        <div class="col-xs-6">Hello World</div>
    </div>
    <div>
        <div class="col-xs-9">Content 70% width auto height</div>
        <div class="col-xs-3">Merry Halloween</div>
    </div>
</div>

The CSS:

div.tablefull {
    display: table;
    table-layout: fixed;
    width: 100%;
    height: 100%;
}

div.tablefull>div.tableheader, div.tablefull>div.tableheader>div{
    height: 0%;
}

div.tablefull>div {
    display: table-row;
}

div.tablefull>div>div {
    display: table-cell;
    height: 100%;
    padding: 0;
}

Return value from exec(@sql)

Was playing with this today... I beleive you can also use @@ROWCOUNT, like this:

DECLARE @SQL VARCHAR(50)
DECLARE @Rowcount INT
SET @SQL = 'SELECT 1 UNION SELECT 2'
EXEC(@SQL)
SET @Rowcount = @@ROWCOUNT
SELECT @Rowcount

Then replace the 'SELECT 1 UNION SELECT 2' with your actual select without the count. I'd suggest just putting 1 in your select, like this:

SELECT 1
FROM dbo.Comm_Services
WHERE....
....

(as opposed to putting SELECT *)

Hope that helps.

Installing a dependency with Bower from URL and specify version

Here's a handy short-hand way to install a specific tag or commit from GitHub via bower.json.

{
  "dependencies": {
    "your-library-name": "<GITHUB-USERNAME>/<REPOSITORY-NAME>#<TAG-OR-COMMIT>"
  }
}

For example:

{
  "dependencies": {
    "custom-jquery": "jquery/jquery#2.0.3"
  }
}

When running WebDriver with Chrome browser, getting message, "Only local connections are allowed" even though browser launches properly

I solved this error by installing the browser driver:

  1. Navigate your browser to seleniumhq.org website
  2. Select the Downloads tab
  3. Scroll down the page to the Browser section and download the driver you want by clicking the link, for example, Google Chrome Driver
  4. Double-click the downloaded file, for example, chromedriver_mac64(1).zip
  5. Double-click the extracted file, for example, chromedriver

Reference: search YouTube.com for the error

Platform: macOS High Sierra 10.13.3

What is the correct JSON content type?

The correct answer is:

Content-Type: application/json

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

I added the following 2 parameters: /np /nfl

So together with the 5 parameters from AndyGeek's answer, which are /njh /njs /ndl /nc /ns you get the following and it's silent:

ROBOCOPY [source] [target] /NFL /NDL /NJH /NJS /nc /ns /np

/NFL : No File List - don't log file names.
/NDL : No Directory List - don't log directory names.
/NJH : No Job Header.
/NJS : No Job Summary.
/NP  : No Progress - don't display percentage copied.
/NS  : No Size - don't log file sizes.
/NC  : No Class - don't log file classes.

ASP.NET 4.5 has not been registered on the Web server

Not required to type c:\

Start -> run-> cmd -> Run as administrator and execute below command


.NET Framework version 4 (32-bit systems)

%windir%\Microsoft.NET\Framework\v4.0.30319\aspnet_regiis.exe -i

.NET Framework version 4 (64-bit systems)

%windir%\Microsoft.NET\Framework64\v4.0.30319\aspnet_regiis.exe -i

Alternatively use Command Prompt from Visual Studio tools: C:\ProgramData\Microsoft\Windows\Start Menu\Programs\Microsoft Visual Studio 2012\Visual Studio Tools>VS2012 x86 Native Tools Command Prompt

Version could vary.. Hope this helps.

How can I change my default database in SQL Server without using MS SQL Server Management Studio?

  1. Click on Change Connection icon
  2. Click Options<<
  3. Select the db from Connect to database drop down

Assign result of dynamic sql to variable

Sample to execute an SQL string within the stored procedure:

(I'm using this to compare the number of entries on each table as first check for a regression test, within a cursor loop)

select @SqlQuery1 = N'select @CountResult1 = (select isnull(count(*),0) from ' + @DatabaseFirst+'.dbo.'+@ObjectName + ')'

execute sp_executesql    @SqlQuery1 , N'@CountResult1 int OUTPUT',     @CountResult1 = @CountResult1 output;

Java Regex Capturing Groups

This is totally OK.

  1. The first group (m.group(0)) always captures the whole area that is covered by your regular expression. In this case, it's the whole string.
  2. Regular expressions are greedy by default, meaning that the first group captures as much as possible without violating the regex. The (.*)(\\d+) (the first part of your regex) covers the ...QT300 int the first group and the 0 in the second.
  3. You can quickly fix this by making the first group non-greedy: change (.*) to (.*?).

For more info on greedy vs. lazy, check this site.

Connecting to SQL Server using windows authentication

Your connection string is wrong

<connectionStrings>
   <add name="ConnStringDb1" connectionString="Data Source=localhost\SQLSERVER;Initial Catalog=YourDataBaseName;Integrated Security=True;" providerName="System.Data.SqlClient" />
</connectionStrings>

Launch Android application without main Activity and start Service on launching application

Yes you can do that by just creating a BroadcastReceiver that calls your Service when your Application boots. Here is a complete answer given by me.
Android - Start service on boot

If you don't want any icon/launcher for you Application you can do that also, just don't create any Activity with

<intent-filter>
    <action android:name="android.intent.action.MAIN" />
    <category android:name="android.intent.category.LAUNCHER" />
</intent-filter>

Just declare your Service as declared normally.

How to open warning/information/error dialog in Swing?

Just complementing: It's kind of obvious, but you can use static imports to give you a hand, like this:

import static javax.swing.JOptionPane.*;

public class SimpleDialog(){
    public static void main(String argv[]) {
        showMessageDialog(null, "Message", "Title", ERROR_MESSAGE);
    }
}

Check last modified date of file in C#

You simply want the File.GetLastWriteTime static method.

Example:

var lastModified = System.IO.File.GetLastWriteTime("C:\foo.bar");

Console.WriteLine(lastModified.ToString("dd/MM/yy HH:mm:ss"));

Note however that in the rare case the last-modified time is not updated by the system when writing to the file (this can happen intentionally as an optimisation for high-frequency writing, e.g. logging, or as a bug), then this approach will fail, and you will instead need to subscribe to file write notifications from the system, constantly listening.

DataAnnotations validation (Regular Expression) in asp.net mvc 4 - razor view

Try @ sign at start of expression. So you wont need to type escape characters just copy paste the regular expression in "" and put @ sign. Like so:

[RegularExpression(@"([a-zA-Z\d]+[\w\d]*|)[a-zA-Z]+[\w\d.]*", ErrorMessage = "Invalid username")]
public string Username { get; set; }

Present and dismiss modal view controller

Swift

self.dismissViewControllerAnimated(true, completion: nil)

Auto-center map with multiple markers in Google Maps API v3

Here's my take on this in case anyone comes across this thread:

This helps protect against non-numerical data destroying either of your final variables that determine lat and lng.

It works by taking in all of your coordinates, parsing them into separate lat and lng elements of an array, then determining the average of each. That average should be the center (and has proven true in my test cases.)

var coords = "50.0160001,3.2840073|50.014458,3.2778274|50.0169713,3.2750587|50.0180745,3.276742|50.0204038,3.2733474|50.0217796,3.2781737|50.0293064,3.2712542|50.0319918,3.2580816|50.0243287,3.2582281|50.0281447,3.2451177|50.0307925,3.2443178|50.0278165,3.2343882|50.0326574,3.2289809|50.0288569,3.2237612|50.0260081,3.2230589|50.0269495,3.2210104|50.0212645,3.2133541|50.0165868,3.1977592|50.0150515,3.1977341|50.0147901,3.1965286|50.0171915,3.1961636|50.0130074,3.1845098|50.0113267,3.1729483|50.0177206,3.1705726|50.0210692,3.1670394|50.0182166,3.158297|50.0207314,3.150927|50.0179787,3.1485753|50.0184944,3.1470782|50.0273077,3.149845|50.024227,3.1340514|50.0244172,3.1236235|50.0270676,3.1244474|50.0260853,3.1184879|50.0344525,3.113806";

var filteredtextCoordinatesArray = coords.split('|');    

    centerLatArray = [];
    centerLngArray = [];


    for (i=0 ; i < filteredtextCoordinatesArray.length ; i++) {

      var centerCoords = filteredtextCoordinatesArray[i]; 
      var centerCoordsArray = centerCoords.split(',');

      if (isNaN(Number(centerCoordsArray[0]))) {      
      } else {
        centerLatArray.push(Number(centerCoordsArray[0]));
      }

      if (isNaN(Number(centerCoordsArray[1]))) {
      } else {
        centerLngArray.push(Number(centerCoordsArray[1]));
      }                    

    }

    var centerLatSum = centerLatArray.reduce(function(a, b) { return a + b; });
    var centerLngSum = centerLngArray.reduce(function(a, b) { return a + b; });

    var centerLat = centerLatSum / filteredtextCoordinatesArray.length ; 
    var centerLng = centerLngSum / filteredtextCoordinatesArray.length ;                                    

    console.log(centerLat);
    console.log(centerLng);

    var mapOpt = {      
    zoom:8,
    center: {lat: centerLat, lng: centerLng}      
    };

Angular 4: InvalidPipeArgument: '[object Object]' for pipe 'AsyncPipe'

In your MoviesService you should import FirebaseListObservable in order to define return type FirebaseListObservable<any[]>

import { AngularFireDatabase, FirebaseListObservable } from 'angularfire2/database';

then get() method should like this-

get (): FirebaseListObservable<any[]>{
        return this.db.list('/movies');
    }

this get() method will return FirebaseListObervable of movies list

In your MoviesComponent should look like this

export class MoviesComponent implements OnInit {
  movies: any[];

  constructor(private moviesDb: MoviesService) { }

  ngOnInit() {
    this.moviesDb.get().subscribe((snaps) => {
       this.movies = snaps;
   });
 }
}

Then you can easily iterate through movies without async pipe as movies[] data is not observable type, your html should be this

ul
  li(*ngFor='let movie of movies')
    {{ movie.title }}

if you declear movies as a

movies: FirebaseListObservable<any[]>;

then you should simply call

movies: FirebaseListObservable<any[]>;
ngOnInit() {
    this.movies = this.moviesDb.get();
}

and your html should be this

ul
  li(*ngFor='let movie of movies | async')
    {{ movie.title }}

How to succinctly write a formula with many variables from a data frame?

You can check the package leaps and in particular the function regsubsets() functions for model selection. As stated in the documentation:

Model selection by exhaustive search, forward or backward stepwise, or sequential replacement

Error Handler - Exit Sub vs. End Sub

Your ProcExit label is your place where you release all the resources whether an error happened or not. For instance:

Public Sub SubA()
  On Error Goto ProcError

  Connection.Open
  Open File for Writing
  SomePreciousResource.GrabIt

ProcExit:  
  Connection.Close
  Connection = Nothing
  Close File
  SomePreciousResource.Release

  Exit Sub

ProcError:  
  MsgBox Err.Description  
  Resume ProcExit
End Sub

How to add minutes to my Date

you can use DateUtils class in org.apache.commons.lang3.time package

int addMinuteTime = 5;
Date targetTime = new Date(); //now
targetTime = DateUtils.addMinutes(targetTime, addMinuteTime); //add minute

How get permission for camera in android.(Specifically Marshmallow)

check using this
if (ContextCompat.checkSelfPermission(this, android.Manifest.permission.CAMERA)
            == PackageManager.PERMISSION_DENIED)

and

How to downgrade or install an older version of Cocoapods

Note that your pod specs will remain, and are located at ~/.cocoapods/ . This directory may also need to be removed if you want a completely fresh install.

They can be removed using pod spec remove SPEC_NAME then pod setup

It may help to do pod spec remove master then pod setup

Event detect when css property changed using Jquery

You can use attrchange jQuery plugin. The main function of the plugin is to bind a listener function on attribute change of HTML elements.

Code sample:

$("#myDiv").attrchange({
    trackValues: true, // set to true so that the event object is updated with old & new values
    callback: function(evnt) {
        if(evnt.attributeName == "display") { // which attribute you want to watch for changes
            if(evnt.newValue.search(/inline/i) == -1) {

                // your code to execute goes here...
            }
        }
    }
});

Cassandra port usage - how are the ports used?

For Apache Cassandra 2.0 you need to take into account the following TCP ports: (See EC2 security group configuration and Apache Cassandra FAQ)

Cassandra

  • 7199 JMX monitoring port
  • 1024 - 65355 Random port required by JMX. Starting with Java 7u4 a specific port can be specified using the com.sun.management.jmxremote.rmi.port property.
  • 7000 Inter-node cluster
  • 7001 SSL inter-node cluster
  • 9042 CQL Native Transport Port
  • 9160 Thrift

DataStax OpsCenter

  • 61620 opscenterd daemon
  • 61621 Agent
  • 8888 Website

Architecture

A possible architecture with Cassandra + OpsCenter on EC2 could look like this: AWS EC2 with OpsCenter

Batch file to map a drive when the folder name contains spaces

I just created some directories, shared them and mapped using:

net use y: "\\mycomputername\folder with spaces"

So this solution gets "works on my machine" certificate. What error code do you get?

Create multiple threads and wait all of them to complete

If you don't want to use the Task class (for instance, in .NET 3.5) you can just start all your threads, and then add them to the list and join them in a foreach loop.

Example:

List<Thread> threads = new List<Thread>();


// Start threads
for(int i = 0; i<10; i++)
{
    int tmp = i; // Copy value for closure
    Thread t = new Thread(() => Console.WriteLine(tmp));
    t.Start;
    threads.Add(t);
}

// Await threads
foreach(Thread thread in threads)
{
    thread.Join();
}

How to support placeholder attribute in IE8 and 9

if you use jquery you can do like this. from this site Placeholder with Jquery

$('[placeholder]').parents('form').submit(function() {
  $(this).find('[placeholder]').each(function() {
    var input = $(this);
    if (input.val() == input.attr('placeholder')) {
      input.val('');
    }
  })
});

these are the alternate links

  1. Placeholder jquery library
  2. HTML5 polyfills -- go for placeholder section

Why, Fatal error: Class 'PHPUnit_Framework_TestCase' not found in ...?

If you have Centos or other Linux distribution you have to install phpunit package, I did that with yum install phpunit and it worked. Maybe you can have to add a repository, but I think it has to work smooth with the default ones (I have CentOS 7)

sql try/catch rollback/commit - preventing erroneous commit after rollback

I used below ms sql script pattern several times successfully which uses Try-Catch,Commit Transaction- Rollback Transaction,Error Tracking.

Your TRY block will be as follows

 BEGIN TRY
 BEGIN TRANSACTION T
 ----
 //your script block
 ----
 COMMIT TRANSACTION T 
 END TRY

Your CATCH block will be as follows

BEGIN CATCH
DECLARE @ErrMsg NVarChar(4000), 
        @ErrNum Int, 
        @ErrSeverity Int, 
        @ErrState Int, 
        @ErrLine Int, 
        @ErrProc NVarChar(200)
 SELECT @ErrNum = Error_Number(), 
       @ErrSeverity = Error_Severity(), 
       @ErrState = Error_State(), 
       @ErrLine = Error_Line(), 
       @ErrProc = IsNull(Error_Procedure(), '-')
 SET @ErrMsg = N'ErrLine: ' + rtrim(@ErrLine) + ', proc: ' + RTRIM(@ErrProc) + ', 
       Message: '+ Error_Message()

Your ROLLBACK script will be part of CATCH block as follows

IF (@@TRANCOUNT) > 0 
BEGIN
PRINT 'ROLLBACK: ' + SUBSTRING(@ErrMsg,1,4000)
ROLLBACK TRANSACTION T
END
ELSE
BEGIN
PRINT SUBSTRING(@ErrMsg,1,4000);   
END

END CATCH

Above different script blocks you need to use as one block. If any error happens in the TRY block it will go the the CATCH block. There it is setting various details about the error number,error severity,error line ..etc. At last all these details will get append to @ErrMsg parameter. Then it will check for the count of transaction (@@TRANCOUNT >0) , ie if anything is there in the transaction for rollback. If it is there then show the error message and ROLLBACK TRANSACTION. Otherwise simply print the error message.

We have kept our COMMIT TRANSACTION T script towards the last line of TRY block in order to make sure that it should commit the transaction(final change in the database) only after all the code in the TRY block has run successfully.

Resource interpreted as stylesheet but transferred with MIME type text/html (seems not related with web server)

I have the same exact problem and after a few minutes fooling around I deciphered that I missed to add the file extension to my header. so I changed the following line :

<link uic-remove rel="stylesheet" href="css/bahblahblah">

to

<link uic-remove rel="stylesheet" href="css/bahblahblah.css"> 

MetadataException: Unable to load the specified metadata resource

I was able to resolve this in Visual Studio 2010, VB.net (ASP.NET) 4.0.

During the entity model wizard, you will be able to see the entity connection string. From there you can copy and paste into your connection string.

The only thing I was missing was the "App_Code." in the connections string.

entityBuilder.Metadata = "res://*/App_Code.Model.csdl|res://*/App_Code.Model.ssdl|res://*/App_Code.Model.msl"

Unable to start the mysql server in ubuntu

I think this is because you are using client software and not the server.

  • mysql is client
  • mysqld is the server

Try: sudo service mysqld start

To check that service is running use: ps -ef | grep mysql | grep -v grep.

Uninstalling:

sudo apt-get purge mysql-server
sudo apt-get autoremove
sudo apt-get autoclean

Re-Installing:

sudo apt-get update
sudo apt-get install mysql-server

Backup entire folder before doing this:

sudo rm /etc/apt/apt.conf.d/50unattended-upgrades*
sudo apt-get update
sudo apt-get upgrade

How to pass parameters to a Script tag?

It's better to Use feature in html5 5 data Attributes

<script src="http://path.to/widget.js" data-width="200" data-height="200">
</script>

Inside the script file http://path.to/widget.js you can get the paremeters in that way:

<script>
function getSyncScriptParams() {
         var scripts = document.getElementsByTagName('script');
         var lastScript = scripts[scripts.length-1];
         var scriptName = lastScript;
         return {
             width : scriptName.getAttribute('data-width'),
             height : scriptName.getAttribute('data-height')
         };
 }
</script>

Python Graph Library

I would like to plug my own graph python library: graph-tool.

It is very fast, since it is implemented in C++ with the Boost Graph Library, and it contains lots of algorithms and extensive documentation.

C#: calling a button event handler method without actually clicking the button

btnTest_Click(null, null);

Provided that the method isn't using either of these parameters (it's very common not to.)

To be honest though this is icky. If you have code that needs to be called you should follow the following convention:

protected void btnTest_Click(object sender, EventArgs e)
{
   SomeSub();
}

protected void SomeOtherFunctionThatNeedsToCallTheCode()
{
   SomeSub();
}

protected void SomeSub()
{
   // ...
}

How to use MapView in android using google map V2?

yes you can use MapView in v2... for further details you can get help from this

https://gist.github.com/joshdholtz/4522551


SomeFragment.java

public class SomeFragment extends Fragment implements OnMapReadyCallback{
 
    MapView mapView;
    GoogleMap map;
 
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View v = inflater.inflate(R.layout.some_layout, container, false);
 
        // Gets the MapView from the XML layout and creates it
        mapView = (MapView) v.findViewById(R.id.mapview);
        mapView.onCreate(savedInstanceState);
 
    
        mapView.getMapAsync(this);
        
 
        return v;
    }
 
   @Override
   public void onMapReady(GoogleMap googleMap) {
       map = googleMap;
       map.getUiSettings().setMyLocationButtonEnabled(false);
       map.setMyLocationEnabled(true);
       /*
       //in old Api Needs to call MapsInitializer before doing any CameraUpdateFactory call
        try {
            MapsInitializer.initialize(this.getActivity());
        } catch (GooglePlayServicesNotAvailableException e) {
            e.printStackTrace();
        } 
       */
        
        // Updates the location and zoom of the MapView
        /*CameraUpdate cameraUpdate = CameraUpdateFactory.newLatLngZoom(new LatLng(43.1, -87.9), 10);
        map.animateCamera(cameraUpdate);*/
        map.moveCamera(CameraUpdateFactory.newLatLng(new LatLng(43.1, -87.9)));

    }

    @Override
    public void onResume() {
        mapView.onResume();
        super.onResume();
    }


    @Override
    public void onPause() {
        super.onPause();
        mapView.onPause();
    }
 
    @Override
    public void onDestroy() {
        super.onDestroy();
        mapView.onDestroy();
    }
 
    @Override
    public void onLowMemory() {
        super.onLowMemory();
        mapView.onLowMemory();
    }
 
}

AndroidManifest.xml

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example"
    android:versionCode="1"
    android:versionName="1.0" >
    
    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="15" />
    
    <uses-permission android:name="android.permission.INTERNET"/>
    <uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES"/>
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
    
    <uses-feature
        android:glEsVersion="0x00020000"
        android:required="true"/>
    
    <permission
        android:name="com.example.permission.MAPS_RECEIVE"
        android:protectionLevel="signature"/>
    <uses-permission android:name="com.example.permission.MAPS_RECEIVE"/>
    
    <application
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        
        <meta-data
            android:name="com.google.android.maps.v2.API_KEY"
            android:value="your_key"/>
        
        <activity
            android:name=".HomeActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    
    </application>
 
</manifest>

some_layout.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent" >
    
    <com.google.android.gms.maps.MapView android:id="@+id/mapview"
        android:layout_width="fill_parent" 
        android:layout_height="fill_parent" />
 
</LinearLayout>

How to have the cp command create any necessary folders for copying a file to a destination

 mkdir -p `dirname /nosuchdirectory/hi.txt` && cp -r urls-resume /nosuchdirectory/hi.txt

How can I run a directive after the dom has finished rendering?

Probably the author won't need my answer anymore. Still, for sake of completeness i feel other users might find it useful. The best and most simple solution is to use $(window).load() inside the body of the returned function. (alternatively you can use document.ready. It really depends if you need all the images or not).

Using $timeout in my humble opinion is a very weak option and may fail in some cases.

Here is the complete code i'd use:

.directive('directiveExample', function(){
   return {
       restrict: 'A',
       link: function($scope, $elem, attrs){

           $(window).load(function() {
               //...JS here...
           });
       }
   }
});

javascript change background color on click

You can use setTimeout():

_x000D_
_x000D_
var addBg = function(e) {_x000D_
  e = e || window.event;_x000D_
  e.preventDefault();_x000D_
  var el = e.target || e.srcElement;_x000D_
  el.className = 'bg';_x000D_
  setTimeout(function() {_x000D_
    removeBg(el);_x000D_
  }, 10 * 1000); //<-- (in miliseconds)_x000D_
};_x000D_
_x000D_
var removeBg = function(el) {_x000D_
  el.className = '';_x000D_
};
_x000D_
div {_x000D_
  border: 1px solid grey;_x000D_
  padding: 5px 7px;_x000D_
  display: inline-block;_x000D_
  margin: 5px;_x000D_
}_x000D_
.bg {_x000D_
  background: orange;_x000D_
}
_x000D_
<body onclick='addBg(event);'>This is body_x000D_
  <br/>_x000D_
  <div onclick='addBg(event);'>This is div_x000D_
  </div>_x000D_
</body>
_x000D_
_x000D_
_x000D_

Using jQuery:

_x000D_
_x000D_
var addBg = function(e) {_x000D_
  e.stopPropagation();_x000D_
  var el = $(this);_x000D_
  el.addClass('bg');_x000D_
  setTimeout(function() {_x000D_
    removeBg(el);_x000D_
  }, 10 * 1000); //<-- (in miliseconds)_x000D_
};_x000D_
_x000D_
var removeBg = function(el) {_x000D_
  $(el).removeClass('bg');_x000D_
};_x000D_
_x000D_
$(function() {_x000D_
  $('body, div').on('click', addBg);_x000D_
});
_x000D_
div {_x000D_
  border: 1px solid grey;_x000D_
  padding: 5px 7px;_x000D_
  display: inline-block;_x000D_
  margin: 5px;_x000D_
}_x000D_
.bg {_x000D_
  background: orange;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>_x000D_
_x000D_
<body>This is body_x000D_
  <br/>_x000D_
  <div>This is div</div>_x000D_
</body>
_x000D_
_x000D_
_x000D_

convert iso date to milliseconds in javascript

Another solution could be to use Number object parser like this:

_x000D_
_x000D_
let result = Number(new Date("2012-02-10T13:19:11+0000"));_x000D_
let resultWithGetTime = (new Date("2012-02-10T13:19:11+0000")).getTime();_x000D_
console.log(result);_x000D_
console.log(resultWithGetTime);
_x000D_
_x000D_
_x000D_

This converts to milliseconds just like getTime() on Date object

Difference between "while" loop and "do while" loop

While Loop:

while(test-condition)
{
      statements;
      increment/decrement;
}
  1. Lower Execution Time and Speed
  2. Entry Conditioned Loop
  3. No fixed number of iterations

Do While Loop:

do
{
      statements;
      increment/decrement;
}while(test-condition);
  1. Higher Execution Time and Speed
  2. Exit Conditioned Loop
  3. Minimum one number of iteration

Find out more on this topic here: Difference Between While and Do While Loop

This is valid for C programming, Java programming and other languages as well because the concepts remain the same, only the syntax changes.

Also, another small but a differentiating factor to note is that the do while loop consists of a semicolon at the end of the while condition.

ASP.Net MVC 4 Form with 2 submit buttons/actions

We can have this in 2 ways,

Either have 2 form submissions within the same View and having 2 Action methods at the controller but you will need to have the required fields to be submitted with the form to be placed within

ex is given here with code Multiple forms in view asp.net mvc with multiple submit buttons

Or

Have 2 or multiple submit buttons say btnSubmit1 and btnSubmit2 and check on the Action method which button was clicked using the code

if (Request.Form["btnSubmit1"] != null)
{
 //
}
if (Request.Form["btnSubmit2"] != null)
{
 //
}

Android WebView progress bar

It's true, there are also more complete option, like changing the name of the app for a sentence you want. Check this tutorial it can help:

http://www.firstdroid.com/2010/08/04/adding-progress-bar-on-webview-android-tutorials/

In that tutorial you have a complete example how to use the progressbar in a webview app.

Adrian.

Finding blocking/locking queries in MS SQL (mssql)

Use the script: sp_blocker_pss08 or SQL Trace/Profiler and the Blocked Process Report event class.

Where is Maven's settings.xml located on Mac OS?

if you install the maven with the brew

you can type the command("mvn -v") in Terminal

see Maven home detail

mvn -v
Apache Maven 3.5.0 (ff8f5e7444045639af65f6095c62210b5713f426; 2017-04-04T03:39:06+08:00)
Maven home: /usr/local/Cellar/maven/3.5.0/libexec
Java version: 1.8.0_121, vendor: Oracle Corporation
Java home: /Library/Java/JavaVirtualMachines/jdk1.8.0_121.jdk/Contents/Home/jre
Default locale: zh_CN, platform encoding: UTF-8
OS name: "mac os x", version: "10.11.5", arch: "x86_64", family: "mac"

Adding CSRFToken to Ajax request

How about this,

$("body").bind("ajaxSend", function(elm, xhr, s){
   if (s.type == "POST") {
      xhr.setRequestHeader('X-CSRF-Token', getCSRFTokenValue());
   }
});

Ref: http://erlend.oftedal.no/blog/?blogid=118

To pass CSRF as parameter,

        $.ajax({
            type: "POST",
            url: "file",
            data: { CSRF: getCSRFTokenValue()}
        })
        .done(function( msg ) {
            alert( "Data: " + msg );
        });

Should ol/ul be inside <p> or outside?

<p>tetxetextex</p>
<ol><li>first element</li></ol>
<p>other textetxeettx</p>

Because both <p> and <ol> are element rendered as block.

Context.startForegroundService() did not then call Service.startForeground()

Please don't call any StartForgroundServices inside onCreate() method, you have to call StartForground services in onStartCommand() after make the worker thread otherwise you will get ANR always , so please don't write complex login in main thread of onStartCommand();

public class Services extends Service {

    private static final String ANDROID_CHANNEL_ID = "com.xxxx.Location.Channel";
    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }


    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            Notification.Builder builder = new Notification.Builder(this, ANDROID_CHANNEL_ID)
                    .setContentTitle(getString(R.string.app_name))
                    .setContentText("SmartTracker Running")
                    .setAutoCancel(true);
            Notification notification = builder.build();
            startForeground(0, notification);
            Log.e("home_button","home button");
        } else {
            NotificationCompat.Builder builder = new NotificationCompat.Builder(this)
                    .setContentTitle(getString(R.string.app_name))
                    .setContentText("SmartTracker is Running...")
                    .setPriority(NotificationCompat.PRIORITY_DEFAULT)
                    .setAutoCancel(true);
            Notification notification = builder.build();
            startForeground(0, notification);
            Log.e("home_button_value","home_button_value");

        }
        return super.onStartCommand(intent, flags, startId);

    }
}

EDIT: Caution! startForeground function can't take 0 as first argument, it will raise an exception! this example contains wrong function call, change 0 to your own const which couldnt be 0 or be greater than Max(Int32)

How to do an array of hashmaps?

You can use something like this:

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


public class testHashes {

public static void main(String args[]){
    Map<String,String> myMap1 = new HashMap<String, String>();

    List<Map<String , String>> myMap  = new ArrayList<Map<String,String>>();

    myMap1.put("URL", "Val0");
    myMap1.put("CRC", "Vla1");
    myMap1.put("SIZE", "Val2");
    myMap1.put("PROGRESS", "Val3");

    myMap.add(0,myMap1);
    myMap.add(1,myMap1);

    for (Map<String, String> map : myMap) {
        System.out.println(map.get("URL"));
        System.out.println(map.get("CRC"));
        System.out.println(map.get("SIZE"));
        System.out.println(map.get("PROGRESS"));
    }

    //System.out.println(myMap);

}


}

JavaScript - populate drop down list with array

You'll need to loop through your array elements, create a new DOM node for each and append it to your object.

var select = document.getElementById("selectNumber"); 
var options = ["1", "2", "3", "4", "5"]; 

for(var i = 0; i < options.length; i++) {
    var opt = options[i];
    var el = document.createElement("option");
    el.textContent = opt;
    el.value = opt;
    select.appendChild(el);
}?

Live example

taking input of a string word by word

(This is for the benefit of others who may refer)

You can simply use cin and a char array. The cin input is delimited by the first whitespace it encounters.

#include<iostream>
using namespace std;

main()
{
    char word[50];
    cin>>word;
    while(word){
        //Do stuff with word[]
        cin>>word;
    }
}

How to `wget` a list of URLs in a text file?

If you also want to preserve the original file name, try with:

wget --content-disposition --trust-server-names -i list_of_urls.txt

WAMP Cannot access on local network 403 Forbidden

For Apache 2.4.9

in addition, look at the httpd-vhosts.conf file in C:\wamp\bin\apache\apache2.4.9\conf\extra

<VirtualHost *:80>
ServerName localhost
ServerAlias localhost
DocumentRoot C:/wamp/www
<Directory "C:/wamp/www/">
Options Indexes FollowSymLinks MultiViews
AllowOverride all
Require local
</Directory>
</VirtualHost>

Change to:

<VirtualHost *:80>
ServerName localhost
ServerAlias localhost
DocumentRoot C:/wamp/www
<Directory "C:/wamp/www/">
Options Indexes FollowSymLinks MultiViews
AllowOverride all
Require all granted
</Directory>
</VirtualHost>

changing from "Require local" to "Require all granted" solved the error 403 in my local network

How to use a DataAdapter with stored procedure and parameter

public class SQLCon
{
  public static string cs = 
   ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString;
}
protected void Page_Load(object sender, EventArgs e)
{
    SqlDataAdapter MyDataAdapter;
    SQLCon cs = new SQLCon();
    DataSet RsUser = new DataSet();
    RsUser = new DataSet();
    using (SqlConnection MyConnection = new SqlConnection(SQLCon.cs))
       {
        MyConnection.Open();
        MyDataAdapter = new SqlDataAdapter("GetAPPID", MyConnection);
        //'Set the command type as StoredProcedure.
        MyDataAdapter.SelectCommand.CommandType = CommandType.StoredProcedure;
        RsUser = new DataSet();
        MyDataAdapter.SelectCommand.Parameters.Add(new SqlParameter("@organizationID", 
        SqlDbType.Int));
        MyDataAdapter.SelectCommand.Parameters["@organizationID"].Value = TxtID.Text;
        MyDataAdapter.Fill(RsUser, "GetAPPID");
       }

      if (RsUser.Tables[0].Rows.Count > 0) //data was found
      {
        Session["AppID"] = RsUser.Tables[0].Rows[0]["AppID"].ToString();
       }
     else
       {

       }    
}    

Where is NuGet.Config file located in Visual Studio project?

If you use proxy, you will have to edit the Nuget.config file.

In Windows 7 and 10, this file is in the path:
C:\Users\YouUser\AppData\Roaming\NuGet.

Include the setting:

<config>
  <add key = "http_proxy" value = "http://Youproxy:8080" />
  <add key = "http_proxy.user" value = "YouProxyUser" />
</config>

Can I use multiple "with"?

Yes - just do it this way:

WITH DependencedIncidents AS
(
  ....
),  
lalala AS
(
  ....
)

You don't need to repeat the WITH keyword

Change visibility of ASP.NET label with JavaScript

Make sure the Visible property is set to true or the control won't render to the page. Then you can use script to manipulate it.

Send Mail to multiple Recipients in java

If you invoke addRecipient multiple times it will add the given recipient to the list of recipients of the given time (TO, CC, BCC)

For example:

message.addRecipient(Message.RecipientType.CC, InternetAddress.parse("[email protected]"));
message.addRecipient(Message.RecipientType.CC, InternetAddress.parse("[email protected]"));
message.addRecipient(Message.RecipientType.CC, InternetAddress.parse("[email protected]"));

Will add the 3 addresses to CC


If you wish to add all addresses at once you should use setRecipients or addRecipients and provide it with an array of addresses

Address[] cc = new Address[] {InternetAddress.parse("[email protected]"),
                               InternetAddress.parse("[email protected]"), 
                               InternetAddress.parse("[email protected]")};
message.addRecipients(Message.RecipientType.CC, cc);

You can also use InternetAddress.parse to parse a list of addresses

message.addRecipients(Message.RecipientType.CC, 
                      InternetAddress.parse("[email protected],[email protected],[email protected]"));

jQuery Mobile Page refresh mechanism

function refreshPage()
{
    jQuery.mobile.changePage(window.location.href, {
        allowSamePageTransition: true,
        transition: 'none',
        reloadPage: true
    });
}

Taken from here http://scottwb.com/blog/2012/06/29/reload-the-same-page-without-blinking-on-jquery-mobile/ also tested on jQuery Mobile 1.2.0

Regex match entire words only

Using \b can yield surprising results. You would be better off figuring out what separates a word from its definition and incorporating that information into your pattern.

#!/usr/bin/perl

use strict; use warnings;

use re 'debug';

my $str = 'S.P.E.C.T.R.E. (Special Executive for Counter-intelligence,
Terrorism, Revenge and Extortion) is a fictional global terrorist
organisation';

my $word = 'S.P.E.C.T.R.E.';

if ( $str =~ /\b(\Q$word\E)\b/ ) {
    print $1, "\n";
}

Output:

Compiling REx "\b(S\.P\.E\.C\.T\.R\.E\.)\b"
Final program:
   1: BOUND (2)
   2: OPEN1 (4)
   4:   EXACT  (9)
   9: CLOSE1 (11)
  11: BOUND (12)
  12: END (0)
anchored "S.P.E.C.T.R.E." at 0 (checking anchored) stclass BOUND minlen 14
Guessing start of match in sv for REx "\b(S\.P\.E\.C\.T\.R\.E\.)\b" against "S.P
.E.C.T.R.E. (Special Executive for Counter-intelligence,"...
Found anchored substr "S.P.E.C.T.R.E." at offset 0...
start_shift: 0 check_at: 0 s: 0 endpos: 1
Does not contradict STCLASS...
Guessed: match at offset 0
Matching REx "\b(S\.P\.E\.C\.T\.R\.E\.)\b" against "S.P.E.C.T.R.E. (Special Exec
utive for Counter-intelligence,"...
   0           |  1:BOUND(2)
   0           |  2:OPEN1(4)
   0           |  4:EXACT (9)
  14      |  9:CLOSE1(11)
  14      | 11:BOUND(12)
                                  failed...
Match failed
Freeing REx: "\b(S\.P\.E\.C\.T\.R\.E\.)\b"

Regular Expressions and negating a whole character group

Using a regex as you described is the simple way (as far as I am aware). If you want a range you could use [^a-f].

How to configure encoding in Maven?

This would be in addition to previous, if someone meets a problem with scandic letters that isn't solved with the solution above.

If the java source files contain scandic letters they need to be interpreted correctly by the Java used for compiling. (e.g. scandic letters used in constants)

Even that the files are stored in UTF-8 and the Maven is configured to use UTF-8, the System Java used by the Maven will still use the system default (eg. in Windows: cp1252).

This will be visible only running the tests via maven (possibly printing the values of these constants in tests. The printed scandic letters would show as '< ?>') If not tested properly, this would corrupt the class files as compile result and be left unnoticed.

To prevent this, you have to set the Java used for compiling to use UTF-8 encoding. It is not enough to have the encoding settings in the maven pom.xml, you need to set the environment variable: JAVA_TOOL_OPTIONS = -Dfile.encoding=UTF8

Also, if using Eclipse in Windows, you may need to set the encoding used in addition to this (if you run individual test via eclipse).

ORA-28000: the account is locked error getting frequently

I have faced this similar issue and resolved it by using following steps :

  1. Open windows command prompt.
  2. Login using the command sqlplus "/ as sysdba"
  3. Then executed the command alter user HR identified by password account unlock

    Please note, the password is the password that I have used.

    By using above steps you can connect to Oracle Database as user HR with the password password.

What is the easiest way to initialize a std::vector with hardcoded elements?

In C++11:

#include <vector>
using std::vector;
...
vector<int> vec1 { 10, 20, 30 };
// or
vector<int> vec2 = { 10, 20, 30 };

Using boost list_of:

#include <vector>
#include <boost/assign/list_of.hpp>
using std::vector;
...
vector<int> vec = boost::assign::list_of(10)(20)(30);

Using boost assign:

#include <vector>
#include <boost/assign/std/vector.hpp>
using std::vector;
...
vector<int> vec;
vec += 10, 20, 30;

Conventional STL:

#include <vector>
using std::vector;
...
static const int arr[] = {10,20,30};
vector<int> vec (arr, arr + sizeof(arr) / sizeof(arr[0]) );

Conventional STL with generic macros:

#include <vector>
#define ARRAY_SIZE(ar) (sizeof(ar) / sizeof(ar[0])
#define ARRAY_END(ar) (ar + ARRAY_SIZE(ar))
using std::vector;
...
static const int arr[] = {10,20,30};
vector<int> vec (arr, ARRAY_END(arr));

Conventional STL with a vector initializer macro:

#include <vector>
#define INIT_FROM_ARRAY(ar) (ar, ar + sizeof(ar) / sizeof(ar[0])
using std::vector;
...
static const int arr[] = {10,20,30};
vector<int> vec INIT_FROM_ARRAY(arr);

What does the ">" (greater-than sign) CSS selector mean?

It matches p elements with class some_class that are directly under a div.

Sorting rows in a data table

 table.DefaultView.Sort = "[occr] DESC";

How to compile .c file with OpenSSL includes?

If the OpenSSL headers are in the openssl sub-directory of the current directory, use:

gcc -I. -o Opentest Opentest.c -lcrypto

The pre-processor looks to create a name such as "./openssl/ssl.h" from the "." in the -I option and the name specified in angle brackets. If you had specified the names in double quotes (#include "openssl/ssl.h"), you might never have needed to ask the question; the compiler on Unix usually searches for headers enclosed in double quotes in the current directory automatically, but it does not do so for headers enclosed in angle brackets (#include <openssl/ssl.h>). It is implementation defined behaviour.

You don't say where the OpenSSL libraries are - you might need to add an appropriate option and argument to specify that, such as '-L /opt/openssl/lib'.

How to disable an input box using angular.js

Use ng-disabled or a special CSS class with ng-class

<input data-ng-model="userInf.username"  
       class="span12 editEmail" 
       type="text"  
       placeholder="[email protected]"  
       pattern="[^@]+@[^@]+\.[a-zA-Z]{2,6}" 
       required 
       ng-disabled="{expression or condition}"
/>

How to get the command line args passed to a running process on unix/linux systems?

On Solaris

     ps -eo pid,comm

similar can be used on unix like systems.

How to send list of file in a folder to a txt file in Linux

If only names of regular files immediately contained within a directory (assume it's ~/dirs) are needed, you can do

find ~/docs -type f -maxdepth 1 > filenames.txt

Spaces cause split in path with PowerShell

Would this do what you want?:

& "C:\Windows Services\MyService.exe"

Use &, the call operator, to invoke commands whose names or paths are stored in quoted strings and/or are referenced via variables, as in the accepted answer. Invoke-Expression is not only the wrong tool to use in this particular case, it should generally be avoided.

What causes: "Notice: Uninitialized string offset" to appear?

Check out the contents of your array with

echo '<pre>' . print_r( $arr, TRUE ) . '</pre>';

TypeScript and array reduce function

Reduce() is..

  • The reduce() method reduces the array to a single value.
  • The reduce() method executes a provided function for each value of the array (from left-to-right).
  • The return value of the function is stored in an accumulator (result/total).

It was ..

let array=[1,2,3];
function sum(acc,val){ return acc+val;} // => can change to (acc,val)=>acc+val
let answer= array.reduce(sum); // answer is 6

Change to

let array=[1,2,3];
let answer=arrays.reduce((acc,val)=>acc+val);

Also you can use in

  1. find max
    let array=[5,4,19,2,7];
    function findMax(acc,val)
    {
     if(val>acc){
       acc=val; 
     }
    }

    let biggest=arrays.reduce(findMax); // 19
  1. find an element that not repeated.
    arr = [1, 2, 5, 4, 6, 8, 9, 2, 1, 4, 5, 8, 9]
    v = 0
    for i in range(len(arr)):
    v = v ^ arr[i]
    print(value)  //6

Make DateTimePicker work as TimePicker only in WinForms

A snippet out of the MSDN:

'The following code sample shows how to create a DateTimePicker that enables users to choose a time only.'

timePicker = new DateTimePicker();
timePicker.Format = DateTimePickerFormat.Time;
timePicker.ShowUpDown = true;

Removing duplicate objects with Underscore for Javascript

When I have an attribute id, this is my preffered way in underscore:

var x = [{i:2}, {i:2, x:42}, {i:4}, {i:3}];
_.chain(x).indexBy("i").values().value();
// > [{i:2, x:42}, {i:4}, {i:3}]

Prevent PDF file from downloading and printing

(disclaimer - I work for Atalasoft)

If you present your PDF documents with the Atalasoft web image viewer, you can prevent the PDF from being downloaded. You could also control printing from javascript on the client side.

XMLHttpRequest blocked by CORS Policy

I believe sideshowbarker 's answer here has all the info you need to fix this. If your problem is just No 'Access-Control-Allow-Origin' header is present on the response you're getting, you can set up a CORS proxy to get around this. Way more info on it in the linked answer

Fake "click" to activate an onclick method

var clickEvent = new MouseEvent('click', {
  view: window,
  bubbles: true,
  cancelable: true
});
var element = document.getElementById('element-id'); 
var cancelled = !element.dispatchEvent(clickEvent);
if (cancelled) {
  // A handler called preventDefault.
  alert("cancelled");
} else {
  // None of the handlers called preventDefault.
  alert("not cancelled");
}

element.dispatchEvent is supported in all major browsers. The example above is based on an sample simulateClick() function on MDN.

Can't install any package with node npm

Try:

npm install underscore

:)

There is no unserscore package in npm registry.

How can I force division to be floating point? Division keeps rounding down to 0?

You can cast to float by doing c = a / float(b). If the numerator or denominator is a float, then the result will be also.


A caveat: as commenters have pointed out, this won't work if b might be something other than an integer or floating-point number (or a string representing one). If you might be dealing with other types (such as complex numbers) you'll need to either check for those or use a different method.

Proper indentation for Python multiline strings

You can use this function trim_indent.

import re


def trim_indent(s: str):
    s = re.sub(r'^\n+', '', s)
    s = re.sub(r'\n+$', '', s)
    spaces = re.findall(r'^ +', s, flags=re.MULTILINE)
    if len(spaces) > 0 and len(re.findall(r'^[^\s]', s, flags=re.MULTILINE)) == 0:
        s = re.sub(r'^%s' % (min(spaces)), '', s, flags=re.MULTILINE)
    return s


print(trim_indent("""


        line one
            line two
                line three
            line two
        line one


"""))

Result:

"""
line one
    line two
        line three
    line two
line one
"""

How to link html pages in same or different folders?

This worked for me <a href="preferedfile name.html">to be clicked <a/>

How do I REALLY reset the Visual Studio window layout?

How about running the following from command line,

Devenv.exe /ResetSettings

You could also save those settings in to a file, like so,

Devenv.exe /ResetSettings "C:\My Files\MySettings.vssettings"

The /ResetSettings switch, Restores Visual Studio default settings. Optionally resets the settings to the specified .vssettings file.

MSDN link

What does {0} mean when found in a string in C#?

It's a placeholder for a parameter much like the %s format specifier acts within printf.

You can start adding extra things in there to determine the format too, though that makes more sense with a numeric variable (examples here).

Initializing C dynamic arrays

You need to allocate a block of memory and use it as an array as:

int *arr = malloc (sizeof (int) * n); /* n is the length of the array */
int i;

for (i=0; i<n; i++)
{
  arr[i] = 0;
}

If you need to initialize the array with zeros you can also use the memset function from C standard library (declared in string.h).

memset (arr, 0, sizeof (int) * n);

Here 0 is the constant with which every locatoin of the array will be set. Note that the last argument is the number of bytes to be set the the constant. Because each location of the array stores an integer therefore we need to pass the total number of bytes as this parameter.

Also if you want to clear the array to zeros, then you may want to use calloc instead of malloc. calloc will return the memory block after setting the allocated byte locations to zero.

After you have finished, free the memory block free (arr).

EDIT1

Note that if you want to assign a particular integer in locations of an integer array using memset then it will be a problem. This is because memset will interpret the array as a byte array and assign the byte you have given, to every byte of the array. So if you want to store say 11243 in each location then it will not be possible.

EDIT2

Also note why every time setting an int array to 0 with memset may not work: Why does "memset(arr, -1, sizeof(arr)/sizeof(int))" not clear an integer array to -1? as pointed out by @Shafik Yaghmour

Add two numbers and display result in textbox with Javascript

When you assign your variables "first_number" and "second_number", you need to change "document.getElementsById" to the singular "document.getElementById".

Can I create view with parameter in MySQL?

CREATE VIEW MyView AS
   SELECT Column, Value FROM Table;


SELECT Column FROM MyView WHERE Value = 1;

Is the proper solution in MySQL, some other SQLs let you define Views more exactly.

Note: Unless the View is very complicated, MySQL will optimize this just fine.

How to find topmost view controller on iOS

This works great for finding the top viewController 1 from any root view controlle

+ (UIViewController *)topViewControllerFor:(UIViewController *)viewController
{
    if(!viewController.presentedViewController)
        return viewController;
    return [MF5AppDelegate topViewControllerFor:viewController.presentedViewController];
}

/* View Controller for Visible View */

AppDelegate *app = [UIApplication sharedApplication].delegate;
UIViewController *visibleViewController = [AppDelegate topViewControllerFor:app.window.rootViewController]; 

What is the iPhone 4 user-agent?

Note: The user agent strings from Facebook's internal browser do indicate the actual physical device. Even the cellphone carrier (eg. AT&T)

Mozilla/5.0 (iPhone; CPU iPhone OS 10_3_3 like Mac OS X) AppleWebKit/603.3.8 (KHTML, like Gecko) Mobile/14G60 [FBAN/FBIOS;FBAV/149.0.0.39.64;FBBV/79173879;FBDV/iPhone7,2;FBMD/iPhone;FBSN/iOS;FBSV/10.3.3;FBSS/2;FBCR/AT&T;FBID/phone;FBLC/en_US;FBOP/5;FBRV/0

Mozilla/5.0 (iPhone; CPU iPhone OS 11_1 like Mac OS X) AppleWebKit/604.3.5 (KHTML, like Gecko) Mobile/15B93 [FBAN/FBIOS;FBAV/148.0.0.45.64;FBBV/78032376;FBDV/iPhone10,4;FBMD/iPhone;FBSN/iOS;FBSV/11.1;FBSS/2;FBCR/AT&T;FBID/phone;FBLC/en_US;FBOP/5;FBRV/0]

These won't be the case in Safari or Chrome from iOS - only within the browser inside the Facebook app.

(I'm getting iPhone9 too though - not quite sure what that is!)

What does template <unsigned int N> mean?

It's perfectly possible to template a class on an integer rather than a type. We can assign the templated value to a variable, or otherwise manipulate it in a way we might with any other integer literal:

unsigned int x = N;

In fact, we can create algorithms which evaluate at compile time (from Wikipedia):

template <int N>
struct Factorial 
{
     enum { value = N * Factorial<N - 1>::value };
};

template <>
struct Factorial<0> 
{
    enum { value = 1 };
};

// Factorial<4>::value == 24
// Factorial<0>::value == 1
void foo()
{
    int x = Factorial<4>::value; // == 24
    int y = Factorial<0>::value; // == 1
}

How do I write a SQL query for a specific date range and date time using SQL Server 2008?

SELECT * FROM TABLE
WHERE DATE BETWEEN '09/16/2010 05:00:00' and '09/21/2010 09:00:00'

Hibernate Auto Increment ID

If you have a numeric column that you want to auto-increment, it might be an option to set columnDefinition directly. This has the advantage, that the schema auto-generates the value even if it is used without hibernate. This might make your code db-specific though:

import javax.persistence.Column;
@Column(columnDefinition = "serial") // postgresql

How to check command line parameter in ".bat" file?

I've been struggling recently with the implementation of complex parameter switches in a batch file so here is the result of my research. None of the provided answers are fully safe, examples:

"%1"=="-?" will not match if the parameter is enclosed in quotes (needed for file names etc.) or will crash if the parameter is in quotes and has spaces (again often seen in file names)

@ECHO OFF
SETLOCAL
echo.
echo starting parameter test...
echo.
rem echo First parameter is %1
if "%1"=="-?" (echo Condition is true, param=%1) else (echo Condition is false, param=%1)
C:\>test.bat -?

starting parameter test...

Condition is true, param=-?

C:\>test.bat "-?"

starting parameter test...

Condition is false, param="-?"

Any combination with square brackets [%1]==[-?] or [%~1]==[-?] will fail in case the parameter has spaces within quotes:

@ECHO OFF
SETLOCAL 
echo.
echo starting parameter test...
echo.
echo First parameter is %1
if [%~1]==[-?] (echo Condition is true, param=%1) else (echo Condition is false, param=%1)

C:\>test.bat "long file name"

starting parameter test...

First parameter is "long file name"
file was unexpected at this time.

The proposed safest solution "%~1"=="-?" will crash with a complex parameter that includes text outside the quotes and text with spaces within the quotes:

@ECHO OFF
SETLOCAL 
echo.
echo starting parameter test...
echo.
echo First parameter is %1
if "%~1"=="-?" (echo Condition is true, param=%1) else (echo Condition is false, param=%1)

C:\>test.bat -source:"long file name"

starting parameter test...

First parameter is -source:"long file name"
file was unexpected at this time.

The only way to ensure all above scenarios are covered is to use EnableDelayedExpansion and to pass the parameters by reference (not by value) using variables. Then even the most complex scenario will work fine:

@ECHO OFF
SETLOCAL EnableDelayedExpansion
echo.
echo starting parameter test...
echo.
echo First parameter is %1
:: we assign the parameter to a variable to pass by reference with delayed expansion
set "var1=%~1"
echo var1 is !var1!
:: we assign the value to compare with to a second variable to pass by reference with delayed expansion
set "var2=-source:"c:\app images"\image.png"
echo var2 is !var2!
if "!var1!"=="!var2!" (echo Condition is true, param=!var1!) else (echo Condition is false, param=!var1!)
C:\>test.bat -source:"c:\app images"\image.png

starting parameter test...

First parameter is -source:"c:\app images"\image.png
var1 is -source:"c:\app images"\image.png
var2 is -source:"c:\app images"\image.png
Condition is true, param=-source:"c:\app images"\image.png

C:\>test.bat -source:"c:\app images"\image1.png

starting parameter test...

First parameter is -source:"c:\app images"\image1.png
var1 is -source:"c:\app images"\image1.png
var2 is -source:"c:\app images"\image.png
Condition is false, param=-source:"c:\app images"\image1.png

C:\>test.bat -source:"c:\app images\image.png"

starting parameter test...

First parameter is -source:"c:\app images\image.png"
var1 is -source:"c:\app images\image.png"
var2 is -source:"c:\app images"\image.png
Condition is false, param=-source:"c:\app images\image.png"

How to refresh materialized view in oracle

You can refresh a materialized view completely as follows:

EXECUTE  
DBMS_SNAPSHOT.REFRESH('Materialized_VIEW_OWNER_NAME.Materialized_VIEW_NAME','COMPLETE');

How to add and remove classes in Javascript without jQuery

The following 3 functions work in browsers which don't support classList:

function hasClass(el, className)
{
    if (el.classList)
        return el.classList.contains(className);
    return !!el.className.match(new RegExp('(\\s|^)' + className + '(\\s|$)'));
}

function addClass(el, className)
{
    if (el.classList)
        el.classList.add(className)
    else if (!hasClass(el, className))
        el.className += " " + className;
}

function removeClass(el, className)
{
    if (el.classList)
        el.classList.remove(className)
    else if (hasClass(el, className))
    {
        var reg = new RegExp('(\\s|^)' + className + '(\\s|$)');
        el.className = el.className.replace(reg, ' ');
    }
}

https://jaketrent.com/post/addremove-classes-raw-javascript/

Set 4 Space Indent in Emacs in Text Mode

The best answers did not work for until I wrote this in the .emacs file:

(global-set-key (kbd "TAB") 'self-insert-command)

Return sql rows where field contains ONLY non-alphanumeric characters

SQL Server doesn't have regular expressions. It uses the LIKE pattern matching syntax which isn't the same.

As it happens, you are close. Just need leading+trailing wildcards and move the NOT

 WHERE whatever NOT LIKE '%[a-z0-9]%'

Image resizing in React Native

This worked for me:

image: {
    flex: 1,
    aspectRatio: 1.5, 
    resizeMode: 'contain',

  }

aspectRatio is just width/height (my image is 45px wide x 30px high).

How to test that no exception is thrown?

You're approaching this the wrong way. Just test your functionality: if an exception is thrown the test will automatically fail. If no exception is thrown, your tests will all turn up green.

I have noticed this question garners interest from time to time so I'll expand a little.

Background to unit testing

When you're unit testing it's important to define to yourself what you consider a unit of work. Basically: an extraction of your codebase that may or may not include multiple methods or classes that represents a single piece of functionality.

Or, as defined in The art of Unit Testing, 2nd Edition by Roy Osherove, page 11:

A unit test is an automated piece of code that invokes the unit of work being tested, and then checks some assumptions about a single end result of that unit. A unit test is almost always written using a unit testing framework. It can be written easily and runs quickly. It's trustworthy, readable, and maintainable. It's consistent in its results as long as production code hasn't changed.

What is important to realize is that one unit of work usually isn't just one method but at the very basic level it is one method and after that it is encapsulated by other unit of works.

enter image description here

Ideally you should have a test method for each separate unit of work so you can always immediately view where things are going wrong. In this example there is a basic method called getUserById() which will return a user and there is a total of 3 unit of works.

The first unit of work should test whether or not a valid user is being returned in the case of valid and invalid input.
Any exceptions that are being thrown by the datasource have to be handled here: if no user is present there should be a test that demonstrates that an exception is thrown when the user can't be found. A sample of this could be the IllegalArgumentException which is caught with the @Test(expected = IllegalArgumentException.class) annotation.

Once you have handled all your usecases for this basic unit of work, you move up a level. Here you do exactly the same, but you only handle the exceptions that come from the level right below the current one. This keeps your testing code well structured and allows you to quickly run through the architecture to find where things go wrong, instead of having to hop all over the place.

Handling a tests' valid and faulty input

At this point it should be clear how we're going to handle these exceptions. There are 2 types of input: valid input and faulty input (the input is valid in the strict sense, but it's not correct).

When you work with valid input you're setting the implicit expectancy that whatever test you write, will work.

Such a method call can look like this: existingUserById_ShouldReturn_UserObject. If this method fails (e.g.: an exception is thrown) then you know something went wrong and you can start digging.

By adding another test (nonExistingUserById_ShouldThrow_IllegalArgumentException) that uses the faulty input and expects an exception you can see whether your method does what it is supposed to do with wrong input.

TL;DR

You were trying to do two things in your test: check for valid and faulty input. By splitting this into two method that each do one thing, you will have much clearer tests and a much better overview of where things go wrong.

By keeping the layered unit of works in mind you can also reduce the amount of tests you need for a layer that is higher in the hierarchy because you don't have to account for every thing that might have gone wrong in the lower layers: the layers below the current one are a virtual guarantee that your dependencies work and if something goes wrong, it's in your current layer (assuming the lower layers don't throw any errors themselves).

Appending items to a list of lists in python

import csv
cols = [' V1', ' I1'] # define your columns here, check the spaces!
data = [[] for col in cols] # this creates a list of **different** lists, not a list of pointers to the same list like you did in [[]]*len(positions) 
with open('data.csv', 'r') as f:
    for rec in csv.DictReader(f):
        for l, col in zip(data, cols):
            l.append(float(rec[col]))
print data

# [[3.0, 3.0], [0.01, 0.01]]

Handling errors in Promise.all

I've found a way (workaround) to do this without making it sync.

So as it was mentioned before Promise.all is all of none.

so... Use an enclosing promise to catch and force resolve.


      let safePromises = originalPrmises.map((imageObject) => {
            return new Promise((resolve) => {
              // Do something error friendly
              promise.then(_res => resolve(res)).catch(_err => resolve(err))
            })
        })
    })

    // safe
    return Promise.all(safePromises)

At least one JAR was scanned for TLDs yet contained no TLDs

If one wants to have the conf\logging.properties read one must (see also here) dump this file into the Servers\Tomcat v7.0 Server at localhost-config\ folder and then add the lines :

-Djava.util.logging.config.file="${workspace_loc}\Servers\Tomcat v7.0 Server at localhost-config\logging.properties" -Djava.util.logging.manager=org.apache.juli.ClassLoaderLogManager

to the VM arguments of the launch configuration one is using.

This may have taken a restart or two (or not) but finally I saw in the console in bright red :

FINE: No TLD files were found in [file:/C:/Dropbox/eclipse_workspaces/javaEE/.metadata/.plugins/org.eclipse.wst.server.core/tmp0/wtpwebapps/ted2012/WEB-INF/lib/logback-classic-1.0.7.jar]. Consider adding the JAR to the tomcat.util.scan.DefaultJarScanner.jarsToSkip or org.apache.catalina.startup.TldConfig.jarsToSkip property in CATALINA_BASE/conf/catalina.properties file. //etc

I still don't know when exactly this FINE warning appears - does not appear immediately on tomcat launch EDIT: from the comment by @Stephan: "The FINE warning appears each time any change is done in the JSP file".


Bonus: To make the warning go away add in catalina.properties :

# Additional JARs (over and above the default JARs listed above) to skip when
# scanning for TLDs. The list must be a comma separated list of JAR file names.
org.apache.catalina.startup.TldConfig.jarsToSkip=logback-classic-1.0.7.jar,\
joda-time-2.1.jar,joda-time-2.1-javadoc.jar,mysql-connector-java-5.1.24-bin.jar,\
logback-core-1.0.7.jar,javax.servlet.jsp.jstl-api-1.2.1.jar

What's the purpose of git-mv?

Maybe git mv has changed since these answers were posted, so I will update briefly. In my view, git mv is not accurately described as short hand for:

 # not accurate: #
 mv oldname newname
 git add newname
 git rm oldname

I use git mv frequently for two reasons that have not been described in previous answers:

  1. Moving large directory structures, where I have mixed content of both tracked and untracked files. Both tracked and untracked files will move, and retain their tracking/untracking status

  2. Moving files and directories that are large, I have always assumed that git mv will reduce the size of the repository DB history size. This is because moving/renaming a file is indexation/reference delta. I have not verified this assumption, but it seems logical.

#1130 - Host ‘localhost’ is not allowed to connect to this MySQL server

Use the IP instead:

DROP USER 'root'@'127.0.0.1'; GRANT ALL PRIVILEGES ON . TO 'root'@'%';

For more possibilities, see this link.

To create the root user, seeing as MySQL is local & all, execute the following from the command line (Start > Run > "cmd" without quotes):

mysqladmin -u root password 'mynewpassword'

Documentation, and Lost root access in MySQL.

Add a thousands separator to a total with Javascript or jQuery?

Below is the working Example:

 $("#estimated-amount-due .content").html("$" + miniCartTotal.toFixed(2).replace(/(\d)(?=(\d{3})+(?!\d))/g, "$1,"));  

This line is sufficient, it works for me. Check the complete code below. Let me know if it works fine for you too.

$(".action.showcart").on('click', function() {
    var miniCartTotal = $("#estimated-subtotal .price").html();
    var miniCartTotalString = miniCartTotal.replace(/\$/g, '');
    var miniCartTotalString = miniCartTotalString.replace(/,/g, ''); 
    var configValue = 5; 

    miniCartTotal = parseFloat(miniCartTotalString) + configValue;
    console.log("updated value " + miniCartTotal);

    $("#estimated-amount-due .content").html("$" + miniCartTotal.toFixed(2).replace(/(\d)(?=(\d{3})+(?!\d))/g, "$1,"));
});

How can I copy a conditional formatting from one document to another?

If you want to copy conditional formatting to another document you can use the "Copy to..." feature for the worksheet (click the tab with the name of the worksheet at the bottom) and copy the worksheet to the other document.

Then you can just copy what you want from that worksheet and right-click select "Paste special" -> "Paste conditional formatting only", as described earlier.

How can I run multiple npm scripts in parallel?

Quick Solution

In this case, I'd say the best bet If this script is for a private module intended to run only on *nix-based machines, you can use the control operator for forking processes, which looks like this: &

An example of doing this in a partial package.json file:

{
  "name": "npm-scripts-forking-example",
  "scripts": {
    "bundle": "watchify -vd -p browserify-hmr index.js -o bundle.js",
    "serve":  "http-server -c 1 -a localhost",
    "serve-bundle": "npm run bundle & npm run serve &"
  }

You'd then execute them both in parallel via npm run serve-bundle. You can enhance the scripts to output the pids of the forked process to a file like so:

"serve-bundle": "npm run bundle & echo \"$!\" > build/bundle.pid && npm run serve & echo \"$!\" > build/serve.pid && npm run open-browser",

Google something like bash control operator for forking to learn more on how it works. I've also provided some further context regarding leveraging Unix techniques in Node projects below:

Further Context RE: Unix Tools & Node.js

If you're not on Windows, Unix tools/techniques often work well to achieve something with Node scripts because:

  1. Much of Node.js lovingly imitates Unix principles
  2. You're on *nix (incl. OS X) and NPM is using a shell anyway

Modules for system tasks in Nodeland are also often abstractions or approximations of Unix tools, from fs to streams.

Subtract minute from DateTime in SQL Server 2005

SELECT DATEADD(minute, -15, '2000-01-01 08:30:00'); 

The second value (-15 in this case) must be numeric (i.e. not a string like '00:15'). If you need to subtract hours and minutes I would recommend splitting the string on the : to get the hours and minutes and subtracting using something like

SELECT DATEADD(minute, -60 * @h - @m, '2000-01-01 08:30:00'); 

where @h is the hour part of your string and @m is the minute part of your string

EDIT:

Here is a better way:

SELECT CAST('2000-01-01 08:30:00' as datetime) - CAST('00:15' AS datetime)

How to make a simple rounded button in Storyboard?

While adding layer.cornerRadius in the storyboard make sure that you don't have leading or trailing spaces. If you do copy paste, you might get spaces inserted. Would be nice if XCode say some kind of warning or error.

Inline CSS styles in React: how to implement a:hover?

<Hoverable hoverStyle={styles.linkHover}>
  <a href="https://example.com" style={styles.link}>
    Go
  </a>
</Hoverable>

Where Hoverable is defined as:

function Hoverable(props) {
  const [hover, setHover] = useState(false);

  const child = Children.only(props.children);

  const onHoverChange = useCallback(
    e => {
      const name = e.type === "mouseenter" ? "onMouseEnter" : "onMouseLeave";
      setHover(!hover);
      if (child.props[name]) {
        child.props[name](e);
      }
    },
    [setHover, hover, child]
  );

  return React.cloneElement(child, {
    onMouseEnter: onHoverChange,
    onMouseLeave: onHoverChange,
    style: Object.assign({}, child.props.style, hover ? props.hoverStyle : {})
  });
}

How to sort a Collection<T>?

If your collections object is a list, I would use the sort method, as proposed in the other answers.

However, if it is not a list, and you don't really care about what type of Collection object is returned, I think it is faster to create a TreeSet instead of a List:

TreeSet sortedSet = new TreeSet(myComparator);
sortedSet.addAll(myCollectionToBeSorted);

Excel tab sheet names vs. Visual Basic sheet names

This will change all worksheet objects' names (from the perspective of the VBA editor) to match that of their sheet names (from the perspective of Excel):

Sub ZZ_Reset_Sheet_CodeNames()
'Changes the internal object name (codename) of each sheet to it's conventional name (based on it's sheet name)

    Dim varItem As Variant

    For Each varItem In ThisWorkbook.VBProject.VBComponents
        'Type 100 is a worksheet
        If varItem.Type = 100 And varItem.Name <> "ThisWorkbook" Then
            varItem.Name = varItem.Properties("Name").Value
        End If
    Next
End Sub

It is important to note that the object name (codename) "(Name)" is being overridden by the property name "Name", and so it must be referenced as a sub-property.

Flatten List in LINQ

Try SelectMany()

var result = iList.SelectMany( i => i );

VBA Copy Sheet to End of Workbook (with Hidden Worksheets)

If you use the following code based on @Siddharth Rout's code, you rename the just copied sheet, no matter, if it is activated or not.

Sub Sample()

    ThisWorkbook.Sheets(1).Copy After:=Sheets(Sheets.Count)
    ThisWorkbook.Sheets(Sheets.Count).Name = "copied sheet!"

End Sub

List names of all tables in a SQL Server 2012 schema

SELECT t.name 
  FROM sys.tables AS t
  INNER JOIN sys.schemas AS s
  ON t.[schema_id] = s.[schema_id]
  WHERE s.name = N'schema_name';

java.lang.IllegalArgumentException: View not attached to window manager

I think your code is correct unlike the other answer suggested. onPostExecute will run on the UI thread. That's the whole point of AsyncTask - you don't have to worry about calling runOnUiThread or deal with handlers. Furthermore, according to the docs, dismiss() can be safely called from any thread (not sure they made this the exception).

Perhaps it's a timing issue where dialog.dismiss() is getting called after the activity is no longer displayed?

What about testing what happens if you comment out the setOnCancelListener and then exit the activity while the background task is running? Then your onPostExecute will try to dismiss an already dismissed dialog. If the app crashes you can probably just check if the dialog is open before dismissing it.

I'm having the exact same problem so I'm going to try it out in code.

How to "grep" for a filename instead of the contents of a file?

The easiest way is

find . | grep test

here find will list all the files in the (.) ie current directory, recursively. And then it is just a simple grep. all the files which name has "test" will appeared.

you can play with grep as per your requirement. Note : As the grep is generic string classification, It can result in giving you not only file names. but if a path has a directory ('/xyz_test_123/other.txt') would also comes to the result set. cheers

Boolean checking in the 'if' condition

Former, of course. Latter is redundant, and only goes to show that you haven't understood the concept of booleans very well.

One more suggestion: Choose a different name for your boolean variable. As per this Java style guide:

is prefix should be used for boolean variables and methods.

isSet, isVisible, isFinished, isFound, isOpen

This is the naming convention for boolean methods and variables used by Sun for the Java core packages.

Using the is prefix solves a common problem of choosing bad boolean names like status or flag. isStatus or isFlag simply doesn't fit, and the programmer is forced to chose more meaningful names.

Setter methods for boolean variables must have set prefix as in:

void setFound(boolean isFound);

There are a few alternatives to the is prefix that fits better in some situations. These are has, can and should prefixes:

boolean hasLicense();
boolean canEvaluate();
boolean shouldAbort = false;

Why does MSBuild look in C:\ for Microsoft.Cpp.Default.props instead of c:\Program Files (x86)\MSBuild? ( error MSB4019)

EDIT: This applies to older versions of Visual Studio / MSBuild (specifically MSVC2015?). With more modern versions, MSBuild is included in Visual Studio Build Tools 2019, and compilers are located in different places and detected in different ways.

This is due to a mismatch of installed MSBuild toolsets and registry settings. It can happen if you did one or more of the following:

  • Install multiple Visual Studio versions in the wrong order
  • Uninstall one or more versions of Visual Studio
  • Manually make registry changes or modifications to the Visual Studio installation

The only safe and reliable solution I know of is to reinstall your OS. If your project needs multiple versions of Visual Studio to build, install the oldest version first. Then fix your code so you can use one single tool to build it, or you or your colleagues will be in the same mess again soon.

If this is not an option for you, first read https://stackoverflow.com/a/41786593/2279059 for a better understanding of the problem and what the various "solutions" actually do. Then, depending on your Visual Studio version and setup, one of the other answers or variations of them may eventually help.

Some more hints:

Set UIButton title UILabel font size programmatically

You can also set the font size, and the font style using something like this. It's a little more than what you're asking for but hey, what the heck...

[myButton.titleLabel setFont:[UIFont fontWithName:@"Helvetica-Bold" size:13.0]];

And… if you're feeling frisky a list of available fonts can be found by implementing this code and then checking the output in your xCode debugger.

Code:

NSArray *familyNames = [[NSArray alloc] initWithArray:[UIFont familyNames]];
NSArray *fontNames;
NSInteger indFamily, indFont;
for (indFamily=0; indFamily<[familyNames count]; ++indFamily)
{
    NSLog(@"Family name: %@", [familyNames objectAtIndex:indFamily]);
    fontNames = [[NSArray alloc] initWithArray:
            [UIFont fontNamesForFamilyName:
            [familyNames objectAtIndex:indFamily]]];
    for (indFont=0; indFont<[fontNames count]; ++indFont)
    {
        NSLog(@"    Font name: %@", [fontNames objectAtIndex:indFont]);
    }
}

Example:

2012-04-02 11:36:34.395 MyApp[3579:707] Family name: Thonburi
2012-04-02 11:36:34.398 MyApp[3579:707]     Font name: Thonburi-Bold
2012-04-02 11:36:34.402 MyApp[3579:707]     Font name: Thonburi
2012-04-02 11:36:34.405 MyApp[3579:707] Family name: Snell Roundhand
2012-04-02 11:36:34.408 MyApp[3579:707]     Font name: SnellRoundhand-Bold
2012-04-02 11:36:34.411 MyApp[3579:707]     Font name: SnellRoundhand-Black
2012-04-02 11:36:34.415 MyApp[3579:707]     Font name: SnellRoundhand
2012-04-02 11:36:34.418 MyApp[3579:707] Family name: Academy Engraved LET
2012-04-02 11:36:34.421 MyApp[3579:707]     Font name: AcademyEngravedLetPlain
2012-04-02 11:36:34.424 MyApp[3579:707] Family name: Marker Felt
2012-04-02 11:36:34.427 MyApp[3579:707]     Font name: MarkerFelt-Wide
2012-04-02 11:36:34.430 MyApp[3579:707]     Font name: MarkerFelt-Thin
2012-04-02 11:36:34.434 MyApp[3579:707] Family name: Geeza Pro
2012-04-02 11:36:34.437 MyApp[3579:707]     Font name: GeezaPro-Bold
2012-04-02 11:36:34.441 MyApp[3579:707]     Font name: GeezaPro
2012-04-02 11:36:34.445 MyApp[3579:707] Family name: Arial Rounded MT Bold
2012-04-02 11:36:34.448 MyApp[3579:707]     Font name: ArialRoundedMTBold
2012-04-02 11:36:34.451 MyApp[3579:707] Family name: Trebuchet MS
2012-04-02 11:36:34.455 MyApp[3579:707]     Font name: TrebuchetMS
2012-04-02 11:36:34.458 MyApp[3579:707]     Font name: TrebuchetMS-Bold
2012-04-02 11:36:34.461 MyApp[3579:707]     Font name: TrebuchetMS-Italic
2012-04-02 11:36:34.464 MyApp[3579:707]     Font name: Trebuchet-BoldItalic
2012-04-02 11:36:34.467 MyApp[3579:707] Family name: Arial
2012-04-02 11:36:34.471 MyApp[3579:707]     Font name: Arial-BoldMT
2012-04-02 11:36:34.474 MyApp[3579:707]     Font name: ArialMT
2012-04-02 11:36:34.477 MyApp[3579:707]     Font name: Arial-ItalicMT
2012-04-02 11:36:34.480 MyApp[3579:707]     Font name: Arial-BoldItalicMT
2012-04-02 11:36:34.483 MyApp[3579:707] Family name: Marion
2012-04-02 11:36:34.487 MyApp[3579:707]     Font name: Marion-Regular
2012-04-02 11:36:34.491 MyApp[3579:707]     Font name: Marion-Bold
2012-04-02 11:36:34.494 MyApp[3579:707]     Font name: Marion-Italic
2012-04-02 11:36:34.503 MyApp[3579:707] Family name: Gurmukhi MN
2012-04-02 11:36:34.507 MyApp[3579:707]     Font name: GurmukhiMN
2012-04-02 11:36:34.511 MyApp[3579:707]     Font name: GurmukhiMN-Bold
2012-04-02 11:36:34.514 MyApp[3579:707] Family name: Malayalam Sangam MN
2012-04-02 11:36:34.518 MyApp[3579:707]     Font name: MalayalamSangamMN-Bold
2012-04-02 11:36:34.522 MyApp[3579:707]     Font name: MalayalamSangamMN
2012-04-02 11:36:34.525 MyApp[3579:707] Family name: Bradley Hand
2012-04-02 11:36:34.529 MyApp[3579:707]     Font name: BradleyHandITCTT-Bold
2012-04-02 11:36:34.532 MyApp[3579:707] Family name: Kannada Sangam MN
2012-04-02 11:36:34.536 MyApp[3579:707]     Font name: KannadaSangamMN
2012-04-02 11:36:34.540 MyApp[3579:707]     Font name: KannadaSangamMN-Bold
2012-04-02 11:36:34.544 MyApp[3579:707] Family name: Bodoni 72 Oldstyle
2012-04-02 11:36:34.548 MyApp[3579:707]     Font name: BodoniSvtyTwoOSITCTT-Book
2012-04-02 11:36:34.552 MyApp[3579:707]     Font name: BodoniSvtyTwoOSITCTT-Bold
2012-04-02 11:36:34.555 MyApp[3579:707]     Font name: BodoniSvtyTwoOSITCTT-BookIt
2012-04-02 11:36:34.559 MyApp[3579:707] Family name: Cochin
2012-04-02 11:36:34.562 MyApp[3579:707]     Font name: Cochin
2012-04-02 11:36:34.566 MyApp[3579:707]     Font name: Cochin-BoldItalic
2012-04-02 11:36:34.570 MyApp[3579:707]     Font name: Cochin-Italic
2012-04-02 11:36:34.573 MyApp[3579:707]     Font name: Cochin-Bold
2012-04-02 11:36:34.577 MyApp[3579:707] Family name: Sinhala Sangam MN
2012-04-02 11:36:34.581 MyApp[3579:707]     Font name: SinhalaSangamMN
2012-04-02 11:36:34.584 MyApp[3579:707]     Font name: SinhalaSangamMN-Bold
2012-04-02 11:36:34.588 MyApp[3579:707] Family name: Hiragino Kaku Gothic ProN
2012-04-02 11:36:34.592 MyApp[3579:707]     Font name: HiraKakuProN-W6
2012-04-02 11:36:34.596 MyApp[3579:707]     Font name: HiraKakuProN-W3
2012-04-02 11:36:34.599 MyApp[3579:707] Family name: Papyrus
2012-04-02 11:36:34.603 MyApp[3579:707]     Font name: Papyrus-Condensed
2012-04-02 11:36:34.607 MyApp[3579:707]     Font name: Papyrus
2012-04-02 11:36:34.614 MyApp[3579:707] Family name: Verdana
2012-04-02 11:36:34.620 MyApp[3579:707]     Font name: Verdana
2012-04-02 11:36:34.626 MyApp[3579:707]     Font name: Verdana-Bold
2012-04-02 11:36:34.674 MyApp[3579:707]     Font name: Verdana-BoldItalic
2012-04-02 11:36:34.690 MyApp[3579:707]     Font name: Verdana-Italic
2012-04-02 11:36:34.730 MyApp[3579:707] Family name: Zapf Dingbats
2012-04-02 11:36:34.748 MyApp[3579:707]     Font name: ZapfDingbatsITC
2012-04-02 11:36:34.752 MyApp[3579:707] Family name: Courier
2012-04-02 11:36:34.757 MyApp[3579:707]     Font name: Courier-Bold
2012-04-02 11:36:34.762 MyApp[3579:707]     Font name: Courier
2012-04-02 11:36:34.769 MyApp[3579:707]     Font name: Courier-BoldOblique
2012-04-02 11:36:34.778 MyApp[3579:707]     Font name: Courier-Oblique
2012-04-02 11:36:34.786 MyApp[3579:707] Family name: Hoefler Text
2012-04-02 11:36:34.793 MyApp[3579:707]     Font name: HoeflerText-Black
2012-04-02 11:36:34.802 MyApp[3579:707]     Font name: HoeflerText-Italic
2012-04-02 11:36:34.810 MyApp[3579:707]     Font name: HoeflerText-Regular
2012-04-02 11:36:34.819 MyApp[3579:707]     Font name: HoeflerText-BlackItalic
2012-04-02 11:36:34.827 MyApp[3579:707] Family name: Euphemia UCAS
2012-04-02 11:36:34.836 MyApp[3579:707]     Font name: EuphemiaUCAS-Bold
2012-04-02 11:36:34.843 MyApp[3579:707]     Font name: EuphemiaUCAS
2012-04-02 11:36:34.848 MyApp[3579:707]     Font name: EuphemiaUCAS-Italic
2012-04-02 11:36:34.853 MyApp[3579:707] Family name: Helvetica
2012-04-02 11:36:34.857 MyApp[3579:707]     Font name: Helvetica-LightOblique
2012-04-02 11:36:34.863 MyApp[3579:707]     Font name: Helvetica
2012-04-02 11:36:34.873 MyApp[3579:707]     Font name: Helvetica-Oblique
2012-04-02 11:36:34.876 MyApp[3579:707]     Font name: Helvetica-BoldOblique
2012-04-02 11:36:34.880 MyApp[3579:707]     Font name: Helvetica-Bold
2012-04-02 11:36:34.884 MyApp[3579:707]     Font name: Helvetica-Light
2012-04-02 11:36:34.887 MyApp[3579:707] Family name: Hiragino Mincho ProN
2012-04-02 11:36:34.892 MyApp[3579:707]     Font name: HiraMinProN-W3
2012-04-02 11:36:34.898 MyApp[3579:707]     Font name: HiraMinProN-W6
2012-04-02 11:36:34.902 MyApp[3579:707] Family name: Bodoni Ornaments
2012-04-02 11:36:34.905 MyApp[3579:707]     Font name: BodoniOrnamentsITCTT
2012-04-02 11:36:34.923 MyApp[3579:707] Family name: Apple Color Emoji
2012-04-02 11:36:34.938 MyApp[3579:707]     Font name: AppleColorEmoji
2012-04-02 11:36:34.942 MyApp[3579:707] Family name: Optima
2012-04-02 11:36:34.946 MyApp[3579:707]     Font name: Optima-ExtraBlack
2012-04-02 11:36:34.950 MyApp[3579:707]     Font name: Optima-Italic
2012-04-02 11:36:34.954 MyApp[3579:707]     Font name: Optima-Regular
2012-04-02 11:36:34.965 MyApp[3579:707]     Font name: Optima-BoldItalic
2012-04-02 11:36:34.969 MyApp[3579:707]     Font name: Optima-Bold
2012-04-02 11:36:34.972 MyApp[3579:707] Family name: Gujarati Sangam MN
2012-04-02 11:36:34.985 MyApp[3579:707]     Font name: GujaratiSangamMN
2012-04-02 11:36:34.989 MyApp[3579:707]     Font name: GujaratiSangamMN-Bold
2012-04-02 11:36:34.993 MyApp[3579:707] Family name: Devanagari Sangam MN
2012-04-02 11:36:34.998 MyApp[3579:707]     Font name: DevanagariSangamMN
2012-04-02 11:36:35.002 MyApp[3579:707]     Font name: DevanagariSangamMN-Bold
2012-04-02 11:36:35.006 MyApp[3579:707] Family name: Times New Roman
2012-04-02 11:36:35.017 MyApp[3579:707]     Font name: TimesNewRomanPS-ItalicMT
2012-04-02 11:36:35.021 MyApp[3579:707]     Font name: TimesNewRomanPS-BoldMT
2012-04-02 11:36:35.032 MyApp[3579:707]     Font name: TimesNewRomanPSMT
2012-04-02 11:36:35.037 MyApp[3579:707]     Font name: TimesNewRomanPS-BoldItalicMT
2012-04-02 11:36:35.041 MyApp[3579:707] Family name: Kailasa
2012-04-02 11:36:35.045 MyApp[3579:707]     Font name: Kailasa
2012-04-02 11:36:35.050 MyApp[3579:707]     Font name: Kailasa-Bold
2012-04-02 11:36:35.053 MyApp[3579:707] Family name: Telugu Sangam MN
2012-04-02 11:36:35.064 MyApp[3579:707]     Font name: TeluguSangamMN-Bold
2012-04-02 11:36:35.068 MyApp[3579:707]     Font name: TeluguSangamMN
2012-04-02 11:36:35.071 MyApp[3579:707] Family name: Heiti SC
2012-04-02 11:36:35.099 MyApp[3579:707]     Font name: STHeitiSC-Medium
2012-04-02 11:36:35.107 MyApp[3579:707]     Font name: STHeitiSC-Light
2012-04-02 11:36:35.111 MyApp[3579:707] Family name: Futura
2012-04-02 11:36:35.115 MyApp[3579:707]     Font name: Futura-Medium
2012-04-02 11:36:35.119 MyApp[3579:707]     Font name: Futura-CondensedExtraBold
2012-04-02 11:36:35.122 MyApp[3579:707]     Font name: Futura-CondensedMedium
2012-04-02 11:36:35.135 MyApp[3579:707]     Font name: Futura-MediumItalic
2012-04-02 11:36:35.155 MyApp[3579:707] Family name: Bodoni 72
2012-04-02 11:36:35.160 MyApp[3579:707]     Font name: BodoniSvtyTwoITCTT-BookIta
2012-04-02 11:36:35.164 MyApp[3579:707]     Font name: BodoniSvtyTwoITCTT-Book
2012-04-02 11:36:35.168 MyApp[3579:707]     Font name: BodoniSvtyTwoITCTT-Bold
2012-04-02 11:36:35.171 MyApp[3579:707] Family name: Baskerville
2012-04-02 11:36:35.183 MyApp[3579:707]     Font name: Baskerville-SemiBoldItalic
2012-04-02 11:36:35.187 MyApp[3579:707]     Font name: Baskerville-Bold
2012-04-02 11:36:35.197 MyApp[3579:707]     Font name: Baskerville-Italic
2012-04-02 11:36:35.245 MyApp[3579:707]     Font name: Baskerville-BoldItalic
2012-04-02 11:36:35.253 MyApp[3579:707]     Font name: Baskerville-SemiBold
2012-04-02 11:36:35.258 MyApp[3579:707]     Font name: Baskerville
2012-04-02 11:36:35.262 MyApp[3579:707] Family name: Chalkboard SE
2012-04-02 11:36:35.266 MyApp[3579:707]     Font name: ChalkboardSE-Regular
2012-04-02 11:36:35.269 MyApp[3579:707]     Font name: ChalkboardSE-Bold
2012-04-02 11:36:35.279 MyApp[3579:707]     Font name: ChalkboardSE-Light
2012-04-02 11:36:35.284 MyApp[3579:707] Family name: Heiti TC
2012-04-02 11:36:35.288 MyApp[3579:707]     Font name: STHeitiTC-Medium
2012-04-02 11:36:35.299 MyApp[3579:707]     Font name: STHeitiTC-Light
2012-04-02 11:36:35.305 MyApp[3579:707] Family name: Copperplate
2012-04-02 11:36:35.310 MyApp[3579:707]     Font name: Copperplate
2012-04-02 11:36:35.313 MyApp[3579:707]     Font name: Copperplate-Light
2012-04-02 11:36:35.317 MyApp[3579:707]     Font name: Copperplate-Bold
2012-04-02 11:36:35.320 MyApp[3579:707] Family name: Party LET
2012-04-02 11:36:35.334 MyApp[3579:707]     Font name: PartyLetPlain
2012-04-02 11:36:35.338 MyApp[3579:707] Family name: American Typewriter
2012-04-02 11:36:35.351 MyApp[3579:707]     Font name: AmericanTypewriter-CondensedLight
2012-04-02 11:36:35.357 MyApp[3579:707]     Font name: AmericanTypewriter-Light
2012-04-02 11:36:35.361 MyApp[3579:707]     Font name: AmericanTypewriter-Bold
2012-04-02 11:36:35.364 MyApp[3579:707]     Font name: AmericanTypewriter
2012-04-02 11:36:35.368 MyApp[3579:707]     Font name: AmericanTypewriter-CondensedBold
2012-04-02 11:36:35.372 MyApp[3579:707]     Font name: AmericanTypewriter-Condensed
2012-04-02 11:36:35.384 MyApp[3579:707] Family name: AppleGothic
2012-04-02 11:36:35.400 MyApp[3579:707]     Font name: AppleGothic
2012-04-02 11:36:35.406 MyApp[3579:707] Family name: Bangla Sangam MN
2012-04-02 11:36:35.411 MyApp[3579:707]     Font name: BanglaSangamMN-Bold
2012-04-02 11:36:35.414 MyApp[3579:707]     Font name: BanglaSangamMN
2012-04-02 11:36:35.418 MyApp[3579:707] Family name: Noteworthy
2012-04-02 11:36:35.422 MyApp[3579:707]     Font name: Noteworthy-Light
2012-04-02 11:36:35.432 MyApp[3579:707]     Font name: Noteworthy-Bold
2012-04-02 11:36:35.436 MyApp[3579:707] Family name: Zapfino
2012-04-02 11:36:35.443 MyApp[3579:707]     Font name: Zapfino
2012-04-02 11:36:35.448 MyApp[3579:707] Family name: Tamil Sangam MN
2012-04-02 11:36:35.452 MyApp[3579:707]     Font name: TamilSangamMN
2012-04-02 11:36:35.456 MyApp[3579:707]     Font name: TamilSangamMN-Bold
2012-04-02 11:36:35.459 MyApp[3579:707] Family name: DB LCD Temp
2012-04-02 11:36:35.463 MyApp[3579:707]     Font name: DBLCDTempBlack
2012-04-02 11:36:35.467 MyApp[3579:707] Family name: Arial Hebrew
2012-04-02 11:36:35.471 MyApp[3579:707]     Font name: ArialHebrew
2012-04-02 11:36:35.475 MyApp[3579:707]     Font name: ArialHebrew-Bold
2012-04-02 11:36:35.479 MyApp[3579:707] Family name: Chalkduster
2012-04-02 11:36:35.482 MyApp[3579:707]     Font name: Chalkduster
2012-04-02 11:36:35.486 MyApp[3579:707] Family name: Georgia
2012-04-02 11:36:35.490 MyApp[3579:707]     Font name: Georgia-Italic
2012-04-02 11:36:35.493 MyApp[3579:707]     Font name: Georgia-BoldItalic
2012-04-02 11:36:35.497 MyApp[3579:707]     Font name: Georgia-Bold
2012-04-02 11:36:35.501 MyApp[3579:707]     Font name: Georgia
2012-04-02 11:36:35.504 MyApp[3579:707] Family name: Helvetica Neue
2012-04-02 11:36:35.508 MyApp[3579:707]     Font name: HelveticaNeue-Bold
2012-04-02 11:36:35.511 MyApp[3579:707]     Font name: HelveticaNeue-CondensedBlack
2012-04-02 11:36:35.515 MyApp[3579:707]     Font name: HelveticaNeue-Medium
2012-04-02 11:36:35.518 MyApp[3579:707]     Font name: HelveticaNeue
2012-04-02 11:36:35.522 MyApp[3579:707]     Font name: HelveticaNeue-Light
2012-04-02 11:36:35.526 MyApp[3579:707]     Font name: HelveticaNeue-CondensedBold
2012-04-02 11:36:35.529 MyApp[3579:707]     Font name: HelveticaNeue-LightItalic
2012-04-02 11:36:35.532 MyApp[3579:707]     Font name: HelveticaNeue-UltraLightItalic
2012-04-02 11:36:35.536 MyApp[3579:707]     Font name: HelveticaNeue-UltraLight
2012-04-02 11:36:35.540 MyApp[3579:707]     Font name: HelveticaNeue-BoldItalic
2012-04-02 11:36:35.543 MyApp[3579:707]     Font name: HelveticaNeue-Italic
2012-04-02 11:36:35.547 MyApp[3579:707] Family name: Gill Sans
2012-04-02 11:36:35.551 MyApp[3579:707]     Font name: GillSans-LightItalic
2012-04-02 11:36:35.555 MyApp[3579:707]     Font name: GillSans-BoldItalic
2012-04-02 11:36:35.558 MyApp[3579:707]     Font name: GillSans-Italic
2012-04-02 11:36:35.562 MyApp[3579:707]     Font name: GillSans
2012-04-02 11:36:35.565 MyApp[3579:707]     Font name: GillSans-Bold
2012-04-02 11:36:35.569 MyApp[3579:707]     Font name: GillSans-Light
2012-04-02 11:36:35.572 MyApp[3579:707] Family name: Palatino
2012-04-02 11:36:35.576 MyApp[3579:707]     Font name: Palatino-Roman
2012-04-02 11:36:35.580 MyApp[3579:707]     Font name: Palatino-Bold
2012-04-02 11:36:35.583 MyApp[3579:707]     Font name: Palatino-BoldItalic
2012-04-02 11:36:35.587 MyApp[3579:707]     Font name: Palatino-Italic
2012-04-02 11:36:35.591 MyApp[3579:707] Family name: Courier New
2012-04-02 11:36:35.594 MyApp[3579:707]     Font name: CourierNewPSMT
2012-04-02 11:36:35.598 MyApp[3579:707]     Font name: CourierNewPS-BoldMT
2012-04-02 11:36:35.601 MyApp[3579:707]     Font name: CourierNewPS-BoldItalicMT
2012-04-02 11:36:35.605 MyApp[3579:707]     Font name: CourierNewPS-ItalicMT
2012-04-02 11:36:35.608 MyApp[3579:707] Family name: Oriya Sangam MN
2012-04-02 11:36:35.612 MyApp[3579:707]     Font name: OriyaSangamMN-Bold
2012-04-02 11:36:35.616 MyApp[3579:707]     Font name: OriyaSangamMN
2012-04-02 11:36:35.619 MyApp[3579:707] Family name: Didot
2012-04-02 11:36:35.623 MyApp[3579:707]     Font name: Didot-Italic
2012-04-02 11:36:35.627 MyApp[3579:707]     Font name: Didot
2012-04-02 11:36:35.630 MyApp[3579:707]     Font name: Didot-Bold
2012-04-02 11:36:35.634 MyApp[3579:707] Family name: Bodoni 72 Smallcaps
2012-04-02 11:36:35.638 MyApp[3579:707]     Font name: BodoniSvtyTwoSCITCTT-Book

String isNullOrEmpty in Java?

For new projects, I've started having every class I write extend the same base class where I can put all the utility methods that are annoyingly missing from Java like this one, the equivalent for collections (tired of writing list != null && ! list.isEmpty()), null-safe equals, etc. I still use Apache Commons for the implementation but this saves a small amount of typing and I haven't seen any negative effects.

How to delete a whole folder and content?

There is a lot of answers, but I decided to add my own, because it's little different. It's based on OOP ;)

I created class DirectoryCleaner, which help me each time when I need to clean some directory.

public class DirectoryCleaner {
    private final File mFile;

    public DirectoryCleaner(File file) {
        mFile = file;
    }

    public void clean() {
        if (null == mFile || !mFile.exists() || !mFile.isDirectory()) return;
        for (File file : mFile.listFiles()) {
            delete(file);
        }
    }

    private void delete(File file) {
        if (file.isDirectory()) {
            for (File child : file.listFiles()) {
                delete(child);
            }
        }
        file.delete();

    }
}

It can be used to solve this problem in next way:

File dir = new File(Environment.getExternalStorageDirectory(), "your_directory_name");
new DirectoryCleaner(dir).clean();
dir.delete();

What is the most efficient/quickest way to loop through rows in VBA (excel)?

For Each is much faster than for I=1 to X, for some reason. Just try to go through the same dictionary,


once with for each Dkey in dDict,


and once with for Dkey = lbound(dDict.keys) to ubound(dDict.keys)

=>You will notice a huge difference, even though you are going through the same construct.

How to detect running app using ADB command

No need to use grep. ps in Android can filter by COMM value (last 15 characters of the package name in case of java app)

Let's say we want to check if com.android.phone is running:

adb shell ps m.android.phone
USER     PID   PPID  VSIZE  RSS     WCHAN    PC         NAME
radio     1389  277   515960 33964 ffffffff 4024c270 S com.android.phone

Filtering by COMM value option has been removed from ps in Android 7.0. To check for a running process by name in Android 7.0 you can use pidof command:

adb shell pidof com.android.phone

It returns the PID if such process was found or an empty string otherwise.

IOS 7 Navigation Bar text and arrow color

It seems that Accessibility controls in the iOS Settings override pretty much everything you try to do color-wise to the navigation bar buttons. Make sure you have all the settings to the default positions (set increase contrast, bold text, button shapes, etc to off) otherwise you won't see anything change. Once I did it, all the color change code started working as expected. You might not need to turn them all off, but I didn't pursue it further.

SQL Query Multiple Columns Using Distinct on One Column Only

select * from tblFruit where
tblFruit_ID in (Select max(tblFruit_ID) FROM tblFruit group by tblFruit_FruitType)

onMeasure custom view explanation

onMeasure() is your opportunity to tell Android how big you want your custom view to be dependent the layout constraints provided by the parent; it is also your custom view's opportunity to learn what those layout constraints are (in case you want to behave differently in a match_parent situation than a wrap_content situation). These constraints are packaged up into the MeasureSpec values that are passed into the method. Here is a rough correlation of the mode values:

  • EXACTLY means the layout_width or layout_height value was set to a specific value. You should probably make your view this size. This can also get triggered when match_parent is used, to set the size exactly to the parent view (this is layout dependent in the framework).
  • AT_MOST typically means the layout_width or layout_height value was set to match_parent or wrap_content where a maximum size is needed (this is layout dependent in the framework), and the size of the parent dimension is the value. You should not be any larger than this size.
  • UNSPECIFIED typically means the layout_width or layout_height value was set to wrap_content with no restrictions. You can be whatever size you would like. Some layouts also use this callback to figure out your desired size before determine what specs to actually pass you again in a second measure request.

The contract that exists with onMeasure() is that setMeasuredDimension() MUST be called at the end with the size you would like the view to be. This method is called by all the framework implementations, including the default implementation found in View, which is why it is safe to call super instead if that fits your use case.

Granted, because the framework does apply a default implementation, it may not be necessary for you to override this method, but you may see clipping in cases where the view space is smaller than your content if you do not, and if you lay out your custom view with wrap_content in both directions, your view may not show up at all because the framework doesn't know how large it is!

Generally, if you are overriding View and not another existing widget, it is probably a good idea to provide an implementation, even if it is as simple as something like this:

@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {

    int desiredWidth = 100;
    int desiredHeight = 100;

    int widthMode = MeasureSpec.getMode(widthMeasureSpec);
    int widthSize = MeasureSpec.getSize(widthMeasureSpec);
    int heightMode = MeasureSpec.getMode(heightMeasureSpec);
    int heightSize = MeasureSpec.getSize(heightMeasureSpec);

    int width;
    int height;

    //Measure Width
    if (widthMode == MeasureSpec.EXACTLY) {
        //Must be this size
        width = widthSize;
    } else if (widthMode == MeasureSpec.AT_MOST) {
        //Can't be bigger than...
        width = Math.min(desiredWidth, widthSize);
    } else {
        //Be whatever you want
        width = desiredWidth;
    }

    //Measure Height
    if (heightMode == MeasureSpec.EXACTLY) {
        //Must be this size
        height = heightSize;
    } else if (heightMode == MeasureSpec.AT_MOST) {
        //Can't be bigger than...
        height = Math.min(desiredHeight, heightSize);
    } else {
        //Be whatever you want
        height = desiredHeight;
    }

    //MUST CALL THIS
    setMeasuredDimension(width, height);
}

Hope that Helps.

R - " missing value where TRUE/FALSE needed "

check the command : NA!=NA : you'll get the result NA, hence the error message.

You have to use the function is.na for your ifstatement to work (in general, it is always better to use this function to check for NA values) :

comments = c("no","yes",NA)
for (l in 1:length(comments)) {
    if (!is.na(comments[l])) print(comments[l])
}
[1] "no"
[1] "yes"

What is the easiest way to install BLAS and LAPACK for scipy?

I got this problem on freeBSD. It seems lapack packages are missing, I solved it installing them (as root) with:

pkg install lapack
pkg install atlas-devel  #not sure this is needed, but just in case

I imagine it could work on other system too using the appropriate package installer (e.g. apt-get)

gradlew: Permission Denied

You need to update the execution permission for gradlew

Locally: chmod +x gradlew

Git:

git update-index --chmod=+x gradlew
git add .
git commit -m "Changing permission of gradlew"
git push

You should see:

mode change 100644 => 100755 gradlew

Injecting $scope into an angular service function()

Well (a long one) ... if you insist to have $scope access inside a service, you can:

Create a getter/setter service

ngapp.factory('Scopes', function (){
  var mem = {};
  return {
    store: function (key, value) { mem[key] = value; },
    get: function (key) { return mem[key]; }
  };
});

Inject it and store the controller scope in it

ngapp.controller('myCtrl', ['$scope', 'Scopes', function($scope, Scopes) {
  Scopes.store('myCtrl', $scope);
}]);

Now, get the scope inside another service

ngapp.factory('getRoute', ['Scopes', '$http', function(Scopes, $http){
  // there you are
  var $scope = Scopes.get('myCtrl');
}]);

Return multiple values from a SQL Server function

Another option would be to use a procedure with output parameters - Using a Stored Procedure with Output Parameters

In HTML5, can the <header> and <footer> tags appear outside of the <body> tag?

According to the HTML standard, the content model of the HTML element is:

A head element followed by a body element.

You can either define the BODY element in the source code:

<html>
    <body>
        ... web-page ...
    </body>
</html>

or you can omit the BODY element:

<html>
    ... web-page ...
</html>

However, it is invalid to place the BODY element inside the web-page content (in-between other elements or text content), like so:

<html>
    ... content ...
    <body>
        ... content ...
    </body>
    ... content ...
</html>

Read .csv file in C

The following code is in plain c language and handles blank spaces. It only allocates memory once, so one free() is needed, for each processed line.

http://ideone.com/mSCgPM

/* Tiny CSV Reader */
/* Copyright (C) 2015, Deligiannidis Konstantinos

This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program.  If not, see <http://w...content-available-to-author-only...u.org/licenses/>.  */


#include <stdio.h>
#include <string.h>
#include <stdlib.h>


/* For more that 100 columns or lines (when delimiter = \n), minor modifications are needed. */
int getcols( const char * const line, const char * const delim, char ***out_storage )

{
const char *start_ptr, *end_ptr, *iter;
char **out;
int i;                                          //For "for" loops in the old c style.
int tokens_found = 1, delim_size, line_size;    //Calculate "line_size" indirectly, without strlen() call.
int start_idx[100], end_idx[100];   //Store the indexes of tokens. Example "Power;": loc('P')=1, loc(';')=6
//Change 100 with MAX_TOKENS or use malloc() for more than 100 tokens. Example: "b1;b2;b3;...;b200"

if ( *out_storage != NULL )                 return -4;  //This SHOULD be NULL: Not Already Allocated
if ( !line || !delim )                      return -1;  //NULL pointers Rejected Here
if ( (delim_size = strlen( delim )) == 0 )  return -2;  //Delimiter not provided

start_ptr = line;   //Start visiting input. We will distinguish tokens in a single pass, for good performance.
                    //Then we are allocating one unified memory region & doing one memory copy.
while ( ( end_ptr = strstr( start_ptr, delim ) ) ) {

    start_idx[ tokens_found -1 ] = start_ptr - line;    //Store the Index of current token
    end_idx[ tokens_found - 1 ] = end_ptr - line;       //Store Index of first character that will be replaced with
                                                        //'\0'. Example: "arg1||arg2||end" -> "arg1\0|arg2\0|end"
    tokens_found++;                                     //Accumulate the count of tokens.
    start_ptr = end_ptr + delim_size;                   //Set pointer to the next c-string within the line
}

for ( iter = start_ptr; (*iter!='\0') ; iter++ );

start_idx[ tokens_found -1 ] = start_ptr - line;    //Store the Index of current token: of last token here.
end_idx[ tokens_found -1 ] = iter - line;           //and the last element that will be replaced with \0

line_size = iter - line;    //Saving CPU cycles: Indirectly Count the size of *line without using strlen();

int size_ptr_region = (1 + tokens_found)*sizeof( char* );   //The size to store pointers to c-strings + 1 (*NULL).
out = (char**) malloc( size_ptr_region + ( line_size + 1 ) + 5 );   //Fit everything there...it is all memory.
//It reserves a contiguous space for both (char**) pointers AND string region. 5 Bytes for "Out of Range" tests.
*out_storage = out;     //Update the char** pointer of the caller function.

//"Out of Range" TEST. Verify that the extra reserved characters will not be changed. Assign Some Values.
//char *extra_chars = (char*) out + size_ptr_region + ( line_size + 1 );
//extra_chars[0] = 1; extra_chars[1] = 2; extra_chars[2] = 3; extra_chars[3] = 4; extra_chars[4] = 5;

for ( i = 0; i < tokens_found; i++ )    //Assign adresses first part of the allocated memory pointers that point to
    out[ i ] = (char*) out + size_ptr_region + start_idx[ i ];  //the second part of the memory, reserved for Data.
out[ tokens_found ] = (char*) NULL; //[ ptr1, ptr2, ... , ptrN, (char*) NULL, ... ]: We just added the (char*) NULL.
                                                    //Now assign the Data: c-strings. (\0 terminated strings):
char *str_region = (char*) out + size_ptr_region;   //Region inside allocated memory which contains the String Data.
memcpy( str_region, line, line_size );   //Copy input with delimiter characters: They will be replaced with \0.

//Now we should replace: "arg1||arg2||arg3" with "arg1\0|arg2\0|arg3". Don't worry for characters after '\0'
//They are not used in standard c lbraries.
for( i = 0; i < tokens_found; i++) str_region[ end_idx[ i ] ] = '\0';

//"Out of Range" TEST. Wait until Assigned Values are Printed back.
//for ( int i=0; i < 5; i++ ) printf("c=%x ", extra_chars[i] ); printf("\n");

// *out memory should now contain (example data):
//[ ptr1, ptr2,...,ptrN, (char*) NULL, "token1\0", "token2\0",...,"tokenN\0", 5 bytes for tests ]
//   |__________________________________^           ^              ^             ^
//          |_______________________________________|              |             |
//                   |_____________________________________________|      These 5 Bytes should be intact.

return tokens_found;
}


int main()

{

char in_line[] = "Arg1;;Th;s is not Del;m;ter;;Arg3;;;;Final";
char delim[] = ";;";
char **columns;
int i;

printf("Example1:\n");
columns = NULL; //Should be NULL to indicate that it is not assigned to allocated memory. Otherwise return -4;

int cols_found = getcols( in_line, delim, &columns);
for ( i = 0; i < cols_found; i++ ) printf("Column[ %d ] = %s\n", i, columns[ i ] );  //<- (1st way).
// (2nd way) // for ( i = 0; columns[ i ]; i++) printf("start_idx[ %d ] = %s\n", i, columns[ i ] );

free( columns );    //Release the Single Contiguous Memory Space.
columns = NULL;     //Pointer = NULL to indicate it does not reserve space and that is ready for the next malloc().

printf("\n\nExample2, Nested:\n\n");

char example_file[] = "ID;Day;Month;Year;Telephone;email;Date of registration\n"
        "1;Sunday;january;2009;123-124-456;[email protected];2015-05-13\n"
        "2;Monday;March;2011;(+30)333-22-55;[email protected];2009-05-23";

char **rows;
int j;

rows = NULL; //getcols() requires it to be NULL. (Avoid dangling pointers, leaks e.t.c).

getcols( example_file, "\n", &rows);
for ( i = 0; rows[ i ]; i++) {
    {
        printf("Line[ %d ] = %s\n", i, rows[ i ] );
        char **columnX = NULL;
        getcols( rows[ i ], ";", &columnX);
        for ( j = 0; columnX[ j ]; j++) printf("  Col[ %d ] = %s\n", j, columnX[ j ] );
        free( columnX );
    }
}

free( rows );
rows = NULL;

return 0;
}

Axios handling errors

call the request function from anywhere without having to use catch().

First, while handling most errors in one place is a good Idea, it's not that easy with requests. Some errors (e.g. 400 validation errors like: "username taken" or "invalid email") should be passed on.

So we now use a Promise based function:

const baseRequest = async (method: string, url: string, data: ?{}) =>
  new Promise<{ data: any }>((resolve, reject) => {
    const requestConfig: any = {
      method,
      data,
      timeout: 10000,
      url,
      headers: {},
    };

    try {
      const response = await axios(requestConfig);
      // Request Succeeded!
      resolve(response);
    } catch (error) {
      // Request Failed!

      if (error.response) {
        // Request made and server responded
        reject(response);
      } else if (error.request) {
        // The request was made but no response was received
        reject(response);
      } else {
        // Something happened in setting up the request that triggered an Error
        reject(response);
      }
    }
  };

you can then use the request like

try {
  response = await baseRequest('GET', 'https://myApi.com/path/to/endpoint')
} catch (error) {
  // either handle errors or don't
}

Connect to Oracle DB using sqlplus

As David Aldridge explained, your parentheses should start right after the sqlplus command, so it should be:

sqlplus 'test/test@(DESCRIPTION=(ADDRESS_LIST=(ADDRESS=(PROTOCOL=TCP)(HOST=hostname.com )(PORT=1521)))(CONNECT_DATA=(SID=mysid))'

Expected response code 220 but got code "", with message "" in Laravel

i was facing this problem and i checked all the answers and nothing worked for me, but then i reset mail.php and didn't touch it and set the mail server from .env file and it worked perfectly, hope this will save the time for someone :).

Center fixed div with dynamic width (CSS)

This works regardless of the size of its contents

.centered {
  position: fixed;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}

source: https://css-tricks.com/quick-css-trick-how-to-center-an-object-exactly-in-the-center/

How do you determine a processing time in Python?

If all you want is the time between two points in code (and it seems that's what you want) I have written tic() toc() functions ala Matlab's implementation. The basic use case is:

tic()

''' some code that runs for an interesting amount of time '''

toc()

# OUTPUT:
# Elapsed time is: 32.42123 seconds

Super, incredibly easy to use, a sort of fire-and-forget kind of code. It's available on Github's Gist https://gist.github.com/tyleha/5174230

Custom sort function in ng-repeat

The following link explains filters in Angular extremely well. It shows how it is possible to define custom sort logic within an ng-repeat. http://toddmotto.com/everything-about-custom-filters-in-angular-js

For sorting object with properties, this is the code I have used: (Note that this sort is the standard JavaScript sort method and not specific to angular) Column Name is the name of the property on which sorting is to be performed.

self.myArray.sort(function(itemA, itemB) {
    if (self.sortOrder === "ASC") {
        return itemA[columnName] > itemB[columnName];
    } else {
        return itemA[columnName] < itemB[columnName];
    }
});

How do I import a sql data file into SQL Server?

A .sql file is a set of commands that can be executed against the SQL server.

Sometimes the .sql file will specify the database, other times you may need to specify this.

You should talk to your DBA or whoever is responsible for maintaining your databases. They will probably want to give the file a quick look. .sql files can do a lot of harm, even inadvertantly.

See the other answers if you want to plunge ahead.

What is a good game engine that uses Lua?

There's our IDE / engine called Codea.

The runtime is iOS only, but it's open source. The development environment is iPad only at the moment.

finished with non zero exit value

when our code has layout.xml file error ,we get this error message. Check your xml files again.

Add new value to an existing array in JavaScript

array = ["value1", "value2", "value3"]

it's not so much jquery as javascript

How can I get phone serial number (IMEI)

try this

 final TelephonyManager tm =(TelephonyManager)getBaseContext().getSystemService(Context.TELEPHONY_SERVICE);

  String deviceid = tm.getDeviceId();

Python read-only property

someone mentioned using a proxy object, I didn't see an example of that so I ended up trying it out, [poorly].

/!\ Please prefer class definitions and class constructors if possible

this code is effectively re-writing class.__new__ (class constructor) except worse in every way. Save yourself the pain and do not use this pattern if you can.

def attr_proxy(obj):
    """ Use dynamic class definition to bind obj and proxy_attrs.
        If you can extend the target class constructor that is 
        cleaner, but its not always trivial to do so.
    """
    proxy_attrs = dict()

    class MyObjAttrProxy():
        def __getattr__(self, name):
            if name in proxy_attrs:
                return proxy_attrs[name]  # overloaded

            return getattr(obj, name)  # proxy

        def __setattr__(self, name, value):
            """ note, self is not bound when overloading methods
            """
            proxy_attrs[name] = value

    return MyObjAttrProxy()


myobj = attr_proxy(Object())
setattr(myobj, 'foo_str', 'foo')

def func_bind_obj_as_self(func, self):
    def _method(*args, **kwargs):
        return func(self, *args, **kwargs)
    return _method

def mymethod(self, foo_ct):
    """ self is not bound because we aren't using object __new__
        you can write the __setattr__ method to bind a self 
        argument, or declare your functions dynamically to bind in 
        a static object reference.
    """
    return self.foo_str + foo_ct

setattr(myobj, 'foo', func_bind_obj_as_self(mymethod, myobj))

String comparison in bash. [[: not found

Is the first line in your script:

#!/bin/bash

or

#!/bin/sh

the sh shell produces this error messages, not bash

How can I work with command line on synology?

The current windows 10 (Version 1803 (OS Build 17134.1)) has SSH built in. With that, just enable SSH from the Control Panel, Terminal & SNMP, be sure you are using an account in the Administrator's group, and you're all set.

Launch Powershell or CMD, enter ssh yourAccountName@diskstation

The first time it will cache off your certificate.

EDIT:

Further detailed explanations can be found on the synology docs page:

How to login to DSM with root permission via SSH Telnet

get path for my .exe

In a Windows Forms project:

For the full path (filename included): string exePath = Application.ExecutablePath;
For the path only: string appPath = Application.StartupPath;