Programs & Examples On #Mousehover

An event that is triggered when the Mouse moves over a GUI component

How to apply a CSS class on hover to dynamically generated submit buttons?

You have two options:

  1. Extend your .paging class definition:

    .paging:hover {
        border:1px solid #999;
        color:#000;
    }
    
  2. Use the DOM hierarchy to apply the CSS style:

    div.paginate input:hover {
        border:1px solid #999;
        color:#000;
    }
    

Can't perform a React state update on an unmounted component

Here is a React Hooks specific solution for

Error

Warning: Can't perform a React state update on an unmounted component.

Solution

You can declare let isMounted = true inside useEffect, which will be changed in the cleanup callback, as soon as the component is unmounted. Before state updates, you now check this variable conditionally:

useEffect(() => {
  let isMounted = true; // note this flag denote mount status
  someAsyncOperation().then(data => {
    if (isMounted) setState(data);
  })
  return () => { isMounted = false }; // use effect cleanup to set flag false, if unmounted
});

_x000D_
_x000D_
const Parent = () => {_x000D_
  const [mounted, setMounted] = useState(true);_x000D_
  return (_x000D_
    <div>_x000D_
      Parent:_x000D_
      <button onClick={() => setMounted(!mounted)}>_x000D_
        {mounted ? "Unmount" : "Mount"} Child_x000D_
      </button>_x000D_
      {mounted && <Child />}_x000D_
      <p>_x000D_
        Unmount Child, while it is still loading. It won't set state later on,_x000D_
        so no error is triggered._x000D_
      </p>_x000D_
    </div>_x000D_
  );_x000D_
};_x000D_
_x000D_
const Child = () => {_x000D_
  const [state, setState] = useState("loading (4 sec)...");_x000D_
  useEffect(() => {_x000D_
    let isMounted = true; // note this mounted flag_x000D_
    fetchData();_x000D_
    return () => {_x000D_
      isMounted = false;_x000D_
    }; // use effect cleanup to set flag false, if unmounted_x000D_
_x000D_
    // simulate some Web API fetching_x000D_
    function fetchData() {_x000D_
      setTimeout(() => {_x000D_
        // drop "if (isMounted)" to trigger error again_x000D_
        if (isMounted) setState("data fetched");_x000D_
      }, 4000);_x000D_
    }_x000D_
  }, []);_x000D_
_x000D_
  return <div>Child: {state}</div>;_x000D_
};_x000D_
_x000D_
ReactDOM.render(<Parent />, document.getElementById("root"));
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.13.0/umd/react.production.min.js" integrity="sha256-32Gmw5rBDXyMjg/73FgpukoTZdMrxuYW7tj8adbN8z4=" crossorigin="anonymous"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.13.0/umd/react-dom.production.min.js" integrity="sha256-bjQ42ac3EN0GqK40pC9gGi/YixvKyZ24qMP/9HiGW7w=" crossorigin="anonymous"></script>_x000D_
<div id="root"></div>_x000D_
<script>var { useReducer, useEffect, useState, useRef } = React</script>
_x000D_
_x000D_
_x000D_

Extension: Custom useAsync Hook

We can encapsulate all the boilerplate into a custom Hook, that just knows, how to deal with and automatically abort async functions in case the component unmounts before:

function useAsync(asyncFn, onSuccess) {
  useEffect(() => {
    let isMounted = true;
    asyncFn().then(data => {
      if (isMounted) onSuccess(data);
    });
    return () => { isMounted = false };
  }, [asyncFn, onSuccess]);
}

_x000D_
_x000D_
// use async operation with automatic abortion on unmount_x000D_
function useAsync(asyncFn, onSuccess) {_x000D_
  useEffect(() => {_x000D_
    let isMounted = true;_x000D_
    asyncFn().then(data => {_x000D_
      if (isMounted) onSuccess(data);_x000D_
    });_x000D_
    return () => {_x000D_
      isMounted = false;_x000D_
    };_x000D_
  }, [asyncFn, onSuccess]);_x000D_
}_x000D_
_x000D_
const Child = () => {_x000D_
  const [state, setState] = useState("loading (4 sec)...");_x000D_
  useAsync(delay, setState);_x000D_
  return <div>Child: {state}</div>;_x000D_
};_x000D_
_x000D_
const Parent = () => {_x000D_
  const [mounted, setMounted] = useState(true);_x000D_
  return (_x000D_
    <div>_x000D_
      Parent:_x000D_
      <button onClick={() => setMounted(!mounted)}>_x000D_
        {mounted ? "Unmount" : "Mount"} Child_x000D_
      </button>_x000D_
      {mounted && <Child />}_x000D_
      <p>_x000D_
        Unmount Child, while it is still loading. It won't set state later on,_x000D_
        so no error is triggered._x000D_
      </p>_x000D_
    </div>_x000D_
  );_x000D_
};_x000D_
_x000D_
const delay = () => new Promise(resolve => setTimeout(() => resolve("data fetched"), 4000));_x000D_
_x000D_
_x000D_
ReactDOM.render(<Parent />, document.getElementById("root"));
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.13.0/umd/react.production.min.js" integrity="sha256-32Gmw5rBDXyMjg/73FgpukoTZdMrxuYW7tj8adbN8z4=" crossorigin="anonymous"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.13.0/umd/react-dom.production.min.js" integrity="sha256-bjQ42ac3EN0GqK40pC9gGi/YixvKyZ24qMP/9HiGW7w=" crossorigin="anonymous"></script>_x000D_
<div id="root"></div>_x000D_
<script>var { useReducer, useEffect, useState, useRef } = React</script>
_x000D_
_x000D_
_x000D_

How can I show/hide component with JSF?

You should use <h:panelGroup ...> tag with attribute rendered. If you set true to rendered, the content of <h:panelGroup ...> won't be shown. Your XHTML file should have something like this:

<h:panelGroup rendered="#{userBean.showPassword}">
    <h:outputText id="password" value="#{userBean.password}"/>
</h:panelGroup>

UserBean.java:

import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
@ManagedBean
@SessionScoped
public class UserBean implements Serializable{
    private boolean showPassword = false;
    private String password = "";

    public boolean isShowPassword(){
        return showPassword;
    }
    public void setPassword(password){
        this.password = password;
    }
    public String getPassword(){
        return this.password;
    }
}

How to redirect output to a file and stdout

You can primarily use Zoredache solution, but If you don't want to overwrite the output file you should write tee with -a option as follow :

ls -lR / | tee -a output.file

The Response content must be a string or object implementing __toString(), "boolean" given after move to psql

So, rather return the whole object first, just wrap it to json_encode and then return it. This will return a proper and valid object.

public function id($id){
    $promotion = Promotion::find($id);
    return json_encode($promotion);
}

Or, For DB this will be just like,

public function id($id){
    $promotion = DB::table('promotions')->first();
    return json_encode($promotion);
}

I think it may help someone else.

How to check iOS version?

/*
 *  System Versioning Preprocessor Macros
 */ 

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

/*
 *  Usage
 */ 

if (SYSTEM_VERSION_LESS_THAN(@"4.0")) {
    ...
}

if (SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(@"3.1.1")) {
    ...
}

How to handle floats and decimal separators with html5 input type number

Appearently Browsers still have troubles (although Chrome and Firefox Nightly do fine). I have a hacky approach for the people that really have to use a number field (maybe because of the little arrows that text fields dont have).

My Solution

I added a keyup event Handler to the form input and tracked the state and set the value once it comes valid again.

Pure JS Snippet JSFIDDLE

_x000D_
_x000D_
var currentString = '';_x000D_
var badState = false;_x000D_
var lastCharacter = null;_x000D_
_x000D_
document.getElementById("field").addEventListener("keyup",($event) => {_x000D_
  if ($event.target.value && !$event.target.validity.badInput) {_x000D_
          currentString = $event.target.value;_x000D_
  } else if ($event.target.validity.badInput) {_x000D_
    if (badState && lastCharacter && lastCharacter.match(/[\.,]/) && !isNaN(+$event.key)) {_x000D_
      $event.target.value = ((+currentString) + (+$event.key / 10));_x000D_
      badState = false;_x000D_
    } else {_x000D_
      badState = true;_x000D_
    }_x000D_
  }_x000D_
  document.getElementById("number").textContent = $event.target.value;_x000D_
  lastCharacter = $event.key;_x000D_
});_x000D_
_x000D_
document.getElementById("field").addEventListener("blur",($event) => {_x000D_
 if (badState) {_x000D_
    $event.target.value = (+currentString);_x000D_
    badState = false;_x000D_
  document.getElementById("number").textContent = $event.target.value;_x000D_
  }_x000D_
});
_x000D_
#result{_x000D_
  padding: 10px;_x000D_
  background-color: orange;_x000D_
  font-size: 25px;_x000D_
  width: 400px;_x000D_
  margin-top: 10px;_x000D_
  display: inline-block;_x000D_
}_x000D_
_x000D_
#field{_x000D_
  padding: 5px;_x000D_
  border-radius: 5px;_x000D_
  border: 1px solid grey;_x000D_
  width: 400px;_x000D_
}
_x000D_
<input type="number" id="field" keyup="keyUpFunction" step="0.01" placeholder="Field for both comma separators">_x000D_
_x000D_
<span id="result" >_x000D_
 <span >Current value: </span>_x000D_
 <span id="number"></span>_x000D_
</span>
_x000D_
_x000D_
_x000D_

Angular 9 Snippet

_x000D_
_x000D_
@Directive({_x000D_
  selector: '[appFloatHelper]'_x000D_
})_x000D_
export class FloatHelperDirective {_x000D_
  private currentString = '';_x000D_
  private badState = false;_x000D_
  private lastCharacter: string = null;_x000D_
_x000D_
  @HostListener("blur", ['$event']) onBlur(event) {_x000D_
    if (this.badState) {_x000D_
      this.model.update.emit((+this.currentString));_x000D_
      this.badState = false;_x000D_
    }_x000D_
  }_x000D_
_x000D_
  constructor(private renderer: Renderer2, private el: ElementRef, private change: ChangeDetectorRef, private zone: NgZone, private model: NgModel) {_x000D_
    this.renderer.listen(this.el.nativeElement, 'keyup', (e: KeyboardEvent) => {_x000D_
      if (el.nativeElement.value && !el.nativeElement.validity.badInput) {_x000D_
        this.currentString = el.nativeElement.value;_x000D_
      } else if (el.nativeElement.validity.badInput) {_x000D_
        if (this.badState && this.lastCharacter && this.lastCharacter.match(/[\.,]/) && !isNaN(+e.key)) {_x000D_
          model.update.emit((+this.currentString) + (+e.key / 10));_x000D_
          el.nativeElement.value = (+this.currentString) + (+e.key / 10);_x000D_
          this.badState = false;_x000D_
        } else {_x000D_
          this.badState = true;_x000D_
        }_x000D_
      }       _x000D_
      this.lastCharacter = e.key;_x000D_
    });_x000D_
  }_x000D_
  _x000D_
}
_x000D_
<input type="number" matInput placeholder="Field for both comma separators" appFloatHelper [(ngModel)]="numberModel">
_x000D_
_x000D_
_x000D_

Find the line number where a specific word appears with "grep"

Use grep -n to get the line number of a match.

I don't think there's a way to get grep to start on a certain line number. For that, use sed. For example, to start at line 10 and print the line number and line for matching lines, use:

sed -n '10,$ { /regex/ { =; p; } }' file

To get only the line numbers, you could use

grep -n 'regex' | sed 's/^\([0-9]\+\):.*$/\1/'

Or you could simply use sed:

sed -n '/regex/=' file

Combining the two sed commands, you get:

sed -n '10,$ { /regex/= }' file

Determine if $.ajax error is a timeout

If your error event handler takes the three arguments (xmlhttprequest, textstatus, and message) when a timeout happens, the status arg will be 'timeout'.

Per the jQuery documentation:

Possible values for the second argument (besides null) are "timeout", "error", "notmodified" and "parsererror".

You can handle your error accordingly then.

I created this fiddle that demonstrates this.

$.ajax({
    url: "/ajax_json_echo/",
    type: "GET",
    dataType: "json",
    timeout: 1000,
    success: function(response) { alert(response); },
    error: function(xmlhttprequest, textstatus, message) {
        if(textstatus==="timeout") {
            alert("got timeout");
        } else {
            alert(textstatus);
        }
    }
});?

With jsFiddle, you can test ajax calls -- it will wait 2 seconds before responding. I put the timeout setting at 1 second, so it should error out and pass back a textstatus of 'timeout' to the error handler.

Hope this helps!

Windows Explorer "Command Prompt Here"

Almost the same as yours:

  • Alt+d, Ctrl+c
  • Win+r
  • cmd /K cd , Ctrl+v, ENTER

Add a new column to existing table in a migration

First rollback your previous migration

php artisan migrate:rollback

After that, you can modify your existing migration file (add new , rename or delete columns) then Re-Run your migration file

php artisan migrate

Scripting SQL Server permissions

Yes, you can use a script like this to generate another script

SET NOCOUNT ON;
DECLARE @NewRole varchar(100), @SourceRole varchar(100);

-- Change as needed
SELECT @SourceRole = 'Giver', @NewRole = 'Taker';

SELECT
    state_desc + ' ' + permission_name + ' ON ' + OBJECT_NAME(major_id) + ' TO ' + @NewRole
FROM
    sys.database_permissions
WHERE
    grantee_principal_id = DATABASE_PRINCIPAL_ID(@SourceRole) AND
    -- 0 = DB,  1 = object/column, 3 = schema. 1 is normally enough
    class <= 3

This is taken from my answer here

Convert np.array of type float64 to type uint8 scaling values

you can use skimage.img_as_ubyte(yourdata) it will make you numpy array ranges from 0->255

from skimage import img_as_ubyte

img = img_as_ubyte(data)
cv2.imshow("Window", img)

How can I find which tables reference a given table in Oracle SQL Developer?

SQL Developer 4.1, released in May of 2015, added a Model tab which shows table foreign keys which refer to your table in an Entity Relationship Diagram format.

commandButton/commandLink/ajax action/listener method not invoked or input value not set/updated

I would mention one more thing that concerns Primefaces's p:commandButton!

When you use a p:commandButton for the action that needs to be done on the server, you can not use type="button" because that is for Push buttons which are used to execute custom javascript without causing an ajax/non-ajax request to the server.

For this purpose, you can dispense the type attribute (default value is "submit") or you can explicitly use type="submit".

Hope this will help someone!

Rails 4 - Strong Parameters - Nested Objects

If it is Rails 5, because of new hash notation: params.permit(:name, groundtruth: [:type, coordinates:[]]) will work fine.

Access item in a list of lists

This code will print each individual number:

for myList in [[10,13,17],[3,5,1],[13,11,12]]:
    for item in myList:
        print(item)

Or for your specific use case:

((50 - List1[0][0]) + List1[0][1]) - List1[0][2]

How many bits is a "word"?

In addition to the other answers, a further example of the variability of word size (from one system to the next) is in the paper Smashing The Stack For Fun And Profit by Aleph One:

We must remember that memory can only be addressed in multiples of the word size. A word in our case is 4 bytes, or 32 bits. So our 5 byte buffer is really going to take 8 bytes (2 words) of memory, and our 10 byte buffer is going to take 12 bytes (3 words) of memory.

Is there a way to ignore a single FindBugs warning?

The FindBugs initial approach involves XML configuration files aka filters. This is really less convenient than the PMD solution but FindBugs works on bytecode, not on the source code, so comments are obviously not an option. Example:

<Match>
   <Class name="com.mycompany.Foo" />
   <Method name="bar" />
   <Bug pattern="DLS_DEAD_STORE_OF_CLASS_LITERAL" />
</Match>

However, to solve this issue, FindBugs later introduced another solution based on annotations (see SuppressFBWarnings) that you can use at the class or at the method level (more convenient than XML in my opinion). Example (maybe not the best one but, well, it's just an example):

@edu.umd.cs.findbugs.annotations.SuppressFBWarnings(
    value="HE_EQUALS_USE_HASHCODE", 
    justification="I know what I'm doing")

Note that since FindBugs 3.0.0 SuppressWarnings has been deprecated in favor of @SuppressFBWarnings because of the name clash with Java's SuppressWarnings.

How to change working directory in Jupyter Notebook?

on Jupyter notebook, try this:

pwd                  #this shows the current directory 

if this is not the directory you like and you would like to change, try this:

import os 
os.chdir ('THIS SHOULD BE YOUR DESIRED DIRECTORY')

Then try pwd again to see if the directory is what you want.

It works for me.

Remove or uninstall library previously added : cocoapods

  1. Remove pod name(which to remove) from Podfile and then
  2. Open Terminal, set project folder path
  3. Run pod install --no-integrate

Generate Java classes from .XSD files...?

Talking about JAXB limitation, a solution when having the same name for different attributes is adding inline jaxb customizations to the xsd:

+

. . binding declarations . .

or external customizations...

You can see further informations on : http://jaxb.java.net/tutorial/section_5_3-Overriding-Names.html

SQL Server : trigger how to read value for Insert, Update, Delete

There is no updated dynamic table. There is just inserted and deleted. On an UPDATE command, the old data is stored in the deleted dynamic table, and the new values are stored in the inserted dynamic table.

Think of an UPDATE as a DELETE/INSERT combination.

How to install a private NPM module without my own registry?

I use the following with a private github repository:

npm install github:mygithubuser/myproject

useState set method not reflecting change immediately

You can solve it by using the useRef hook but then it's will not re-render when it' updated. I have created a hooks called useStateRef, that give you the good from both worlds. It's like a state that when it's updated the Component re-render, and it's like a "ref" that always have the latest value.

See this example:

var [state,setState,ref]=useStateRef(0)

It works exactly like useState but in addition, it gives you the current state under ref.current

Learn more:

How do I get the scroll position of a document?

$(document).height() //returns window height

$(document).scrollTop() //returns scroll position from top of document

Efficient way to Handle ResultSet in Java

Here is the code little modified that i got it from google -

 List data_table = new ArrayList<>();
    Class.forName("oracle.jdbc.driver.OracleDriver");
            con = DriverManager.getConnection(conn_url, user_id, password);
            Statement stmt = con.createStatement();
            System.out.println("query_string: "+query_string);
            ResultSet rs = stmt.executeQuery(query_string);
            ResultSetMetaData rsmd = rs.getMetaData();


            int row_count = 0;
            while (rs.next()) {
                HashMap<String, String> data_map = new HashMap<>();
                if (row_count == 240001) {
                    break;
                }
                for (int i = 1; i <= rsmd.getColumnCount(); i++) {
                    data_map.put(rsmd.getColumnName(i), rs.getString(i));
                }
                data_table.add(data_map);
                row_count = row_count + 1;
            }
            rs.close();
            stmt.close();
            con.close();

What exactly is nullptr?

It is a keyword because the standard will specify it as such. ;-) According to the latest public draft (n2914)

2.14.7 Pointer literals [lex.nullptr]

pointer-literal:
nullptr

The pointer literal is the keyword nullptr. It is an rvalue of type std::nullptr_t.

It's useful because it does not implicitly convert to an integral value.

How to show live preview in a small popup of linked page on mouse over on link?

You can use an iframe to display a preview of the page on mouseover:

_x000D_
_x000D_
.box{_x000D_
    display: none;_x000D_
    width: 100%;_x000D_
}_x000D_
_x000D_
a:hover + .box,.box:hover{_x000D_
    display: block;_x000D_
    position: relative;_x000D_
    z-index: 100;_x000D_
}
_x000D_
This live preview for <a href="https://en.wikipedia.org/">Wikipedia</a>_x000D_
  <div class="box">_x000D_
    <iframe src="https://en.wikipedia.org/" width = "500px" height = "500px">_x000D_
    </iframe>_x000D_
  </div> _x000D_
remains open on mouseover.
_x000D_
_x000D_
_x000D_

Here's an example with multiple live previews:

_x000D_
_x000D_
.box{_x000D_
    display: none;_x000D_
    width: 100%;_x000D_
}_x000D_
_x000D_
a:hover + .box,.box:hover{_x000D_
    display: block;_x000D_
    position: relative;_x000D_
    z-index: 100;_x000D_
}
_x000D_
Live previews for <a href="https://en.wikipedia.org/">Wikipedia</a>_x000D_
  <div class="box">_x000D_
     <iframe src="https://en.wikipedia.org/" width = "500px" height = "500px">_x000D_
     </iframe>_x000D_
  </div> _x000D_
and <a href="https://www.jquery.com/">JQuery</a>_x000D_
  <div class="box">_x000D_
     <iframe src="https://www.jquery.com/" width = "500px" height = "500px">_x000D_
     </iframe>_x000D_
  </div> _x000D_
will appear when these links are moused over.
_x000D_
_x000D_
_x000D_

Using LIMIT within GROUP BY to get N results per group?

Please try below stored procedure. I have already verified. I am getting proper result but without using groupby.

CREATE DEFINER=`ks_root`@`%` PROCEDURE `first_five_record_per_id`()
BEGIN
DECLARE query_string text;
DECLARE datasource1 varchar(24);
DECLARE done INT DEFAULT 0;
DECLARE tenants varchar(50);
DECLARE cur1 CURSOR FOR SELECT rid FROM demo1;
DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = 1;

    SET @query_string='';

      OPEN cur1;
      read_loop: LOOP

      FETCH cur1 INTO tenants ;

      IF done THEN
        LEAVE read_loop;
      END IF;

      SET @datasource1 = tenants;
      SET @query_string = concat(@query_string,'(select * from demo  where `id` = ''',@datasource1,''' order by rate desc LIMIT 5) UNION ALL ');

       END LOOP; 
      close cur1;

    SET @query_string  = TRIM(TRAILING 'UNION ALL' FROM TRIM(@query_string));  
  select @query_string;
PREPARE stmt FROM @query_string;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;

END

Change value of input onchange?

You can't access your fieldname as a global variable. Use document.getElementById:

function updateInput(ish){
    document.getElementById("fieldname").value = ish;
}

and

onchange="updateInput(this.value)"

Make a link in the Android browser start up my app?

Try my simple trick:

        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            if(url.startsWith("classRegister:")) {                  
                Intent MnRegister = new Intent(getApplicationContext(), register.class); startActivity(MnRegister);
            }               
            view.loadUrl(url);
            return true;
        }

and my html link:

<a href="classRegister:true">Go to register.java</a>

or you can make < a href="classRegister:true" > <- "true" value for class filename

however this script work for mailto link :)

        if (url.startsWith("mailto:")) {
            String[] blah_email = url.split(":");
            Intent emailIntent = new Intent(android.content.Intent.ACTION_SEND);
            emailIntent.setType("text/plain");
            emailIntent.putExtra(android.content.Intent.EXTRA_EMAIL, new String[]{blah_email[1]});
            emailIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, what_ever_you_want_the_subject_to_be)");
            Log.v("NOTICE", "Sending Email to: " + blah_email[1] + " with subject: " + what_ever_you_want_the_subject_to_be);
            startActivity(emailIntent);
        }

Convert Float to Int in Swift

You can get an integer representation of your float by passing the float into the Integer initializer method.

Example:

Int(myFloat)

Keep in mind, that any numbers after the decimal point will be loss. Meaning, 3.9 is an Int of 3 and 8.99999 is an integer of 8.

Difference between numeric, float and decimal in SQL Server

Not a complete answer, but a useful link:

"I frequently do calculations against decimal values. In some cases casting decimal values to float ASAP, prior to any calculations, yields better accuracy. "

http://sqlblog.com/blogs/alexander_kuznetsov/archive/2008/12/20/for-better-precision-cast-decimals-before-calculations.aspx

Set android shape color programmatically

Expanding on Vikram's answer, if you are coloring dynamic views, like recycler view items, etc.... Then you probably want to call mutate() before you set the color. If you don't do this, any views that have a common drawable (i.e a background) will also have their drawable changed/colored.

public static void setBackgroundColorAndRetainShape(final int color, final Drawable background) {

    if (background instanceof ShapeDrawable) {
        ((ShapeDrawable) background.mutate()).getPaint().setColor(color);
    } else if (background instanceof GradientDrawable) {
        ((GradientDrawable) background.mutate()).setColor(color);
    } else if (background instanceof ColorDrawable) {
        ((ColorDrawable) background.mutate()).setColor(color);
    }else{
        Log.w(TAG,"Not a valid background type");
    }

}

Rails DateTime.now without Time

If you want today's date without the time, just use Date.today

How do I get into a non-password protected Java keystore or change the password?

Getting into a non-password protected Java keystore and changing the password can be done with a help of Java programming language itself.

That article contains the code for that:

thetechawesomeness.ideasmatter.info

How to remove the first Item from a list?

With list slicing, see the Python tutorial about lists for more details:

>>> l = [0, 1, 2, 3, 4]
>>> l[1:]
[1, 2, 3, 4]

How can I see what I am about to push with git?

For a list of files to be pushed, run:

git diff --stat --cached [remote/branch]

example:

git diff --stat --cached origin/master

For the code diff of the files to be pushed, run:

git diff [remote repo/branch]

To see full file paths of the files that will change, run:

git diff --numstat [remote repo/branch]

If you want to see these diffs in a GUI, you will need to configure git for that. See How do I view 'git diff' output with a visual diff program?.

C# Passing Function as Argument

Using the Func as mentioned above works but there are also delegates that do the same task and also define intent within the naming:

public delegate double MyFunction(double x);

public double Diff(double x, MyFunction f)
{
    double h = 0.0000001;

    return (f(x + h) - f(x)) / h;
}

public double MyFunctionMethod(double x)
{
    // Can add more complicated logic here
    return x + 10;
}

public void Client()
{
    double result = Diff(1.234, x => x * 456.1234);
    double secondResult = Diff(2.345, MyFunctionMethod);
}

What's the difference between emulation and simulation?

I was confused between the two processes. I found this simple explaination about the difference between Emulators and Simulators

  1. Simulator:
    Suppose you have written assembly program in a file and corresponding exe file is ready. The simulator is the pc software which reads the instructions from the exe and 'minmics' the operation of the processor.

  2. Emulator:
    Emulator is a (PC software + a processor). The Processor can be plugged into the TARGET BOARD when you want to test the developed software in real time to check run time bugs. When not in use it can be unplugged. The Processor will have a parallel or JTAG interface with the PC for downloading the exe file for execution.

Hence, whereas the Simulator is slow in execution, Emulator will be able to give real time verification of the developed code. Generally you will test your developed code on simulator first and then go for checking on emulator.

source : http://www.dsprelated.com/groups/c6x/show/148.php

Remove leading comma from a string

var s = ",'first string','more','even more'";  
s.split(/'?,'?/).filter(function(v) { return v; });

Results in:

["first string", "more", "even more'"]

First split with commas possibly surrounded by single quotes,
then filter the non-truthy (empty) parts out.

Java switch statement multiple cases

// Noncompliant Code Example

switch (i) {
  case 1:
    doFirstThing();
    doSomething();
    break;
  case 2:
    doSomethingDifferent();
    break;
  case 3:  // Noncompliant; duplicates case 1's implementation
    doFirstThing();
    doSomething();
    break;
  default:
    doTheRest();
}

if (a >= 0 && a < 10) {
  doFirstThing();

  doTheThing();
}
else if (a >= 10 && a < 20) {
  doTheOtherThing();
}
else if (a >= 20 && a < 50) {
  doFirstThing();
  doTheThing();  // Noncompliant; duplicates first condition
}
else {
  doTheRest();
}

//Compliant Solution

switch (i) {
  case 1:
  case 3:
    doFirstThing();
    doSomething();
    break;
  case 2:
    doSomethingDifferent();
    break;
  default:
    doTheRest();
}

if ((a >= 0 && a < 10) || (a >= 20 && a < 50)) {
  doFirstThing();
  doTheThing();
}
else if (a >= 10 && a < 20) {
  doTheOtherThing();
}
else {
  doTheRest();
}

How do I check if a column is empty or null in MySQL?

You can also do

SELECT * FROM table WHERE column_name LIKE ''

The inverse being

SELECT * FROM table WHERE column_name NOT LIKE ''

how to use "AND", "OR" for RewriteCond on Apache?

After many struggles and to achive a general, flexible and more readable solution, in my case I ended up saving the ORs results into ENV variables and doing the ANDs of those variables.

# RESULT_ONE = A OR B
RewriteRule ^ - [E=RESULT_ONE:False]
RewriteCond ...A... [OR]
RewriteCond ...B...
RewriteRule ^ - [E=RESULT_ONE:True]

# RESULT_TWO = C OR D
RewriteRule ^ - [E=RESULT_TWO:False]
RewriteCond ...C... [OR]
RewriteCond ...D...
RewriteRule ^ - [E=RESULT_TWO:True]

# if ( RESULT_ONE AND RESULT_TWO ) then ( RewriteRule ...something... )
RewriteCond %{ENV:RESULT_ONE} =True
RewriteCond %{ENV:RESULT_TWO} =True
RewriteRule ...something...

Requirements:

Delete/Reset all entries in Core Data?

Assuming you are using MagicalRecord and have a default persistence store:

I don't like all the solutions that assume certain files to exist and/or demand entering the entities names or classes. This is a Swift(2), safe way to delete all the data from all the entities. After deleting it will recreate a fresh stack too (I am actually not sure as to how neccessery this part is).

It's godo for "logout" style situations when you want to delete everything but have a working store and moc to get new data in (once the user logs in...)

extension NSManagedObject {

    class func dropAllData() {

        MagicalRecord.saveWithBlock({ context in

            for name in NSManagedObjectModel.MR_defaultManagedObjectModel().entitiesByName.keys {
                do { try self.deleteAll(name, context: context) }
                catch { print("?? ?? Error when deleting \(name): \(error)") }
            }

            }) { done, err in
                MagicalRecord.cleanUp()
                MagicalRecord.setupCoreDataStackWithStoreNamed("myStoreName")
        }
    }

    private class func deleteAll(name: String, context ctx: NSManagedObjectContext) throws {
        let all = NSFetchRequest(entityName: name)
        all.includesPropertyValues = false

        let allObjs = try ctx.executeFetchRequest(all)
        for obj in allObjs {
            obj.MR_deleteEntityInContext(ctx)
        }

    }
}

Explicit Return Type of Lambda

The return type of a lambda (in C++11) can be deduced, but only when there is exactly one statement, and that statement is a return statement that returns an expression (an initializer list is not an expression, for example). If you have a multi-statement lambda, then the return type is assumed to be void.

Therefore, you should do this:

  remove_if(rawLines.begin(), rawLines.end(), [&expression, &start, &end, &what, &flags](const string& line) -> bool
  {
    start = line.begin();
    end = line.end();
    bool temp = boost::regex_search(start, end, what, expression, flags);
    return temp;
  })

But really, your second expression is a lot more readable.

Exception is: InvalidOperationException - The current type, is an interface and cannot be constructed. Are you missing a type mapping?

May be You are not registering the Controllers. Try below code:

Step 1. Write your own controller factory class ControllerFactory :DefaultControllerFactory by implementing defaultcontrollerfactory in models folder

  public class ControllerFactory :DefaultControllerFactory
    {
    protected override IController GetControllerInstance(RequestContext         requestContext, Type controllerType)
        {
            try
            {
                if (controllerType == null)
                    throw new ArgumentNullException("controllerType");

                if (!typeof(IController).IsAssignableFrom(controllerType))
                    throw new ArgumentException(string.Format(
                        "Type requested is not a controller: {0}",
                        controllerType.Name),
                        "controllerType");

                return MvcUnityContainer.Container.Resolve(controllerType) as IController;
            }
            catch
            {
                return null;
            }

        }
        public static class MvcUnityContainer
        {
            public static UnityContainer Container { get; set; }
        }
    }

Step 2:Regigster it in BootStrap: inBuildUnityContainer method

private static IUnityContainer BuildUnityContainer()
    {
      var container = new UnityContainer();

      // register all your components with the container here
      // it is NOT necessary to register your controllers

      // e.g. container.RegisterType<ITestService, TestService>();    
      //RegisterTypes(container);
      container = new UnityContainer();
      container.RegisterType<IProductRepository, ProductRepository>();


      MvcUnityContainer.Container = container;
      return container;
    }

Step 3: In Global Asax.

protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();

            WebApiConfig.Register(GlobalConfiguration.Configuration);
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);
            AuthConfig.RegisterAuth();
            Bootstrapper.Initialise();
            ControllerBuilder.Current.SetControllerFactory(typeof(ControllerFactory));

        }

And you are done

How to use the ProGuard in Android Studio?

You're probably not actually signing the release build of the APK via the signing wizard. You can either build the release APK from the command line with the command:

./gradlew assembleRelease

or you can choose the release variant from the Build Variants view and build it from the GUI:

IDE main window showing Build Variants

Foreach Control in form, how can I do something to all the TextBoxes in my Form?

simple using linq, change as you see fit for whatever control your dealing with.

        private void DisableButtons()
    {
        foreach (var ctl in Controls.OfType<Button>())
        {
            ctl.Enabled = false;
        }
    }

    private void EnableButtons()
    {
        foreach (var ctl in Controls.OfType<Button>())
        {
            ctl.Enabled = true;
        }
    }

Compiling php with curl, where is curl installed?

None of these will allow you to compile PHP with cURL enabled.

In order to compile with cURL, you need libcurl header files (.h files). They are usually found in /usr/include/curl. They generally are bundled in a separate development package.

Per example, to install libcurl in Ubuntu:

sudo apt-get install libcurl4-gnutls-dev

Or CentOS:

sudo yum install curl-devel

Then you can just do:

./configure --with-curl # other options...

If you compile cURL manually, you can specify the path to the files without the lib or include suffix. (e.g.: /usr/local if cURL headers are in /usr/local/include/curl).

How can I delete a service in Windows?

Here is a vbs script that was passed down to me:

Set servicelist = GetObject("winmgmts:").InstancesOf ("Win32_Service")

for each service in servicelist
    sname = lcase(service.name)
    If sname = "NameOfMyService" Then 
        msgbox(sname)
        service.delete ' the internal name of your service
    end if
next

Why would a JavaScript variable start with a dollar sign?

In the context of AngularJS, the $ prefix is used only for identifiers in the framework's code. Users of the framework are instructed not to use it in their own identifiers:

Angular Namespaces $ and $$

To prevent accidental name collisions with your code, Angular prefixes names of public objects with $ and names of private objects with $$. Please do not use the $ or $$ prefix in your code.

Source: https://docs.angularjs.org/api

How to prevent page from reloading after form submit - JQuery

The <button> element, when placed in a form, will submit the form automatically unless otherwise specified. You can use the following 2 strategies:

  1. Use <button type="button"> to override default submission behavior
  2. Use event.preventDefault() in the onSubmit event to prevent form submission

Solution 1:

  • Advantage: simple change to markup
  • Disadvantage: subverts default form behavior, especially when JS is disabled. What if the user wants to hit "enter" to submit?

Insert extra type attribute to your button markup:

<button id="button" type="button" value="send" class="btn btn-primary">Submit</button>

Solution 2:

  • Advantage: form will work even when JS is disabled, and respects standard form UI/UX such that at least one button is used for submission

Prevent default form submission when button is clicked. Note that this is not the ideal solution because you should be in fact listening to the submit event, not the button click event:

$(document).ready(function () {
  // Listen to click event on the submit button
  $('#button').click(function (e) {

    e.preventDefault();

    var name = $("#name").val();
    var email = $("#email").val();

    $.post("process.php", {
      name: name,
      email: email
    }).complete(function() {
        console.log("Success");
      });
  });
});

Better variant:

In this improvement, we listen to the submit event emitted from the <form> element:

$(document).ready(function () {
  // Listen to submit event on the <form> itself!
  $('#main').submit(function (e) {

    e.preventDefault();

    var name = $("#name").val();
    var email = $("#email").val();

    $.post("process.php", {
      name: name,
      email: email
    }).complete(function() {
        console.log("Success");
      });
  });
});

Even better variant: use .serialize() to serialize your form, but remember to add name attributes to your input:

The name attribute is required for .serialize() to work, as per jQuery's documentation:

For a form element's value to be included in the serialized string, the element must have a name attribute.

<input type="text" id="name" name="name" class="form-control mb-2 mr-sm-2 mb-sm-0" id="inlineFormInput" placeholder="Jane Doe">
<input type="text" id="email" name="email" class="form-control" id="inlineFormInputGroup" placeholder="[email protected]">

And then in your JS:

$(document).ready(function () {
  // Listen to submit event on the <form> itself!
  $('#main').submit(function (e) {

    // Prevent form submission which refreshes page
    e.preventDefault();

    // Serialize data
    var formData = $(this).serialize();

    // Make AJAX request
    $.post("process.php", formData).complete(function() {
      console.log("Success");
    });
  });
});

How to stop an unstoppable zombie job on Jenkins without restarting the server?

If you have an unstoppable Pipeline job, try the following:

  1. Abort the job by clicking the red X next to the build progress bar
  2. Click on "Pause/resume" on the build to pause
  3. Click on "Pause/resume" again to resume the build

Pause/Resume pipeline job

Jenkins will realize that the job should be terminated and stops the build

Javascript Regular Expression Remove Spaces

In production and works across line breaks

This is used in several apps to clean user-generated content removing extra spacing/returns etc but retains the meaning of spaces.

text.replace(/[\n\r\s\t]+/g, ' ')

Programmatically change the src of an img tag

Give your img tag an id, then you can

document.getElementById("imageid").src="../template/save.png";

Sending email with PHP from an SMTP server

The problem is that PHP mail() function has a very limited functionality. There are several ways to send mail from PHP.

  1. mail() uses SMTP server on your system. There are at least two servers you can use on Windows: hMailServer and xmail. I spent several hours configuring and getting them up. First one is simpler in my opinion. Right now, hMailServer is working on Windows 7 x64.
  2. mail() uses SMTP server on remote or virtual machine with Linux. Of course, real mail service like Gmail doesn't allow direct connection without any credentials or keys. You can set up virtual machine or use one located in your LAN. Most linux distros have mail server out of the box. Configure it and have fun. I use default exim4 on Debian 7 that listens its LAN interface.
  3. Mailing libraries use direct connections. Libs are easier to set up. I used SwiftMailer and it perfectly sends mail from Gmail account. I think that PHPMailer is pretty good too.

No matter what choice is your, I recommend you use some abstraction layer. You can use PHP library on your development machine running Windows and simply mail() function on production machine with Linux. Abstraction layer allows you to interchange mail drivers depending on system which your application is running on. Create abstract MyMailer class or interface with abstract send() method. Inherit two classes MyPhpMailer and MySwiftMailer. Implement send() method in appropriate ways.

How do I check if the user is pressing a key?

In java you don't check if a key is pressed, instead you listen to KeyEvents. The right way to achieve your goal is to register a KeyEventDispatcher, and implement it to maintain the state of the desired key:

import java.awt.KeyEventDispatcher;
import java.awt.KeyboardFocusManager;
import java.awt.event.KeyEvent;

public class IsKeyPressed {
    private static volatile boolean wPressed = false;
    public static boolean isWPressed() {
        synchronized (IsKeyPressed.class) {
            return wPressed;
        }
    }

    public static void main(String[] args) {
        KeyboardFocusManager.getCurrentKeyboardFocusManager().addKeyEventDispatcher(new KeyEventDispatcher() {

            @Override
            public boolean dispatchKeyEvent(KeyEvent ke) {
                synchronized (IsKeyPressed.class) {
                    switch (ke.getID()) {
                    case KeyEvent.KEY_PRESSED:
                        if (ke.getKeyCode() == KeyEvent.VK_W) {
                            wPressed = true;
                        }
                        break;

                    case KeyEvent.KEY_RELEASED:
                        if (ke.getKeyCode() == KeyEvent.VK_W) {
                            wPressed = false;
                        }
                        break;
                    }
                    return false;
                }
            }
        });
    }
}

Then you can always use:

if (IsKeyPressed.isWPressed()) {
    // do your thing.
}

You can, of course, use same method to implement isPressing("<some key>") with a map of keys and their state wrapped inside IsKeyPressed.

Visual Studio 2015 Update 3 Offline Installer (ISO)

The ISO file that suggested in the accepted answer is still not complete. The very complete offline installer is about 24GB! There is only one way to get it. follow these steps:

  1. Download Web Installer from Microsoft Web Site
  2. Execute the Installer. NOTE: the installer is still a simple downloader for the real web-installer.
  3. After running the real web installer, Run Windows Task manager and find the real web installer path that is stored in your temp folder
  4. copy the real installer somewhere else. like C:\VS Community\
  5. Open Command Prompt and execute the installer that you copied to C:\VS Community\ with this argument: /Layout .
  6. Now installer will download the FULL offline installer to your selected folder!

Good Luck

How do I rename a column in a database table using SQL?

ALTER TABLE is standard SQL. But it's not completely implemented in many database systems.

Wait until ActiveWorkbook.RefreshAll finishes - VBA

If you're not married to using Excel Web Query, you might try opening the URL as a separate Workbook instead. Going that route lets you work on the resulting data once the web request completes, just like if you turn off "Enable background refresh."

The nice thing is though, Excel displays a progress bar during the request, instead of just freezing up / showing a load message in the destination cell.

See my answer on this question: How can I post-process the data from an Excel web query when the query is complete?

The tradeoff of that approach is you have to manage processing the data you get back yourself - Excel won't put it in a given destination for you.

We ended up going this route after we tried something pretty similar to what you seem to have been doing.

Avoid duplicates in INSERT INTO SELECT query in SQL Server

A simple DELETE before the INSERT would suffice:

DELETE FROM Table2 WHERE Id = (SELECT Id FROM Table1)
INSERT INTO Table2 (Id, name) SELECT Id, name FROM Table1

Switching Table1 for Table2 depending on which table's Id and name pairing you want to preserve.

Printing integer variable and string on same line in SQL

Double check if you have set and initial value for int and decimal values to be printed.

This sample is printing an empty line

declare @Number INT
print 'The number is : ' + CONVERT(VARCHAR, @Number)

And this sample is printing -> The number is : 1

declare @Number INT = 1
print 'The number is : ' + CONVERT(VARCHAR, @Number)

How to convert comma separated string into numeric array in javascript

You can use the String split method to get the single numbers as an array of strings. Then convert them to numbers with the unary plus operator, the Number function or parseInt, and add them to your array:

var arr = [1,2,3],
    strVale = "130,235,342,124 ";
var strings = strVale.split(",");
for (var i=0; i<strVale.length; i++)
    arr.push( + strings[i] );

Or, in one step, using Array map to convert them and applying them to one single push:

arr.push.apply(arr, strVale.split(",").map(Number));

How to do Base64 encoding in node.js?

crypto now supports base64 (reference):

cipher.final('base64') 

So you could simply do:

var cipher = crypto.createCipheriv('des-ede3-cbc', encryption_key, iv);
var ciph = cipher.update(plaintext, 'utf8', 'base64');
ciph += cipher.final('base64');

var decipher = crypto.createDecipheriv('des-ede3-cbc', encryption_key, iv);
var txt = decipher.update(ciph, 'base64', 'utf8');
txt += decipher.final('utf8');

Getting number of elements in an iterator in Python

Presumably, you want count the number of items without iterating through, so that the iterator is not exhausted, and you use it again later. This is possible with copy or deepcopy

import copy

def get_iter_len(iterator):
    return sum(1 for _ in copy.copy(iterator))

###############################################

iterator = range(0, 10)
print(get_iter_len(iterator))

if len(tuple(iterator)) > 1:
    print("Finding the length did not exhaust the iterator!")
else:
    print("oh no! it's all gone")

The output is "Finding the length did not exhaust the iterator!"

Optionally (and unadvisedly), you can shadow the built-in len function as follows:

import copy

def len(obj, *, len=len):
    try:
        if hasattr(obj, "__len__"):
            r = len(obj)
        elif hasattr(obj, "__next__"):
            r = sum(1 for _ in copy.copy(obj))
        else:
            r = len(obj)
    finally:
        pass
    return r

failed to resolve com.android.support:appcompat-v7:22 and com.android.support:recyclerview-v7:21.1.2

i solve it

change 22.0.0 to 21.0.3

dependencies {

 compile fileTree(dir: 'libs', include: ['*.jar'])

//compile 'com.android.support:appcompat-v7:22.0.0'

compile 'com.android.support:appcompat-v7:21.0.3'  }

maybe i have download the com.android.support:appcompat-v7:21.0.3 but have not got the compile 'com.android.support:appcompat-v7:22.0.0'

when i use SDK Manager update my support library and support repository , the problem dismissed.

Is it possible to refresh a single UITableViewCell in a UITableView?

Just to update these answers slightly with the new literal syntax in iOS 6--you can use Paths = @[indexPath] for a single object, or Paths = @[indexPath1, indexPath2,...] for multiple objects.

Personally, I've found the literal syntax for arrays and dictionaries to be immensely useful and big time savers. It's just easier to read, for one thing. And it removes the need for a nil at the end of any multi-object list, which has always been a personal bugaboo. We all have our windmills to tilt with, yes? ;-)

Just thought I'd throw this into the mix. Hope it helps.

Looping through array and removing items, without breaking for loop

There are lot of wonderful answers on this thread already. However I wanted to share my experience when I tried to solve "remove nth element from array" in ES5 context.

JavaScript arrays have different methods to add/remove elements from start or end. These are:

arr.push(ele) - To add element(s) at the end of the array 
arr.unshift(ele) - To add element(s) at the beginning of the array
arr.pop() - To remove last element from the array 
arr.shift() - To remove first element from the array 

Essentially none of the above methods can be used directly to remove nth element from the array.

A fact worth noting is that this is in contrast with java iterator's using which it is possible to remove nth element for a collection while iterating.

This basically leaves us with only one array method Array.splice to perform removal of nth element (there are other things you could do with these methods as well, but in the context of this question I am focusing on removal of elements):

Array.splice(index,1) - removes the element at the index 

Here is the code copied from original answer (with comments):

_x000D_
_x000D_
var arr = ["one", "two", "three", "four"];_x000D_
var i = arr.length; //initialize counter to array length _x000D_
_x000D_
while (i--) //decrement counter else it would run into IndexOutBounds exception_x000D_
{_x000D_
  if (arr[i] === "four" || arr[i] === "two") {_x000D_
    //splice modifies the original array_x000D_
    arr.splice(i, 1); //never runs into IndexOutBounds exception _x000D_
    console.log("Element removed. arr: ");_x000D_
_x000D_
  } else {_x000D_
    console.log("Element not removed. arr: ");_x000D_
  }_x000D_
  console.log(arr);_x000D_
}
_x000D_
_x000D_
_x000D_

Another noteworthy method is Array.slice. However the return type of this method is the removed elements. Also this doesn't modify original array. Modified code snippet as follows:

_x000D_
_x000D_
var arr = ["one", "two", "three", "four"];_x000D_
var i = arr.length; //initialize counter to array length _x000D_
_x000D_
while (i--) //decrement counter _x000D_
{_x000D_
  if (arr[i] === "four" || arr[i] === "two") {_x000D_
    console.log("Element removed. arr: ");_x000D_
    console.log(arr.slice(i, i + 1));_x000D_
    console.log("Original array: ");_x000D_
    console.log(arr);_x000D_
  }_x000D_
}
_x000D_
_x000D_
_x000D_

Having said that, we can still use Array.slice to remove nth element as shown below. However it is lot more code (hence inefficient)

_x000D_
_x000D_
var arr = ["one", "two", "three", "four"];_x000D_
var i = arr.length; //initialize counter to array length _x000D_
_x000D_
while (i--) //decrement counter _x000D_
{_x000D_
  if (arr[i] === "four" || arr[i] === "two") {_x000D_
    console.log("Array after removal of ith element: ");_x000D_
    arr = arr.slice(0, i).concat(arr.slice(i + 1));_x000D_
    console.log(arr);_x000D_
  }_x000D_
_x000D_
}
_x000D_
_x000D_
_x000D_

The Array.slice method is extremely important to achieve immutability in functional programming à la redux

Git - remote: Repository not found

For Mac

Open KeyChain Access and find your pssword account on password category ( you can search it on top right keychain access page)

when you find it , delete all keys related to your git source control. and try it again

enter image description here

[Ljava.lang.Object; cannot be cast to

Your query execution will return list of Object[].

List result_source = LoadSource.list();
for(Object[] objA : result_source) {
    // read it all
}

How to use stringstream to separate comma separated strings

#include <iostream>
#include <string>
#include <sstream>
using namespace std;
int main()
{
    std::string input = "abc,def,   ghi";
    std::istringstream ss(input);
    std::string token;
    size_t pos=-1;
    while(ss>>token) {
      while ((pos=token.rfind(',')) != std::string::npos) {
        token.erase(pos, 1);
      }
      std::cout << token << '\n';
    }
}

Declare variable in table valued function

There are two flavors of table valued functions. One that is just a select statement and one that can have more rows than just a select statement.

This can not have a variable:

create function Func() returns table
as
return
select 10 as ColName

You have to do like this instead:

create function Func()
returns @T table(ColName int)
as
begin
  declare @Var int
  set @Var = 10
  insert into @T(ColName) values (@Var)
  return
end

Comparing two java.util.Dates to see if they are in the same day

How about:

SimpleDateFormat fmt = new SimpleDateFormat("yyyyMMdd");
return fmt.format(date1).equals(fmt.format(date2));

You can also set the timezone to the SimpleDateFormat, if needed.

Connection pooling options with JDBC: DBCP vs C3P0

DBCP is out of date and not production grade. Some time back we conducted an in-house analysis of the two, creating a test fixture which generated load and concurrency against the two to assess their suitability under real life conditions.

DBCP consistently generated exceptions into our test application and struggled to reach levels of performance which C3P0 was more than capable of handling without any exceptions.

C3P0 also robustly handled DB disconnects and transparent reconnects on resume whereas DBCP never recovered connections if the link was taken out from beneath it. Worse still DBCP was returning Connection objects to the application for which the underlying transport had broken.

Since then we have used C3P0 in 4 major heavy-load consumer web apps and have never looked back.

UPDATE: It turns out that after many years of sitting on a shelf, the Apache Commons folk have taken DBCP out of dormancy and it is now, once again, an actively developed project. Thus my original post may be out of date.

That being said, I haven't yet experienced this new upgraded library's performance, nor heard of it being de-facto in any recent app framework, yet.

How to type in textbox using Selenium WebDriver (Selenium 2) with Java?

This is simple if you only use Selenium WebDriver, and forget the usage of Selenium-RC. I'd go like this.

WebDriver driver = new FirefoxDriver();
WebElement email = driver.findElement(By.id("email"));
email.sendKeys("[email protected]");

The reason for NullPointerException however is that your variable driver has never been started, you start FirefoxDriver in a variable wb thas is never being used.

How do you change text to bold in Android?

If you're drawing it then this will do it:

TextPaint.setFlags(Paint.FAKE_BOLD_TEXT_FLAG);

SQLAlchemy ORDER BY DESCENDING?

Complementary at @Radu answer, As in SQL, you can add the table name in the parameter if you have many table with the same attribute.

.order_by("TableName.name desc")

How do I get cURL to not show the progress bar?

Since curl 7.67.0 (2019-11-06) there is --no-progress-meter, which does exactly this, and nothing else. From the man page:

   --no-progress-meter
         Option to switch off the progress meter output without muting or
         otherwise affecting warning and informational messages like  -s,
         --silent does.

         Note  that  this  is the negated option name documented. You can
         thus use --progress-meter to enable the progress meter again.

         See also -v, --verbose and -s, --silent. Added in 7.67.0.

It's available in Ubuntu =20.04 and Debian =11 (Bullseye).

For a bit of history on curl's verbosity options, you can read Daniel Stenberg's blog post.

How to search for a string in cell array in MATLAB?

I guess the following code could do the trick:

strs = {'HA' 'KU' 'LA' 'MA' 'TATA'}
ind=find(ismember(strs,'KU'))

This returns

ans = 
     2

Currency formatting in Python

#printing the variable 'Total:' in a format that looks like this '9,348.237'

print ('Total:',   '{:7,.3f}'.format(zum1))

where the '{:7,.3f}' es the number of spaces for formatting the number in this case is a million with 3 decimal points. Then you add the '.format(zum1). The zum1 is tha variable that has the big number for the sum of all number in my particular program. Variable can be anything that you decide to use.

Drop default constraint on a column in TSQL

I would suggest:

DECLARE @sqlStatement nvarchar(MAX),
        @tableName nvarchar(50) = 'TripEvent',
        @columnName nvarchar(50) = 'CreatedDate';

SELECT                  @sqlStatement = 'ALTER TABLE ' + @tableName + ' DROP CONSTRAINT ' + dc.name + ';'
        FROM            sys.default_constraints AS dc
            LEFT JOIN   sys.columns AS sc
                ON      (dc.parent_column_id = sc.column_id)
        WHERE           dc.parent_object_id = OBJECT_ID(@tableName)
        AND         type_desc = 'DEFAULT_CONSTRAINT'
        AND         sc.name = @columnName
PRINT'   ['+@tableName+']:'+@@SERVERNAME+'.'+DB_NAME()+'@'+CONVERT(VarChar, GETDATE(), 127)+';  '+@sqlStatement;
IF(LEN(@sqlStatement)>0)EXEC sp_executesql @sqlStatement

How to make an array of arrays in Java

Like this:

String[][] arrays = { array1, array2, array3, array4, array5 };

or

String[][] arrays = new String[][] { array1, array2, array3, array4, array5 };

(The latter syntax can be used in assignments other than at the point of the variable declaration, whereas the shorter syntax only works with declarations.)

How to generate all permutations of a list?

for Python we can use itertools and import both permutations and combinations to solve your problem

from itertools import product, permutations
A = ([1,2,3])
print (list(permutations(sorted(A),2)))

Check date with todays date

public static boolean itIsToday(long date){
    boolean result = false;
    try{
        Calendar calendarData = Calendar.getInstance();
        calendarData.setTimeInMillis(date);
        calendarData.set(Calendar.HOUR_OF_DAY, 0);
        calendarData.set(Calendar.MINUTE, 0);
        calendarData.set(Calendar.SECOND, 0);
        calendarData.set(Calendar.MILLISECOND, 0);

        Calendar calendarToday = Calendar.getInstance();
        calendarToday.setTimeInMillis(System.currentTimeMillis());
        calendarToday.set(Calendar.HOUR_OF_DAY, 0);
        calendarToday.set(Calendar.MINUTE, 0);
        calendarToday.set(Calendar.SECOND, 0);
        calendarToday.set(Calendar.MILLISECOND, 0);

        if(calendarToday.getTimeInMillis() == calendarData.getTimeInMillis()) {
            result = true;
        }
    }catch (Exception exception){
        Log.e(TAG, exception);
    }
    return result;
}

How to enable file upload on React's Material UI simple input?

You can use Material UI's Input and InputLabel components. Here's an example if you were using them to input spreadsheet files.

import { Input, InputLabel } from "@material-ui/core";

const styles = {
  hidden: {
    display: "none",
  },
  importLabel: {
    color: "black",
  },
};

<InputLabel htmlFor="import-button" style={styles.importLabel}>
    <Input
        id="import-button"
        inputProps={{
          accept:
            ".csv, application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.ms-excel",
        }}
        onChange={onInputChange}
        style={styles.hidden}
        type="file"
    />
    Import Spreadsheet
</InputLabel>

PHP Converting Integer to Date, reverse of strtotime

The time() function displays the seconds between now and the unix epoch , 01 01 1970 (00:00:00 GMT). The strtotime() transforms a normal date format into a time() format. So the representation of that date into seconds will be : 1388516401

Source: http://www.php.net/time

Restoring MySQL database from physical files

From the answer of @Vicent, I already restore MySQL database as below:

Step 1. Shutdown Mysql server

Step 2. Copy database in your database folder (in linux, the default location is /var/lib/mysql). Keep same name of the database, and same name of database in mysql mode.

sudo cp -rf   /mnt/ubuntu_426/var/lib/mysql/database1 /var/lib/mysql/

Step 3: Change own and change mode the folder:

sudo chown -R mysql:mysql /var/lib/mysql/database1
sudo chmod -R 660 /var/lib/mysql/database1
sudo chown  mysql:mysql /var/lib/mysql/database1 
sudo chmod 700 /var/lib/mysql/database1

Step 4: Copy ibdata1 in your database folder

sudo cp /mnt/ubuntu_426/var/lib/mysql/ibdata1 /var/lib/mysql/

sudo chown mysql:mysql /var/lib/mysql/ibdata1

Step 5: copy ib_logfile0 and ib_logfile1 files in your database folder.

sudo cp /mnt/ubuntu_426/var/lib/mysql/ib_logfile0 /var/lib/mysql/

sudo cp /mnt/ubuntu_426/var/lib/mysql/ib_logfile1 /var/lib/mysql/

Remember change own and change root of those files:

sudo chown -R mysql:mysql /var/lib/mysql/ib_logfile0

sudo chown -R mysql:mysql /var/lib/mysql/ib_logfile1

or

sudo chown -R mysql:mysql /var/lib/mysql

Step 6 (Optional): My site has configuration to store files in a specific location, then I copy those to corresponding location, exactly.

Step 7: Start your Mysql server. Everything come back and enjoy it.

That is it.

See more info at: https://biolinh.wordpress.com/2017/04/01/restoring-mysql-database-from-physical-files-debianubuntu/

Remove an onclick listener

Just put,it has worked for me

itemView.setOnClickListener(null);

Shell Script Syntax Error: Unexpected End of File

I had this problem when running some script in cygwin. Fixed by running dos2unix on the script, with proper description of problem and solution given in that answer

how to activate a textbox if I select an other option in drop down box

Simply

<select id = 'color2'
        name = 'color'
        onchange = "if ($('#color2').val() == 'others') {
                      $('#color').show();
                    } else {
                      $('#color').hide();
                    }">
  <option value="red">RED</option>
  <option value="blue">BLUE</option>
  <option value="others">others</option>
</select>

<input type = 'text'
       name = 'color'
       id = 'color' />

edit: requires JQuery plugin

Set initial focus in an Android application

Use the code below,

TableRow _tableRow =(TableRow)findViewById(R.id.tableRowMainBody);
tableRow.requestFocus();

that should work.

Git error: src refspec master does not match any

You've created a new repository and added some files to the index, but you haven't created your first commit yet. After you've done:

 git add a_text_file.txt 

... do:

 git commit -m "Initial commit."

... and those errors should go away.

Make columns of equal width in <table>

Use following property same as table and its fully dynamic:

_x000D_
_x000D_
ul {_x000D_
    width: 100%;_x000D_
    display: table;_x000D_
    table-layout: fixed; /* optional, for equal spacing */_x000D_
    border-collapse: collapse;_x000D_
}_x000D_
li {_x000D_
    display: table-cell;_x000D_
    text-align: center;_x000D_
    border: 1px solid pink;_x000D_
    vertical-align: middle;_x000D_
}
_x000D_
<ul>_x000D_
  <li>foo<br>foo</li>_x000D_
  <li>barbarbarbarbar</li>_x000D_
  <li>baz klxjgkldjklg </li>_x000D_
  <li>baz</li>_x000D_
  <li>baz lds.jklklds</li>_x000D_
</ul>
_x000D_
_x000D_
_x000D_

May be its solve your issue.

Cannot deserialize the current JSON object (e.g. {"name":"value"}) into type 'System.Collections.Generic.List`1

As the error message is trying very hard to tell you, you can't deserialize a single object into a collection (List<>).

You want to deserialize into a single RootObject.

mysqli_fetch_array while loop columns

Try this...

while($row = mysqli_fetch_array($result, MYSQLI_ASSOC)) {

what do <form action="#"> and <form method="post" action="#"> do?

Action normally specifies the file/page that the form is submitted to (using the method described in the method paramater (post, get etc.))

An action of # indicates that the form stays on the same page, simply suffixing the url with a #. Similar use occurs in anchors. <a href=#">Link</a> for example, will stay on the same page.

Thus, the form is submitted to the same page, which then processes the data etc.

JQuery get all elements by class name

With the code in the question, you're only dealing interacting with the first of the four entries returned by that selector.

Code below as a fiddle: https://jsfiddle.net/c4nhpqgb/

I want to be overly clear that you have four items that matched that selector, so you need to deal with each explicitly. Using eq() is a little more explicit making this point than the answers using map, though map or each is what you'd probably use "in real life" (jquery docs for eq here).

<html>
    <head>
        <script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js" ></script>
    </head>

    <body>
        <div class="mbox">Block One</div>
        <div class="mbox">Block Two</div>
        <div class="mbox">Block Three</div>
        <div class="mbox">Block Four</div>

        <div id="outige"></div>
        <script>
            // using the $ prefix to use the "jQuery wrapped var" convention
            var i, $mvar = $('.mbox');

            // convenience method to display unprocessed html on the same page
            function logit( string )
            {
                var text = document.createTextNode( string );
                $('#outige').append(text);
                $('#outige').append("<br>");
            }

            logit($mvar.length);

            for (i=0; i<$mvar.length; i++)    {
                logit($mvar.eq(i).html());
            }
        </script>
    </body>

</html>

Output from logit calls (after the initial four div's display):

4
Block One
Block Two
Block Three
Block Four

How do I list loaded plugins in Vim?

Not a VIM user myself, so forgive me if this is totally offbase. But according to what I gather from the following VIM Tips site:

" where was an option set  
:scriptnames            : list all plugins, _vimrcs loaded (super)  
:verbose set history?   : reveals value of history and where set  
:function               : list functions  
:func SearchCompl       : List particular function

What is the difference between git clone and checkout?

git clone is to fetch your repositories from the remote git server.

git checkout is to checkout your desired status of your repository (like branches or particular files).

E.g., you are currently on master branch and you want to switch into develop branch.

git checkout develop_branch

E.g., you want to checkout to a particular status of a particular file

git checkout commit_point_A -- <filename>

Here is a good reference for you to learn Git, lets you understand much more easily.

How to use NSURLConnection to connect with SSL for an untrusted cert?

I posted some gist code (based on someone else's work which I note) that lets you properly authenticate against a self generated certificate (and how to get a free certificate - see comments bottom of Cocoanetics)

My code is here github

libc++abi.dylib: terminating with uncaught exception of type NSException (lldb)

Yet another possible cause:

In my case, I had a xib and was calling Bundle.main.loadNibNamed(... at which point it was crashing. All my IBOutlets and IBActions seemed fine. In the end I noticed that the nib was actually loading, but then when I tried to access the first (and only) view (nib.first), that was not working. In fact nib.count was returning a very large integer (max int?), instead of the expected 1. I tried re-adding the view, but still no luck.

In the end, I deleted the whole xib file and started again (but I kept some of the views in my clipboard so I can paste them instead of recreating them again).

This worked!

Proper way to use AJAX Post in jquery to pass model from strongly typed MVC3 view

You can skip the var declaration and the stringify. Otherwise, that will work just fine.

$.ajax({
    url: '/home/check',
    type: 'POST',
    data: {
        Address1: "423 Judy Road",
        Address2: "1001",
        City: "New York",
        State: "NY",
        ZipCode: "10301",
        Country: "USA"
    },
    contentType: 'application/json; charset=utf-8',
    success: function (data) {
        alert(data.success);
    },
    error: function () {
        alert("error");
    }
});

R: numeric 'envir' arg not of length one in predict()

There are several problems here:

  1. The newdata argument of predict() needs a predictor variable. You should thus pass it values for Coupon, instead of Total, which is the response variable in your model.

  2. The predictor variable needs to be passed in as a named column in a data frame, so that predict() knows what the numbers its been handed represent. (The need for this becomes clear when you consider more complicated models, having more than one predictor variable).

  3. For this to work, your original call should pass df in through the data argument, rather than using it directly in your formula. (This way, the name of the column in newdata will be able to match the name on the RHS of the formula).

With those changes incorporated, this will work:

model <- lm(Total ~ Coupon, data=df)
new <- data.frame(Coupon = df$Coupon)
predict(model, newdata = new, interval="confidence")

Getting the base url of the website and globally passing it to twig in Symfony 2

Base url is defined inside Symfony\Component\Routing\RequestContext.

It can be fetched from controller like this:

$this->container->get('router')->getContext()->getBaseUrl()

Linq on DataTable: select specific column into datatable, not whole table

Try Access DataTable easiest way which can help you for getting perfect idea for accessing DataTable, DataSet using Linq...

Consider following example, suppose we have DataTable like below.

DataTable ObjDt = new DataTable("List");
ObjDt.Columns.Add("WorkName", typeof(string));
ObjDt.Columns.Add("Price", typeof(decimal));
ObjDt.Columns.Add("Area", typeof(string));
ObjDt.Columns.Add("Quantity",typeof(int));
ObjDt.Columns.Add("Breath",typeof(decimal));
ObjDt.Columns.Add("Length",typeof(decimal));

Here above is the code for DatTable, here we assume that there are some data are available in this DataTable, and we have to bind Grid view of particular by processing some data as shown below.

Area | Quantity | Breath | Length | Price = Quantity * breath *Length

Than we have to fire following query which will give us exact result as we want.

var data = ObjDt.AsEnumerable().Select
            (r => new
            {
                Area = r.Field<string>("Area"),
                Que = r.Field<int>("Quantity"),
                Breath = r.Field<decimal>("Breath"),
                Length = r.Field<decimal>("Length"),
                totLen = r.Field<int>("Quantity") * (r.Field<decimal>("Breath") * r.Field<decimal>("Length"))
            }).ToList();

We just have to assign this data variable as Data Source.

By using this simple Linq query we can get all our accepts, and also we can perform all other LINQ queries with this…

How can I bind a background color in WPF/XAML?

I recommend reading the following blog post about debugging data binding: http://beacosta.com/blog/?p=52

And for this concrete issue: If you look at the compiler warnings, you will notice that you property has been hiding the Window.Background property (or Control or whatever class the property defines).

HashMap to return default value for non-found keys?

You can simply create a new class that inherits HashMap and add getDefault method. Here is a sample code:

public class DefaultHashMap<K,V> extends HashMap<K,V> {
    public V getDefault(K key, V defaultValue) {
        if (containsKey(key)) {
            return get(key);
        }

        return defaultValue;
    }
}

I think that you should not override get(K key) method in your implementation, because of the reasons specified by Ed Staub in his comment and because you will break the contract of Map interface (this can potentially lead to some hard-to-find bugs).

python JSON only get keys in first level

As Karthik mentioned, dct.keys() will work but it will return all the keys in dict_keys type not in list type. So if you want all the keys in a list, then list(dct.keys()) will work.

Get ASCII value at input word

char ch='A';

System.out.println((int)ch);

$.focus() not working

I also had this problem. The solution that worked in my case was using the tabindex property on the HTML element.

I was using ng-repeat for some li elements inside a list and I was not able to bring focus to the first li using .focus(), so I simply added the tabindex attribute to each li during the loop.

so now <li ng-repeat="user in users track by $index" tabindex="{{$index+1}}"></li>

That +1 was index starts from 0. Also make sure that the element is present in DOM before calling the .focus() function

I hope this helps.

The most accurate way to check JS object's type?

Old question I know. You don't need to convert it. See this function:

function getType( oObj )
{
    if( typeof oObj === "object" )
    {
          return ( oObj === null )?'Null':
          // Check if it is an alien object, for example created as {world:'hello'}
          ( typeof oObj.constructor !== "function" )?'Object':
          // else return object name (string)
          oObj.constructor.name;              
    }   

    // Test simple types (not constructed types)
    return ( typeof oObj === "boolean")?'Boolean':
           ( typeof oObj === "number")?'Number':
           ( typeof oObj === "string")?'String':
           ( typeof oObj === "function")?'Function':false;

}; 

Examples:

function MyObject() {}; // Just for example

console.log( getType( new String( "hello ") )); // String
console.log( getType( new Function() );         // Function
console.log( getType( {} ));                    // Object
console.log( getType( [] ));                    // Array
console.log( getType( new MyObject() ));        // MyObject

var bTest = false,
    uAny,  // Is undefined
    fTest  function() {};

 // Non constructed standard types
console.log( getType( bTest ));                 // Boolean
console.log( getType( 1.00 ));                  // Number
console.log( getType( 2000 ));                  // Number
console.log( getType( 'hello' ));               // String
console.log( getType( "hello" ));               // String
console.log( getType( fTest ));                 // Function
console.log( getType( uAny ));                  // false, cannot produce
                                                // a string

Low cost and simple.

Image resizing client-side with JavaScript before upload to the server

In my experience, this example has been the best solution for uploading a resized picture: https://zocada.com/compress-resize-images-javascript-browser/

It uses the HTML5 Canvas feature.

The code is as 'simple' as this:

compress(e) {
    const fileName = e.target.files[0].name;
    const reader = new FileReader();
    reader.readAsDataURL(e.target.files[0]);
    reader.onload = event => {
        const img = new Image();
        img.src = event.target.result;
        img.onload = () => {
                const elem = document.createElement('canvas');
                const width = Math.min(800, img.width);
                const scaleFactor = width / img.width;
                elem.width = width;
                elem.height = img.height * scaleFactor;

                const ctx = elem.getContext('2d');
                // img.width and img.height will contain the original dimensions
                ctx.drawImage(img, 0, 0, width, img.height * scaleFactor);
                ctx.canvas.toBlob((blob) => {
                    const file = new File([blob], fileName, {
                        type: 'image/jpeg',
                        lastModified: Date.now()
                    });
                }, 'image/jpeg', 1);
            },
            reader.onerror = error => console.log(error);
    };
}

There are two downsides with this solution.

The first one is related with the image rotation, due to ignoring EXIF data. I couldn't tackle this issue, and wasn't so important in my use case, but will be glad to hear any feedback.

The second downside is the lack of support foe IE/Edge (not the Chrome based version though), and I won't put any time on that.

How do I check if a variable is of a certain type (compare two types) in C?

For that purpose I have written a simple C program for that... It is in github...GitHub Link

Here how it works... First convert your double into a char string named s..

char s[50];
sprintf(s,"%.2f", yo);

Then use my dtype function to determine the type... My function will return a single character...You can use it like this...

char type=dtype(s);
//Return types are :
//i for integer
//f for float or decimals
//c for character...

Then you can use comparison to check it... That's it...

Private pages for a private Github repo

You could host password in a repository and then just hide the page behind hidden address, that is derived from that password. This is not a very secure way, but it is simple.

Demonstration

How should strace be used?

strace lists all system calls done by the process it's applied to. If you don't know what system calls mean, you won't be able to get much mileage from it.

Nevertheless, if your problem involves files or paths or environment values, running strace on the problematic program and redirecting the output to a file and then grepping that file for your path/file/env string may help you see what your program is actually attempting to do, as distinct from what you expected it to.

Angular 2: How to write a for loop, not a foreach loop

You can instantiate an empty array with a given number of entries if you pass an int to the Array constructor and then iterate over it via ngFor.

In your component code :

export class ForLoop {
  fakeArray = new Array(12);
}

In your template :

<ul>
  <li *ngFor="let a of fakeArray; let index = index">Something {{ index }}</li>
</ul>

The index properties give you the iteration number.

Live version

MySQL Where DateTime is greater than today

I guess you looking for CURDATE() or NOW() .

  SELECT name, datum 
  FROM tasks 
  WHERE datum >= CURDATE()

LooK the rsult of NOW and CURDATE

   NOW()                    CURDATE()        
   2008-11-11 12:45:34      2008-11-11       

How to get last items of a list in Python?

The last 9 elements can be read from left to right using numlist[-9:], or from right to left using numlist[:-10:-1], as you want.

>>> a=range(17)
>>> print a
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16]
>>> print a[-9:]
[8, 9, 10, 11, 12, 13, 14, 15, 16]
>>> print a[:-10:-1]
[16, 15, 14, 13, 12, 11, 10, 9, 8]

jQuery keypress() event not firing?

With jQuery, I've done it this way:

function checkKey(e){
     switch (e.keyCode) {
        case 40:
            alert('down');
            break;
        case 38:
            alert('up');
            break;
        case 37:
            alert('left');
            break;
        case 39:
            alert('right');
            break;
        default:
            alert('???');  
            }      
}

if ($.browser.mozilla) {
    $(document).keypress (checkKey);
} else {
    $(document).keydown (checkKey);
}

Also, try these plugins, which looks like they do all that work for you:

http://www.openjs.com/scripts/events/keyboard_shortcuts

http://www.webappers.com/2008/07/31/bind-a-hot-key-combination-with-jquery-hotkeys/

Java OCR implementation

Just found this one (don't know it, not tested, check yourself)

Ron Cemer Java OCR


As you only need this for curiosity you could look into the source of this applet.

It does OCR of handwritten characters with a neural network

Java OCR: Handwriting Recognition

Java String split removed empty values

you may have multiple separators, including whitespace characters, commas, semicolons, etc. take those in repeatable group with []+, like:

 String[] tokens = "a , b,  ,c; ;d,      ".split( "[,; \t\n\r]+" );

you'll have 4 tokens -- a, b, c, d

leading separators in the source string need to be removed before applying this split.

as answer to question asked:

String data = "5|6|7||8|9||";
String[] split = data.split("[\\| \t\n\r]+");

whitespaces added just in case if you'll have those as separators along with |

How do I create a table based on another table

select * into newtable from oldtable

Should I use @EJB or @Inject

Here is a good discussion on the topic. Gavin King recommends @Inject over @EJB for non remote EJBs.

http://www.seamframework.org/107780.lace

or

https://web.archive.org/web/20140812065624/http://www.seamframework.org/107780.lace

Re: Injecting with @EJB or @Inject?

  1. Nov 2009, 20:48 America/New_York | Link Gavin King

That error is very strange, since EJB local references should always be serializable. Bug in glassfish, perhaps?

Basically, @Inject is always better, since:

it is more typesafe,
it supports @Alternatives, and
it is aware of the scope of the injected object.

I recommend against the use of @EJB except for declaring references to remote EJBs.

and

Re: Injecting with @EJB or @Inject?

  1. Nov 2009, 17:42 America/New_York | Link Gavin King

    Does it mean @EJB better with remote EJBs?

For a remote EJB, we can't declare metadata like qualifiers, @Alternative, etc, on the bean class, since the client simply isn't going to have access to that metadata. Furthermore, some additional metadata must be specified that we don't need for the local case (global JNDI name of whatever). So all that stuff needs to go somewhere else: namely the @Produces declaration.

How to fix .pch file missing on build?

In case this is happening to you on a server build (AppCenter) and yo uaer using CocoaPods ensure that your Podfile is checked in.

AppCenter only runs the "pod install" command if it finds a Pofile and it DOES NOT find the PODS folder on the files.

I had the folder checked-in, but because git automatically ignores .pch files (check you .gitignore to veryfy this), my .pch weren'nt being checked in.

I sorted my issue by forcing the .pch files to check it, but Deleting the PODS folder should work too, since Appcenter will run the pod install command in that case.

Hoppefully this helps somebody.

Run-time error '1004' - Method 'Range' of object'_Global' failed

Change

Range(DataImportColumn & DataImportRow).Offset(0, 2).Value

to

Cells(DataImportRow,DataImportColumn).Value

When you just have the row and the column then you can use the cells() object. The syntax is Cells(Row,Column)

Also one more tip. You might want to fully qualify your Cells object. for example

ThisWorkbook.Sheets("WhatEver").Cells(DataImportRow,DataImportColumn).Value

PHP Curl UTF-8 Charset

$output = curl_exec($ch);
$result = iconv("Windows-1251", "UTF-8", $output);

How can I check if a value is a json object?

I don't really like the accepted answer. First and foremost it requires jQuery, which is not always available or required. Secondly, it does a full stringification of the object which to me is overkill. Here's a simple function that thoroughly detects whether a value is JSON-like, using nothing more than a few parts of the lodash library for genericity.

import * as isNull from 'lodash/isNull'
import * as isPlainObject from 'lodash/isPlainObject'
import * as isNumber from 'lodash/isNumber'
import * as isBoolean from 'lodash/isBoolean'
import * as isString from 'lodash/isString'
import * as isArray from 'lodash/isArray'

function isJSON(val) {
  if (isNull(val)
   || isBoolean(val)
   || isString(val))
    return true;
  if (isNumber(val)) 
     return !isNaN(val) && isFinite(val)
  if (isArray(val))
    return Array.prototype.every.call(val, isJSON)
  if (isPlainObject(val)) {
    for (const key of Object.keys(val)) {
      if (!isJSON(val[key]))
        return false
    }
    return true
  }
  return false
}

I've even taken the time to put it up in npm as a package: https://npmjs.com/package/is-json-object. Use it together with something like Webpack to get it in the browser.

Hope this helps someone!

What is CMake equivalent of 'configure --prefix=DIR && make all install '?

The ":PATH" part in the accepted answer can be omitted. This syntax may be more memorable:

cmake -DCMAKE_INSTALL_PREFIX=/usr . && make all install

...as used in the answers here.

Key Listeners in python?

There is a way to do key listeners in python. This functionality is available through pynput.

Command line:

$ pip install pynput

Python code:

from pynput import keyboard
# your code here

Angular - Use pipes in services and components

If you don't want do 'new myPipe()' because you're injecting dependencies to pipe, you can inject in component like provider and use without new.

Example:

    // In your component...

    import { Component, OnInit } from '@angular/core';
    import { myPipe} from './pipes';

    @Component({
      selector: 'my-component',
      template: '{{ data }}',
      providers: [ myPipe ]
    })
    export class MyComponent() implements OnInit {
      data = 'some data';
      constructor(private myPipe: myPipe) {}

      ngOnInit() {
        this.data = this.myPipe.transform(this.data);
      }
    }

How to add number of days to today's date?

you can try this and don't need JQuery: timeSolver.js

For example, add 5 day on today:

var newDay = timeSolver.add(new Date(),5,"day");

You also can add by hour, month...etc. please see for more infomation.

How can I find out what FOREIGN KEY constraint references a table in SQL Server?

I found this answer quite simple and did the trick for what I needed: https://stackoverflow.com/a/12956348/652519

A summary from the link, use this query:

EXEC sp_fkeys 'TableName'

Quick and simple. I was able to locate all the foreign key tables, respective columns and foreign key names of 15 tables pretty quickly.

As @mdisibio noted below, here's a link to the documentation that details the different parameters that can be used: https://docs.microsoft.com/en-us/sql/relational-databases/system-stored-procedures/sp-fkeys-transact-sql

How do I create documentation with Pydoc?

As RocketDonkey suggested, your module itself needs to have some docstrings.

For example, in myModule/__init__.py:

"""
The mod module
"""

You'd also want to generate documentation for each file in myModule/*.py using

pydoc myModule.thefilename

to make sure the generated files match the ones that are referenced from the main module documentation file.

Fetch API request timeout?

there's no timeout support in the fetch API yet. But it could be achieved by wrapping it in a promise.

for eg.

  function fetchWrapper(url, options, timeout) {
    return new Promise((resolve, reject) => {
      fetch(url, options).then(resolve, reject);

      if (timeout) {
        const e = new Error("Connection timed out");
        setTimeout(reject, timeout, e);
      }
    });
  }

How to end C++ code

To break a condition use the return(0);

So, in your case it would be:

    if(x==1)
    {
        return 0;
    }

Why can't I do <img src="C:/localfile.jpg">?

I have tried a lot of techniques and finally found one in C# side and JS Side. You cannot give a physical path to src attribute but you can give the base64 string as a src to Img tag. Lets look into the below C# code example.

<asp:Image ID="imgEvid" src="#" runat="server" Height="99px"/>

C# code

 if (File.Exists(filepath)
                            {
                                byte[] imageArray = System.IO.File.ReadAllBytes(filepath);
                                string base64ImageRepresentation = Convert.ToBase64String(imageArray);
                                var val = $"data: image/png; base64,{base64ImageRepresentation}";
                                imgEvid.Attributes.Add("src", val);
                            }

Hope this will help

Cannot start GlassFish 4.1 from within Netbeans 8.0.1 Service area

If you are using netbeans 7 and greater with oracle xe do the following on netbeans :

  1. go to services tab
  2. under servers, remove glassfish
  3. add back glassfish server
  4. input port number 9090 for http access

Glassfish can use that one if available or some random port number is created

Using async/await for multiple tasks

I was curious to see the results of the methods provided in the question as well as the accepted answer, so I put it to the test.

Here's the code:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;

namespace AsyncTest
{
    class Program
    {
        class Worker
        {
            public int Id;
            public int SleepTimeout;

            public async Task DoWork(DateTime testStart)
            {
                var workerStart = DateTime.Now;
                Console.WriteLine("Worker {0} started on thread {1}, beginning {2} seconds after test start.",
                    Id, Thread.CurrentThread.ManagedThreadId, (workerStart-testStart).TotalSeconds.ToString("F2"));
                await Task.Run(() => Thread.Sleep(SleepTimeout));
                var workerEnd = DateTime.Now;
                Console.WriteLine("Worker {0} stopped; the worker took {1} seconds, and it finished {2} seconds after the test start.",
                   Id, (workerEnd-workerStart).TotalSeconds.ToString("F2"), (workerEnd-testStart).TotalSeconds.ToString("F2"));
            }
        }

        static void Main(string[] args)
        {
            var workers = new List<Worker>
            {
                new Worker { Id = 1, SleepTimeout = 1000 },
                new Worker { Id = 2, SleepTimeout = 2000 },
                new Worker { Id = 3, SleepTimeout = 3000 },
                new Worker { Id = 4, SleepTimeout = 4000 },
                new Worker { Id = 5, SleepTimeout = 5000 },
            };

            var startTime = DateTime.Now;
            Console.WriteLine("Starting test: Parallel.ForEach...");
            PerformTest_ParallelForEach(workers, startTime);
            var endTime = DateTime.Now;
            Console.WriteLine("Test finished after {0} seconds.\n",
                (endTime - startTime).TotalSeconds.ToString("F2"));

            startTime = DateTime.Now;
            Console.WriteLine("Starting test: Task.WaitAll...");
            PerformTest_TaskWaitAll(workers, startTime);
            endTime = DateTime.Now;
            Console.WriteLine("Test finished after {0} seconds.\n",
                (endTime - startTime).TotalSeconds.ToString("F2"));

            startTime = DateTime.Now;
            Console.WriteLine("Starting test: Task.WhenAll...");
            var task = PerformTest_TaskWhenAll(workers, startTime);
            task.Wait();
            endTime = DateTime.Now;
            Console.WriteLine("Test finished after {0} seconds.\n",
                (endTime - startTime).TotalSeconds.ToString("F2"));

            Console.ReadKey();
        }

        static void PerformTest_ParallelForEach(List<Worker> workers, DateTime testStart)
        {
            Parallel.ForEach(workers, worker => worker.DoWork(testStart).Wait());
        }

        static void PerformTest_TaskWaitAll(List<Worker> workers, DateTime testStart)
        {
            Task.WaitAll(workers.Select(worker => worker.DoWork(testStart)).ToArray());
        }

        static Task PerformTest_TaskWhenAll(List<Worker> workers, DateTime testStart)
        {
            return Task.WhenAll(workers.Select(worker => worker.DoWork(testStart)));
        }
    }
}

And the resulting output:

Starting test: Parallel.ForEach...
Worker 1 started on thread 1, beginning 0.21 seconds after test start.
Worker 4 started on thread 5, beginning 0.21 seconds after test start.
Worker 2 started on thread 3, beginning 0.21 seconds after test start.
Worker 5 started on thread 6, beginning 0.21 seconds after test start.
Worker 3 started on thread 4, beginning 0.21 seconds after test start.
Worker 1 stopped; the worker took 1.90 seconds, and it finished 2.11 seconds after the test start.
Worker 2 stopped; the worker took 3.89 seconds, and it finished 4.10 seconds after the test start.
Worker 3 stopped; the worker took 5.89 seconds, and it finished 6.10 seconds after the test start.
Worker 4 stopped; the worker took 5.90 seconds, and it finished 6.11 seconds after the test start.
Worker 5 stopped; the worker took 8.89 seconds, and it finished 9.10 seconds after the test start.
Test finished after 9.10 seconds.

Starting test: Task.WaitAll...
Worker 1 started on thread 1, beginning 0.01 seconds after test start.
Worker 2 started on thread 1, beginning 0.01 seconds after test start.
Worker 3 started on thread 1, beginning 0.01 seconds after test start.
Worker 4 started on thread 1, beginning 0.01 seconds after test start.
Worker 5 started on thread 1, beginning 0.01 seconds after test start.
Worker 1 stopped; the worker took 1.00 seconds, and it finished 1.01 seconds after the test start.
Worker 2 stopped; the worker took 2.00 seconds, and it finished 2.01 seconds after the test start.
Worker 3 stopped; the worker took 3.00 seconds, and it finished 3.01 seconds after the test start.
Worker 4 stopped; the worker took 4.00 seconds, and it finished 4.01 seconds after the test start.
Worker 5 stopped; the worker took 5.00 seconds, and it finished 5.01 seconds after the test start.
Test finished after 5.01 seconds.

Starting test: Task.WhenAll...
Worker 1 started on thread 1, beginning 0.00 seconds after test start.
Worker 2 started on thread 1, beginning 0.00 seconds after test start.
Worker 3 started on thread 1, beginning 0.00 seconds after test start.
Worker 4 started on thread 1, beginning 0.00 seconds after test start.
Worker 5 started on thread 1, beginning 0.00 seconds after test start.
Worker 1 stopped; the worker took 1.00 seconds, and it finished 1.00 seconds after the test start.
Worker 2 stopped; the worker took 2.00 seconds, and it finished 2.00 seconds after the test start.
Worker 3 stopped; the worker took 3.00 seconds, and it finished 3.00 seconds after the test start.
Worker 4 stopped; the worker took 4.00 seconds, and it finished 4.00 seconds after the test start.
Worker 5 stopped; the worker took 5.00 seconds, and it finished 5.00 seconds after the test start.
Test finished after 5.00 seconds.

Javascript window.open pass values using POST

For what it's worth, here's the previously provided code encapsulated within a function.

openWindowWithPost("http://www.example.com/index.php", {
    p: "view.map",
    coords: encodeURIComponent(coords)
});

Function definition:

function openWindowWithPost(url, data) {
    var form = document.createElement("form");
    form.target = "_blank";
    form.method = "POST";
    form.action = url;
    form.style.display = "none";

    for (var key in data) {
        var input = document.createElement("input");
        input.type = "hidden";
        input.name = key;
        input.value = data[key];
        form.appendChild(input);
    }

    document.body.appendChild(form);
    form.submit();
    document.body.removeChild(form);
}

XmlSerializer: remove unnecessary xsi and xsd namespaces

I'm using:

public class Person
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
}

class Program
{
    static void Main(string[] args)
    {
        const string DEFAULT_NAMESPACE = "http://www.something.org/schema";
        var serializer = new XmlSerializer(typeof(Person), DEFAULT_NAMESPACE);
        var namespaces = new XmlSerializerNamespaces();
        namespaces.Add("", DEFAULT_NAMESPACE);

        using (var stream = new MemoryStream())
        {
            var someone = new Person
            {
                FirstName = "Donald",
                LastName = "Duck"
            };
            serializer.Serialize(stream, someone, namespaces);
            stream.Position = 0;
            using (var reader = new StreamReader(stream))
            {
                Console.WriteLine(reader.ReadToEnd());
            }
        }
    }
}

To get the following XML:

<?xml version="1.0"?>
<Person xmlns="http://www.something.org/schema">
  <FirstName>Donald</FirstName>
  <LastName>Duck</LastName>
</Person>

If you don't want the namespace, just set DEFAULT_NAMESPACE to "".

How do you reverse a string in place in JavaScript?

function reverse(str){
var s = "";
for (var i = str.length - 1; i >= 0; i--){
    s += str[i];
}
return s;
};
reverse("your string comes here")

check / uncheck checkbox using jquery?

For jQuery 1.6+ :

.attr() is deprecated for properties; use the new .prop() function instead as:

$('#myCheckbox').prop('checked', true); // Checks it
$('#myCheckbox').prop('checked', false); // Unchecks it

For jQuery < 1.6:

To check/uncheck a checkbox, use the attribute checked and alter that. With jQuery you can do:

$('#myCheckbox').attr('checked', true); // Checks it
$('#myCheckbox').attr('checked', false); // Unchecks it

Cause you know, in HTML, it would look something like:

<input type="checkbox" id="myCheckbox" checked="checked" /> <!-- Checked -->
<input type="checkbox" id="myCheckbox" /> <!-- Unchecked -->

However, you cannot trust the .attr() method to get the value of the checkbox (if you need to). You will have to rely in the .prop() method.

How to delete a specific line in a file?

This is a "fork" from @Lother's answer (which I believe that should be considered the right answer).


For a file like this:

$ cat file.txt 
1: october rust
2: november rain
3: december snow

This fork from Lother's solution works fine:

#!/usr/bin/python3.4

with open("file.txt","r+") as f:
    new_f = f.readlines()
    f.seek(0)
    for line in new_f:
        if "snow" not in line:
            f.write(line)
    f.truncate()

Improvements:

  • with open, which discard the usage of f.close()
  • more clearer if/else for evaluating if string is not present in the current line

Adding rows dynamically with jQuery

This will get you close, the add button has been removed out of the table so you might want to consider this...

<script type="text/javascript">
    $(document).ready(function() {
        $("#add").click(function() {
          $('#mytable tbody>tr:last').clone(true).insertAfter('#mytable tbody>tr:last');
          return false;
        });
    });
</script>

HTML markup looks like this

  <a  id="add">+</a></td>
  <table id="mytable" width="300" border="1" cellspacing="0" cellpadding="2">
  <tbody>
    <tr>
      <td>Name</td>
    </tr>
    <tr class="person">
      <td><input type="text" name="name" id="name" /></td>
    </tr>
    </tbody>
  </table>

EDIT To empty a value of a textbox after insert..

    $('#mytable tbody>tr:last').clone(true).insertAfter('#mytable tbody>tr:last');
    $('#mytable tbody>tr:last #name').val('');
    return false;

EDIT2 Couldn't help myself, to reset all dropdown lists in the inserted TR you can do this

$("#mytable tbody>tr:last").each(function() {this.reset();});           

I will leave the rest to you!

Ignore case in Python strings

You could translate each string to lowercase once --- lazily only when you need it, or as a prepass to the sort if you know you'll be sorting the entire collection of strings. There are several ways to attach this comparison key to the actual data being sorted, but these techniques should be addressed in a separate issue.

Note that this technique can be used not only to handle upper/lower case issues, but for other types of sorting such as locale specific sorting, or "Library-style" title sorting that ignores leading articles and otherwise normalizes the data before sorting it.

Use IntelliJ to generate class diagram

IntelliJ IDEA 14+

  • Show diagram popup

    Right click on a type/class/package > Diagrams > Show Diagram Popup...
    or Ctrl+Alt+U

  • Show diagram (opens a new tab)

    Right click on a type/class/package > Diagrams > Show Diagram...
    or Ctrl+Alt+Shift+U

    right click Diagrams Show Diagram

By default, you see only the classes/interfaces names. If you want to see more details, go to File > Settings... > Tools > Diagrams and check what you want (E.g.: Fields, Methods, etc.)


P.S.: You need IntelliJ IDEA Ultimate, because this feature is not supported in Community Edition. If you go to File > Settings... > Plugins, you can see that there is not UML Support plugin in Community Edition.

How can I get the height of an element using css only

Unfortunately, it is not possible to "get" the height of an element via CSS because CSS is not a language that returns any sort of data other than rules for the browser to adjust its styling.

Your resolution can be achieved with jQuery, or alternatively, you can fake it with CSS3's transform:translateY(); rule.


The CSS Route

If we assume that your target div in this instance is 200px high - this would mean that you want the div to have a margin of 190px?

This can be achieved by using the following CSS:

.dynamic-height {
    -webkit-transform: translateY(100%); //if your div is 200px, this will move it down by 200px, if it is 100px it will down by 100px etc
    transform: translateY(100%);         //if your div is 200px, this will move it down by 200px, if it is 100px it will down by 100px etc
    margin-top: -10px;
}

In this instance, it is important to remember that translateY(100%) will move the element in question downwards by a total of it's own length.

The problem with this route is that it will not push element below it out of the way, where a margin would.


The jQuery Route

If faking it isn't going to work for you, then your next best bet would be to implement a jQuery script to add the correct CSS for you.

jQuery(document).ready(function($){ //wait for the document to load
    $('.dynamic-height').each(function(){ //loop through each element with the .dynamic-height class
        $(this).css({
            'margin-top' : $(this).outerHeight() - 10 + 'px' //adjust the css rule for margin-top to equal the element height - 10px and add the measurement unit "px" for valid CSS
        });
    });
});

ImportError: No module named model_selection

To install scikit-learn version 18.0, I used both commands:

conda update scikit-learn

pip install -U scikit-learn

But it does not work. There was a problem "Cannot install 'scikit-learn'. It is a distutils installed project and thus we cannot accurately determine which files belong to it which would lead to only a partial uninstall".

Finally, i can install it by using following command:

pip install --user --upgrade scikit-learn==0.18.0

select records from postgres where timestamp is in certain range

Another option to make PostgreSQL use an index for your original query, is to create an index on the expression you are using:

create index arrival_year on reservations ( extract(year from arrival) );

That will open PostgreSQL with the possibility to use an index for

select * 
FROM reservations 
WHERE extract(year from arrival) = 2012;

Note that the expression in the index must be exactly the same expression as used in the where clause to make this work.

Getting a better understanding of callback functions in JavaScript

There are 3 main possibilities to execute a function:

var callback = function(x, y) {
    // "this" may be different depending how you call the function
    alert(this);
};
  1. callback(argument_1, argument_2);
  2. callback.call(some_object, argument_1, argument_2);
  3. callback.apply(some_object, [argument_1, argument_2]);

The method you choose depends whether:

  1. You have the arguments stored in an Array or as distinct variables.
  2. You want to call that function in the context of some object. In this case, using the "this" keyword in that callback would reference the object passed as argument in call() or apply(). If you don't want to pass the object context, use null or undefined. In the latter case the global object would be used for "this".

Docs for Function.call, Function.apply

How can I convert String to Int?

You can use either,

int i = Convert.ToInt32(TextBoxD1.Text);

or

int i = int.Parse(TextBoxD1.Text);

Capture key press (or keydown) event on DIV element

(1) Set the tabindex attribute:

<div id="mydiv" tabindex="0" />

(2) Bind to keydown:

 $('#mydiv').on('keydown', function(event) {
    //console.log(event.keyCode);
    switch(event.keyCode){
       //....your actions for the keys .....
    }
 });

To set the focus on start:

$(function() {
   $('#mydiv').focus();
});

To remove - if you don't like it - the div focus border, set outline: none in the CSS.

See the table of keycodes for more keyCode possibilities.

All of the code assuming you use jQuery.

#

Filtering DataGridView without changing datasource

A simpler way is to transverse the data, and hide the lines with the Visible property.

// Prevent exception when hiding rows out of view
CurrencyManager currencyManager = (CurrencyManager)BindingContext[dataGridView3.DataSource];
currencyManager.SuspendBinding();

// Show all lines
for (int u = 0; u < dataGridView3.RowCount; u++)
{
    dataGridView3.Rows[u].Visible = true;
    x++;
}

// Hide the ones that you want with the filter you want.
for (int u = 0; u < dataGridView3.RowCount; u++)
{
    if (dataGridView3.Rows[u].Cells[4].Value == "The filter string")
    {
        dataGridView3.Rows[u].Visible = true;
    }
    else
    {
        dataGridView3.Rows[u].Visible = false;
    }
}

// Resume data grid view binding
currencyManager.ResumeBinding();

Just an idea... it works for me.

Run Stored Procedure in SQL Developer?

--for setting buffer size needed most of time to avoid `anonymous block completed` message
set serveroutput on size 30000;

-- declaration block in case output need to catch
DECLARE
--declaration for in and out parameter
  V_OUT_1 NUMBER;
  V_OUT_2 VARCHAR2(200);
BEGIN

--your stored procedure name
   schema.package.procedure(
  --declaration for in and out parameter
    V_OUT_1 => V_OUT_1,
    V_OUT_2 => V_OUT_2
  );
  V_OUT_1 := V_OUT_1;
  V_OUT_2 := V_OUT_2;
  -- console output, no need to open DBMS OUTPUT seperatly
  -- also no need to print each output on seperat line 
  DBMS_OUTPUT.PUT_LINE('Ouput => ' || V_OUT_1 || ': ' || V_OUT_2);
END;

What does 'low in coupling and high in cohesion' mean

Long story short, low coupling as I understood it meant components can be swapped out without affecting the proper functioning of a system. Basicaly modulize your system into functioning components that can be updated individually without breaking the system

SQL Server Output Clause into a scalar variable

Way later but still worth mentioning is that you can also use variables to output values in the SET clause of an UPDATE or in the fields of a SELECT;

DECLARE @val1 int;
DECLARE @val2 int;
UPDATE [dbo].[PortalCounters_TEST]
SET @val1 = NextNum, @val2 = NextNum = NextNum + 1
WHERE [Condition] = 'unique value'
SELECT @val1, @val2

In the example above @val1 has the before value and @val2 has the after value although I suspect any changes from a trigger would not be in val2 so you'd have to go with the output table in that case. For anything but the simplest case, I think the output table will be more readable in your code as well.

One place this is very helpful is if you want to turn a column into a comma-separated list;

DECLARE @list varchar(max) = '';
DECLARE @comma varchar(2) = '';
SELECT @list = @list + @comma + County, @comma = ', ' FROM County
print @list

How do I view the SSIS packages in SQL Server Management Studio?

  1. you could find it under intergration services option in object explorer.
  2. you could find the packages under integration services catalog where all packages are deployed.

Can I change the checkbox size using CSS?

you can chnage the height and width in the code below

_x000D_
_x000D_
.checkmark {_x000D_
    position: absolute;_x000D_
    top: 0;_x000D_
    left: 0;_x000D_
    height: 20px;_x000D_
    width: 20px;_x000D_
    border-radius:5px;_x000D_
    border:1px solid #ff7e02;_x000D_
}
_x000D_
<div class="check">_x000D_
_x000D_
     <label class="container1">Architecture/Landscape_x000D_
            _x000D_
_x000D_
    <input type="checkbox" checked="checked">_x000D_
            _x000D_
_x000D_
    <span class="checkmark"></span>_x000D_
         _x000D_
_x000D_
 </label>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Application Error - The connection to the server was unsuccessful. (file:///android_asset/www/index.html)

For my case, the problem was due to losing of the internet connection in my WiFi.

printf with std::string?

It's compiling because printf isn't type safe, since it uses variable arguments in the C sense1. printf has no option for std::string, only a C-style string. Using something else in place of what it expects definitely won't give you the results you want. It's actually undefined behaviour, so anything at all could happen.

The easiest way to fix this, since you're using C++, is printing it normally with std::cout, since std::string supports that through operator overloading:

std::cout << "Follow this command: " << myString;

If, for some reason, you need to extract the C-style string, you can use the c_str() method of std::string to get a const char * that is null-terminated. Using your example:

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

int main()
{
    using namespace std;

    string myString = "Press ENTER to quit program!";
    cout << "Come up and C++ me some time." << endl;
    printf("Follow this command: %s", myString.c_str()); //note the use of c_str
    cin.get();

    return 0;
}

If you want a function that is like printf, but type safe, look into variadic templates (C++11, supported on all major compilers as of MSVC12). You can find an example of one here. There's nothing I know of implemented like that in the standard library, but there might be in Boost, specifically boost::format.


[1]: This means that you can pass any number of arguments, but the function relies on you to tell it the number and types of those arguments. In the case of printf, that means a string with encoded type information like %d meaning int. If you lie about the type or number, the function has no standard way of knowing, although some compilers have the ability to check and give warnings when you lie.

how to overwrite css style

You can add your styles in the required page after the external style sheet so they'll cascade and overwrite the first set of rules.

<link rel="stylesheet" href="allpages.css">
<style>
.flex-control-thumbs li {
  width: auto;
  float: none;
}
</style>

What regex will match every character except comma ',' or semi-colon ';'?

[^,;]+         

You haven't specified the regex implementation you are using. Most of them have a Split method that takes delimiters and split by them. You might want to use that one with a "normal" (without ^) character class:

[,;]+

error: function returns address of local variable

a is defined locally in the function, and can't be used outside the function. If you want to return a char array from the function, you'll need to allocate it dynamically:

char *a = malloc(1000);

And at some point call free on the returned pointer.

You should also see a warning at this line: char b = "blah";: you're trying to assign a string literal to a char.

How can I plot data with confidence intervals?

Here is a plotrix solution:

set.seed(0815)
x <- 1:10
F <- runif(10,1,2) 
L <- runif(10,0,1)
U <- runif(10,2,3)

require(plotrix)
plotCI(x, F, ui=U, li=L)

enter image description here

And here is a ggplot solution:

set.seed(0815)
df <- data.frame(x =1:10,
                 F =runif(10,1,2),
                 L =runif(10,0,1),
                 U =runif(10,2,3))

require(ggplot2)
ggplot(df, aes(x = x, y = F)) +
  geom_point(size = 4) +
  geom_errorbar(aes(ymax = U, ymin = L))

enter image description here

UPDATE: Here is a base solution to your edits:

set.seed(1234)
x <- rnorm(20)
df <- data.frame(x = x,
                 y = x + rnorm(20))

plot(y ~ x, data = df)

# model
mod <- lm(y ~ x, data = df)

# predicts + interval
newx <- seq(min(df$x), max(df$x), length.out=100)
preds <- predict(mod, newdata = data.frame(x=newx), 
                 interval = 'confidence')

# plot
plot(y ~ x, data = df, type = 'n')
# add fill
polygon(c(rev(newx), newx), c(rev(preds[ ,3]), preds[ ,2]), col = 'grey80', border = NA)
# model
abline(mod)
# intervals
lines(newx, preds[ ,3], lty = 'dashed', col = 'red')
lines(newx, preds[ ,2], lty = 'dashed', col = 'red')

enter image description here

exporting multiple modules in react.js

When you

import App from './App.jsx';

That means it will import whatever you export default. You can rename App class inside App.jsx to whatever you want as long as you export default it will work but you can only have one export default.

So you only need to export default App and you don't need to export the rest.

If you still want to export the rest of the components, you will need named export.

https://developer.mozilla.org/en/docs/web/javascript/reference/statements/export

How to copy a dictionary and only edit the copy

>>> dict2 = dict1
# dict2 is bind to the same Dict object which binds to dict1, so if you modify dict2, you will modify the dict1

There are many ways to copy Dict object, I simply use

dict_1 = {
           'a':1,
           'b':2
         }
dict_2 = {}
dict_2.update(dict_1)

Arrays vs Vectors: Introductory Similarities and Differences

I'll add that arrays are very low-level constructs in C++ and you should try to stay away from them as much as possible when "learning the ropes" -- even Bjarne Stroustrup recommends this (he's the designer of C++).

Vectors come very close to the same performance as arrays, but with a great many conveniences and safety features. You'll probably start using arrays when interfacing with API's that deal with raw arrays, or when building your own collections.

Vertically align text next to an image?

Another thing you can do is set the text's line-height to the size of the images within the <div>. Then set the images to vertical-align: middle;

That's seriously the easiest way.

How do I kill a VMware virtual machine that won't die?

Here's what I did based on

a) @Espo 's comments and
b) the fact that I only had Windows Task Manager to play with....

I logged onto the host machine, opened Task Manager and used the view menu to add the PID column to the Processes tab.

I wrote down (yes, with paper and a pen) the PID's for each and every instance of the vmware-wmx.exe process that was running on the box.

Using the VMWare console, I suspended the errant virtual machine.

When I resumed it, I could then identify the vmware-vmx process that corresponded to my machine and could kill it.

There doesn't seem to have been any ill effects so far.

ORDER BY date and time BEFORE GROUP BY name in mysql

As I am not allowed to comment on user1908688's answer, here a hint for MariaDB users:

SELECT *
FROM (
     SELECT *
     ORDER BY date ASC, time ASC
     LIMIT 18446744073709551615
     ) AS sub
GROUP BY sub.name

https://mariadb.com/kb/en/mariadb/why-is-order-by-in-a-from-subquery-ignored/

java.math.BigInteger cannot be cast to java.lang.Integer

As we see from the javaDoc, BigInteger is not a subclass of Integer:

java.lang.Object                      java.lang.Object
   java.lang.Number                       java.lang.Number
      java.math.BigInteger                    java.lang.Integer

And that's the reason why casting from BigInteger to Integer is impossible.

Casting of java primitives will do some conversion (like casting from double to int) while casting of types will never transform classes.

What should I use to open a url instead of urlopen in urllib3

You do not have to install urllib3. You can choose any HTTP-request-making library that fits your needs and feed the response to BeautifulSoup. The choice is though usually requests because of the rich feature set and convenient API. You can install requests by entering pip install requests in the command line. Here is a basic example:

from bs4 import BeautifulSoup
import requests

url = "url"
response = requests.get(url)

soup = BeautifulSoup(response.content, "html.parser")

Cannot ping AWS EC2 instance

I will like to mention some rare ISP induced problems. Occasionally following happends to me with BSNL. its one of those wierd problems that takes hours out of your daily life. In such case one might raise the issue with ISP or change ISP.

  1. Amazon instance can be accessed from browser (all open ports)
  2. Same cannot be pinged from console
  3. ssh / telnet doesnot works either.

What does the arrow operator, '->', do in Java?

It's a lambda expression.

It means that, from the listOfCars, arg0 is one of the items of that list. With that item he is going to do, hence the ->, whatever is inside of the brackets.

In this example, he's going to return a list of cars that fit the condition

Car.SEDAN == ((Car)arg0).getStyle();

Add support library to Android Studio project

Android no longer downloading the libraries from the SDK manager, it has to be accessed through Google's Maven repository.

You will have to do something similar to this in your build.gradle file:

allprojects {
    repositories {
        jcenter()
        maven {
            url "https://maven.google.com"
        }
    }
}



dependencies {
    ...
    compile "com.android.support:support-core-utils:27.0.2"
}

Find more details about the setting up process here and about the different support library revisions here.

scrollTop jquery, scrolling to div with id?

try this:

$('html, body').animate({scrollTop:$('#xxx').position().top}, 'slow');
$('#xxx').focus();

Where can I find the .apk file on my device, when I download any app and install?

You can do that I believe. It needs root permission. If you want to know where your apk files are stored, open a emulator and then go to

DDMS>File Explorer-> you can see a directory by name "data" -> Click on it and you will see a "app" folder.

Your apks are stored there. In fact just copying a apk directly to the folder works for me with emulators.

Git Bash won't run my python files?

Add following line in you .bashrc file

############################
# Environment path setting #
############################
export PATH=/c/Python27:/c/Python27/Scripts:$PATH

Laravel: How do I parse this json data in view blade?

For such case, you can do like this

@foreach (json_decode($leads->member) as $member)
     {{ $genre }}
@endforeach

Call a React component method from outside

I use this helper method to render components and return an component instance. Methods can be called on that instance.

static async renderComponentAt(componentClass, props, parentElementId){
         let componentId = props.id;
        if(!componentId){
            throw Error('Component has no id property. Please include id:"...xyz..." to component properties.');
        }

        let parentElement = document.getElementById(parentElementId);

        return await new Promise((resolve, reject) => {
            props.ref = (component)=>{
                resolve(component);
            };
            let element = React.createElement(componentClass, props, null);
            ReactDOM.render(element, parentElement);
        });
    }

How can I get the assembly file version

There are three versions: assembly, file, and product. They are used by different features and take on different default values if you don't explicit specify them.

string assemblyVersion = Assembly.GetExecutingAssembly().GetName().Version.ToString(); 
string assemblyVersion = Assembly.LoadFile("your assembly file").GetName().Version.ToString(); 
string fileVersion = FileVersionInfo.GetVersionInfo(Assembly.GetExecutingAssembly().Location).FileVersion; 
string productVersion = FileVersionInfo.GetVersionInfo(Assembly.GetExecutingAssembly().Location).ProductVersion;

The server principal is not able to access the database under the current security context in SQL Server MS 2012

SQL Logins are defined at the server level, and must be mapped to Users in specific databases.

In SSMS object explorer, under the server you want to modify, expand Security > Logins, then double-click the appropriate user which will bring up the "Login Properties" dialog.

Select User Mapping, which will show all databases on the server, with the ones having an existing mapping selected. From here you can select additional databases (and be sure to select which roles in each database that user should belong to), then click OK to add the mappings.

enter image description here

These mappings can become disconnected after a restore or similar operation. In this case, the user may still exist in the database but is not actually mapped to a login. If that happens, you can run the following to restore the login:

USE {database};
ALTER USER {user} WITH login = {login}

You can also delete the DB user and recreate it from the Login Properties dialog, but any role memberships or other settings would need to be recreated.

Simple two column html layout without using tables

Well, if you want the super easiest method, just put

<div class="left">left</div>
<div class="right">right</div>

.left {
    float: left;    
}

though you may need more than that depending on what other layout requirements you have.

JS how to cache a variable

You have three options:

  1. Cookies: https://developer.mozilla.org/en-US/docs/DOM/document.cookie
  2. DOMStorage (sessionStorage or localStorage): https://developer.mozilla.org/en-US/docs/DOM/Storage
  3. If your users are logged in, you could persist data in your server's DB that is keyed to a user (or group)

C#, Looping through dataset and show each record from a dataset column

foreach (DataRow dr in ds.Tables[0].Rows)
{
    //your code here
}

JQuery find first parent element with specific class prefix

Jquery later allowed you to to find the parents with the .parents() method.

Hence I recommend using:

var $div = $('#divid').parents('div[class^="div-a"]');

This gives all parent nodes matching the selector. To get the first parent matching the selector use:

var $div = $('#divid').parents('div[class^="div-a"]').eq(0);

For other such DOM traversal queries, check out the documentation on traversing the DOM.

How can I calculate the difference between two ArrayLists?

In Java, you can use the Collection interface's removeAll method.

// Create a couple ArrayList objects and populate them
// with some delicious fruits.
Collection firstList = new ArrayList() {{
    add("apple");
    add("orange");
}};

Collection secondList = new ArrayList() {{
    add("apple");
    add("orange");
    add("banana");
    add("strawberry");
}};

// Show the "before" lists
System.out.println("First List: " + firstList);
System.out.println("Second List: " + secondList);

// Remove all elements in firstList from secondList
secondList.removeAll(firstList);

// Show the "after" list
System.out.println("Result: " + secondList);

The above code will produce the following output:

First List: [apple, orange]
Second List: [apple, orange, banana, strawberry]
Result: [banana, strawberry]

Sql query to insert datetime in SQL Server

You will want to use the YYYYMMDD for unambiguous date determination in SQL Server.

insert into table1(approvaldate)values('20120618 10:34:09 AM');

If you are married to the dd-mm-yy hh:mm:ss xm format, you will need to use CONVERT with the specific style.

insert into table1 (approvaldate)
       values (convert(datetime,'18-06-12 10:34:09 PM',5));

5 here is the style for Italian dates. Well, not just Italians, but that's the culture it's attributed to in Books Online.

How to get a unix script to run every 15 seconds?

If you insist of running your script from cron:

* * * * * /foo/bar/your_script
* * * * * sleep 15; /foo/bar/your_script
* * * * * sleep 30; /foo/bar/your_script
* * * * * sleep 45; /foo/bar/your_script

and replace your script name&path to /foo/bar/your_script

Posting JSON Data to ASP.NET MVC

If you've got ther JSON data coming in as a string (e.g. '[{"id":1,"name":"Charles"},{"id":8,"name":"John"},{"id":13,"name":"Sally"}]')

Then I'd use JSON.net and use Linq to JSON to get the values out...

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{

    if (Request["items"] != null)
    {
        var items = Request["items"].ToString(); // Get the JSON string
        JArray o = JArray.Parse(items); // It is an array so parse into a JArray
        var a = o.SelectToken("[0].name").ToString(); // Get the name value of the 1st object in the array
        // a == "Charles"
    }
}
}

How do I make a request using HTTP basic authentication with PHP curl?

Michael Dowling's very actively maintained Guzzle is a good way to go. Apart from the elegant interface, asynchronous calling and PSR compliance, it makes the authentication headers for REST calls dead simple:

// Create a client with a base URL
$client = new GuzzleHttp\Client(['base_url' => 'http://myservices.io']);

// Send a request to http://myservices.io/status with basic authentication
$response = $client->get('/status', ['auth' => ['username', 'password']]);

See the docs.

Regular Expressions: Is there an AND operator?

Why not use awk?
with awk regex AND, OR matters is so simple

awk '/WORD1/ && /WORD2/ && /WORD3/' myfile

How to change the default message of the required field in the popover of form-control in bootstrap?

$("input[required]").attr("oninvalid", "this.setCustomValidity('Say Somthing!')");

this work if you move to previous or next field by mouse, but by enter key, this is not work !!!

Why does this iterative list-growing code give IndexError: list assignment index out of range?

j is an empty list, but you're attempting to write to element [0] in the first iteration, which doesn't exist yet.

Try the following instead, to add a new element to the end of the list:

for l in i:
    j.append(l)

Of course, you'd never do this in practice if all you wanted to do was to copy an existing list. You'd just do:

j = list(i)

Alternatively, if you wanted to use the Python list like an array in other languages, then you could pre-create a list with its elements set to a null value (None in the example below), and later, overwrite the values in specific positions:

i = [1, 2, 3, 5, 8, 13]
j = [None] * len(i)
#j == [None, None, None, None, None, None]
k = 0

for l in i:
   j[k] = l
   k += 1

The thing to realise is that a list object will not allow you to assign a value to an index that doesn't exist.

How to click on hidden element in Selenium WebDriver?

If the <div> has id or name then you can use find_element_by_id or find_element_by_name

You can also try with class name, css and xpath

find_element_by_class_name
find_element_by_css_selector
find_element_by_xpath

How to select Python version in PyCharm?

File -> Settings

Preferences->Project Interpreter->Python Interpreters

If it's not listed add it.

enter image description here