Programs & Examples On #E notices

Undefined variable: $_SESSION

Turned out there was some extra code in the AppModel that was messing things up:

in beforeFind and afterFind:

App::Import("Session");
$session = new CakeSession();
$sim_id = $session->read("Simulation.id");

I don't know why, but that was what the problem was. Removing those lines fixed the issue I was having.

Raw SQL Query without DbSet - Entity Framework Core

I know it's an old question, but maybe it helps someone to call stored procedures without adding DTOs as DbSets.

https://stackoverflow.com/a/62058345/3300944

How do I run Python code from Sublime Text 2?

You can use SublimeREPL (you need to have Package Control installed first).

Bootstrap 4, How do I center-align a button?

Use text-center class in the parent container for Bootstrap 4

Apply multiple functions to multiple groupby columns

Ted's answer is amazing. I ended up using a smaller version of that in case anyone is interested. Useful when you are looking for one aggregation that depends on values from multiple columns:

create a dataframe

df=pd.DataFrame({'a': [1,2,3,4,5,6], 'b': [1,1,0,1,1,0], 'c': ['x','x','y','y','z','z']})


   a  b  c
0  1  1  x
1  2  1  x
2  3  0  y
3  4  1  y
4  5  1  z
5  6  0  z

grouping and aggregating with apply (using multiple columns)

df.groupby('c').apply(lambda x: x['a'][(x['a']>1) & (x['b']==1)].mean())

c
x    2.0
y    4.0
z    5.0

grouping and aggregating with aggregate (using multiple columns)

I like this approach since I can still use aggregate. Perhaps people will let me know why apply is needed for getting at multiple columns when doing aggregations on groups.

It seems obvious now, but as long as you don't select the column of interest directly after the groupby, you will have access to all the columns of the dataframe from within your aggregation function.

only access to the selected column

df.groupby('c')['a'].aggregate(lambda x: x[x>1].mean())

access to all columns since selection is after all the magic

df.groupby('c').aggregate(lambda x: x[(x['a']>1) & (x['b']==1)].mean())['a']

or similarly

df.groupby('c').aggregate(lambda x: x['a'][(x['a']>1) & (x['b']==1)].mean())

I hope this helps.

php date validation

Though checkdate is good, this seems much concise function to validate and also you can give formats. [Source]

function validateDate($date, $format = 'Y-m-d H:i:s') {
    $d = DateTime::createFromFormat($format, $date);
    return $d && $d->format($format) == $date;
}

function was copied from this answer or php.net


The extra ->format() is needed for cases where the date is invalid but createFromFormat still manages to create a DateTime object. For example:

// Gives "2016-11-10 ..." because Thursday falls on Nov 10
DateTime::createFromFormat('D M j Y', 'Thu Nov 9 2016');

// false, Nov 9 is a Wednesday
validateDate('Thu Nov 9 2016', 'D M j Y');

JSON.Net Self referencing loop detected

The fix is to ignore loop references and not to serialize them. This behaviour is specified in JsonSerializerSettings.

Single JsonConvert with an overload:

JsonConvert.SerializeObject((from a in db.Events where a.Active select a).ToList(), Formatting.Indented,
    new JsonSerializerSettings() {
        ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore
    }
);

If you'd like to make this the default behaviour, add a Global Setting with code in Application_Start() in Global.asax.cs:

JsonConvert.DefaultSettings = () => new JsonSerializerSettings {
     Formatting = Newtonsoft.Json.Formatting.Indented,
     ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore
};

Reference: https://github.com/JamesNK/Newtonsoft.Json/issues/78

Create autoincrement key in Java DB using NetBeans IDE

If you want to use Netbeans to define tables read this https://codezone4.wordpress.com/2012/06/19/java-database-application-using-javadb-part-1/ Simply define column as integer and create database, then grab structure to a temporary file, then delete table. Right clik to tables folder and select recreate table, select saved file and edit script for auto increment.

LDAP server which is my base dn

The base dn is dc=example,dc=com.

I don't know about openca, but I will try this answer since you got very little traffic so far.

A base dn is the point from where a server will search for users. So I would try to simply use admin as a login name.

If openca behaves like most ldap aware applications, this is what is going to happen :

  1. An ldap search for the user admin will be done by the server starting at the base dn (dc=example,dc=com).
  2. When the user is found, the full dn (cn=admin,dc=example,dc=com) will be used to bind with the supplied password.
  3. The ldap server will hash the password and compare with the stored hash value. If it matches, you're in.

Getting step 1 right is the hardest part, but mostly because we don't get to do it often. Things you have to look out for in your configuraiton file are :

  • The dn your application will use to bind to the ldap server. This happens at application startup, before any user comes to authenticate. You will have to supply a full dn, maybe something like cn=admin,dc=example,dc=com.
  • The authentication method. It is usually a "simple bind".
  • The user search filter. Look at the attribute named objectClass for your admin user. It will be either inetOrgPerson or user. There will be others like top, you can ignore them. In your openca configuration, there should be a string like (objectClass=inetOrgPerson). Whatever it is, make sure it matches your admin user's object Class. You can specify two object class with this search filter (|(objectClass=inetOrgPerson)(objectClass=user)).

Download an LDAP Browser, such as Apache's Directory Studio. Connect using your application's credentials, so you will see what your application sees.

How to empty a Heroku database

Check your heroku version. I just updated mine to 2.29.0, as follows:

heroku --version
#=> heroku-gem/2.29.0 (x86_64-linux) ruby/1.9.3

Now you can run:

heroku pg:reset DATABASE --confirm YOUR_APP_NAME

Then create your database and seed it in a single command:

heroku run rake db:setup

Now restart and try your app:

heroku restart
heroku open

Getting Excel to refresh data on sheet from within VBA

I had an issue with turning off a background image (a DRAFT watermark) in VBA. My change wasn't showing up (which was performed with the Sheets(1).PageSetup.CenterHeader = "" method) - so I needed a way to refresh. The ActiveSheet.EnableCalculation approach partly did the trick, but didn't cover unused cells.

In the end I found what I needed with a one liner that made the image vanish when it was no longer set :-

Application.ScreenUpdating = True

Validate Dynamically Added Input fields

In regards to @RitchieD response, here is a jQuery plugin version to make things easier if you are using jQuery.

(function ($) {

    $.fn.initValidation = function () {

        $(this).removeData("validator");
        $(this).removeData("unobtrusiveValidation");
        $.validator.unobtrusive.parse(this);

        return this;
    };

}(jQuery));

This can be used like this:

$("#SomeForm").initValidation();

Oracle SQL convert date format from DD-Mon-YY to YYYYMM

Am I missing something? You can just convert offer_date in the comparison:

SELECT *
FROM offers
WHERE to_char(offer_date, 'YYYYMM') = (SELECT to_date(create_date, 'YYYYMM') FROM customers where id = '12345678') AND
      offer_rate > 0 

What does the @Valid annotation indicate in Spring?

I wanted to add more details about how the @Valid works, especially in spring.

Everything you'd want to know about validation in spring is explained clearly and in detail in https://reflectoring.io/bean-validation-with-spring-boot/, but I'll copy the answer to how @Valid works incase the link goes down.

The @Valid annotation can be added to variables in a rest controller method to validate them. There are 3 types of variables that can be validated:

  • the request body,
  • variables within the path (e.g. id in /foos/{id}) and,
  • query parameters.

So now... how does spring "validate"? You can define constraints to the fields of a class by annotating them with certain annotations. Then, you pass an object of that class into a Validator which checks if the constraints are satisfied.

For example, suppose I had controller method like this:

@RestController
class ValidateRequestBodyController {

  @PostMapping("/validateBody")
  ResponseEntity<String> validateBody(@Valid @RequestBody Input input) {
    return ResponseEntity.ok("valid");
  }

}

So this is a POST request which takes in a response body, and we're mapping that response body to a class Input.

Here's the class Input:

class Input {

  @Min(1)
  @Max(10)
  private int numberBetweenOneAndTen;

  @Pattern(regexp = "^[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}$")
  private String ipAddress;
  
  // ...
}

The @Valid annotation will tell spring to go and validate the data passed into the controller by checking to see that the integer numberBetweenOneAndTen is between 1 and 10 inclusive because of those min and max annotations. It'll also check to make sure the ip address passed in matches the regular expression in the annotation.

side note: the regular expression isn't perfect.. you could pass in 3 digit numbers that are greater than 255 and it would still match the regular expression.


Here's an example of validating a query variable and path variable:

@RestController
@Validated
class ValidateParametersController {

  @GetMapping("/validatePathVariable/{id}")
  ResponseEntity<String> validatePathVariable(
      @PathVariable("id") @Min(5) int id) {
    return ResponseEntity.ok("valid");
  }
  
  @GetMapping("/validateRequestParameter")
  ResponseEntity<String> validateRequestParameter(
      @RequestParam("param") @Min(5) int param) { 
    return ResponseEntity.ok("valid");
  }
}

In this case, since the query variable and path variable are just integers instead of just complex classes, we put the constraint annotation @Min(5) right on the parameter instead of using @Valid.

Loop X number of times

Use:

1..10 | % { write "loop $_" }

Output:

PS D:\temp> 1..10 | % { write "loop $_" }
loop 1
loop 2
loop 3
loop 4
loop 5
loop 6
loop 7
loop 8
loop 9
loop 10

Slice indices must be integers or None or have __index__ method

Your debut and fin values are floating point values, not integers, because taille is a float.

Make those values integers instead:

item = plateau[int(debut):int(fin)]

Alternatively, make taille an integer:

taille = int(sqrt(len(plateau)))

JNI converting jstring to char *

Here's a a couple of useful link that I found when I started with JNI

http://en.wikipedia.org/wiki/Java_Native_Interface
http://download.oracle.com/javase/1.5.0/docs/guide/jni/spec/functions.html

concerning your problem you can use this

JNIEXPORT void JNICALL Java_ClassName_MethodName(JNIEnv *env, jobject obj, jstring javaString)   
{
   const char *nativeString = env->GetStringUTFChars(javaString, 0);

   // use your string

   env->ReleaseStringUTFChars(javaString, nativeString);
}

Auto insert date and time in form input field?

Im not do not know all of the technical language but I could not find the answer anywhere so I came up with this and it worked... Good Luck!

$time = date("Y/m/d h:i:s");

$sql = "INSERT INTO *yourtablenamehere* ('dt')  VALUES ('$time')";

Exchange Powershell - How to invoke Exchange 2010 module from inside script?

I know this is an old question, but rather than adding the snapin which is apparently unsupported, I just looked at the EMS shortcut properties and copied those commands.

The full shortcut target is:

C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe -noexit -command ". 'C:\Program Files\Microsoft\Exchange Server\V14\bin\RemoteExchange.ps1'; Connect-ExchangeServer -auto"

So I put the following at the start of my script and it seemed to function as expected:

. 'C:\Program Files\Microsoft\Exchange Server\V14\bin\RemoteExchange.ps1'
Connect-ExchangeServer -auto

Notes:

  • Has to be run in 64bit PS
  • This was tested on a server with just the Management Tools installed. It automatically connected to our existing Exchange infrastructure.
  • No extensive testing has been done, so I do not know if this method is viable. I will edit this post if I run into any issues.

Creating a 3D sphere in Opengl using Visual C++

Here's the code:

glPushMatrix();
glTranslatef(18,2,0);
glRotatef(angle, 0, 0, 0.7);
glColor3ub(0,255,255);
glutWireSphere(3,10,10);
glPopMatrix();

ImageView in circular through xml

I have a simple solution. Create a new Image asset by right clicking your package name and selecting New->Image asset. Enter name (any name) and path (location of image in your system). Then click Next and Finish. If you enter name of image as 'img', a round image with the name 'img_round' is created automatically in mipmap folder.

Then, do this :

<ImageView
        android:layout_width="100dp"
        android:layout_height="100dp"
        android:src="@mipmap/img_round"/>

Your preview may still show a rectangular image. But if you run the app on your device, it will be round.

How to empty a char array?

Use bzero(array name, no.of bytes to be cleared);

Getting attribute of element in ng-click function in angularjs

Even more simple, pass the $event object to ng-click to access the event properties. As an example:

<a ng-click="clickEvent($event)" class="exampleClass" id="exampleID" data="exampleData" href="">Click Me</a>

Within your clickEvent() = function(obj) {} function you can access the data value like this:

var dataValue = obj.target.attributes.data.value;

Which would return exampleData.

Here's a full jsFiddle.

How can I install MacVim on OS X?

That Macvim is obsolete. Use https://github.com/macvim-dev/macvim instead

See the FAQ (https://github.com/b4winckler/macvim/wiki/FAQ#how-can-i-open-files-from-terminal) for how to install the mvim script for launching from the command line

How to change an image on click using CSS alone?

some people have suggested the "visited", but the visited links remain in the browsers cache, so the next time your user visits the page, the link will have the second image.. i dont know it that's the desired effect you want. Anyway you coul mix JS and CSS:

<style>
.off{
    color:red;
}
.on{
    color:green;
}
</style>
<a href="" class="off" onclick="this.className='on';return false;">Foo</a>

using the onclick event, you can change (or toggle maybe?) the class name of the element. In this example i change the text color but you could also change the background image.

Good Luck

You should not use <Link> outside a <Router>

I'm assuming that you are using React-Router V4, as you used the same in the original Sandbox Link.

You are rendering the Main component in the call to ReactDOM.render that renders a Link and Main component is outside of Router, that's why it is throwing the error:

You should not use <Link> outside a <Router>

Changes:

  1. Use any one of these Routers, BrowserRouter/HashRouter etc..., because you are using React-Router V4.

  2. Router can have only one child, so wrap all the routes in a div or Switch.

  3. React-Router V4, doesn't have the concept of nested routes, if you wants to use nested routes then define those routes directly inside that component.


Check this working example with each of these changes.

Parent Component:

const App = () => (
  <BrowserRouter>
    <div className="sans-serif">
      <Route path="/" component={Main} />
      <Route path="/view/:postId" component={Single} />
    </div>
  </BrowserRouter>
);

render(<App />, document.getElementById('root'));

Main component from route

import React from 'react';
import { Link } from 'react-router-dom';

export default () => (
  <div>
    <h1>
      <Link to="/">Redux example</Link>
    </h1>
  </div>
)

Etc.


Also check this answer: Nested routes with react router v4

Powershell command to hide user from exchange address lists

You will have to pass one of the valid Identity values like DN, domain\user etc to the Set-Mailbox cmdlet. Currently you are not passing anything.

Can (a== 1 && a ==2 && a==3) ever evaluate to true?

By overriding valueOf in a class declaration, it can be done:

class Thing {
    constructor() {
        this.value = 1;
    }

    valueOf() {
        return this.value++;
    }
}

const a = new Thing();

if(a == 1 && a == 2 && a == 3) {
    console.log(a);
}

What happens is that valueOf is called in each comparison operator. On the first one, a will equal 1, on the second, a will equal 2, and so on and so forth, because each time valueOf is called, the value of a is incremented.

Therefore the console.log will fire and output (in my terminal anyways) Thing: { value: 4}, indicating the conditional was true.

How to set a maximum execution time for a mysql query?

You can find the answer on this other S.O. question:

MySQL - can I limit the maximum time allowed for a query to run?

a cron job that runs every second on your database server, connecting and doing something like this:

  • SHOW PROCESSLIST
  • Find all connections with a query time larger than your maximum desired time
  • Run KILL [process id] for each of those processes

Enable ASP.NET ASMX web service for HTTP POST / GET requests

Actually, I found a somewhat quirky way to do this. Add the protocol to your web.config, but inside a location element. Specify the webservice location as the path attribute, like so:

<location path="YourWebservice.asmx">
  <system.web>
    <webServices>
      <protocols>
        <add name="HttpGet"/>
        <add name="HttpPost"/>
      </protocols>
    </webServices>
  </system.web>
</location>

How to concatenate items in a list to a single string?

We can specify how we have to join the string. Instead of '-', we can use ' '

sentence = ['this','is','a','sentence']
s=(" ".join(sentence))
print(s)

Can an Option in a Select tag carry multiple values?

Instead of storing the options on the client-side, another way to do this is to store the options as sub-array elements of an associative/indexed array on the server-side. The values of the select tag would then just contain the keys used to dereference the sub-array.

Here is some example code. This is written in PHP since the OP mentioned PHP, but it can be adapted to whatever server-side language you are using:

<FORM action="" method="POST">
    <SELECT NAME="Testing">  
        <OPTION VALUE="1"> One </OPTION> 
        <OPTION VALUE="2"> Two </OPTION>
        <OPTION VALUE="3"> Three </OPTION>
    </SELECT>
</FORM>

PHP:

<?php
$options = array(
    1 => array('value1' => '1', 'value2' => '2010'),
    2 => array('value1' => '2', 'value2' => '2122'),
    3 => array('value1' => '3', 'value2' => '0'),
);
echo 'Selected option value 1: ' . $options[$_POST['Testing']]['value1'] . '<br>';
echo 'Selected option value 2: ' . $options[$_POST['Testing']]['value2'] . '<br>';

Capturing TAB key in text box

I would advise against changing the default behaviour of a key. I do as much as possible without touching a mouse, so if you make my tab key not move to the next field on a form I will be very aggravated.

A shortcut key could be useful however, especially with large code blocks and nesting. Shift-TAB is a bad option because that normally takes me to the previous field on a form. Maybe a new button on the WMD editor to insert a code-TAB, with a shortcut key, would be possible?

'if' in prolog?

First, let's recall some classical first order logic:

"If P then Q else R" is equivalent to "(P and Q) or (non_P and R)".


How can we express "if-then-else" like that in Prolog?

Let's take the following concrete example:

If X is a member of list [1,2] then X equals 2 else X equals 4.

We can match above pattern ("If P then Q else R") if ...

  • condition P is list_member([1,2],X),
  • negated condition non_P is non_member([1,2],X),
  • consequence Q is X=2, and
  • alternative R is X=4.

To express list (non-)membership in a pure way, we define:

list_memberd([E|Es],X) :-
   (  E = X
   ;  dif(E,X),
      list_memberd(Es,X)
   ).

non_member(Es,X) :-
   maplist(dif(X),Es).

Let's check out different ways of expressing "if-then-else" in Prolog!

  1. (P,Q ; non_P,R)

    ?-      (list_memberd([1,2],X), X=2 ; non_member([1,2],X), X=4).
    X = 2 ; X = 4.
    ?- X=2, (list_memberd([1,2],X), X=2 ; non_member([1,2],X), X=4), X=2.
    X = 2 ; false.
    ?-      (list_memberd([1,2],X), X=2 ; non_member([1,2],X), X=4), X=2.
    X = 2 ; false.
    ?- X=4, (list_memberd([1,2],X), X=2 ; non_member([1,2],X), X=4), X=4.
    X = 4.
    ?-      (list_memberd([1,2],X), X=2 ; non_member([1,2],X), X=4), X=4.
    X = 4.
    

    Correctness score 5/5. Efficiency score 3/5.

  2. (P -> Q ; R)

    ?-      (list_memberd([1,2],X) -> X=2 ; X=4).
    false.                                                % WRONG
    ?- X=2, (list_memberd([1,2],X) -> X=2 ; X=4), X=2.
    X = 2.
    ?-      (list_memberd([1,2],X) -> X=2 ; X=4), X=2.
    false.                                                % WRONG
    ?- X=4, (list_memberd([1,2],X) -> X=2 ; X=4), X=4.
    X = 4.
    ?-      (list_memberd([1,2],X) -> X=2 ; X=4), X=4.
    false.                                                % WRONG
    

    Correctness score 2/5. Efficiency score 2/5.

  3. (P *-> Q ; R)

    ?-      (list_memberd([1,2],X) *-> X=2 ; X=4).
    X = 2 ; false.                                        % WRONG
    ?- X=2, (list_memberd([1,2],X) *-> X=2 ; X=4), X=2.
    X = 2 ; false.
    ?-      (list_memberd([1,2],X) *-> X=2 ; X=4), X=2.
    X = 2 ; false.
    ?- X=4, (list_memberd([1,2],X) *-> X=2 ; X=4), X=4.
    X = 4.
    ?-      (list_memberd([1,2],X) *-> X=2 ; X=4), X=4.
    false.                                                % WRONG
    

    Correctness score 3/5. Efficiency score 1/5.


(Preliminary) summary:

  1. (P,Q ; non_P,R) is correct, but needs a discrete implementation of non_P.

  2. (P -> Q ; R) loses declarative semantics when instantiation is insufficient.

  3. (P *-> Q ; R) is "less" incomplete than (P -> Q ; R), but still has similar woes.


Luckily for us, there are alternatives: Enter the logically monotone control construct if_/3!

We can use if_/3 together with the reified list-membership predicate memberd_t/3 like so:

?-      if_(memberd_t(X,[1,2]), X=2, X=4).
X = 2 ; X = 4.
?- X=2, if_(memberd_t(X,[1,2]), X=2, X=4), X=2.
X = 2.
?-      if_(memberd_t(X,[1,2]), X=2, X=4), X=2.
X = 2 ; false.
?- X=4, if_(memberd_t(X,[1,2]), X=2, X=4), X=4.
X = 4.
?-      if_(memberd_t(X,[1,2]), X=2, X=4), X=4.
X = 4.

Correctness score 5/5. Efficiency score 4/5.

Converting an OpenCV Image to Black and White

Here's a two line code I found online that might be helpful for a beginner

# Absolute value of the 32/64
abs_image_in32_64 = np.absolute(image_in32_64)

image_8U = np.uint8(abs_image_in32_64)

Set the text in a span

Try it.. It will first look for anchor tag that contain span with class "ui-icon-circle-triangle-w", then it set the text of span to "<<".

$('a span.ui-icon-circle-triangle-w').text('<<');

Div Size Automatically size of content

I faced the same issue and I resolved it by using: max-width: fit-content;

Combine two integer arrays

Task: Given two int arrays array1 and array2 of the same length, zip should return an array that's twice as long, in which the elements of array1 and array2 are interleaved. That is, element #0 of the result array is array1[0], element #1 is array2[0], element #2 is array1[1], element #3 is array2[1], and so on.

public static int [] zip(int [ ] array1, int [] array2) {
//make sure both arrays have same length
if (array1.length != array2.length) {
    throw new IllegalArgumentException("Unequal array lengths - zip not possible");
}

int [] zippedArray = new int [array1.length+ array2.length]; 
int idx_1 = 0;
int idx_2 = 0;

//for each element of first array, add to new array if index of new array is even

for (int i=0; i < zippedArray.length; i+=2){
    zippedArray[i]= array1[idx_1++];
}
for (int i=1; i < zippedArray.length; i+=2){
    zippedArray[i]= array2[idx_2++];
}

//check contents of new array       
for (int item: zippedArray){
    System.out.print(item + " ");
}

return zippedArray;

}

T-SQL split string based on delimiter

SELECT CASE 
        WHEN CHARINDEX('/', myColumn, 0) = 0
            THEN myColumn
        ELSE LEFT(myColumn, CHARINDEX('/', myColumn, 0)-1)
        END AS FirstName
    ,CASE 
        WHEN CHARINDEX('/', myColumn, 0) = 0
            THEN ''
        ELSE RIGHT(myColumn, CHARINDEX('/', REVERSE(myColumn), 0)-1)
        END AS LastName
FROM MyTable

Error: Module not specified (IntelliJ IDEA)

This is because the className value which you are passing as argument for
forName(String className) method is not found or doesn't exists, or you a re passing the wrong value as the class name. Here is also a link which could help you.

1. https://docs.oracle.com/javase/7/docs/api/java/lang/ClassNotFoundException.html
2. https://docs.oracle.com/javase/7/docs/api/java/lang/Class.html#forName(java.lang.String)

Update

Module not specified

According to the snapshot you have provided this problem is because you have not determined the app module of your project, so I suggest you to choose the app module from configuration. For example:

enter image description here

jquery how to get the page's current screen top position?

Use this to get the page scroll position.

var screenTop = $(document).scrollTop();

$('#content').css('top', screenTop);

grep for special characters in Unix

The one that worked for me is:

grep -e '->'

The -e means that the next argument is the pattern, and won't be interpreted as an argument.

From: http://www.linuxquestions.org/questions/programming-9/how-to-grep-for-string-769460/

How to perform mouseover function in Selenium WebDriver using Java?

Check this example how we could implement this.

enter image description here

public class HoverableDropdownTest {

    private WebDriver driver;
    private Actions action;

    //Edit: there may have been a typo in the '- >' expression (I don't really want to add this comment but SO insist on ">6 chars edit"...
    Consumer < By > hover = (By by) -> {
        action.moveToElement(driver.findElement(by))
              .perform();
    };

    @Test
    public void hoverTest() {
        driver.get("https://www.bootply.com/render/6FC76YQ4Nh");

        hover.accept(By.linkText("Dropdown"));
        hover.accept(By.linkText("Dropdown Link 5"));
        hover.accept(By.linkText("Dropdown Submenu Link 5.4"));
        hover.accept(By.linkText("Dropdown Submenu Link 5.4.1"));
    }

    @BeforeTest
    public void setupDriver() {
        driver = new FirefoxDriver();
        action = new Actions(driver);
    }

    @AfterTest
    public void teardownDriver() {
        driver.quit();
    }

}

For detailed answer, check here - http://www.testautomationguru.com/selenium-webdriver-automating-hoverable-multilevel-dropdowns/

Object of class stdClass could not be converted to string

What I was looking for is a way to fetch the data

so I used this $data = $this->db->get('table_name')->result_array();

and then fetched my data just as you operate on array objects.

$data[0]['field_name']

No need to worry about type casting or anything just straight to the point.

So it worked for me.

What is the difference between npm install and npm run build?

  • npm install installs the depedendencies in your package.json config.
  • npm run build runs the script "build" and created a script which runs your application - let's say server.js
  • npm start runs the "start" script which will then be "node server.js"

It's difficult to tell exactly what the issue was but basically if you look at your scripts configuration, I would guess that "build" uses some kind of build tool to create your application while "start" assumes the build has been done but then fails if the file is not there.

You are probably using bower or grunt - I seem to remember that a typical grunt application will have defined those scripts as well as a "clean" script to delete the last build.

Build tools tend to create a file in a bin/, dist/, or build/ folder which the start script then calls - e.g. "node build/server.js". When your npm start fails, it is probably because you called npm clean or similar to delete the latest build so your application file is not present causing npm start to fail.

npm build's source code - to touch on the discussion in this question - is in github for you to have a look at if you like. If you run npm build directly and you have a "build" script defined, it will exit with an error asking you to call your build script as npm run-script build so it's not the same as npm run script.

I'm not quite sure what npm build does, but it seems to be related to postinstall and packaging scripts in dependencies. I assume that this might be making sure that any CLI build scripts's or native libraries required by dependencies are built for the specific environment after downloading the package. This will be why link and install call this script.

CharSequence VS String in Java?

CharSequence is an interface and String implements it. You can instantiate a String but you could not do that for CharSequence since it is an interface. You can find other implementations in CharSequence in the official Java website.

Getting text from td cells with jQuery

$(".field-group_name").each(function() {
        console.log($(this).text());
    });

How to generate a random number in C++?

Here is a solution. Create a function that returns the random number and place it outside the main function to make it global. Hope this helps

#include <iostream>
#include <cstdlib>
#include <ctime>
int rollDie();
using std::cout;
int main (){
    srand((unsigned)time(0));
    int die1;
    int die2;
    for (int n=10; n>0; n--){
    die1 = rollDie();
    die2 = rollDie();
    cout << die1 << " + " << die2 << " = " << die1 + die2 << "\n";
}
system("pause");
return 0;
}
int rollDie(){
    return (rand()%6)+1;
}

How to resolve ambiguous column names when retrieving results?

@Jason. You are correct except that php is the culprit and not mysql. If you put your JOIN in Mysql Workbench you will get three columns with the exact same name (one for each table) but not with the same data (some will be null if that table has no match for the JOIN).

In php if you use MYSQL_NUM in mysql_fetch_array() then you will get all columns. The problem is when you use mysql_fetch_array() with MYSQL_ASSOC. Then, inside that function, php is building the return value like so:

$row['dup'] = [value from table1]

and later on...

$row['dup'] = [value from table2]

...

$row['dup'] = [value from table3]

So you will get only the value from table3. The problem is that a result set from mysql can contain columns with the same name but associative arrays in php don't allow duplicate keys in arrays. When the data is saved in associative arrays, in php, some information is silently lost...

Windows batch: echo without new line

Echo with preceding space and without newline

As stated by Pedro earlier, echo without new line and with preceding space works (provided "9" is a true [BackSpace]).

<nul set /p=.9    Hello everyone

I had some issues getting it to work in Windows 10 with the new console but managed the following way.
In CMD type:

echo .?>bs.txt

I got "?" by pressing [Alt] + [8]
(the actual symbol may vary depending upon codepage).

Then it's easy to copy the result from "bs.txt" using Notepad.exe to where it's needed.

@echo off
<nul set /p "_s=.?    Hello everyone"
echo: here

How do you increase the max number of concurrent connections in Apache?

change the MaxClients directive. it is now on 256.

How to read/process command line arguments?

Also with python3 you might find convenient to use Extended Iterable Unpacking to handle optional positional arguments without additional dependencies:

try:
   _, arg1, arg2, arg3, *_ = sys.argv + [None] * 2
except ValueError:
   print("Not enough arguments", file=sys.stderr) # unhandled exception traceback is meaningful enough also
   exit(-1)

The above argv unpack makes arg2 and arg3 "optional" - if they are not specified in argv, they will be None, while if the first is not specified, ValueError will be thouwn:

Traceback (most recent call last):
  File "test.py", line 3, in <module>
    _, arg1, arg2, arg3, *_ = sys.argv + [None] * 2
ValueError: not enough values to unpack (expected at least 4, got 3)

C# generics syntax for multiple type parameter constraints

void foo<TOne, TTwo>() 
   where TOne : BaseOne
   where TTwo : BaseTwo

More info here:
http://msdn.microsoft.com/en-us/library/d5x73970.aspx

How to connect wireless network adapter to VMWare workstation?

Change your network adapter to a bridged connection, this will directly connect to your computers physical network.

setting global sql_mode in mysql

In my case i have to change file /etc/mysql/mysql.conf.d/mysqld.cnf change this under [mysqld]

Paste this line on [mysqld] portion

sql_mode = "STRICT_TRANS_TABLES,NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION"

How to use Lambda in LINQ select statement

You appear to be trying to mix query expression syntax and "normal" lambda expression syntax. You can either use:

IEnumerable<SelectListItem> stores =
        from store in database.Stores
        where store.CompanyID == curCompany.ID
        select new SelectListItem { Value = store.Name, Text = store.ID};
ViewBag.storeSelector = stores;

Or:

IEnumerable<SelectListItem> stores = database.Stores
        .Where(store => store.CompanyID == curCompany.ID)
        .Select(s => new SelectListItem { Value = s.Name, Text = s.ID});
ViewBag.storeSelector = stores;

You can't mix the two like you're trying to.

How to pass a null variable to a SQL Stored Procedure from C#.net code

try this! syntax less lines and even more compact! don't forget to add the properties you want to add with this approach!

cmd.Parameters.Add(new SqlParameter{SqlValue=(object)username??DBNull.Value,ParameterName="user" }  );

Opposite of %in%: exclude rows with values specified in a vector

The package collapse has it built in: %!in%.

How to compile Tensorflow with SSE4.2 and AVX instructions?

These are SIMD vector processing instruction sets.

Using vector instructions is faster for many tasks; machine learning is such a task.

Quoting the tensorflow installation docs:

To be compatible with as wide a range of machines as possible, TensorFlow defaults to only using SSE4.1 SIMD instructions on x86 machines. Most modern PCs and Macs support more advanced instructions, so if you're building a binary that you'll only be running on your own machine, you can enable these by using --copt=-march=native in your bazel build command.

Get week day name from a given month, day and year individually in SQL Server

I used

select
case
when (extract (weekday from DATE)=0) then 'Sunday'

and so on...

0 Sunday, 1 Monday...

Compute row average in pandas

We can find the the mean of a row using the range function, i.e in your case, from the Y1961 column to the Y1965

df['mean'] = df.iloc[:, 0:4].mean(axis=1)

And if you want to select individual columns

df['mean'] = df.iloc[:, [0,1,2,3,4].mean(axis=1)

How to compile and run a C/C++ program on the Android system

You can compile your C programs with an ARM cross-compiler:

arm-linux-gnueabi-gcc -static -march=armv7-a test.c -o test

Then you can push your compiled binary file to somewhere (don't push it in to the SD card):

adb push test /data/local/tmp/test

C# looping through an array

Not too difficult. Just increment the counter of the for loop by 3 each iteration and then offset the indexer to get the batch of 3 at a time:

for(int i=0; i < theData.Length; i+=3)
{
    var item1 = theData[i];
    var item2 = theData[i+1];
    var item3 = theData[i+2];
}

If the length of the array wasn't garuanteed to be a multiple of three, you would need to check the upper bound with theData.Length - 2 instead.

decimal vs double! - Which one should I use and when?

Decimal is for exact values. Double is for approximate values.

USD: $12,345.67 USD (Decimal)
CAD: $13,617.27 (Decimal)
Exchange Rate: 1.102932 (Double)

Add a column to existing table and uniquely number them on MS SQL Server

This will depend on the database but for SQL Server, this could be achieved as follows:

alter table Example
add NewColumn int identity(1,1)

Git: Remove committed file after push

  1. Get the hash code of last commit.

    • git log
  2. Revert the commit
    • git revert <hash_code_from_git_log>
  3. Push the changes
    • git push

check out in the GHR. you might get what ever you need, hope you this is useful

How to open an existing project in Eclipse?

from Eclipse main gui: select "Window->Show View->Other->General->Project Explorer" Double-clicking on "Project Explorer" brings up the "Project Explorer" window which shows every project in your workspace. That worked for me.

Good luck.

Remove or uninstall library previously added : cocoapods

Remove pod name from Podfile then Open Terminal, set project folder path and Run pod update command.

NOTE: pod update will update all the libraries to the latest version and will also remove those libraries whose name have been removed from podfile.

Python Iterate Dictionary by Index

There are some very good answers here. I'd like to add the following here as well:

some_dict = {
    "foo": "bar",
    "lorem": "ipsum"
}

for index, (key, value) in enumerate(some_dict.items()):
    print(index, key, value)

results in

0 foo bar
1 lorem ipsum

Appears to work with Python 2.7 and 3.5

Display date in dd/mm/yyyy format in vb.net

if you want to display date along with time when you export to Excel then you can use this

xlWorkSheet.Cells(nRow, 3).NumberFormat = "dd/mm/yy h:mm AM/PM"

Check if a time is between two times (time DataType)

I suspect you want to check that it's after 11pm or before 7am:

select *
from MyTable
where CAST(Created as time) >= '23:00:00' 
   or CAST(Created as time) < '07:00:00'

In java how to get substring from a string till a character c?

The accepted answer is correct but it doesn't tell you how to use it. This is how you use indexOf and substring functions together.

String filename = "abc.def.ghi";     // full file name
int iend = filename.indexOf("."); //this finds the first occurrence of "." 
//in string thus giving you the index of where it is in the string

// Now iend can be -1, if lets say the string had no "." at all in it i.e. no "." is found. 
//So check and account for it.

String subString;
if (iend != -1) 
{
    subString= filename.substring(0 , iend); //this will give abc
}

String "true" and "false" to boolean

As far as i know there is no built in way of casting strings to booleans, but if your strings only consist of 'true' and 'false' you could shorten your method to the following:

def to_boolean(str)
  str == 'true'
end

Unit testing private methods in C#

Another thought here is to extend testing to "internal" classes/methods, giving more of a white-box sense of this testing. You can use InternalsVisibleToAttribute on the assembly to expose these to separate unit testing modules.

In combination with sealed class you can approach such encapsulation that test method are visible only from unittest assembly your methods. Consider that protected method in sealed class is de facto private.

[assembly: InternalsVisibleTo("MyCode.UnitTests")]
namespace MyCode.MyWatch
{
    #pragma warning disable CS0628 //invalid because of InternalsVisibleTo
    public sealed class MyWatch
    {
        Func<DateTime> _getNow = delegate () { return DateTime.Now; };


       //construktor for testing purposes where you "can change DateTime.Now"
       internal protected MyWatch(Func<DateTime> getNow)
       {
           _getNow = getNow;
       }

       public MyWatch()
       {            
       }
   }
}

And unit test:

namespace MyCode.UnitTests
{

[TestMethod]
public void TestminuteChanged()
{
    //watch for traviling in time
    DateTime baseTime = DateTime.Now;
    DateTime nowforTesting = baseTime;
    Func<DateTime> _getNowForTesting = delegate () { return nowforTesting; };

    MyWatch myWatch= new MyWatch(_getNowForTesting );
    nowforTesting = baseTime.AddMinute(1); //skip minute
    //TODO check myWatch
}

[TestMethod]
public void TestStabilityOnFebruary29()
{
    Func<DateTime> _getNowForTesting = delegate () { return new DateTime(2024, 2, 29); };
    MyWatch myWatch= new MyWatch(_getNowForTesting );
    //component does not crash in overlap year
}
}

How can I get all a form's values that would be submitted without submitting

If your form tag is like

<form action="" method="post" id="BookPackageForm">

Then fetch the form element by using forms object.

var formEl = document.forms.BookPackageForm;

Get the data from the form by using FormData objects.

var formData = new FormData(formEl);

Get the value of the fields by the form data object.

var name = formData.get('name');

Call a method of a controller from another controller using 'scope' in AngularJS

The best approach for you to communicate between the two controllers is to use events.

Scope Documentation

In this check out $on, $broadcast and $emit.

In general use case the usage of angular.element(catapp).scope() was designed for use outside the angular controllers, like within jquery events.

Ideally in your usage you would write an event in controller 1 as:

$scope.$on("myEvent", function (event, args) {
   $scope.rest_id = args.username;
   $scope.getMainCategories();
});

And in the second controller you'd just do

$scope.initRestId = function(){
   $scope.$broadcast("myEvent", {username: $scope.user.username });
};

Edit: Realised it was communication between two modules

Can you try including the firstApp module as a dependency to the secondApp where you declare the angular.module. That way you can communicate to the other app.

How can I merge two commits into one if I already started rebase?

Since I use git cherry-pick for just about everything, to me it comes natural to do so even here.

Given that I have branchX checked out and there are two commits at the tip of it, of which I want to create one commit combining their content, I do this:

git checkout HEAD^ // Checkout the privious commit
git cherry-pick --no-commit branchX // Cherry pick the content of the second commit
git commit --amend // Create a new commit with their combined content

If i want to update branchX as well (and I suppose this is the down side of this method) I also have to:

git checkout branchX
git reset --hard <the_new_commit>

How does numpy.newaxis work and when to use it?

Simply put, numpy.newaxis is used to increase the dimension of the existing array by one more dimension, when used once. Thus,

  • 1D array will become 2D array

  • 2D array will become 3D array

  • 3D array will become 4D array

  • 4D array will become 5D array

and so on..

Here is a visual illustration which depicts promotion of 1D array to 2D arrays.

newaxis canva visualization


Scenario-1: np.newaxis might come in handy when you want to explicitly convert a 1D array to either a row vector or a column vector, as depicted in the above picture.

Example:

# 1D array
In [7]: arr = np.arange(4)
In [8]: arr.shape
Out[8]: (4,)

# make it as row vector by inserting an axis along first dimension
In [9]: row_vec = arr[np.newaxis, :]     # arr[None, :]
In [10]: row_vec.shape
Out[10]: (1, 4)

# make it as column vector by inserting an axis along second dimension
In [11]: col_vec = arr[:, np.newaxis]     # arr[:, None]
In [12]: col_vec.shape
Out[12]: (4, 1)

Scenario-2: When we want to make use of numpy broadcasting as part of some operation, for instance while doing addition of some arrays.

Example:

Let's say you want to add the following two arrays:

 x1 = np.array([1, 2, 3, 4, 5])
 x2 = np.array([5, 4, 3])

If you try to add these just like that, NumPy will raise the following ValueError :

ValueError: operands could not be broadcast together with shapes (5,) (3,)

In this situation, you can use np.newaxis to increase the dimension of one of the arrays so that NumPy can broadcast.

In [2]: x1_new = x1[:, np.newaxis]    # x1[:, None]
# now, the shape of x1_new is (5, 1)
# array([[1],
#        [2],
#        [3],
#        [4],
#        [5]])

Now, add:

In [3]: x1_new + x2
Out[3]:
array([[ 6,  5,  4],
       [ 7,  6,  5],
       [ 8,  7,  6],
       [ 9,  8,  7],
       [10,  9,  8]])

Alternatively, you can also add new axis to the array x2:

In [6]: x2_new = x2[:, np.newaxis]    # x2[:, None]
In [7]: x2_new     # shape is (3, 1)
Out[7]: 
array([[5],
       [4],
       [3]])

Now, add:

In [8]: x1 + x2_new
Out[8]: 
array([[ 6,  7,  8,  9, 10],
       [ 5,  6,  7,  8,  9],
       [ 4,  5,  6,  7,  8]])

Note: Observe that we get the same result in both cases (but one being the transpose of the other).


Scenario-3: This is similar to scenario-1. But, you can use np.newaxis more than once to promote the array to higher dimensions. Such an operation is sometimes needed for higher order arrays (i.e. Tensors).

Example:

In [124]: arr = np.arange(5*5).reshape(5,5)

In [125]: arr.shape
Out[125]: (5, 5)

# promoting 2D array to a 5D array
In [126]: arr_5D = arr[np.newaxis, ..., np.newaxis, np.newaxis]    # arr[None, ..., None, None]

In [127]: arr_5D.shape
Out[127]: (1, 5, 5, 1, 1)

As an alternative, you can use numpy.expand_dims that has an intuitive axis kwarg.

# adding new axes at 1st, 4th, and last dimension of the resulting array
In [131]: newaxes = (0, 3, -1)
In [132]: arr_5D = np.expand_dims(arr, axis=newaxes)
In [133]: arr_5D.shape
Out[133]: (1, 5, 5, 1, 1)

More background on np.newaxis vs np.reshape

newaxis is also called as a pseudo-index that allows the temporary addition of an axis into a multiarray.

np.newaxis uses the slicing operator to recreate the array while numpy.reshape reshapes the array to the desired layout (assuming that the dimensions match; And this is must for a reshape to happen).

Example

In [13]: A = np.ones((3,4,5,6))
In [14]: B = np.ones((4,6))
In [15]: (A + B[:, np.newaxis, :]).shape     # B[:, None, :]
Out[15]: (3, 4, 5, 6)

In the above example, we inserted a temporary axis between the first and second axes of B (to use broadcasting). A missing axis is filled-in here using np.newaxis to make the broadcasting operation work.


General Tip: You can also use None in place of np.newaxis; These are in fact the same objects.

In [13]: np.newaxis is None
Out[13]: True

P.S. Also see this great answer: newaxis vs reshape to add dimensions

How to write JUnit test with Spring Autowire?

In Spring 2.1.5 at least, the XML file can be conveniently replaced by annotations. Piggy backing on @Sembrano's answer, I have this. "Look ma, no XML".

It appears I to had list all the classes I need @Autowired in the @ComponentScan

@RunWith(SpringJUnit4ClassRunner.class)
@ComponentScan(
    basePackageClasses = {
            OwnerService.class
            })
@EnableAutoConfiguration
public class OwnerIntegrationTest {
    
    @Autowired
    OwnerService ownerService;
    
    @Test
    public void testOwnerService() {
       Assert.assertNotNull(ownerService);
    }
}

What are the pros and cons of parquet format compared to other formats?

Avro is a row-based storage format for Hadoop.

Parquet is a column-based storage format for Hadoop.

If your use case typically scans or retrieves all of the fields in a row in each query, Avro is usually the best choice.

If your dataset has many columns, and your use case typically involves working with a subset of those columns rather than entire records, Parquet is optimized for that kind of work.

Source

Create a basic matrix in C (input by user !)

//R stands for ROW and C stands for COLUMN:

//i stands for ROW and j stands for COLUMN:

#include<stdio.h>

int main(){

    int M[100][100];

    int R,C,i,j;

    printf("Please enter how many rows you want:\n");

    scanf("%d",& R);

    printf("Please enter how column you want:\n");

    scanf("%d",& C);

    printf("Please enter your matrix:\n");

    for(i = 0; i < R; i++){

        for(j = 0; j < C; j++){

            scanf("%d", &M[i][j]);

        }

        printf("\n");

    }
    for(i = 0; i < R; i++){

        for(j = 0; j < C; j++){

            printf("%d\t", M[i][j]);

        }
        printf("\n");

   }

   getch();

   return 0;
}

non static method cannot be referenced from a static context

Violating the Java naming conventions (variable names and method names start with lowercase, class names start with uppercase) is contributing to your confusion.

The variable Random is only "in scope" inside the main method. It's not accessible to any methods called by main. When you return from main, the variable disappears (it's part of the stack frame).

If you want all of the methods of your class to use the same Random instance, declare a member variable:

class MyObj {
  private final Random random = new Random();
  public void compTurn() {
    while (true) {
      int a = random.nextInt(10);
      if (possibles[a] == 1) 
        break;
    }
  }
}

Error:Execution failed for task ':app:transformClassesWithJarMergingForDebug'

All the above not working for me.. Because I am using Facebook Ad dependency..

Incase If anybody using this dependency compile 'com.facebook.android:audience-network-sdk:4.16.0'

Try this code instead of above

compile ('com.facebook.android:audience-network-sdk:4.16.0'){
exclude group: 'com.google.android.gms'
}

How to return temporary table from stored procedure

First create a real, permanent table as a template that has the required layout for the returned temporary table, using a naming convention that identifies it as a template and links it symbolically to the SP, eg tmp_SPName_Output. This table will never contain any data.

In the SP, use INSERT to load data into a temp table following the same naming convention, e.g. #SPName_Output which is assumed to exist. You can test for its existence and return an error if it does not.

Before calling the sp use this simple select to create the temp table:

SELECT TOP(0) * INTO #SPName_Output FROM tmp_SPName_Output;
EXEC SPName;
-- Now process records in #SPName_Output;

This has these distinct advantages:

  • The temp table is local to the current session, unlike ##, so will not clash with concurrent calls to the SP from different sessions. It is also dropped automatically when out of scope.
  • The template table is maintained alongside the SP, so if changes are made to the output (new columns added, for example) then pre-existing callers of the SP do not break. The caller does not need to be changed.
  • You can define any number of output tables with different naming for one SP and fill them all. You can also define alternative outputs with different naming and have the SP check the existence of the temp tables to see which need to be filled.
  • Similarly, if major changes are made but you want to keep backwards compatibility, you can have a new template table and naming for the later version but still support the earlier version by checking which temp table the caller has created.

ASP.NET MVC 3 Razor: Include JavaScript file in the head tag

You can use Named Sections.

_Layout.cshtml

<head>
    <script type="text/javascript" src="@Url.Content("/Scripts/jquery-1.6.2.min.js")"></script>
    @RenderSection("JavaScript", required: false)
</head>

_SomeView.cshtml

@section JavaScript
{
   <script type="text/javascript" src="@Url.Content("/Scripts/SomeScript.js")"></script>
   <script type="text/javascript" src="@Url.Content("/Scripts/AnotherScript.js")"></script>
}

What does the "+" (plus sign) CSS selector mean?

+ selector is called Adjacent Sibling Selector.

For example, the selector p + p, selects the p elements immediately following the p elements

It can be thought of as a looking outside selector which checks for the immediately following element.

Here is a sample snippet to make things more clear:

_x000D_
_x000D_
body {_x000D_
  font-family: Tahoma;_x000D_
  font-size: 12px;_x000D_
}_x000D_
p + p {_x000D_
  margin-left: 10px;_x000D_
}
_x000D_
<div>_x000D_
  <p>Header paragraph</p>_x000D_
  <p>This is a paragraph</p>_x000D_
  <p>This is another paragraph</p>_x000D_
  <p>This is yet another paragraph</p>_x000D_
  <hr>_x000D_
  <p>Footer paragraph</p>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Since we are one the same topic, it is worth mentioning another selector, ~ selector, which is General Sibling Selector

For example, p ~ p selects all the p which follows the p doesn't matter where it is, but both p should be having the same parent.

Here is how it looks like with the same markup:

_x000D_
_x000D_
body {_x000D_
  font-family: Tahoma;_x000D_
  font-size: 12px;_x000D_
}_x000D_
p ~ p {_x000D_
  margin-left: 10px;_x000D_
}
_x000D_
<div>_x000D_
  <p>Header paragraph</p>_x000D_
  <p>This is a paragraph</p>_x000D_
  <p>This is another paragraph</p>_x000D_
  <p>This is yet another paragraph</p>_x000D_
  <hr>_x000D_
  <p>Footer paragraph</p>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Notice that the last p is also matched in this sample.

How to get the Facebook user id using the access token

Check out this answer, which describes, how to get ID response. First, you need to create method get data:

const https = require('https');
getFbData = (accessToken, apiPath, callback) => {
    const options = {
        host: 'graph.facebook.com',
        port: 443,
        path: `${apiPath}access_token=${accessToken}`, // apiPath example: '/me/friends'
        method: 'GET'
    };

    let buffer = ''; // this buffer will be populated with the chunks of the data received from facebook
    const request = https.get(options, (result) => {
        result.setEncoding('utf8');
        result.on('data', (chunk) => {
            buffer += chunk;
        });

        result.on('end', () => {
            callback(buffer);
        });
    });

    request.on('error', (e) => {
        console.log(`error from facebook.getFbData: ${e.message}`)
    });

    request.end();
}

Then simply use your method whenever you want, like this:

getFbData(access_token, '/me?fields=id&', (result) => {
      console.log(result);
});

Why does Path.Combine not properly concatenate filenames that start with Path.DirectorySeparatorChar?

Not knowing the actual details, my guess is that it makes an attempt to join like you might join relative URIs. For example:

urljoin('/some/abs/path', '../other') = '/some/abs/other'

This means that when you join a path with a preceding slash, you are actually joining one base to another, in which case the second gets precedence.

What is System, out, println in System.out.println() in Java

The first answer you posted (System is a built-in class...) is pretty spot on.

You can add that the System class contains large portions which are native and that is set up by the JVM during startup, like connecting the System.out printstream to the native output stream associated with the "standard out" (console).

Why is synchronized block better than synchronized method?

It's not a matter of better, just different.

When you synchronize a method, you are effectively synchronizing to the object itself. In the case of a static method, you're synchronizing to the class of the object. So the following two pieces of code execute the same way:

public synchronized int getCount() {
    // ...
}

This is just like you wrote this.

public int getCount() {
    synchronized (this) {
        // ...
    }
}

If you want to control synchronization to a specific object, or you only want part of a method to be synchronized to the object, then specify a synchronized block. If you use the synchronized keyword on the method declaration, it will synchronize the whole method to the object or class.

Select count(*) from result query

select count(*) from(select count(SID) from Test where Date = '2012-12-10' group by SID)select count(*) from(select count(SID) from Test where Date = '2012-12-10' group by SID)

should works

pip install - locale.Error: unsupported locale setting

The root cause is: your environment variable LC_ALL is missing or invalid somehow

Short answer-

just run the following command:

$ export LC_ALL=C

If you keep getting the error in new terminal windows, add it at the bottom of your .bashrc file.

Long answer-

Here is my locale settings:

$ locale
LANG=en_US.UTF-8
LANGUAGE=
LC_CTYPE="C"
LC_NUMERIC="C"
LC_TIME="C"
LC_COLLATE="C"
LC_MONETARY="C"
LC_MESSAGES="C"
LC_PAPER="C"
LC_NAME="C"
LC_ADDRESS="C"
LC_TELEPHONE="C"
LC_MEASUREMENT="C"
LC_IDENTIFICATION="C"
LC_ALL=C

Python2.7

    $ uname -a
    Linux debian 3.16.0-4-amd64 #1 SMP Debian 3.16.7-ckt11-1+deb8u6 (2015-11-09) x86_64 GNU/Linux
    $ python --version
    Python 2.7.9
    $ pip --version
    pip 8.1.1 from /usr/local/lib/python2.7/dist-packages (python 2.7)
    $ unset LC_ALL
    $ pip install virtualenv
    Traceback (most recent call last):
      File "/usr/local/bin/pip", line 11, in <module>
        sys.exit(main())
      File "/usr/local/lib/python2.7/dist-packages/pip/__init__.py", line 215, in main
        locale.setlocale(locale.LC_ALL, '')
      File "/usr/lib/python2.7/locale.py", line 579, in setlocale
        return _setlocale(category, locale)
    locale.Error: unsupported locale setting
    $ export LC_ALL=C
    $ pip install virtualenv
    Requirement already satisfied (use --upgrade to upgrade): virtualenv in /usr/local/lib/python2.7/dist-packages

Differences between key, superkey, minimal superkey, candidate key and primary key

Primary key is a subset of super key. Which is uniquely define and other field are depend on it. In a table their can be just one primary key and rest sub set are candidate key or alternate keys.

Securely storing passwords for use in python script

the secure way is encrypt your sensitive data by AES and the encryption key is derivation by password-based key derivation function (PBE), the master password used to encrypt/decrypt the encrypt key for AES.

master password -> secure key-> encrypt data by the key

You can use pbkdf2

from PBKDF2 import PBKDF2
from Crypto.Cipher import AES
import os
salt = os.urandom(8)    # 64-bit salt
key = PBKDF2("This passphrase is a secret.", salt).read(32) # 256-bit key
iv = os.urandom(16)     # 128-bit IV
cipher = AES.new(key, AES.MODE_CBC, iv)

make sure to store the salt/iv/passphrase , and decrypt using same salt/iv/passphase

Weblogic used similar approach to protect passwords in config files

scroll up and down a div on button click using jquery

To solve your other problem, where you need to set scrolled if the user scrolls manually, you'd have to attach a handler to the window scroll event. Generally this is a bad idea as the handler will fire a lot, a common technique is to set a timeout, like so:

var timer = 0;
$(window).scroll(function() {
  if (timer) {
    clearTimeout(timer);
  }
  timer = setTimeout(function() {
    scrolled = $(window).scrollTop();
  }, 250);
});

How to check whether a given string is valid JSON in Java

Using Playframework 2.6, the Json library found in the java api can also be used to simply parse the string. The string can either be a json element of json array. Since the returned value is not of importance here we just catch the parse error to determine that the string is a correct json string or not.

    import play.libs.Json;

    public static Boolean isValidJson(String value) {
        try{
            Json.parse(value);
            return true;
        } catch(final Exception e){
            return false;
        }
    }

PHP: Get the key from an array in a foreach loop

you need nested foreach loops

foreach($samplearr as $key => $item){
   echo $key;
    foreach($item as $detail){
       echo $detail['value1'] . " " . $detail['value2']
     }
 }

Can Windows Containers be hosted on linux?

While Docker for Windows is perfectly able to run Linux containers, the converse, while theoretically possible, is not implemented due to practical reasons.

The most obvious one is, while Docker for Windows can run a Linux VM freely, Docker for Linux would require a Windows license in order to run it inside a VM.

Also, Linux is completely customizable, so the Linux VM used by Docker for Windows has been stripped down to just a few MB, containing only the bare minimum needed to run the containers, while the smallest Windows distribution available is about 1.5 GB. It may not be an impracticable size, but it is much more cumbersome than the Linux on Windows counterpart.

While it is certainly possible for someone to sell a Docker for Linux variation bundled with a Windows license and ready to run Windows containers under Linux (and I don't know if such product exists), the bottom line is that you can't avoid paying Windows vendor lock-in price: both in money and storage space.

Why "net use * /delete" does not work but waits for confirmation in my PowerShell script?

Try this:

net use * /delete /y

The /y key makes it select Yes in prompt silently

CodeIgniter activerecord, retrieve last insert id?

Last insert id means you can get inserted auto increment id by using this method in active record,

$this->db->insert_id() 
// it can be return insert id it is 
// similar to the mysql_insert_id in core PHP

You can refer this link you can find some more stuff.

Information from executing a query

What's HTML character code 8203?

It's the Unicode Character 'ZERO WIDTH SPACE' (U+200B).

this character is intended for line break control; it has no width, but its presence between two characters does not prevent increased letter spacing in justification

As per the given code sample, the entity is entirely superfluous in this context. It must be inserted by some accident, most likely by a buggy editor trying to do smart things with whitespace or highlighting, or an enduser using a keyboard language wherein this character is natively been used, such as Arabic.

PHP write file from input to txt

If you use file_put_contents you don't need to do a fopen -> fwrite -> fclose, the file_put_contents does all that for you. You should also check if the webserver has write rights in the directory where you are trying to write your "data.txt" file.

Depending on your PHP version (if it's old) you might not have the file_get/put_contents functions. Check your webserver log to see if any error appeared when you executed the script.

Can I obtain method parameter name using Java reflection?

if you use the eclipse, see the bellow image to allow the compiler to store the information about method parameters

enter image description here

What is the difference between MOV and LEA?

Basically ... "Move into REG ... after computing it..." it seems to be nice for other purposes as well :)

if you just forget that the value is a pointer you can use it for code optimizations/minimization ...what ever..

MOV EBX , 1
MOV ECX , 2

;//with 1 instruction you got result of 2 registers in 3rd one ...
LEA EAX , [EBX+ECX+5]

EAX = 8

originaly it would be:

MOV EAX, EBX
ADD EAX, ECX
ADD EAX, 5

how to query LIST using linq

var persons = new List<Person>
    {
        new Person {ID = 1, Name = "jhon", Salary = 2500},
        new Person {ID = 2, Name = "Sena", Salary = 1500},
        new Person {ID = 3, Name = "Max", Salary = 5500},
        new Person {ID = 4, Name = "Gen", Salary = 3500}
    };

var acertainperson = persons.Where(p => p.Name == "jhon").First();
Console.WriteLine("{0}: {1} points",
    acertainperson.Name, acertainperson.Salary);

jhon: 2500 points

var doingprettywell = persons.Where(p => p.Salary > 2000);
            foreach (var person in doingprettywell)
            {
                Console.WriteLine("{0}: {1} points",
                    person.Name, person.Salary);
            }

jhon: 2500 points
Max: 5500 points
Gen: 3500 points

        var astupidcalc = from p in persons
                          where p.ID > 2
                          select new
                                     {
                                         Name = p.Name,
                                         Bobos = p.Salary*p.ID,
                                         Bobotype = "bobos"
                                     };
        foreach (var person in astupidcalc)
        {
            Console.WriteLine("{0}: {1} {2}",
                person.Name, person.Bobos, person.Bobotype);
        }

Max: 16500 bobos
Gen: 14000 bobos

How to get Exception Error Code in C#

Building on Preet Sangha's solution, the following should safely cover the scenario where you're working with a large solution with the potential for several Inner Exceptions.

 try
 {
     object result = processClass.InvokeMethod("Create", methodArgs);
 }
 catch (Exception e)
 {
     // Here I was hoping to get an error code.
     if (ExceptionContainsErrorCode(e, 10004))
     {
         // Execute desired actions
     }
 }

...

private bool ExceptionContainsErrorCode(Exception e, int ErrorCode)
{
    Win32Exception winEx = e as Win32Exception;
    if (winEx != null && ErrorCode == winEx.ErrorCode) 
        return true;

    if (e.InnerException != null) 
        return ExceptionContainsErrorCode(e.InnerException, ErrorCode);

    return false;
}

This code has been unit tested.

I won't harp too much on the need for coming to appreciate and implement good practice when it comes to Exception Handling by managing each expected Exception Type within their own blocks.

Open S3 object as a string with Boto3

read will return bytes. At least for Python 3, if you want to return a string, you have to decode using the right encoding:

import boto3

s3 = boto3.resource('s3')

obj = s3.Object(bucket, key)
obj.get()['Body'].read().decode('utf-8') 

How do you create a dropdownlist from an enum in ASP.NET MVC?

A super easy way to get this done - without all the extension stuff that seems overkill is this:

Your enum:

    public enum SelectedLevel
    {
       Level1,
       Level2,
       Level3,
       Level4
    }

Inside of your controller bind the Enum to a List:

    List<SelectedLevel> myLevels = Enum.GetValues(typeof(SelectedLevel)).Cast<SelectedLevel>().ToList();

After that throw it into a ViewBag:

    ViewBag.RequiredLevel = new SelectList(myLevels);

Finally simply bind it to the View:

    @Html.DropDownList("selectedLevel", (SelectList)ViewBag.RequiredLevel, new { @class = "form-control" })

This is by far the easiest way I found and does not require any extensions or anything that crazy.

UPDATE: See Andrews comment below.

Python Variable Declaration

There's no need to declare new variables in Python. If we're talking about variables in functions or modules, no declaration is needed. Just assign a value to a name where you need it: mymagic = "Magic". Variables in Python can hold values of any type, and you can't restrict that.

Your question specifically asks about classes, objects and instance variables though. The idiomatic way to create instance variables is in the __init__ method and nowhere else — while you could create new instance variables in other methods, or even in unrelated code, it's just a bad idea. It'll make your code hard to reason about or to maintain.

So for example:

class Thing(object):

    def __init__(self, magic):
        self.magic = magic

Easy. Now instances of this class have a magic attribute:

thingo = Thing("More magic")
# thingo.magic is now "More magic"

Creating variables in the namespace of the class itself leads to different behaviour altogether. It is functionally different, and you should only do it if you have a specific reason to. For example:

class Thing(object):

    magic = "Magic"

    def __init__(self):
        pass

Now try:

thingo = Thing()
Thing.magic = 1
# thingo.magic is now 1

Or:

class Thing(object):

    magic = ["More", "magic"]

    def __init__(self):
        pass

thing1 = Thing()
thing2 = Thing()
thing1.magic.append("here")
# thing1.magic AND thing2.magic is now ["More", "magic", "here"]

This is because the namespace of the class itself is different to the namespace of the objects created from it. I'll leave it to you to research that a bit more.

The take-home message is that idiomatic Python is to (a) initialise object attributes in your __init__ method, and (b) document the behaviour of your class as needed. You don't need to go to the trouble of full-blown Sphinx-level documentation for everything you ever write, but at least some comments about whatever details you or someone else might need to pick it up.

Why maven settings.xml file is not there?

settings.xml is not required (and thus not autocreated in ~/.m2 folder) unless you want to change the default settings.

Standalone maven and the maven in eclipse will use the same local repository (~/.m2 folder). This means if some artifacts/dependencies are downloaded by standalone maven, it will not be again downloaded by maven in eclipse.

Based on the version of Eclipse that you use, you may have different maven version in eclipse compared to the standalone. It should not matter in most cases.

MySQL: Error Code: 1118 Row size too large (> 8126). Changing some columns to TEXT or BLOB

None of the answers to date mention the effect of the innodb_page_size parameter. Possibly because changing this parameter was not a supported operation prior to MySQL 5.7.6. From the documentation:

The maximum row length, except for variable-length columns (VARBINARY, VARCHAR, BLOB and TEXT), is slightly less than half of a database page for 4KB, 8KB, 16KB, and 32KB page sizes. For example, the maximum row length for the default innodb_page_size of 16KB is about 8000 bytes. For an InnoDB page size of 64KB, the maximum row length is about 16000 bytes. LONGBLOB and LONGTEXT columns must be less than 4GB, and the total row length, including BLOB and TEXT columns, must be less than 4GB.

Note that increasing the page size is not without its drawbacks. Again from the documentation:

As of MySQL 5.7.6, 32KB and 64KB page sizes are supported but ROW_FORMAT=COMPRESSED is still unsupported for page sizes greater than 16KB. For both 32KB and 64KB page sizes, the maximum record size is 16KB. For innodb_page_size=32k, extent size is 2MB. For innodb_page_size=64k, extent size is 4MB.

A MySQL instance using a particular InnoDB page size cannot use data files or log files from an instance that uses a different page size. This limitation could affect restore or downgrade operations using data from MySQL 5.6, which does support page sizes other than 16KB.

Is JavaScript guaranteed to be single-threaded?

That's a good question. I'd love to say “yes”. I can't.

JavaScript is usually considered to have a single thread of execution visible to scripts(*), so that when your inline script, event listener or timeout is entered, you remain completely in control until you return from the end of your block or function.

(*: ignoring the question of whether browsers really implement their JS engines using one OS-thread, or whether other limited threads-of-execution are introduced by WebWorkers.)

However, in reality this isn't quite true, in sneaky nasty ways.

The most common case is immediate events. Browsers will fire these right away when your code does something to cause them:

_x000D_
_x000D_
var l= document.getElementById('log');_x000D_
var i= document.getElementById('inp');_x000D_
i.onblur= function() {_x000D_
    l.value+= 'blur\n';_x000D_
};_x000D_
setTimeout(function() {_x000D_
    l.value+= 'log in\n';_x000D_
    l.focus();_x000D_
    l.value+= 'log out\n';_x000D_
}, 100);_x000D_
i.focus();
_x000D_
<textarea id="log" rows="20" cols="40"></textarea>_x000D_
<input id="inp">
_x000D_
_x000D_
_x000D_

Results in log in, blur, log out on all except IE. These events don't just fire because you called focus() directly, they could happen because you called alert(), or opened a pop-up window, or anything else that moves the focus.

This can also result in other events. For example add an i.onchange listener and type something in the input before the focus() call unfocuses it, and the log order is log in, change, blur, log out, except in Opera where it's log in, blur, log out, change and IE where it's (even less explicably) log in, change, log out, blur.

Similarly calling click() on an element that provides it calls the onclick handler immediately in all browsers (at least this is consistent!).

(I'm using the direct on... event handler properties here, but the same happens with addEventListener and attachEvent.)

There's also a bunch of circumstances in which events can fire whilst your code is threaded in, despite you having done nothing to provoke it. An example:

_x000D_
_x000D_
var l= document.getElementById('log');_x000D_
document.getElementById('act').onclick= function() {_x000D_
    l.value+= 'alert in\n';_x000D_
    alert('alert!');_x000D_
    l.value+= 'alert out\n';_x000D_
};_x000D_
window.onresize= function() {_x000D_
    l.value+= 'resize\n';_x000D_
};
_x000D_
<textarea id="log" rows="20" cols="40"></textarea>_x000D_
<button id="act">alert</button>
_x000D_
_x000D_
_x000D_

Hit alert and you'll get a modal dialogue box. No more script executes until you dismiss that dialogue, yes? Nope. Resize the main window and you will get alert in, resize, alert out in the textarea.

You might think it's impossible to resize a window whilst a modal dialogue box is up, but not so: in Linux, you can resize the window as much as you like; on Windows it's not so easy, but you can do it by changing the screen resolution from a larger to a smaller one where the window doesn't fit, causing it to get resized.

You might think, well, it's only resize (and probably a few more like scroll) that can fire when the user doesn't have active interaction with the browser because script is threaded. And for single windows you might be right. But that all goes to pot as soon as you're doing cross-window scripting. For all browsers other than Safari, which blocks all windows/tabs/frames when any one of them is busy, you can interact with a document from the code of another document, running in a separate thread of execution and causing any related event handlers to fire.

Places where events that you can cause to be generated can be raised whilst script is still threaded:

  • when the modal popups (alert, confirm, prompt) are open, in all browsers but Opera;

  • during showModalDialog on browsers that support it;

  • the “A script on this page may be busy...” dialogue box, even if you choose to let the script continue to run, allows events like resize and blur to fire and be handled even whilst the script is in the middle of a busy-loop, except in Opera.

  • a while ago for me, in IE with the Sun Java Plugin, calling any method on an applet could allow events to fire and script to be re-entered. This was always a timing-sensitive bug, and it's possible Sun have fixed it since (I certainly hope so).

  • probably more. It's been a while since I tested this and browsers have gained complexity since.

In summary, JavaScript appears to most users, most of the time, to have a strict event-driven single thread of execution. In reality, it has no such thing. It is not clear how much of this is simply a bug and how much deliberate design, but if you're writing complex applications, especially cross-window/frame-scripting ones, there is every chance it could bite you — and in intermittent, hard-to-debug ways.

If the worst comes to the worst, you can solve concurrency problems by indirecting all event responses. When an event comes in, drop it in a queue and deal with the queue in order later, in a setInterval function. If you are writing a framework that you intend to be used by complex applications, doing this could be a good move. postMessage will also hopefully soothe the pain of cross-document scripting in the future.

Convert char to int in C and C++

(This answer addresses the C++ side of things, but the sign extension problem exists in C too.)

Handling all three char types (signed, unsigned, and char) is more delicate than it first appears. Values in the range 0 to SCHAR_MAX (which is 127 for an 8-bit char) are easy:

char c = somevalue;
signed char sc = c;
unsigned char uc = c;
int n = c;

But, when somevalue is outside of that range, only going through unsigned char gives you consistent results for the "same" char values in all three types:

char c = somevalue;
signed char sc = c;
unsigned char uc = c;
// Might not be true: int(c) == int(sc) and int(c) == int(uc).
int nc = (unsigned char)c;
int nsc = (unsigned char)sc;
int nuc = (unsigned char)uc;
// Always true: nc == nsc and nc == nuc.

This is important when using functions from ctype.h, such as isupper or toupper, because of sign extension:

char c = negative_char;  // Assuming CHAR_MIN < 0.
int n = c;
bool b = isupper(n);  // Undefined behavior.

Note the conversion through int is implicit; this has the same UB:

char c = negative_char;
bool b = isupper(c);

To fix this, go through unsigned char, which is easily done by wrapping ctype.h functions through safe_ctype:

template<int (&F)(int)>
int safe_ctype(unsigned char c) { return F(c); }

//...
char c = CHAR_MIN;
bool b = safe_ctype<isupper>(c);  // No UB.

std::string s = "value that may contain negative chars; e.g. user input";
std::transform(s.begin(), s.end(), s.begin(), &safe_ctype<toupper>);
// Must wrap toupper to eliminate UB in this case, you can't cast
// to unsigned char because the function is called inside transform.

This works because any function taking any of the three char types can also take the other two char types. It leads to two functions which can handle any of the types:

int ord(char c) { return (unsigned char)c; }
char chr(int n) {
  assert(0 <= n);  // Or other error-/sanity-checking.
  assert(n <= UCHAR_MAX);
  return (unsigned char)n;
}

// Ord and chr are named to match similar functions in other languages
// and libraries.

ord(c) always gives you a non-negative value – even when passed a negative char or negative signed char – and chr takes any value ord produces and gives back the exact same char.

In practice, I would probably just cast through unsigned char instead of using these, but they do succinctly wrap the cast, provide a convenient place to add error checking for int-to-char, and would be shorter and more clear when you need to use them several times in close proximity.

How to use OpenCV SimpleBlobDetector

Note: all the examples here are using the OpenCV 2.X API.

In OpenCV 3.X, you need to use:

Ptr<SimpleBlobDetector> d = SimpleBlobDetector::create(params);

See also: the transition guide: http://docs.opencv.org/master/db/dfa/tutorial_transition_guide.html#tutorial_transition_hints_headers

"Use the new keyword if hiding was intended" warning

@wdavo is correct. The same is also true for functions.

If you override a base function, like Update, then in your subclass you need:

new void Update()
{
  //do stufff
}

Without the new at the start of the function decleration you will get the warning flag.

What is the difference between Set and List?

Set:

Cannot have duplicate values Ordering depends on implementation. By default it is not ordered Cannot have access by index

List:

Can have duplicate values Ordered by default Can have access by index

VBA procedure to import csv file into access

The easiest way to do it is to link the CSV-file into the Access database as a table. Then you can work on this table as if it was an ordinary access table, for instance by creating an appropriate query based on this table that returns exactly what you want.

You can link the table either manually or with VBA like this

DoCmd.TransferText TransferType:=acLinkDelim, TableName:="tblImport", _
    FileName:="C:\MyData.csv", HasFieldNames:=true

UPDATE

Dim db As DAO.Database

' Re-link the CSV Table
Set db = CurrentDb
On Error Resume Next:   db.TableDefs.Delete "tblImport":   On Error GoTo 0
db.TableDefs.Refresh
DoCmd.TransferText TransferType:=acLinkDelim, TableName:="tblImport", _
    FileName:="C:\MyData.csv", HasFieldNames:=true
db.TableDefs.Refresh

' Perform the import
db.Execute "INSERT INTO someTable SELECT col1, col2, ... FROM tblImport " _
   & "WHERE NOT F1 IN ('A1', 'A2', 'A3')"
db.Close:   Set db = Nothing

How do I set bold and italic on UILabel of iPhone/iPad?

I recently wrote a blog post about the restrictions of the UIFont API and how to solve it. You can see it at here

With the code I provide there, you can get your desired UIFont as easy as:

UIFont *myFont = [FontResolver fontWithDescription:@"font-family: Helvetica; font-weight: bold; font-style: italic;"];

And then set it to your UILabel (or whatever) with: myLabel.font = myFont;

What are naming conventions for MongoDB?

Even if no convention is specified about this, manual references are consistently named after the referenced collection in the Mongo documentation, for one-to-one relations. The name always follows the structure <document>_id.

For example, in a dogs collection, a document would have manual references to external documents named like this:

{
  name: 'fido',
  owner_id: '5358e4249611f4a65e3068ab',
  race_id: '5358ee549611f4a65e3068ac',
  colour: 'yellow'
  ...
}

This follows the Mongo convention of naming _id the identifier for every document.

Hexadecimal string to byte array in C

Apart from the excellent answers above I though I would write a C function that does not use any libraries and has some guards against bad strings.

uint8_t* datahex(char* string) {

    if(string == NULL) 
       return NULL;

    size_t slength = strlen(string);
    if((slength % 2) != 0) // must be even
       return NULL;

    size_t dlength = slength / 2;

    uint8_t* data = malloc(dlength);
    memset(data, 0, dlength);

    size_t index = 0;
    while (index < slength) {
        char c = string[index];
        int value = 0;
        if(c >= '0' && c <= '9')
          value = (c - '0');
        else if (c >= 'A' && c <= 'F') 
          value = (10 + (c - 'A'));
        else if (c >= 'a' && c <= 'f')
          value = (10 + (c - 'a'));
        else {
          free(data);
          return NULL;
        }

        data[(index/2)] += value << (((index + 1) % 2) * 4);

        index++;
    }

    return data;
}

Explanation:

a. index / 2 | Division between integers will round down the value, so 0/2 = 0, 1/2 = 0, 2/2 = 1, 3/2 = 1, 4/2 = 2, 5/2 = 2, etc. So, for every 2 string characters we add the value to 1 data byte.

b. (index + 1) % 2 | We want odd numbers to result to 1 and even to 0 since the first digit of a hex string is the most significant and needs to be multiplied by 16. so for index 0 => 0 + 1 % 2 = 1, index 1 => 1 + 1 % 2 = 0 etc.

c. << 4 | Shift by 4 is multiplying by 16. example: b00000001 << 4 = b00010000

Short form for Java if statement

Simple & clear:

String manType = hasMoney() ? "rich" : "poor";

long version:

      String manType;
    if (hasMoney()) {
        manType = "rich";
    } else {
        manType = "poor";
    }

or how I'm using it to be clear for other code readers:

 String manType = "poor";
    if (hasMoney())
        manType = "rich";

Where is the Global.asax.cs file?

It don't create normally; you need to add it by yourself.

After adding Global.asax by

  • Right clicking your website -> Add New Item -> Global Application Class -> Add

You need to add a class

  • Right clicking App_Code -> Add New Item -> Class -> name it Global.cs -> Add

Inherit the newly generated by System.Web.HttpApplication and copy all the method created Global.asax to Global.cs and also add an inherit attribute to the Global.asax file.

Your Global.asax will look like this: -

<%@ Application Language="C#" Inherits="Global" %>

Your Global.cs in App_Code will look like this: -

public class Global : System.Web.HttpApplication
{
    public Global()
    {
        //
        // TODO: Add constructor logic here
        //
    }

    void Application_Start(object sender, EventArgs e)
    {
        // Code that runs on application startup

    }
    /// Many other events like begin request...e.t.c, e.t.c
}

What's the difference between window.location and document.location in JavaScript?

At least in IE, it has a little difference on local file:

document.URL will return "file://C:\projects\abc\a.html"

but window.location.href will return "file:///C:/projects/abc/a.html"

One is back slash, one is forward slash.

onCreateOptionsMenu inside Fragments

try this,

@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
    inflater.inflate(R.menu.menu_sample, menu);
    super.onCreateOptionsMenu(menu,inflater);
}

Finally, in onCreateView method, add this line to make the options appear in your Toolbar

setHasOptionsMenu(true);

Where can I view Tomcat log files in Eclipse?

Double click and open the server. Go to 'Arguments'. -Dcatalina.base= .. something. Go to that something. Your logs are there.

Is it possible to use the instanceof operator in a switch statement?

While it is not possible to write a switch statement, it is possible to branch out to specific processing for each given type. One way of doing this is to use standard double dispatch mechanism. An example where we want to "switch" based on type is Jersey Exception mapper where we need to map multitude of exceptions to error responses. While for this specific case there is probably a better way (i.e. using a polymorphic method that translates each exception to an error response), using double dispatch mechanism is still useful and practical.

interface Processable {
    <R> R process(final Processor<R> processor);
}

interface Processor<R> {
    R process(final A a);
    R process(final B b);
    R process(final C c);
    // for each type of Processable
    ...
}

class A implements Processable {
    // other class logic here

    <R> R process(final Processor<R> processor){
        return processor.process(this);
    }
}

class B implements Processable {
    // other class logic here

    <R> R process(final Processor<R> processor){
        return processor.process(this);
    }
}

class C implements Processable {
    // other class logic here

    <R> R process(final Processor<R> processor){
        return processor.process(this);
    }
}

Then where ever the "switch" is needed, you can do it as follows:

public class LogProcessor implements Processor<String> {
    private static final Logger log = Logger.for(LogProcessor.class);

    public void logIt(final Processable base) {
        log.info("Logging for type {}", process(base));
    }

    // Processor methods, these are basically the effective "case" statements
    String process(final A a) {
        return "Stringifying A";
    }

    String process(final B b) {
        return "Stringifying B";
    }

    String process(final C c) {
        return "Stringifying C";
    }
}

get client time zone from browser

For now, the best bet is probably jstz as suggested in mbayloon's answer.

For completeness, it should be mentioned that there is a standard on it's way: Intl. You can see this in Chrome already:

> Intl.DateTimeFormat().resolvedOptions().timeZone
"America/Los_Angeles"

(This doesn't actually follow the standard, which is one more reason to stick with the library)

How to transition to a new view controller with code only using Swift

For anyone doing this on iOS8, this is what I had to do:

I have a swift class file titled SettingsView.swift and a .xib file named SettingsView.xib. I run this in MasterViewController.swift (or any view controller really to open a second view controller)

@IBAction func openSettings(sender: AnyObject) {
        var mySettings: SettingsView = SettingsView(nibName: "SettingsView", bundle: nil) /<--- Notice this "nibName" 
        var modalStyle: UIModalTransitionStyle = UIModalTransitionStyle.CoverVertical
        mySettings.modalTransitionStyle = modalStyle
        self.presentViewController(mySettings, animated: true, completion: nil)

    }

Android Google Maps API V2 Zoom to Current Location

youmap.animateCamera(CameraUpdateFactory.newLatLngZoom(currentlocation, 16));

16 is the zoom level

Create nice column output in python

Transposing the columns like that is a job for zip:

>>> a = [['a', 'b', 'c'], ['aaaaaaaaaa', 'b', 'c'], ['a', 'bbbbbbbbbb', 'c']]
>>> list(zip(*a))
[('a', 'aaaaaaaaaa', 'a'), ('b', 'b', 'bbbbbbbbbb'), ('c', 'c', 'c')]

To find the required length of each column, you can use max:

>>> trans_a = zip(*a)
>>> [max(len(c) for c in b) for b in trans_a]
[10, 10, 1]

Which you can use, with suitable padding, to construct strings to pass to print:

>>> col_lenghts = [max(len(c) for c in b) for b in trans_a]
>>> padding = ' ' # You might want more
>>> padding.join(s.ljust(l) for s,l in zip(a[0], col_lenghts))
'a          b          c'

How to get a tab character?

Try &emsp;

as per the docs :

The character entities &ensp; and &emsp; denote an en space and an em space respectively, where an en space is half the point size and an em space is equal to the point size of the current font. For fixed pitch fonts, the user agent can treat the en space as being equivalent to A space character, and the em space as being equuivalent to two space characters.

Docs link : https://www.w3.org/MarkUp/html3/specialchars.html

How to call javascript function from code-behind

If the order of the execution is not important and you need both some javascript AND some codebehind to be fired on an asp element, heres what you can do.

What you can take away from my example: I have a div covering the ASP control that I want both javascript and codebehind to be ran from. The div's onClick method AND the calendar's OnSelectionChanged event both get fired this way.

In this example, i am using an ASP Calendar control, and im controlling it from both javascript and codebehind:

Front end code:

        <div onclick="showHideModal();">
            <asp:Calendar 
                OnSelectionChanged="DatepickerDateChange" ID="DatepickerCalendar" runat="server" 
                BorderWidth="1px" DayNameFormat="Shortest" Font-Names="Verdana" 
                Font-Size="8pt" ShowGridLines="true" BackColor="#B8C9E1" BorderColor="#003E51" Width="100%"> 
                <OtherMonthDayStyle ForeColor="#6C5D34"> </OtherMonthDayStyle> 
                <DayHeaderStyle  ForeColor="black" BackColor="#D19000"> </DayHeaderStyle>
                <TitleStyle BackColor="#B8C9E1" ForeColor="Black"> </TitleStyle> 
                <DayStyle BackColor="White"> </DayStyle> 
                <SelectedDayStyle BackColor="#003E51" Font-Bold="True"> </SelectedDayStyle> 
            </asp:Calendar>
        </div>

Codebehind:

        protected void DatepickerDateChange(object sender, EventArgs e)
        {
            if (toFromPicked.Value == "MainContent_fromDate")
            {
                fromDate.Text = DatepickerCalendar.SelectedDate.ToShortDateString();
            }
            else
            {
                toDate.Text = DatepickerCalendar.SelectedDate.ToShortDateString();
            }
        }

Print ArrayList

Assuming that houseAddress.get(i) is an ArrayList you can add toString() after the ArrayList :

for(int i = 0; i < houseAddress.size(); i++) {   
    System.out.print(houseAddress.get(i).toString());
} 

A general example:

ArrayList<Double> a = new ArrayList();
a.add(2.);
a.add(32.);
System.out.println(a.toString());
// output
// [2.0, 32.0]

Character Limit on Instagram Usernames

Limit - 30 symbols. Username must contains only letters, numbers, periods and underscores.

Running Node.Js on Android

I just had a jaw-drop moment - Termux allows you to install NodeJS on an Android device!

It seems to work for a basic Websocket Speed Test I had on hand. The http served by it can be accessed both locally and on the network.

There is a medium post that explains the installation process

Basically: 1. Install termux 2. apt install nodejs 3. node it up!

One restriction I've run into - it seems the shared folders don't have the necessary permissions to install modules. It might just be a file permission thing. The private app storage works just fine.

Why so red? IntelliJ seems to think every declaration/method cannot be found/resolved

IntelliJ sometimes gets confused all by itself, even without the external changes Korgen described (though that is a good way to consistently reproduce it).

Click File -> Synchronize, and IntelliJ should see that everything is okay again.

If that doesn't work, IntelliJ's caches might be corrupt (this used to happen a lot more often than it does now); in that case, regenerate them by

Clicking File -> Invalidate Caches and restarting the IDE

(though loading the project will take a while while the caches are recreated).

"npm config set registry https://registry.npmjs.org/" is not working in windows bat file

We can also run npm install with registry options for multiple custom registry URLs.

npm install --registry=https://registry.npmjs.org/ 
npm install --registry=https://custom.npm.registry.com/ 

Recursively find all files newer than a given time

So there's another way (and it is portable to some extent_

(python <<EOF
import fnmatch
import os
import os.path as path
import time

matches = []
def find(dirname=None, newerThan=3*24*3600, olderThan=None):
    for root, dirnames, filenames in os.walk(dirname or '.'):
        for filename in fnmatch.filter(filenames, '*'):
            filepath = os.path.join(root, filename)
            matches.append(path)
            ts_now = time.time()
            newer = ts_now - path.getmtime(filepath) < newerThan
            older = ts_now - path.getmtime(filepath) > newerThan
            if newerThan and newer or olderThan and older: print filepath
    for dirname in dirnames:
        if dirname not in ['.', '..']:
            print 'dir:', dirname
            find(dirname)
find('.')
EOF
) | xargs -I '{}' echo found file modified within 3 days '{}'

CORS error :Request header field Authorization is not allowed by Access-Control-Allow-Headers in preflight response

You have to add options also in allowed headers. browser sends a preflight request before original request is sent. See below

 res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,PATCH,OPTIONS');

From source https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/OPTIONS

In CORS, a preflight request with the OPTIONS method is sent, so that the server can respond whether it is acceptable to send the request with these parameters. The Access-Control-Request-Method header notifies the server as part of a preflight request that when the actual request is sent, it will be sent with a POST request method. The Access-Control-Request-Headers header notifies the server that when the actual request is sent, it will be sent with a X-PINGOTHER and Content-Type custom headers. The server now has an opportunity to determine whether it wishes to accept a request under these circumstances.

EDITED

You can avoid this manual configuration by using npmjs.com/package/cors npm package.I have used this method also, it is clear and easy.

Selecting Values from Oracle Table Variable / Array?

The sql array type is not neccessary. Not if the element type is a primitive one. (Varchar, number, date,...)

Very basic sample:

declare
  type TPidmList is table of sgbstdn.sgbstdn_pidm%type;
  pidms TPidmList;
begin
  select distinct sgbstdn_pidm
  bulk collect into pidms
  from sgbstdn
  where sgbstdn_majr_code_1 = 'HS04'
  and sgbstdn_program_1 = 'HSCOMPH';

  -- do something with pidms

  open :someCursor for
    select value(t) pidm
    from table(pidms) t;
end;

When you want to reuse it, then it might be interesting to know how that would look like. If you issue several commands than those could be grouped in a package. The private package variable trick from above has its downsides. When you add variables to a package, you give it state and now it doesn't act as a stateless bunch of functions but as some weird sort of singleton object instance instead.

e.g. When you recompile the body, it will raise exceptions in sessions that already used it before. (because the variable values got invalided)

However, you could declare the type in a package (or globally in sql), and use it as a paramter in methods that should use it.

create package Abc as
  type TPidmList is table of sgbstdn.sgbstdn_pidm%type;

  function CreateList(majorCode in Varchar, 
                      program in Varchar) return TPidmList;

  function Test1(list in TPidmList) return PLS_Integer;
  -- "in" to make it immutable so that PL/SQL can pass a pointer instead of a copy
  procedure Test2(list in TPidmList);
end;

create package body Abc as

  function CreateList(majorCode in Varchar, 
                      program in Varchar) return TPidmList is
    result TPidmList;
  begin
    select distinct sgbstdn_pidm
    bulk collect into result
    from sgbstdn
    where sgbstdn_majr_code_1 = majorCode
    and sgbstdn_program_1 = program;

    return result;
  end;

  function Test1(list in TPidmList) return PLS_Integer is
    result PLS_Integer := 0;
  begin
    if list is null or list.Count = 0 then
      return result;
    end if;

    for i in list.First .. list.Last loop
      if ... then
        result := result + list(i);
      end if;
    end loop;
  end;

  procedure Test2(list in TPidmList) as
  begin
    ...
  end;

  return result;
end;

How to call it:

declare
  pidms constant Abc.TPidmList := Abc.CreateList('HS04', 'HSCOMPH');
  xyz PLS_Integer;
begin
  Abc.Test2(pidms);
  xyz := Abc.Test1(pidms);
  ...

  open :someCursor for
    select value(t) as Pidm,
           xyz as SomeValue
    from   table(pidms) t;
end;

ImportError: No module named 'django.core.urlresolvers'

use from django.urls import reverse instead of from django.core.urlresolvers import reverse

How do write IF ELSE statement in a MySQL query

You probably want to use a CASE expression.

They look like this:

SELECT col1, col2, (case when (action = 2 and state = 0) 
 THEN
      1 
 ELSE
      0 
 END)
 as state from tbl1;

When is del useful in Python?

Once I had to use:

del serial
serial = None

because using only:

serial = None

didn't release the serial port fast enough to immediately open it again. From that lesson I learned that del really meant: "GC this NOW! and wait until it's done" and that is really useful in a lot of situations. Of course, you may have a system.gc.del_this_and_wait_balbalbalba(obj).

Intent.putExtra List

Assuming that your List is a list of strings make data an ArrayList<String> and use intent.putStringArrayListExtra("data", data)

Here is a skeleton of the code you need:

  1. Declare List

    private List<String> test;
    
  2. Init List at appropriate place

    test = new ArrayList<String>();
    

    and add data as appropriate to test.

  3. Pass to intent as follows:

    Intent intent = getIntent();  
    intent.putStringArrayListExtra("test", (ArrayList<String>) test);
    
  4. Retrieve data as follows:

    ArrayList<String> test = getIntent().getStringArrayListExtra("test");
    

Hope that helps.

git with IntelliJ IDEA: Could not read from remote repository

IntelliJ's built-in SSH client seems to hash its known_hosts, but the one I had had its host names in clear text.

When I deleted the file and let IntelliJ create a new one, with only my (hashed) GitLab server and nothing else, it worked.

It's also not possible to mix it - keep some unhashed entries together with hashed entries for IntelliJ. So, you have to configure your other SSH clients to use hashed hosts.

Concrete Javascript Regex for Accented Characters (Diacritics)

The accented Latin range \u00C0-\u017F was not quite enough for my database of names, so I extended the regex to

[a-zA-Z\u00C0-\u024F]
[a-zA-Z\u00C0-\u024F\u1E00-\u1EFF] // includes even more Latin chars

I added these code blocks (\u00C0-\u024F includes three adjacent blocks at once):

Note that \u00C0-\u00FF is actually only a part of Latin-1 Supplement. It skips unprintable control signals and all symbols except for the awkwardly-placed multiply × \u00D7 and divide ÷ \u00F7.

[a-zA-Z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u024F] // exclude ×÷

If you need more code points, you can find more ranges on Wikipedia's List of Unicode characters. For example, you could also add Latin Extended-C, D, and E, but I left them out because only historians seem interested in them now, and the D and E sets don't even render correctly in my browser.

The original regex stopping at \u017F borked on the name "?enol". According to FontSpace's Unicode Analyzer, that first character is \u0218, LATIN CAPITAL LETTER S WITH COMMA BELOW. (Yeah, it's usually spelled with a cedilla-S \u015E, "Senol." But I'm not flying to Turkey to go tell him, "You're spelling your name wrong!")

JUnit test for System.out.println()

If the function is printing to System.out, you can capture that output by using the System.setOut method to change System.out to go to a PrintStream provided by you. If you create a PrintStream connected to a ByteArrayOutputStream, then you can capture the output as a String.

// Create a stream to hold the output
ByteArrayOutputStream baos = new ByteArrayOutputStream();
PrintStream ps = new PrintStream(baos);
// IMPORTANT: Save the old System.out!
PrintStream old = System.out;
// Tell Java to use your special stream
System.setOut(ps);
// Print some output: goes to your special stream
System.out.println("Foofoofoo!");
// Put things back
System.out.flush();
System.setOut(old);
// Show what happened
System.out.println("Here: " + baos.toString());

apache server reached MaxClients setting, consider raising the MaxClients setting

I recommend to use bellow formula suggested on Apache:

MaxClients = (total RAM - RAM for OS - RAM for external programs) / (RAM per httpd process)

Find my script here which is running on Rhel 6.7. you can made change according to your OS.

#!/bin/bash

echo "HostName=`hostname`"

#Formula
#MaxClients . (RAM - size_all_other_processes)/(size_apache_process)
total_httpd_processes_size=`ps -ylC httpd --sort:rss | awk '{ sum += $9 } END { print sum }'`
#echo "total_httpd_processes_size=$total_httpd_processes_size"
total_http_processes_count=`ps -ylC httpd --sort:rss | wc -l`
echo "total_http_processes_count=$total_http_processes_count"
AVG_httpd_process_size=$(expr $total_httpd_processes_size / $total_http_processes_count)
echo "AVG_httpd_process_size=$AVG_httpd_process_size"
total_httpd_process_size_MB=$(expr $AVG_httpd_process_size / 1024)
echo "total_httpd_process_size_MB=$total_httpd_process_size_MB"
total_pttpd_used_size=$(expr $total_httpd_processes_size / 1024)
echo "total_pttpd_used_size=$total_pttpd_used_size"
total_RAM_size=`free -m |grep Mem |awk '{print $2}'`
echo "total_RAM_size=$total_RAM_size"
total_used_size=`free -m |grep Mem |awk '{print $3}'`
echo "total_used_size=$total_used_size"
size_all_other_processes=$(expr $total_used_size - $total_pttpd_used_size)
echo "size_all_other_processes=$size_all_other_processes"
remaining_memory=$(($total_RAM_size - $size_all_other_processes))
echo "remaining_memory=$remaining_memory"
MaxClients=$((($total_RAM_size - $size_all_other_processes) / $total_httpd_process_size_MB))
echo "MaxClients=$MaxClients"
exit

how to make a cell of table hyperlink

Not exactly making the cell a link, but the table itself. I use this as a button in e-mails, giving me div-like controls.

_x000D_
_x000D_
<a href="https://www.foo.bar" target="_blank" style="color: white; font-weight: bolder; text-decoration: none;">
  <table style="margin-left: auto; margin-right: auto;" align="center">
    <tr>
      <td style="padding: 20px; height: 60px;" bgcolor="#00b389">Go to Foo Bar</td>
    </tr>
  </table>
</a>
_x000D_
_x000D_
_x000D_

C++ static virtual members?

While Alsk has already given a pretty detailed answer, I'd like to add an alternative, since I think his enhanced implementation is overcomplicated.

We start with an abstract base class, that provides the interface for all the object types:

class Object
{
public:
    virtual char* GetClassName() = 0;
};

Now we need an actual implementation. But to avoid having to write both the static and the virtual methods, we will have our actual object classes inherit the virtual methods. This does obviously only work, if the base class knows how to access the static member function. So we need to use a template and pass the actual objects class name to it:

template<class ObjectType>
class ObjectImpl : public Object
{
public:
    virtual char* GetClassName()
    {
        return ObjectType::GetClassNameStatic();
    }
};

Finally we need to implement our real object(s). Here we only need to implement the static member function, the virtual member functions will be inherited from the ObjectImpl template class, instantiated with the name of the derived class, so it will access it's static members.

class MyObject : public ObjectImpl<MyObject>
{
public:
    static char* GetClassNameStatic()
    {
        return "MyObject";
    }
};

class YourObject : public ObjectImpl<YourObject>
{
public:
    static char* GetClassNameStatic()
    {
        return "YourObject";
    }
};

Let's add some code to test:

char* GetObjectClassName(Object* object)
{
    return object->GetClassName();
}

int main()
{
    MyObject myObject;
    YourObject yourObject;

    printf("%s\n", MyObject::GetClassNameStatic());
    printf("%s\n", myObject.GetClassName());
    printf("%s\n", GetObjectClassName(&myObject));
    printf("%s\n", YourObject::GetClassNameStatic());
    printf("%s\n", yourObject.GetClassName());
    printf("%s\n", GetObjectClassName(&yourObject));

    return 0;
}

Addendum (Jan 12th 2019):

Instead of using the GetClassNameStatic() function, you can also define the the class name as a static member, even "inline", which IIRC works since C++11 (don't get scared by all the modifiers :)):

class MyObject : public ObjectImpl<MyObject>
{
public:
    // Access this from the template class as `ObjectType::s_ClassName` 
    static inline const char* const s_ClassName = "MyObject";

    // ...
};

Changing git commit message after push (given that no one pulled from remote)

If you want to modify an older commit, not the last one, you will need to use rebase command as explained in here,Github help page , on the Amending the message of older or multiple commit messages section

Java FileReader encoding issue

For another as Latin languages for example Cyrillic you can use something like this:

FileReader fr = new FileReader("src/text.txt", StandardCharsets.UTF_8);

and be sure that your .txt file is saved with UTF-8 (but not as default ANSI) format. Cheers!

Access denied for user 'root'@'localhost' with PHPMyAdmin

Edit your phpmyadmin config.inc.php file and if you have Password, insert that in front of Password in following code:

$cfg['Servers'][$i]['verbose'] = 'localhost';
$cfg['Servers'][$i]['host'] = 'localhost';
$cfg['Servers'][$i]['port'] = '3306';
$cfg['Servers'][$i]['socket'] = '';
$cfg['Servers'][$i]['connect_type'] = 'tcp';
$cfg['Servers'][$i]['extension'] = 'mysqli';
$cfg['Servers'][$i]['auth_type'] = 'config';
$cfg['Servers'][$i]['user'] = '**your-root-username**';
$cfg['Servers'][$i]['password'] = '**root-password**';
$cfg['Servers'][$i]['AllowNoPassword'] = true;

Regular expression to match a line that doesn't contain a word

As long as you are dealing with lines, simply mark the negative matches and target the rest.

In fact, I use this trick with sed because ^((?!hede).)*$ looks not supported by it.

For the desired output

  1. Mark the negative match: (e.g. lines with hede), using a character not included in the whole text at all. An emoji could probably be a good choice for this purpose.

    s/(.*hede)/\1/g
    
  2. Target the rest (the unmarked strings: e.g. lines without hede). Suppose you want to keep only the target and delete the rest (as you want):

    s/^.*//g
    

For a better understanding

Suppose you want to delete the target:

  1. Mark the negative match: (e.g. lines with hede), using a character not included in the whole text at all. An emoji could probably be a good choice for this purpose.

    s/(.*hede)/\1/g
    
  2. Target the rest (the unmarked strings: e.g. lines without hede). Suppose you want to delete the target:

    s/^[^].*//g
    
  3. Remove the mark:

    s///g
    

Vue JS mounted()

You can also move mounted out of the Vue instance and make it a function in the top-level scope. This is also a useful trick for server side rendering in Vue.

function init() {
  // Use `this` normally
}

new Vue({
  methods:{
    init
  },
  mounted(){
    init.call(this)
  }
})

Letter Count on a string

One problem is that you are using count to refer both to the position in the word that you are checking, and the number of char you have seen, and you are using char to refer both to the input character you are checking, and the current character in the string. Use separate variables instead.

Also, move the return statement outside the loop; otherwise you will always return after checking the first character.

Finally, you only need one loop to iterate over the string. Get rid of the outer while loop and you will not need to track the position in the string.

Taking these suggestions, your code would look like this:

def count_letters(word, char):
  count = 0
  for c in word:
    if char == c:
      count += 1
  return count

Python function attributes - uses and abuses

You can do objects the JavaScript way... It makes no sense but it works ;)

>>> def FakeObject():
...   def test():
...     print "foo"
...   FakeObject.test = test
...   return FakeObject
>>> x = FakeObject()
>>> x.test()
foo

How to call controller from the button click in asp.net MVC 4

You are mixing razor and aspx syntax,if your view engine is razor just do this:

<button class="btn btn-info" type="button" id="addressSearch"   
          onclick="location.href='@Url.Action("List", "Search")'">

numbers not allowed (0-9) - Regex Expression in javascript

\D is a non-digit, and so then \D* is any number of non-digits in a row. So your whole string should match ^\D*$.

Check on http://rubular.com/r/AoWBmrbUkN it works perfectly.

You can also try on http://regexpal.com/ OR http://www.regextester.com/

How to programmatically set the Image source

{yourImageName.Source = new BitmapImage(new Uri("ms-appx:///Assets/LOGO.png"));}

LOGO refers to your image

Hoping to help anyone. :)

PySpark: multiple conditions in when clause

it should works at least in pyspark 2.4

tdata = tdata.withColumn("Age",  when((tdata.Age == "") & (tdata.Survived == "0") , "NewValue").otherwise(tdata.Age))

Why is git push gerrit HEAD:refs/for/master used instead of git push origin master

The documentation for Gerrit, in particular the "Push changes" section, explains that you push to the "magical refs/for/'branch' ref using any Git client tool".

The following image is taken from the Intro to Gerrit. When you push to Gerrit, you do git push gerrit HEAD:refs/for/<BRANCH>. This pushes your changes to the staging area (in the diagram, "Pending Changes"). Gerrit doesn't actually have a branch called <BRANCH>; it lies to the git client.

Internally, Gerrit has its own implementation for the Git and SSH stacks. This allows it to provide the "magical" refs/for/<BRANCH> refs.

When a push request is received to create a ref in one of these namespaces Gerrit performs its own logic to update the database, and then lies to the client about the result of the operation. A successful result causes the client to believe that Gerrit has created the ref, but in reality Gerrit hasn’t created the ref at all. [Link - Gerrit, "Gritty Details"].

The Gerrit workflow

After a successful patch (i.e, the patch has been pushed to Gerrit, [putting it into the "Pending Changes" staging area], reviewed, and the review has passed), Gerrit pushes the change from the "Pending Changes" into the "Authoritative Repository", calculating which branch to push it into based on the magic it did when you pushed to refs/for/<BRANCH>. This way, successfully reviewed patches can be pulled directly from the correct branches of the Authoritative Repository.

int value under 10 convert to string two digit number

You can also do it this way

private static string GetPaddingSequence(int padding)
{
      StringBuilder SB = new StringBuilder();
      for (int i = 0; i < padding; i++)
      {
           SB.Append("0");
      }

      return SB.ToString();
  }

public static string FormatNumber(int number, int padding)
{
    return number.ToString(GetPaddingSequence(padding));
}

Finally call the function FormatNumber

string x = FormatNumber(1,2);

Output will be 01 which is based on your padding parameter. Increasing it will increase the number of 0s

Adding 1 hour to time variable

for this problem please follow bellow code:

$time= '10:09';
$new_time=date('H:i',strtotime($time.'+ 1 hour'));
echo $new_time;`
// now output will be: 11:09

android.content.res.Resources$NotFoundException: String resource ID #0x0

When you try to set text in Edittext or textview you should pass only String format.

dateTime.setText(app.getTotalDl());

to

dateTime.setText(String.valueOf(app.getTotalDl()));

How can I pad an int with leading zeros when using cout << operator?

I would use the following function. I don't like sprintf; it doesn't do what I want!!

#define hexchar(x)    ((((x)&0x0F)>9)?((x)+'A'-10):((x)+'0'))
typedef signed long long   Int64;

// Special printf for numbers only
// See formatting information below.
//
//    Print the number "n" in the given "base"
//    using exactly "numDigits".
//    Print +/- if signed flag "isSigned" is TRUE.
//    Use the character specified in "padchar" to pad extra characters.
//
//    Examples:
//    sprintfNum(pszBuffer, 6, 10, 6,  TRUE, ' ',   1234);  -->  " +1234"
//    sprintfNum(pszBuffer, 6, 10, 6, FALSE, '0',   1234);  -->  "001234"
//    sprintfNum(pszBuffer, 6, 16, 6, FALSE, '.', 0x5AA5);  -->  "..5AA5"
void sprintfNum(char *pszBuffer, int size, char base, char numDigits, char isSigned, char padchar, Int64 n)
{
    char *ptr = pszBuffer;

    if (!pszBuffer)
    {
        return;
    }

    char *p, buf[32];
    unsigned long long x;
    unsigned char count;

    // Prepare negative number
    if (isSigned && (n < 0))
    {
        x = -n;
    }
    else
    {
        x = n;
    }

    // Set up small string buffer
    count = (numDigits-1) - (isSigned?1:0);
    p = buf + sizeof (buf);
    *--p = '\0';

    // Force calculation of first digit
    // (to prevent zero from not printing at all!!!)
    *--p = (char)hexchar(x%base);
    x = x / base;

    // Calculate remaining digits
    while(count--)
    {
        if(x != 0)
        {
            // Calculate next digit
            *--p = (char)hexchar(x%base);
            x /= base;
        }
        else
        {
            // No more digits left, pad out to desired length
            *--p = padchar;
        }
    }

    // Apply signed notation if requested
    if (isSigned)
    {
        if (n < 0)
        {
            *--p = '-';
        }
        else if (n > 0)
        {
            *--p = '+';
        }
        else
        {
            *--p = ' ';
        }
    }

    // Print the string right-justified
    count = numDigits;
    while (count--)
    {
        *ptr++ = *p++;
    }
    return;
}

Replace all double quotes within String

This is to remove double quotes in a string.

str1 = str.replace(/"/g, "");
alert(str1);

Sqlite or MySql? How to decide?

SQLite out-of-the-box is not really feature-full regarding concurrency. You will get into trouble if you have hundreds of web requests hitting the same SQLite database.

You should definitely go with MySQL or PostgreSQL.

If it is for a single-person project, SQLite will be easier to setup though.

Finding element's position relative to the document

I've found the following method to be the most reliable when dealing with edge cases that trip up offsetTop/offsetLeft.

function getPosition(element) {
    var clientRect = element.getBoundingClientRect();
    return {left: clientRect.left + document.body.scrollLeft,
            top: clientRect.top + document.body.scrollTop};
}

OSError: [WinError 193] %1 is not a valid Win32 application

The error is pretty clear. The file hello.py is not an executable file. You need to specify the executable:

subprocess.call(['python.exe', 'hello.py', 'htmlfilename.htm'])

You'll need python.exe to be visible on the search path, or you could pass the full path to the executable file that is running the calling script:

import sys
subprocess.call([sys.executable, 'hello.py', 'htmlfilename.htm'])

Error: Cannot access file bin/Debug/... because it is being used by another process

I had the same issue in Visual Studio 2013. I'm not sure what caused this for my project, but I was able to fix it by cleaning the solution and rebuilding it.

  1. Build > Clean Solution
  2. Build > Rebuild Solution

Javascript Src Path

src="/clock.js"

be careful it's root of the domain.

P.S. and please use lowercase for attribute names.

Internet Explorer 11 detection

Edit 18 Nov 2016

This code also work (for those who prefer another solution , without using ActiveX)

var isIE11 = !!window.MSInputMethodContext && !!document.documentMode;
  // true on IE11
  // false on Edge and other IEs/browsers.

Original Answer

In order to check Ie11 , you can use this : ( tested)

(or run this)

!(window.ActiveXObject) && "ActiveXObject" in window

I have all VMS of IE :

enter image description here

enter image description here

enter image description here

enter image description here

Notice : this wont work for IE11 :

as you can see here , it returns true :

enter image description here

So what can we do :

Apparently , they added the machine bit space :

ie11 :

"Mozilla/5.0 (Windows NT 6.3; WOW64; Trident/7.0; .NET4.0E; .NET4.0C; .NET CLR 3.5.30729; .NET CLR 2.0.50727; .NET CLR 3.0.30729; rv:11.0) like Gecko"

ie12 :

"Mozilla/5.0 (Windows NT 6.3; Win64; x64; Trident/7.0; .NET4.0E; .NET4.0C; .NET CLR 3.5.30729; .NET CLR 2.0.50727; .NET CLR 3.0.30729; rv:11.0) like Gecko"

so we can do:

/x64|x32/ig.test(window.navigator.userAgent)

this will return true only for ie11.

HighCharts Hide Series Name from the Legend

showInLegend is a series-specific option that can hide the series from the legend. If the requirement is to hide the legends completely then it is better to use enabled: false property as shown below:

legend: { enabled: false }

More information about legend is here

How to create full path with node's fs.mkdirSync?

You can use the next function

const recursiveUpload = (path: string) => { const paths = path.split("/")

const fullPath = paths.reduce((accumulator, current) => {
  fs.mkdirSync(accumulator)
  return `${accumulator}/${current}`
  })

  fs.mkdirSync(fullPath)

  return fullPath
}

So what it does:

  1. Create paths variable, where it stores every path by itself as an element of the array.
  2. Adds "/" at the end of each element in the array.
  3. Makes for the cycle:
    1. Creates a directory from the concatenation of array elements which indexes are from 0 to current iteration. Basically, it is recursive.

Hope that helps!

By the way, in Node v10.12.0 you can use recursive path creation by giving it as the additional argument.

fs.mkdir('/tmp/a/apple', { recursive: true }, (err) => { if (err) throw err; });

https://nodejs.org/api/fs.html#fs_fs_mkdirsync_path_options

javascript windows alert with redirect function

Alert will block the program flow so you can just write the following.

echo ("<script LANGUAGE='JavaScript'>
    window.alert('Succesfully Updated');
    window.location.href='http://someplace.com';
    </script>");

LinkButton Send Value to Code Behind OnClick

Try and retrieve the text property of the link button in the code behind:

protected void ENameLinkBtn_Click (object sender, EventArgs e)
{
   string val = ((LinkButton)sender).Text
}

How can I generate random number in specific range in Android?

int min = 65;
int max = 80;

Random r = new Random();
int i1 = r.nextInt(max - min + 1) + min;

Note that nextInt(int max) returns an int between 0 inclusive and max exclusive. Hence the +1.

How to close activity and go back to previous activity in android

You have to use this in your MainActivity

 Intent intent = new Intent(context , yourActivity);

            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK |Intent.FLAG_ACTIVITY_MULTIPLE_TASK);
            context.startActivity(intent);

The flag will start multiple tasks that will keep your MainActivity, when you call finish it will kill the other activity and get you back to the MainActivity

How to create an empty array in Swift?

You could use

var firstNames: [String] = []

How to convert ASCII code (0-255) to its corresponding character?

upper answer only near solving the Problem. heres your answer:

Integer.decode(Character.toString(char c));

How to use hex color values

#ffffff are actually 3 color components in hexadecimal notation - red ff, green ff and blue ff. You can write hexadecimal notation in Swift using 0x prefix, e.g 0xFF

To simplify the conversion, let's create an initializer that takes integer (0 - 255) values:

extension UIColor {
   convenience init(red: Int, green: Int, blue: Int) {
       assert(red >= 0 && red <= 255, "Invalid red component")
       assert(green >= 0 && green <= 255, "Invalid green component")
       assert(blue >= 0 && blue <= 255, "Invalid blue component")

       self.init(red: CGFloat(red) / 255.0, green: CGFloat(green) / 255.0, blue: CGFloat(blue) / 255.0, alpha: 1.0)
   }

   convenience init(rgb: Int) {
       self.init(
           red: (rgb >> 16) & 0xFF,
           green: (rgb >> 8) & 0xFF,
           blue: rgb & 0xFF
       )
   }
}

Usage:

let color = UIColor(red: 0xFF, green: 0xFF, blue: 0xFF)
let color2 = UIColor(rgb: 0xFFFFFF)

How to get alpha?

Depending on your use case, you can simply use the native UIColor.withAlphaComponent method, e.g.

let semitransparentBlack = UIColor(rgb: 0x000000).withAlphaComponent(0.5)

Or you can add an additional (optional) parameter to the above methods:

convenience init(red: Int, green: Int, blue: Int, a: CGFloat = 1.0) {
    self.init(
        red: CGFloat(red) / 255.0,
        green: CGFloat(green) / 255.0,
        blue: CGFloat(blue) / 255.0,
        alpha: a
    )
}

convenience init(rgb: Int, a: CGFloat = 1.0) {
    self.init(
        red: (rgb >> 16) & 0xFF,
        green: (rgb >> 8) & 0xFF,
        blue: rgb & 0xFF,
        a: a
    )
}

(we cannot name the parameter alpha because of a name collision with the existing initializer).

Called as:

let color = UIColor(red: 0xFF, green: 0xFF, blue: 0xFF, a: 0.5)
let color2 = UIColor(rgb: 0xFFFFFF, a: 0.5)

To get the alpha as an integer 0-255, we can

convenience init(red: Int, green: Int, blue: Int, a: Int = 0xFF) {
    self.init(
        red: CGFloat(red) / 255.0,
        green: CGFloat(green) / 255.0,
        blue: CGFloat(blue) / 255.0,
        alpha: CGFloat(a) / 255.0
    )
}

// let's suppose alpha is the first component (ARGB)
convenience init(argb: Int) {
    self.init(
        red: (argb >> 16) & 0xFF,
        green: (argb >> 8) & 0xFF,
        blue: argb & 0xFF,
        a: (argb >> 24) & 0xFF
    )
}

Called as

let color = UIColor(red: 0xFF, green: 0xFF, blue: 0xFF, a: 0xFF)
let color2 = UIColor(argb: 0xFFFFFFFF)

Or a combination of the previous methods. There is absolutely no need to use strings.

Hive load CSV with commas in quoted fields

The problem is that Hive doesn't handle quoted texts. You either need to pre-process the data by changing the delimiter between the fields (e.g: with a Hadoop-streaming job) or you can also give a try to use a custom CSV SerDe which uses OpenCSV to parse the files.

invalid conversion from 'const char*' to 'char*'

First of all this code snippet

char *addr=NULL;
strcpy(addr,retstring().c_str());

is invalid because you did not allocate memory where you are going to copy retstring().c_str().

As for the error message then it is clear enough. The type of expression data.str().c_str() is const char * but the third parameter of the function is declared as char *. You may not assign an object of type const char * to an object of type char *. Either the function should define the third parameter as const char * if it does not change the object pointed by the third parameter or you may not pass argument of type const char *.

Retrieve column values of the selected row of a multicolumn Access listbox

For multicolumn listbox extract data from any column of selected row by

 listboxControl.List(listboxControl.ListIndex,col_num)

where col_num is required column ( 0 for first column)

How to create and write to a txt file using VBA

To elaborate on Ben's answer:

If you add a reference to Microsoft Scripting Runtime and correctly type the variable fso you can take advantage of autocompletion (Intellisense) and discover the other great features of FileSystemObject.

Here is a complete example module:

Option Explicit

' Go to Tools -> References... and check "Microsoft Scripting Runtime" to be able to use
' the FileSystemObject which has many useful features for handling files and folders
Public Sub SaveTextToFile()

    Dim filePath As String
    filePath = "C:\temp\MyTestFile.txt"

    ' The advantage of correctly typing fso as FileSystemObject is to make autocompletion
    ' (Intellisense) work, which helps you avoid typos and lets you discover other useful
    ' methods of the FileSystemObject
    Dim fso As FileSystemObject
    Set fso = New FileSystemObject
    Dim fileStream As TextStream

    ' Here the actual file is created and opened for write access
    Set fileStream = fso.CreateTextFile(filePath)

    ' Write something to the file
    fileStream.WriteLine "something"

    ' Close it, so it is not locked anymore
    fileStream.Close

    ' Here is another great method of the FileSystemObject that checks if a file exists
    If fso.FileExists(filePath) Then
        MsgBox "Yay! The file was created! :D"
    End If

    ' Explicitly setting objects to Nothing should not be necessary in most cases, but if
    ' you're writing macros for Microsoft Access, you may want to uncomment the following
    ' two lines (see https://stackoverflow.com/a/517202/2822719 for details):
    'Set fileStream = Nothing
    'Set fso = Nothing

End Sub

Node: log in a file instead of the console

Straight from nodejs's API docs on Console

const output = fs.createWriteStream('./stdout.log');
const errorOutput = fs.createWriteStream('./stderr.log');
// custom simple logger
const logger = new Console(output, errorOutput);
// use it like console
const count = 5;
logger.log('count: %d', count);
// in stdout.log: count 5

Tool for comparing 2 binary files in Windows

In Cygwin:

$cmp -bl <file1> <file2>

diffs binary offsets and values are in decimal and octal respectively.. Vladi.

Uncaught (in promise): Error: StaticInjectorError(AppModule)[options]

It also might be that you haven't declared you Dependency Injected service, as a provider in the component that you injected it to. That was my case :)

How to use group by with union in t-sql

with UnionTable as  
(
    SELECT a.id, a.time FROM dbo.a
    UNION
    SELECT b.id, b.time FROM dbo.b
) SELECT id FROM UnionTable GROUP BY id

Use of "global" keyword in Python

The keyword global is only useful to change or create global variables in a local context, although creating global variables is seldom considered a good solution.

def bob():
    me = "locally defined"    # Defined only in local context
    print(me)

bob()
print(me)     # Asking for a global variable

The above will give you:

locally defined
Traceback (most recent call last):
  File "file.py", line 9, in <module>
    print(me)
NameError: name 'me' is not defined

While if you use the global statement, the variable will become available "outside" the scope of the function, effectively becoming a global variable.

def bob():
    global me
    me = "locally defined"   # Defined locally but declared as global
    print(me)

bob()
print(me)     # Asking for a global variable

So the above code will give you:

locally defined
locally defined

In addition, due to the nature of python, you could also use global to declare functions, classes or other objects in a local context. Although I would advise against it since it causes nightmares if something goes wrong or needs debugging.

How do I fix a compilation error for unhandled exception on call to Thread.sleep()?

Thread.sleep can throw an InterruptedException which is a checked exception. All checked exceptions must either be caught and handled or else you must declare that your method can throw it. You need to do this whether or not the exception actually will be thrown. Not declaring a checked exception that your method can throw is a compile error.

You either need to catch it:

try {
    Thread.sleep(1000);
} catch (InterruptedException e) {
    e.printStackTrace();
    // handle the exception...        
    // For example consider calling Thread.currentThread().interrupt(); here.
}

Or declare that your method can throw an InterruptedException:

public static void main(String[]args) throws InterruptedException

Related

How to change angular port from 4200 to any other

you can also enter the below command in your angular cli where you normally enter npm start

ng serve --host "ip-address" --port "port-number"

Calculate text width with JavaScript

The Element.getClientRects() method returns a collection of DOMRect objects that indicate the bounding rectangles for each CSS border box in a client. The returned value is a collection of DOMRect objects, one for each CSS border box associated with the element. Each DOMRect object contains read-only left, top, right and bottom properties describing the border box, in pixels, with the top-left relative to the top-left of the viewport.

Element.getClientRects() by Mozilla Contributors is licensed under CC-BY-SA 2.5.

Summing up all returned rectangle widths yields the total text width in pixels.

_x000D_
_x000D_
document.getElementById('in').addEventListener('input', function (event) {_x000D_
    var span = document.getElementById('text-render')_x000D_
    span.innerText = event.target.value_x000D_
    var rects = span.getClientRects()_x000D_
    var widthSum = 0_x000D_
    for (var i = 0; i < rects.length; i++) {_x000D_
        widthSum += rects[i].right - rects[i].left_x000D_
    }_x000D_
    document.getElementById('width-sum').value = widthSum_x000D_
})
_x000D_
<p><textarea id='in'></textarea></p>_x000D_
<p><span id='text-render'></span></p>_x000D_
<p>Sum of all widths: <output id='width-sum'>0</output>px</p>
_x000D_
_x000D_
_x000D_

Code for best fit straight line of a scatter plot in python

Have implemented @Micah 's solution to generate a trendline with a few changes and thought I'd share:

  • Coded as a function
  • Option for a polynomial trendline (input order=2)
  • Function can also just return the coefficient of determination (R^2, input Rval=True)
  • More Numpy array optimisations

Code:

def trendline(xd, yd, order=1, c='r', alpha=1, Rval=False):
    """Make a line of best fit"""

    #Calculate trendline
    coeffs = np.polyfit(xd, yd, order)

    intercept = coeffs[-1]
    slope = coeffs[-2]
    power = coeffs[0] if order == 2 else 0

    minxd = np.min(xd)
    maxxd = np.max(xd)

    xl = np.array([minxd, maxxd])
    yl = power * xl ** 2 + slope * xl + intercept

    #Plot trendline
    plt.plot(xl, yl, c, alpha=alpha)

    #Calculate R Squared
    p = np.poly1d(coeffs)

    ybar = np.sum(yd) / len(yd)
    ssreg = np.sum((p(xd) - ybar) ** 2)
    sstot = np.sum((yd - ybar) ** 2)
    Rsqr = ssreg / sstot

    if not Rval:
        #Plot R^2 value
        plt.text(0.8 * maxxd + 0.2 * minxd, 0.8 * np.max(yd) + 0.2 * np.min(yd),
                 '$R^2 = %0.2f$' % Rsqr)
    else:
        #Return the R^2 value:
        return Rsqr

Java Webservice Client (Best way)

You can find some resources related to developing web services client using Apache axis2 here.

http://today.java.net/pub/a/today/2006/12/13/invoking-web-services-using-apache-axis2.html

Below posts gives good explanations about developing web services using Apache axis2.

http://www.ibm.com/developerworks/opensource/library/ws-webaxis1/

http://wso2.org/library/136

Call two functions from same onclick

Try this

<input id ="btn" type="button" value="click" onclick="pay();cls()"/>

What is HTTP "Host" header?

The Host Header tells the webserver which virtual host to use (if set up). You can even have the same virtual host using several aliases (= domains and wildcard-domains). In this case, you still have the possibility to read that header manually in your web app if you want to provide different behavior based on different domains addressed. This is possible because in your webserver you can (and if I'm not mistaken you must) set up one vhost to be the default host. This default vhost is used whenever the host header does not match any of the configured virtual hosts.

That means: You get it right, although saying "multiple hosts" may be somewhat misleading: The host (the addressed machine) is the same, what really gets resolved to the IP address are different domain names (including subdomains) that are also referred to as hostnames (but not hosts!).


Although not part of the question, a fun fact: This specification led to problems with SSL in early days because the web server has to deliver the certificate that corresponds to the domain the client has addressed. However, in order to know what certificate to use, the webserver should have known the addressed hostname in advance. But because the client sends that information only over the encrypted channel (which means: after the certificate has already been sent), the server had to assume you browsed the default host. That meant one ssl-secured domain per IP address / port-combination.

This has been overcome with Server Name Indication; however, that again breaks some privacy, as the server name is now transferred in plain text again, so every man-in-the-middle would see which hostname you are trying to connect to.

Although the webserver would know the hostname from Server Name Indication, the Host header is not obsolete, because the Server Name Indication information is only used within the TLS handshake. With an unsecured connection, there is no Server Name Indication at all, so the Host header is still valid (and necessary).

Another fun fact: Most webservers (if not all) reject your HTTP request if it does not contain exactly one Host header, even if it could be omitted because there is only the default vhost configured. That means the minimum required information in an http-(get-)request is the first line containing METHOD RESOURCE and PROTOCOL VERSION and at least the Host header, like this:

GET /someresource.html HTTP/1.1
Host: www.example.com

In the MDN Documentation on the "Host" header they actually phrase it like this:

A Host header field must be sent in all HTTP/1.1 request messages. A 400 (Bad Request) status code will be sent to any HTTP/1.1 request message that lacks a Host header field or contains more than one.

As mentioned by Darrel Miller, the complete specs can be found in RFC7230.