This ruby-lang syntax. The correct answer is to check the ruby-lang documentation. All other explanations obfuscate.
"ruby-lang docs Abbreviated Assignment".
https://docs.ruby-lang.org/en/2.4.0/syntax/assignment_rdoc.html#label-Abbreviated+Assignment
This answer has been updated to Swift 3
I always think it is nice to have a very simple, self-contained example so that nothing is assumed when I am learning a new task. This answer is that for deleting UITableView
rows. The project performs like this:
This project is based on the UITableView example for Swift.
Create a new project and replace the ViewController.swift code with the following.
import UIKit
class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
// These strings will be the data for the table view cells
var animals: [String] = ["Horse", "Cow", "Camel", "Pig", "Sheep", "Goat"]
let cellReuseIdentifier = "cell"
@IBOutlet var tableView: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
// It is possible to do the following three things in the Interface Builder
// rather than in code if you prefer.
self.tableView.register(UITableViewCell.self, forCellReuseIdentifier: cellReuseIdentifier)
tableView.delegate = self
tableView.dataSource = self
}
// number of rows in table view
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.animals.count
}
// create a cell for each table view row
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell:UITableViewCell = self.tableView.dequeueReusableCell(withIdentifier: cellReuseIdentifier) as UITableViewCell!
cell.textLabel?.text = self.animals[indexPath.row]
return cell
}
// method to run when table view cell is tapped
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
print("You tapped cell number \(indexPath.row).")
}
// this method handles row deletion
func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
if editingStyle == .delete {
// remove the item from the data model
animals.remove(at: indexPath.row)
// delete the table view row
tableView.deleteRows(at: [indexPath], with: .fade)
} else if editingStyle == .insert {
// Not used in our example, but if you were adding a new row, this is where you would do it.
}
}
}
The single key method in the code above that enables row deletion is the last one. Here it is again for emphasis:
// this method handles row deletion
func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
if editingStyle == .delete {
// remove the item from the data model
animals.remove(at: indexPath.row)
// delete the table view row
tableView.deleteRows(at: [indexPath], with: .fade)
} else if editingStyle == .insert {
// Not used in our example, but if you were adding a new row, this is where you would do it.
}
}
Add a UITableView
to the View Controller in the storyboard. Use auto layout to pin the four sides of the table view to the edges of the View Controller. Control drag from the table view in the storyboard to the @IBOutlet var tableView: UITableView!
line in the code.
That's all. You should be able to run your app now and delete rows by swiping left and tapping "Delete".
Change the "Delete" button text
Add the following method:
func tableView(_ tableView: UITableView, titleForDeleteConfirmationButtonForRowAt indexPath: IndexPath) -> String? {
return "Erase"
}
Custom button actions
Add the following method.
func tableView(_ tableView: UITableView, editActionsForRowAt indexPath: IndexPath) -> [UITableViewRowAction]? {
// action one
let editAction = UITableViewRowAction(style: .default, title: "Edit", handler: { (action, indexPath) in
print("Edit tapped")
})
editAction.backgroundColor = UIColor.blue
// action two
let deleteAction = UITableViewRowAction(style: .default, title: "Delete", handler: { (action, indexPath) in
print("Delete tapped")
})
deleteAction.backgroundColor = UIColor.red
return [editAction, deleteAction]
}
Note that this is only available from iOS 8. See this answer for more details.
Updated for iOS 11
Actions can be placed either leading or trailing the cell using methods added to the UITableViewDelegate API in iOS 11.
func tableView(_ tableView: UITableView,
leadingSwipeActionsConfigurationForRowAt indexPath: IndexPath) -> UISwipeActionsConfiguration?
{
let editAction = UIContextualAction(style: .normal, title: "Edit", handler: { (ac:UIContextualAction, view:UIView, success:(Bool) -> Void) in
success(true)
})
editAction.backgroundColor = .blue
return UISwipeActionsConfiguration(actions: [editAction])
}
func tableView(_ tableView: UITableView,
trailingSwipeActionsConfigurationForRowAt indexPath: IndexPath) -> UISwipeActionsConfiguration?
{
let deleteAction = UIContextualAction(style: .normal, title: "Delete", handler: { (ac:UIContextualAction, view:UIView, success:(Bool) -> Void) in
success(true)
})
deleteAction.backgroundColor = .red
return UISwipeActionsConfiguration(actions: [deleteAction])
}
You should use the csv
module to read the tab-separated value file. Do not read it into memory in one go. Each row you read has all the information you need to write rows to the output CSV file, after all. Keep the output file open throughout.
import csv
with open('sample.txt', newline='') as tsvin, open('new.csv', 'w', newline='') as csvout:
tsvin = csv.reader(tsvin, delimiter='\t')
csvout = csv.writer(csvout)
for row in tsvin:
count = int(row[4])
if count > 0:
csvout.writerows([row[2:4] for _ in range(count)])
or, using the itertools
module to do the repeating with itertools.repeat()
:
from itertools import repeat
import csv
with open('sample.txt', newline='') as tsvin, open('new.csv', 'w', newline='') as csvout:
tsvin = csv.reader(tsvin, delimiter='\t')
csvout = csv.writer(csvout)
for row in tsvin:
count = int(row[4])
if count > 0:
csvout.writerows(repeat(row[2:4], count))
All those libraries are not the solution for the problem in this post. This libraries just open a webpage to the app on google play. Instead this Play core library has more consistent interface.
So I think this is the problem, ProGuard: it obfscates some classes enough https://stackoverflow.com/a/63650212/10117882
Method overloading is a compile time polymorphism, let's take an example to understand the concept.
class Person //person.java file
{
public static void main ( String[] args )
{
Eat e = new Eat();
e.eat(noodle); //line 6
}
void eat (Noodles n) //Noodles is a object line 8
{
}
void eat ( Pizza p) //Pizza is a object
{
}
}
In this example, Person has a eat method which represents that he can either eat Pizza or Noodles. That the method eat is overloaded when we compile this Person.java the compiler resolves the method call " e.eat(noodles) [which is at line 6] with the method definition specified in line 8 that is it method which takes noodles as parameter and the entire process is done by Compiler so it is Compile time Polymorphism. The process of replacement of the method call with method definition is called as binding, in this case, it is done by the compiler so it is called as early binding.
var responseData = //Fetch Data
string jsonData = JsonConvert.SerializeObject(responseData, Formatting.None);
System.IO.File.WriteAllText(Server.MapPath("~/JsonData/jsondata.txt"), jsonData);
Let me first repeat what others already said, by quoting from the article "Structured Programming with go to Statements" by Donald Knuth:
We should forget about small efficiencies, say about 97% of the time: premature optimization is the root of all evil.
Yet we should not pass up our opportunities in that critical 3%. A good programmer will not be lulled into complacency by such reasoning, he will be wise to look carefully at the critical code; but only after that code has been identified.
(emphasis by me)
So if you have identified that a seemingly trivial operation like the computation of the minimum of three numbers is the actual bottleneck (that is, the "critical 3%") in your application, then you may consider optimizing it.
And in this case, this is actually possible: The Math#min(double,double)
method in Java has very special semantics:
Returns the smaller of two double values. That is, the result is the value closer to negative infinity. If the arguments have the same value, the result is that same value. If either value is NaN, then the result is NaN. Unlike the numerical comparison operators, this method considers negative zero to be strictly smaller than positive zero. If one argument is positive zero and the other is negative zero, the result is negative zero.
One can have a look at the implementation, and see that it's actually rather complex:
public static double min(double a, double b) {
if (a != a)
return a; // a is NaN
if ((a == 0.0d) &&
(b == 0.0d) &&
(Double.doubleToRawLongBits(b) == negativeZeroDoubleBits)) {
// Raw conversion ok since NaN can't map to -0.0.
return b;
}
return (a <= b) ? a : b;
}
Now, it may be important to point out that this behavior is different from a simple comparison. This can easily be examined with the following example:
public class MinExample
{
public static void main(String[] args)
{
test(0.0, 1.0);
test(1.0, 0.0);
test(-0.0, 0.0);
test(Double.NaN, 1.0);
test(1.0, Double.NaN);
}
private static void test(double a, double b)
{
double minA = Math.min(a, b);
double minB = a < b ? a : b;
System.out.println("a: "+a);
System.out.println("b: "+b);
System.out.println("minA "+minA);
System.out.println("minB "+minB);
if (Double.doubleToRawLongBits(minA) !=
Double.doubleToRawLongBits(minB))
{
System.out.println(" -> Different results!");
}
System.out.println();
}
}
However: If the treatment of NaN
and positive/negative zero is not relevant for your application, you can replace the solution that is based on Math.min
with a solution that is based on a simple comparison, and see whether it makes a difference.
This will, of course, be application dependent. Here is a simple, artificial microbenchmark (to be taken with a grain of salt!)
import java.util.Random;
public class MinPerformance
{
public static void main(String[] args)
{
bench();
}
private static void bench()
{
int runs = 1000;
for (int size=10000; size<=100000; size+=10000)
{
Random random = new Random(0);
double data[] = new double[size];
for (int i=0; i<size; i++)
{
data[i] = random.nextDouble();
}
benchA(data, runs);
benchB(data, runs);
}
}
private static void benchA(double data[], int runs)
{
long before = System.nanoTime();
double sum = 0;
for (int r=0; r<runs; r++)
{
for (int i=0; i<data.length-3; i++)
{
sum += minA(data[i], data[i+1], data[i+2]);
}
}
long after = System.nanoTime();
System.out.println("A: length "+data.length+", time "+(after-before)/1e6+", result "+sum);
}
private static void benchB(double data[], int runs)
{
long before = System.nanoTime();
double sum = 0;
for (int r=0; r<runs; r++)
{
for (int i=0; i<data.length-3; i++)
{
sum += minB(data[i], data[i+1], data[i+2]);
}
}
long after = System.nanoTime();
System.out.println("B: length "+data.length+", time "+(after-before)/1e6+", result "+sum);
}
private static double minA(double a, double b, double c)
{
return Math.min(a, Math.min(b, c));
}
private static double minB(double a, double b, double c)
{
if (a < b)
{
if (a < c)
{
return a;
}
return c;
}
if (b < c)
{
return b;
}
return c;
}
}
(Disclaimer: Microbenchmarking in Java is an art, and for more reliable results, one should consider using JMH or Caliper).
Running this with JRE 1.8.0_31 may result in something like
....
A: length 90000, time 545.929078, result 2.247805342620906E7
B: length 90000, time 441.999193, result 2.247805342620906E7
A: length 100000, time 608.046928, result 2.5032781001456387E7
B: length 100000, time 493.747898, result 2.5032781001456387E7
This at least suggests that it might be possible to squeeze out a few percent here (again, in a very artifical example).
Analyzing this further, by looking at the hotspot disassembly output created with
java -server -XX:+UnlockDiagnosticVMOptions -XX:+TraceClassLoading -XX:+LogCompilation -XX:+PrintAssembly MinPerformance
one can see the optimized versions of both methods, minA
and minB
.
First, the output for the method that uses Math.min
:
Decoding compiled method 0x0000000002992310:
Code:
[Entry Point]
[Verified Entry Point]
[Constants]
# {method} {0x000000001c010910} 'minA' '(DDD)D' in 'MinPerformance'
# parm0: xmm0:xmm0 = double
# parm1: xmm1:xmm1 = double
# parm2: xmm2:xmm2 = double
# [sp+0x60] (sp of caller)
0x0000000002992480: mov %eax,-0x6000(%rsp)
0x0000000002992487: push %rbp
0x0000000002992488: sub $0x50,%rsp
0x000000000299248c: movabs $0x1c010cd0,%rsi
0x0000000002992496: mov 0x8(%rsi),%edi
0x0000000002992499: add $0x8,%edi
0x000000000299249c: mov %edi,0x8(%rsi)
0x000000000299249f: movabs $0x1c010908,%rsi ; {metadata({method} {0x000000001c010910} 'minA' '(DDD)D' in 'MinPerformance')}
0x00000000029924a9: and $0x3ff8,%edi
0x00000000029924af: cmp $0x0,%edi
0x00000000029924b2: je 0x00000000029924e8 ;*dload_0
; - MinPerformance::minA@0 (line 58)
0x00000000029924b8: vmovsd %xmm0,0x38(%rsp)
0x00000000029924be: vmovapd %xmm1,%xmm0
0x00000000029924c2: vmovapd %xmm2,%xmm1 ;*invokestatic min
; - MinPerformance::minA@4 (line 58)
0x00000000029924c6: nop
0x00000000029924c7: callq 0x00000000028c6360 ; OopMap{off=76}
;*invokestatic min
; - MinPerformance::minA@4 (line 58)
; {static_call}
0x00000000029924cc: vmovapd %xmm0,%xmm1 ;*invokestatic min
; - MinPerformance::minA@4 (line 58)
0x00000000029924d0: vmovsd 0x38(%rsp),%xmm0 ;*invokestatic min
; - MinPerformance::minA@7 (line 58)
0x00000000029924d6: nop
0x00000000029924d7: callq 0x00000000028c6360 ; OopMap{off=92}
;*invokestatic min
; - MinPerformance::minA@7 (line 58)
; {static_call}
0x00000000029924dc: add $0x50,%rsp
0x00000000029924e0: pop %rbp
0x00000000029924e1: test %eax,-0x27623e7(%rip) # 0x0000000000230100
; {poll_return}
0x00000000029924e7: retq
0x00000000029924e8: mov %rsi,0x8(%rsp)
0x00000000029924ed: movq $0xffffffffffffffff,(%rsp)
0x00000000029924f5: callq 0x000000000297e260 ; OopMap{off=122}
;*synchronization entry
; - MinPerformance::minA@-1 (line 58)
; {runtime_call}
0x00000000029924fa: jmp 0x00000000029924b8
0x00000000029924fc: nop
0x00000000029924fd: nop
0x00000000029924fe: mov 0x298(%r15),%rax
0x0000000002992505: movabs $0x0,%r10
0x000000000299250f: mov %r10,0x298(%r15)
0x0000000002992516: movabs $0x0,%r10
0x0000000002992520: mov %r10,0x2a0(%r15)
0x0000000002992527: add $0x50,%rsp
0x000000000299252b: pop %rbp
0x000000000299252c: jmpq 0x00000000028ec620 ; {runtime_call}
0x0000000002992531: hlt
0x0000000002992532: hlt
0x0000000002992533: hlt
0x0000000002992534: hlt
0x0000000002992535: hlt
0x0000000002992536: hlt
0x0000000002992537: hlt
0x0000000002992538: hlt
0x0000000002992539: hlt
0x000000000299253a: hlt
0x000000000299253b: hlt
0x000000000299253c: hlt
0x000000000299253d: hlt
0x000000000299253e: hlt
0x000000000299253f: hlt
[Stub Code]
0x0000000002992540: nop ; {no_reloc}
0x0000000002992541: nop
0x0000000002992542: nop
0x0000000002992543: nop
0x0000000002992544: nop
0x0000000002992545: movabs $0x0,%rbx ; {static_stub}
0x000000000299254f: jmpq 0x000000000299254f ; {runtime_call}
0x0000000002992554: nop
0x0000000002992555: movabs $0x0,%rbx ; {static_stub}
0x000000000299255f: jmpq 0x000000000299255f ; {runtime_call}
[Exception Handler]
0x0000000002992564: callq 0x000000000297b9e0 ; {runtime_call}
0x0000000002992569: mov %rsp,-0x28(%rsp)
0x000000000299256e: sub $0x80,%rsp
0x0000000002992575: mov %rax,0x78(%rsp)
0x000000000299257a: mov %rcx,0x70(%rsp)
0x000000000299257f: mov %rdx,0x68(%rsp)
0x0000000002992584: mov %rbx,0x60(%rsp)
0x0000000002992589: mov %rbp,0x50(%rsp)
0x000000000299258e: mov %rsi,0x48(%rsp)
0x0000000002992593: mov %rdi,0x40(%rsp)
0x0000000002992598: mov %r8,0x38(%rsp)
0x000000000299259d: mov %r9,0x30(%rsp)
0x00000000029925a2: mov %r10,0x28(%rsp)
0x00000000029925a7: mov %r11,0x20(%rsp)
0x00000000029925ac: mov %r12,0x18(%rsp)
0x00000000029925b1: mov %r13,0x10(%rsp)
0x00000000029925b6: mov %r14,0x8(%rsp)
0x00000000029925bb: mov %r15,(%rsp)
0x00000000029925bf: movabs $0x515db148,%rcx ; {external_word}
0x00000000029925c9: movabs $0x2992569,%rdx ; {internal_word}
0x00000000029925d3: mov %rsp,%r8
0x00000000029925d6: and $0xfffffffffffffff0,%rsp
0x00000000029925da: callq 0x00000000512a9020 ; {runtime_call}
0x00000000029925df: hlt
[Deopt Handler Code]
0x00000000029925e0: movabs $0x29925e0,%r10 ; {section_word}
0x00000000029925ea: push %r10
0x00000000029925ec: jmpq 0x00000000028c7340 ; {runtime_call}
0x00000000029925f1: hlt
0x00000000029925f2: hlt
0x00000000029925f3: hlt
0x00000000029925f4: hlt
0x00000000029925f5: hlt
0x00000000029925f6: hlt
0x00000000029925f7: hlt
One can see that the treatment of special cases involves some effort - compared to the output that uses simple comparisons, which is rather straightforward:
Decoding compiled method 0x0000000002998790:
Code:
[Entry Point]
[Verified Entry Point]
[Constants]
# {method} {0x000000001c0109c0} 'minB' '(DDD)D' in 'MinPerformance'
# parm0: xmm0:xmm0 = double
# parm1: xmm1:xmm1 = double
# parm2: xmm2:xmm2 = double
# [sp+0x20] (sp of caller)
0x00000000029988c0: sub $0x18,%rsp
0x00000000029988c7: mov %rbp,0x10(%rsp) ;*synchronization entry
; - MinPerformance::minB@-1 (line 63)
0x00000000029988cc: vucomisd %xmm0,%xmm1
0x00000000029988d0: ja 0x00000000029988ee ;*ifge
; - MinPerformance::minB@3 (line 63)
0x00000000029988d2: vucomisd %xmm1,%xmm2
0x00000000029988d6: ja 0x00000000029988de ;*ifge
; - MinPerformance::minB@22 (line 71)
0x00000000029988d8: vmovapd %xmm2,%xmm0
0x00000000029988dc: jmp 0x00000000029988e2
0x00000000029988de: vmovapd %xmm1,%xmm0 ;*synchronization entry
; - MinPerformance::minB@-1 (line 63)
0x00000000029988e2: add $0x10,%rsp
0x00000000029988e6: pop %rbp
0x00000000029988e7: test %eax,-0x27688ed(%rip) # 0x0000000000230000
; {poll_return}
0x00000000029988ed: retq
0x00000000029988ee: vucomisd %xmm0,%xmm2
0x00000000029988f2: ja 0x00000000029988e2 ;*ifge
; - MinPerformance::minB@10 (line 65)
0x00000000029988f4: vmovapd %xmm2,%xmm0
0x00000000029988f8: jmp 0x00000000029988e2
0x00000000029988fa: hlt
0x00000000029988fb: hlt
0x00000000029988fc: hlt
0x00000000029988fd: hlt
0x00000000029988fe: hlt
0x00000000029988ff: hlt
[Exception Handler]
[Stub Code]
0x0000000002998900: jmpq 0x00000000028ec920 ; {no_reloc}
[Deopt Handler Code]
0x0000000002998905: callq 0x000000000299890a
0x000000000299890a: subq $0x5,(%rsp)
0x000000000299890f: jmpq 0x00000000028c7340 ; {runtime_call}
0x0000000002998914: hlt
0x0000000002998915: hlt
0x0000000002998916: hlt
0x0000000002998917: hlt
Whether or not there are cases where such an optimization really makes a difference in an application is hard to tell. But at least, the bottom line is:
Math#min(double,double)
method is not the same as a simple comparison, and the treatment of the special cases does not come for freeMath#min
is not necessary, and then a comparison-based approach may be more efficientmin(double,double,double)
anyhow, for better convenience and readability, and then it would be easy to do two runs with the different implementations, and see whether it really affects the performance.(Side note: The integer type methods, like Math.min(int,int)
actually are a simple comparison - so I would expect no difference for these).
None of these answers worked for me. I'm now using:
document.addEventListener('dragleave', function(e){
var top = e.pageY;
var right = document.body.clientWidth - e.pageX;
var bottom = document.body.clientHeight - e.pageY;
var left = e.pageX;
if(top < 10 || right < 20 || bottom < 10 || left < 10){
console.log('Mouse has moved out of window');
}
});
I'm using this for a drag and drop file uploading widget. It's not absolutely accurate, being triggered when the mouse gets to a certain distance from the edge of the window.
You cannot set focus to a control if it has not been rendered. Form.Load() occurs before the controls are rendered.
Go to the form's events and double click the "Shown" event. In the form's shown event handler call the control.Focus() method.
private void myForm_Shown(object sender, EventArgs e)
{
// Call textbox's focus method
txtMyTextbox.Focus();
}
In macOS Catalina, and possibly some earlier versions, you can find out where the command line tools are installed using:
xcode-select -p
a.k.a. xcode-select --print-path
Which will, if it is installed, respond with something like:
/Library/Developer/CommandLineTools
To find out which version you have installed there, you can use:
xcode-select -v
a.k.a. xcode-select --version
Which will return something like:
xcode-select version 2370.
However, if you attempt to upgrade it to the latest version, assuming it is installed, using this:
xcode-select --install
You will receive in response:
xcode-select: error: command line tools are already installed, use "Software Update" to install updates
Which rather erroneously gives the impression you need to use Spotlight find something called 'Software Update'. In actual fact, you need to continue in the Terminal, and use this:
softwareupdate -i -a
a.k.a. softwareupdate --install --all
Which tries to update everything it can and may well respond with:
Software Update Tool
Finding available software
No new software available.
To find out which versions of the different Apple SDKs are installed on your machine, use this:
xcodebuild -showsdks
Not exactly what you ask for, but I've found it easier to just all agree on a coding standard astyle can generate and then automate the process.
For me what's working: I downloaded an old version of Java 1.7
I actually set my JAVA_HOME from C:/program files X86/Java BUT after I installed the 1.7 version I had another Java in program files/Java. And at this moment I found the tools.jar here. Then I changed for this new path and it's working
There is a way to remove the line.
1) Follow this tutorial: android-tabs-with-fragments
2) Then apply the RelativeLayout change that Leaudro suggested above (apply the layout props to all FrameLayouts).
You can also add an ImageView to the tab.xml in item #1 and get a very iPhone like look to the tabs.
Here is a screenshot of what I'm working on right now. I still have some work to do, mainly make a selector for the icons and ensure equal horizontal distribution, but you get the idea. In my case, I'm using fragments, but the same principals should apply to a standard tab view.
You can use React.PropTypes.shape()
as an argument to React.PropTypes.arrayOf()
:
// an array of a particular shape.
ReactComponent.propTypes = {
arrayWithShape: React.PropTypes.arrayOf(React.PropTypes.shape({
color: React.PropTypes.string.isRequired,
fontSize: React.PropTypes.number.isRequired,
})).isRequired,
}
See the Prop Validation section of the documentation.
UPDATE
As of react v15.5
, using React.PropTypes
is deprecated and the standalone package prop-types
should be used instead :
// an array of a particular shape.
import PropTypes from 'prop-types'; // ES6
var PropTypes = require('prop-types'); // ES5 with npm
ReactComponent.propTypes = {
arrayWithShape: PropTypes.arrayOf(PropTypes.shape({
color: PropTypes.string.isRequired,
fontSize: PropTypes.number.isRequired,
})).isRequired,
}
ThisWorkbook.Sheets.Add After:=Sheets(Sheets.Count)
ActiveSheet.Name = "XYZ"
(when you add a worksheet, anyway it'll be the active sheet)
There is also
getfacl /directory/directory/
which includes ACL
A good introduction on Linux ACL here
That entire block is misplaced.
class Example(object):
def main(self):
print "Hello World!"
if __name__ == '__main__':
Example().main()
But you really shouldn't be using a class just to run your main code.
You can do the following during declaration:
String names[] = {"Ankit","Bohra","Xyz"};
And if you want to do this somewhere after declaration:
String names[];
names = new String[] {"Ankit","Bohra","Xyz"};
As stated in the relevant RxJS documentation, the .subscribe()
method can take a third argument that is called on completion if there are no errors.
For reference:
[onNext]
(Function
): Function to invoke for each element in the observable sequence.[onError]
(Function
): Function to invoke upon exceptional termination of the observable sequence.[onCompleted]
(Function
): Function to invoke upon graceful termination of the observable sequence.
Therefore you can handle your routing logic in the onCompleted
callback since it will be called upon graceful termination (which implies that there won't be any errors when it is called).
this.httpService.makeRequest()
.subscribe(
result => {
// Handle result
console.log(result)
},
error => {
this.errors = error;
},
() => {
// 'onCompleted' callback.
// No errors, route to new page here
}
);
As a side note, there is also a .finally()
method which is called on completion regardless of the success/failure of the call. This may be helpful in scenarios where you always want to execute certain logic after an HTTP request regardless of the result (i.e., for logging purposes or for some UI interaction such as showing a modal).
Rx.Observable.prototype.finally(action)
Invokes a specified action after the source observable sequence terminates gracefully or exceptionally.
For instance, here is a basic example:
import { Observable } from 'rxjs/Rx';
import 'rxjs/add/operator/finally';
// ...
this.httpService.getRequest()
.finally(() => {
// Execute after graceful or exceptionally termination
console.log('Handle logging logic...');
})
.subscribe (
result => {
// Handle result
console.log(result)
},
error => {
this.errors = error;
},
() => {
// No errors, route to new page
}
);
We have two files, foo.c and bar.c.
Here is foo.c
#include <stdio.h>
volatile unsigned int stop_now = 0;
extern void bar_function(void);
int main(void)
{
while (1) {
bar_function();
stop_now = 1;
}
return 0;
}
Now, here is bar.c
#include <stdio.h>
extern volatile unsigned int stop_now;
void bar_function(void)
{
if (! stop_now) {
printf("Hello, world!\n");
sleep(30);
}
}
As you can see, we have no shared header between foo.c and bar.c , however bar.c needs something declared in foo.c when it's linked, and foo.c needs a function from bar.c when it's linked.
By using 'extern', you are telling the compiler that whatever follows it will be found (non-static) at link time; don't reserve anything for it in the current pass since it will be encountered later. Functions and variables are treated equally in this regard.
It's very useful if you need to share some global between modules and don't want to put / initialize it in a header.
Technically, every function in a library public header is 'extern', however labeling them as such has very little to no benefit, depending on the compiler. Most compilers can figure that out on their own. As you see, those functions are actually defined somewhere else.
In the above example, main() would print hello world only once, but continue to enter bar_function(). Also note, bar_function() is not going to return in this example (since it's just a simple example). Just imagine stop_now being modified when a signal is serviced (hence, volatile) if this doesn't seem practical enough.
Externs are very useful for things like signal handlers, a mutex that you don't want to put in a header or structure, etc. Most compilers will optimize to ensure that they don't reserve any memory for external objects, since they know they'll be reserving it in the module where the object is defined. However, again, there's little point in specifying it with modern compilers when prototyping public functions.
Hope that helps :)
<script ...
function(){
var someJsVar = "<c:out value='${someJstLVarFromBackend}'/>";
}
</script>
This works even if you dont have a hidden/non-hidden input field set somewhere in the jsp.
Doing the following steps helped in my case:
1) open Settings 2) go to Git and Uncheck "Use credential helper" checkbox 3) Do git pull 4) Enter password in the pop up dialog
if you are looking to do it via code on specific conditions, here is the solution worked for me. I have used in middleware to block certain users: these lines from below is the actual code to logout:
$auth = new LoginController();
$auth->logout($request);
Complete File:
namespace App\Http\Middleware;
use Closure;
use Auth;
use App\Http\Controllers\Auth\LoginController;
class ExcludeCustomers{
public function handle($request, Closure $next){
$user = Auth::guard()->user();
if( $user->role == 3 ) {
$auth = new LoginController();
$auth->logout($request);
header("Location: https://google.com");
die();
}
return $next($request);
}
}
With an already-set origin master, you just have to use the below command -
git pull "https://github.com/yourUserName/yourRepo.git"
select right(rtrim('94342KMR'),3)
This will fetch the last 3 right string.
select substring(rtrim('94342KMR'),1,len('94342KMR')-3)
This will fetch the remaining Characters.
So I did some tests with sqlite for very large files, and came to some conclusions (at least for my specific application).
The tests involve a single sqlite file with either a single table, or multiple tables. Each table had about 8 columns, almost all integers, and 4 indices.
The idea was to insert enough data until sqlite files were about 50GB.
Single Table
I tried to insert multiple rows into a sqlite file with just one table. When the file was about 7GB (sorry I can't be specific about row counts) insertions were taking far too long. I had estimated that my test to insert all my data would take 24 hours or so, but it did not complete even after 48 hours.
This leads me to conclude that a single, very large sqlite table will have issues with insertions, and probably other operations as well.
I guess this is no surprise, as the table gets larger, inserting and updating all the indices take longer.
Multiple Tables
I then tried splitting the data by time over several tables, one table per day. The data for the original 1 table was split to ~700 tables.
This setup had no problems with the insertion, it did not take longer as time progressed, since a new table was created for every day.
Vacuum Issues
As pointed out by i_like_caffeine, the VACUUM command is a problem the larger the sqlite file is. As more inserts/deletes are done, the fragmentation of the file on disk will get worse, so the goal is to periodically VACUUM to optimize the file and recover file space.
However, as pointed out by documentation, a full copy of the database is made to do a vacuum, taking a very long time to complete. So, the smaller the database, the faster this operation will finish.
Conclusions
For my specific application, I'll probably be splitting out data over several db files, one per day, to get the best of both vacuum performance and insertion/delete speed.
This complicates queries, but for me, it's a worthwhile tradeoff to be able to index this much data. An additional advantage is that I can just delete a whole db file to drop a day's worth of data (a common operation for my application).
I'd probably have to monitor table size per file as well to see when the speed will become a problem.
It's too bad that there doesn't seem to be an incremental vacuum method other than auto vacuum. I can't use it because my goal for vacuum is to defragment the file (file space isn't a big deal), which auto vacuum does not do. In fact, documentation states it may make fragmentation worse, so I have to resort to periodically doing a full vacuum on the file.
there is some change since the 0.16 so here how i did,
import in the pubspec.yaml
dependencies:
flutter:
sdk: flutter
intl: ^0.16.1
then use
txdate= DateTime.now()
DateFormat.yMMMd().format(txdate)
@RequestBody annotation binds the HTTPRequest body to the domain object. Spring automatically deserializes incoming HTTP Request to object using HttpMessageConverters. HttpMessageConverter converts body of request to resolve the method argument depending on the content type of the request. Many examples how to use converters https://upcodein.com/search/jc/mg/ResponseBody/page/0
Based on the previous answer,
from urllib.request import Request, urlopen
#specify url
url = 'https://xyz/xyz'
req = Request(url, headers={'User-Agent': 'XYZ/3.0'})
response = urlopen(req, timeout=20).read()
This worked for me by extending the timeout.
ReImport the dependencies if it is a maven project
Persistent user input using recursive function:
def askName():
return input("Write your name: ").strip() or askName()
name = askName()
def askAge():
try: return int(input("Enter your age: "))
except ValueError: return askAge()
age = askAge()
and finally, the question requirement:
def askAge():
try: return int(input("Enter your age: "))
except ValueError: return askAge()
age = askAge()
responseAge = [
"You are able to vote in the United States!",
"You are not able to vote in the United States.",
][int(age < 18)]
print(responseAge)
I Set variables in onCreate(), save scroll position in onPause() and set scroll position in onResume()
public static int index = -1;
public static int top = -1;
LinearLayoutManager mLayoutManager;
@Override
public void onCreate(Bundle savedInstanceState)
{
//Set Variables
super.onCreate(savedInstanceState);
cRecyclerView = ( RecyclerView )findViewById(R.id.conv_recycler);
mLayoutManager = new LinearLayoutManager(this);
cRecyclerView.setHasFixedSize(true);
cRecyclerView.setLayoutManager(mLayoutManager);
}
@Override
public void onPause()
{
super.onPause();
//read current recyclerview position
index = mLayoutManager.findFirstVisibleItemPosition();
View v = cRecyclerView.getChildAt(0);
top = (v == null) ? 0 : (v.getTop() - cRecyclerView.getPaddingTop());
}
@Override
public void onResume()
{
super.onResume();
//set recyclerview position
if(index != -1)
{
mLayoutManager.scrollToPositionWithOffset( index, top);
}
}
Long story short, node draws from V8, which is internally single-threaded. There are ways to work around the constraints for CPU-intensive tasks.
At one point (0.7) the authors tried to introduce isolates as a way of implementing multiple threads of computation, but were ultimately removed: https://groups.google.com/forum/#!msg/nodejs/zLzuo292hX0/F7gqfUiKi2sJ
cron
is dangerous. If one instance of cron fails to finish before the next is due, they are likely to fight each other.
It would be better to have a continuously running job that would delete some rows, sleep some, then repeat.
Also, INDEX(datetime)
is very important for avoiding deadlocks.
But, if the datetime test includes more than, say, 20% of the table, the DELETE
will do a table scan. Smaller chunks deleted more often is a workaround.
Another reason for going with smaller chunks is to lock fewer rows.
Bottom line:
INDEX(datetime)
Other deletion techniques: http://mysql.rjweb.org/doc.php/deletebig
In CSS2.1, an element can only have at most one of any kind of pseudo-element at any time. (This means an element can have both a :before
and an :after
pseudo-element — it just cannot have more than one of each kind.)
As a result, when you have multiple :before
rules matching the same element, they will all cascade and apply to a single :before
pseudo-element, as with a normal element. In your example, the end result looks like this:
.circle.now:before {
content: "Now";
font-size: 19px;
color: black;
}
As you can see, only the content
declaration that has highest precedence (as mentioned, the one that comes last) will take effect — the rest of the declarations are discarded, as is the case with any other CSS property.
This behavior is described in the Selectors section of CSS2.1:
Pseudo-elements behave just like real elements in CSS with the exceptions described below and elsewhere.
This implies that selectors with pseudo-elements work just like selectors for normal elements. It also means the cascade should work the same way. Strangely, CSS2.1 appears to be the only reference; neither css3-selectors nor css3-cascade mention this at all, and it remains to be seen whether it will be clarified in a future specification.
If an element can match more than one selector with the same pseudo-element, and you want all of them to apply somehow, you will need to create additional CSS rules with combined selectors so that you can specify exactly what the browser should do in those cases. I can't provide a complete example including the content
property here, since it's not clear for instance whether the symbol or the text should come first. But the selector you need for this combined rule is either .circle.now:before
or .now.circle:before
— whichever selector you choose is personal preference as both selectors are equivalent, it's only the value of the content
property that you will need to define yourself.
If you still need a concrete example, see my answer to this similar question.
The legacy css3-content specification contains a section on inserting multiple ::before
and ::after
pseudo-elements using a notation that's compatible with the CSS2.1 cascade, but note that that particular document is obsolete — it hasn't been updated since 2003, and no one has implemented that feature in the past decade. The good news is that the abandoned document is actively undergoing a rewrite in the guise of css-content-3 and css-pseudo-4. The bad news is that the multiple pseudo-elements feature is nowhere to be found in either specification, presumably owing, again, to lack of implementer interest.
You are all wrong! Why? Because all you need is this code to work:
(image View) / C# Img is : your Image box
Keep this as is, without change ("ms-appx:///) this is code not your app name Images is your folder in your project you can change it. dog.png is your file in your folder, as well as i do my folder 'Images' and file 'dog.png' So the uri is :"ms-appx:///Images/dog.png" and my code :
private void Button_Click(object sender, RoutedEventArgs e)
{
img.Source = new BitmapImage(new Uri("ms-appx:///Images/dog.png"));
}
I have had this issue in a case where the static
function was called before it was declared. Moving the function declaration to anywhere above the call solved my problem.
I know this is an older post, but I just got hit with a similar issue and was able to resolve it, so I thought I'd share.
(Update: As noted in the comments below, this answer was before the inclusion of the "git stash" feature to eGit.)
What I did was:
Hope that helps.
You can use:
String.prototype.replaceAll = function(search, replace) {
if (replace === undefined) {
return this.toString();
}
return this.split(search).join(replace);
}
UPDATE table
SET A = IF(A > 0 AND A < 1, 1, IF(A > 1 AND A < 2, 2, A))
WHERE A IS NOT NULL;
you might want to use CEIL()
if A
is always a floating point value > 0
and <= 2
It is perfectly fine if you want to go with the display: table-cell
solution. But instead of hacking it out, we have a better way to accomplish the same using display: flex;
. flex
is something which has a decent support.
.wrap {_x000D_
height: 200px;_x000D_
width: 200px;_x000D_
border: 1px solid #aaa;_x000D_
margin: 10px;_x000D_
display: flex;_x000D_
}_x000D_
_x000D_
.wrap span {_x000D_
align-self: flex-end;_x000D_
}
_x000D_
<div class="wrap">_x000D_
<span>Align me to the bottom</span>_x000D_
</div>
_x000D_
In the above example, we first set the parent element to display: flex;
and later, we use align-self
to flex-end
. This helps you push the item to the end of the flex
parent.
flex
)If you want to align the text to the bottom, you don't have to write so many properties for that, using display: table-cell;
with vertical-align: bottom;
is enough
div {_x000D_
display: table-cell;_x000D_
vertical-align: bottom;_x000D_
border: 1px solid #f00;_x000D_
height: 100px;_x000D_
width: 100px;_x000D_
}
_x000D_
<div>Hello</div>
_x000D_
You can actually use plyr
's rename
function as part of dplyr
chains. I think every function that a) takes a data.frame
as the first argument and b) returns a data.frame
works for chaining. Here is an example:
library('plyr')
library('dplyr')
DF = data.frame(var=1:5)
DF %>%
# `rename` from `plyr`
rename(c('var'='x')) %>%
# `mutate` from `dplyr` (note order in which libraries are loaded)
mutate(x.sq=x^2)
# x x.sq
# 1 1 1
# 2 2 4
# 3 3 9
# 4 4 16
# 5 5 25
UPDATE: The current version of dplyr
supports renaming directly as part of the select
function (see Romain Francois post above). The general statement about using non-dplyr functions as part of dplyr
chains is still valid though and rename
is an interesting example.
I've personally never found it useful to set M2_HOME
.
What counts is your $PATH environment. Hijacking part of the answer from Danix, all you need is:
export PATH=/Users/xxx/sdk/apache-maven-3.0.5/bin:$PATH
The mvn
script computes M2_HOME
for you anyway for what it's worth.
I think the challenge here is not to call upon global()
I would personally define a list for your (dynamic) variables to be held and then append to it within a for loop. Then use a separate for loop to view each entry or even execute other operations.
Here is an example - I have a number of network switches (say between 2 and 8) at various BRanches. Now I need to ensure I have a way to determining how many switches are available (or alive - ping test) at any given branch and then perform some operations on them.
Here is my code:
import requests
import sys
def switch_name(branchNum):
# s is an empty list to start with
s = []
#this FOR loop is purely for creating and storing the dynamic variable names in s
for x in range(1,8,+1):
s.append("BR" + str(branchNum) + "SW0" + str(x))
#this FOR loop is used to read each of the switch in list s and perform operations on
for i in s:
print(i,"\n")
# other operations can be executed here too for each switch (i) - like SSH in using paramiko and changing switch interface VLAN etc.
def main():
# for example's sake - hard coding the site code
branchNum= "123"
switch_name(branchNum)
if __name__ == '__main__':
main()
Output is:
BR123SW01
BR123SW02
BR123SW03
BR123SW04
BR123SW05
BR123SW06
BR123SW07
Windows 7 requires that you intentionally ask for certain privileges so that a malicious program can't do bad things to you. If the free calculator you downloaded needed to be run as an administrator, you would know something is up. There are OS commands to elevate the privilege of your application (which will request confirmation from the user).
A good description can be found at:
I had a case where I was entering text into a field after which the text would be removed automatically. Turned out it was due to some site functionality where you had to press the enter key after entering the text into the field. So, after sending your barcode text with sendKeys method, send 'enter' directly after it. Note that you will have to import the selenium Keys class. See my code below.
import org.openqa.selenium.Keys;
String barcode="0000000047166";
WebElement element_enter = driver.findElement(By.xpath("//*[@id='div-barcode']"));
element_enter.findElement(By.xpath("your xpath")).sendKeys(barcode);
element_enter.sendKeys(Keys.RETURN); // this will result in the return key being pressed upon the text field
I hope it helps..
while (true)
{//ie is the WebBrowser object
if (ie.ReadyState == tagREADYSTATE.READYSTATE_COMPLETE)
{
break;
}
Thread.Sleep(500);
}
I used this way to wait untill the page loads.
Try the following:
Uninstall-Package Newtonsoft.Json -Force
Followed by:
Install-Package Newtonsoft.Json -Version <press tab key for autocomplete>
Your 100% means 100% of the viewport, you can fix that using the vw unit besides the % unit at the width. The problem is that 100vw is related to the viewport, besides % is related to parent tag. Do like that:
.table-cell-wrapper {
width: 100vw;
height: 100%;
display: table-cell;
vertical-align: middle;
text-align: center;
}
Press Ctrl + Space
to get a autocomplete hint.
<div class="feedbackCont" onblur="hidefeedback();">
<div class="feedbackb" onclick="showfeedback();" ></div>
<div class="feedbackhide" tabindex="1"> </div>
</div>
function hidefeedback(){
$j(".feedbackhide").hide();
}
function showfeedback(){
$j(".feedbackhide").show();
$j(".feedbackCont").attr("tabindex",1).focus();
}
This is the simplest solution I came up with.
You can use ExpandoObject Class
which is in System.Dynamic
namespace.
dynamic MyDynamic = new ExpandoObject();
MyDynamic.A = "A";
MyDynamic.B = "B";
MyDynamic.C = "C";
MyDynamic.SomeProperty = SomeValue
MyDynamic.number = 10;
MyDynamic.Increment = (Action)(() => { MyDynamic.number++; });
More Info can be found at ExpandoObject MSDN
Either use casting as others have already said, or multiply one of the int variables by 1.0
:
double firstSolution = ((1.0* b1 * a22 - b2 * a12) / (a11 * a22 - a12 * a21));
"We usually put ' (space)' after the first sentence before a new line, but it doesn't work in Jupyter."
That inspired me to try using two spaces instead of just one - and it worked!!
(Of course, that functionality could possibly have been introduced between when the question was asked in January 2017, and when my answer was posted in March 2018.)
If you strictly want to use Date ( java.util.Date
), or without any use of external Library. Use this :
public Boolean compareDateWithoutTime(Date d1, Date d2) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
return sdf.format(d1).equals(sdf.format(d2));
}
Note: This code is untested
Define a record for your refCursor return type, call it rec. For example:
TYPE MyRec IS RECORD (col1 VARCHAR2(10), col2 VARCHAR2(20), ...); --define the record
rec MyRec; -- instantiate the record
Once you have the refcursor returned from your procedure, you can add the following code where your comments are now:
LOOP
FETCH refCursor INTO rec;
EXIT WHEN refCursor%NOTFOUND;
dbms_output.put_line(rec.col1||','||rec.col2||','||...);
END LOOP;
You can also use:
@Scripts.RenderFormat("<script type=\"text/javascript\" src=\"{0}\"></script>", "~/bundles/mybundle")
To specify the format of your output in a scenario where you need to use Charset, Type, etc.
jquery version of teshguru script for automatically detect input[file] and style
<html>
<head>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.7.2.min.js"></script>
<style>
#yourBtn{
position: relative;
top: 150px;
font-family: calibri;
width: 150px;
padding: 10px;
-webkit-border-radius: 5px;
-moz-border-radius: 5px;
border: 1px dashed #BBB;
text-align: center;
background-color: #DDD;
cursor:pointer;
}
</style>
<script type="text/javascript">
$(document).ready(function()
{
$('input[type=file]').each(function()
{
$(this).attr('onchange',"sub(this)");
$('<div id="yourBtn" onclick="getFile()">click to upload a file</div>').insertBefore(this);
$(this).wrapAll('<div style="height: 0px;width: 0px; overflow:hidden;"></div>');
});
});
function getFile(){
$('input[type=file]').click();
}
function sub(obj){
var file = obj.value;
var fileName = file.split("\\");
document.getElementById("yourBtn").innerHTML = fileName[fileName.length-1];
}
</script>
</head>
<body>
<?php
var_dump($_FILES);
?>
<center>
<form action="" method="post" enctype="multipart/form-data" name="myForm">
<input id="upfile" name="file" type="file" value="upload"/>
<input type="submit" value='submit' >
</form>
</center>
</body>
</html>
Per Mozilla's Map documentation, you can initialize as follows:
private _gridOptions:Map<string, Array<string>> =
new Map([
["1", ["test"]],
["2", ["test2"]]
]);
Always remember to be careful with nulls in pl/sql conditional clauses as null is never greater, smaller, equal or unequal to anything. Best way to avoid them is to use nvl.
For example
declare
i integer;
begin
if i <> 1 then
i:=1;
foobar();
end if;
end;
/
Never goes inside the if clause.
These would work.
if 1<>nvl(i,1) then
if i<> 1 or i is null then
Try entering the url inside the function
$location.url('http://www.google.com')
If you use numpy
, this is easy:
slice = arr[:2,:2]
or if you want the 0's,
slice = arr[0:2,0:2]
You'll get the same result.
*note that slice
is actually the name of a builtin-type. Generally, I would advise giving your object a different "name".
Another way, if you're working with lists of lists*:
slice = [arr[i][0:2] for i in range(0,2)]
(Note that the 0's here are unnecessary: [arr[i][:2] for i in range(2)]
would also work.).
What I did here is that I take each desired row 1 at a time (arr[i]
). I then slice the columns I want out of that row and add it to the list that I'm building.
If you naively try: arr[0:2]
You get the first 2 rows which if you then slice again arr[0:2][0:2]
, you're just slicing the first two rows over again.
*This actually works for numpy arrays too, but it will be slow compared to the "native" solution I posted above.
Nobody seems to be explaining the difference between an array and an object.
[]
is declaring an array.
{}
is declaring an object.
An array has all the features of an object with additional features (you can think of an array like a sub-class of an object) where additional methods and capabilities are added in the Array sub-class. In fact, typeof [] === "object"
to further show you that an array is an object.
The additional features consist of a magic .length
property that keeps track of the number of items in the array and a whole slew of methods for operating on the array such as .push()
, .pop()
, .slice()
, .splice()
, etc... You can see a list of array methods here.
An object gives you the ability to associate a property name with a value as in:
var x = {};
x.foo = 3;
x["whatever"] = 10;
console.log(x.foo); // shows 3
console.log(x.whatever); // shows 10
Object properties can be accessed either via the x.foo
syntax or via the array-like syntax x["foo"]
. The advantage of the latter syntax is that you can use a variable as the property name like x[myvar]
and using the latter syntax, you can use property names that contain characters that Javascript won't allow in the x.foo
syntax.
A property name can be any string value.
An array is an object so it has all the same capabilities of an object plus a bunch of additional features for managing an ordered, sequential list of numbered indexes starting from 0
and going up to some length. Arrays are typically used for an ordered list of items that are accessed by numerical index. And, because the array is ordered, there are lots of useful features to manage the order of the list .sort()
or to add or remove things from the list.
You can also try this.
select db_name(dbid) dbname, filename from sys.sysaltfiles
It is a little difficult to answer your specific question without a full, reproducible example. However something like this should work:
#Turn your 'treatment' column into a character vector
data$Treatment <- as.character(data$Treatment)
#Then turn it back into a factor with the levels in the correct order
data$Treatment <- factor(data$Treatment, levels=unique(data$Treatment))
In this example, the order of the factor will be the same as in the data.csv
file.
If you prefer a different order, you can order them by hand:
data$Treatment <- factor(data$Treatment, levels=c("Y", "X", "Z"))
However this is dangerous if you have a lot of levels: if you get any of them wrong, that will cause problems.
With the recent release of bootstrap 3, and the glyphicons being merged back to the main Bootstrap repo, Bootstrap CDN is now serving the complete Bootstrap 3.0 css including Glyphicons. The Bootstrap css reference is all you need to include: Glyphicons and its dependencies are on relative paths on the CDN site and are referenced in bootstrap.min.css
.
In html:
<link href="//netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap.min.css" rel="stylesheet">
In css:
@import url("//netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap.min.css");
Here is a working demo.
Note that you have to use .glyphicon
classes instead of .icon
:
Example:
<span class="glyphicon glyphicon-heart"></span>
Also note that you would still need to include bootstrap.min.js
for usage of Bootstrap JavaScript components, see Bootstrap CDN for url.
If you want to use the Glyphicons separately, you can do that by directly referencing the Glyphicons css on Bootstrap CDN.
In html:
<link href="//netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap-glyphicons.css" rel="stylesheet">
In css:
@import url("//netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap-glyphicons.css");
Since the css
file already includes all the needed Glyphicons dependencies (which are in a relative path on the Bootstrap CDN site), adding the css
file is all there is to do to start using Glyphicons.
Here is a working demo of the Glyphicons without Bootstrap.
Imports System.Data.SqlClient
Imports System.Data.Sql
Imports System.IO
Imports System.Configuration
Dim connectionString As String = ConfigurationManager.ConnectionStrings("ConString").ConnectionString
Dim cn As New SqlConnection(connectionString)
Dim cmd As New SqlCommand
Dim dr As SqlDataAdapter
Just an FYI warning for people looking at SUDS, until this ticket is resolved, SUDS does not support the "choice" tag in WSDL:
https://fedorahosted.org/suds/ticket/342
see: suds and choice tag
Also you can keep clients refferences. But this makes your memmory busy.
Create an empty object and set your clients into it.
const myClientList = {};
server.on("connection", (socket) => {
console.info(`Client connected [id=${socket.id}]`);
myClientList[socket.id] = socket;
});
socket.on("disconnect", (socket) => {
delete myClientList[socket.id];
});
then call your specific client by id from the object
myClientList[specificId].emit("blabla","somedata");
You must group both columns, group and sub-group, then use the aggregate function COUNT()
.
SELECT
group, subgroup, COUNT(*)
FROM
groups
GROUP BY
group, subgroup
The usual way to check whether something can be converted to an int
is to try
it and see, following the EAFP principle:
try:
int_value = int(string_value)
except ValueError:
# it wasn't an int, do something appropriate
else:
# it was an int, do something appropriate
So, in your case:
for item in mylist:
try:
int_value = int(item)
except ValueError:
pass
else:
mynewlist.append(item) # or append(int_value) if you want numbers
In most cases, a loop around some trivial code that ends with mynewlist.append(item)
can be turned into a list comprehension, generator expression, or call to map
or filter
. But here, you can't, because there's no way to put a try
/except
into an expression.
But if you wrap it up in a function, you can:
def raises(func, *args, **kw):
try:
func(*args, **kw)
except:
return True
else:
return False
mynewlist = [item for item in mylist if not raises(int, item)]
… or, if you prefer:
mynewlist = filter(partial(raises, int), item)
It's cleaner to use it this way:
def raises(exception_types, func, *args, **kw):
try:
func(*args, **kw)
except exception_types:
return True
else:
return False
This way, you can pass it the exception (or tuple of exceptions) you're expecting, and those will return True
, but if any unexpected exceptions are raised, they'll propagate out. So:
mynewlist = [item for item in mylist if not raises(ValueError, int, item)]
… will do what you want, but:
mynewlist = [item for item in mylist if not raises(ValueError, item, int)]
… will raise a TypeError
, as it should.
My solution was a little bit different and faster :)
Go to VSCode and in Terminal write:
config credential.helper wincred
Go to Visual Studio (no VSCode) and make a git pull. A popup will show asking for credentials. Put your credentials for the repo
Go to VSCode and make a git pull. Credentials were automatically fetched from wincred store
Credentials are automatically created and stored in wincredentials, so the next time you cannot be asked for credentials. (also a Personal Access Token will be provided from visualstudio.com if you are using DevOps hosted git repo).
Open angular.json file and find budgets
keyword.
It should look like:
"budgets": [
{
"type": "initial",
"maximumWarning": "2mb",
"maximumError": "5mb"
}
]
As you’ve probably guessed you can increase the maximumWarning
value to prevent this warning, i.e.:
"budgets": [
{
"type": "initial",
"maximumWarning": "4mb", <===
"maximumError": "5mb"
}
]
A performance budget is a group of limits to certain values that affect site performance, that may not be exceeded in the design and development of any web project.
In our case budget is the limit for bundle sizes.
See also:
Jquery has trim() function which basically turns something like this " FOo Bar " into "FOo Bar".
var string = " My String with Multiple lines ";
string.trim(); // output "My String with Multiple lines"
It is much more usefull because it is automatically removes empty spaces at the beginning and at the end of string as well. No regex needed.
I assume this is either difficult or impossible for the compiler team to implement for some reason.
No, it is not at all difficult or impossible to implement -- the fact that you implemented it yourself is a testament to that fact. Rather, it is an incredibly bad idea and so we don't allow it, so as to protect you from making this mistake.
call to Monitor.Exit within ExitDisposable.Dispose seems to block indefinitely (most of the time) causing deadlocks as other threads attempt to acquire the lock. I suspect the unreliability of my work around and the reason await statements are not allowed in lock statement are somehow related.
Correct, you have discovered why we made it illegal. Awaiting inside a lock is a recipe for producing deadlocks.
I'm sure you can see why: arbitrary code runs between the time the await returns control to the caller and the method resumes. That arbitrary code could be taking out locks that produce lock ordering inversions, and therefore deadlocks.
Worse, the code could resume on another thread (in advanced scenarios; normally you pick up again on the thread that did the await, but not necessarily) in which case the unlock would be unlocking a lock on a different thread than the thread that took out the lock. Is that a good idea? No.
I note that it is also a "worst practice" to do a yield return
inside a lock
, for the same reason. It is legal to do so, but I wish we had made it illegal. We're not going to make the same mistake for "await".
If you follow your link, it tells you that the error results from the $injector not being able to resolve your dependencies. This is a common issue with angular when the javascript gets minified/uglified/whatever you're doing to it for production.
The issue is when you have e.g. a controller;
angular.module("MyApp").controller("MyCtrl", function($scope, $q) {
// your code
})
The minification changes $scope
and $q
into random variables that doesn't tell angular what to inject. The solution is to declare your dependencies like this:
angular.module("MyApp")
.controller("MyCtrl", ["$scope", "$q", function($scope, $q) {
// your code
}])
That should fix your problem.
Just to re-iterate, everything I've said is at the link the error message provides to you.
One thing no one has pointed out is that you can use LATERAL
queries to apply a user-defined function on every selected row.
For instance:
CREATE OR REPLACE FUNCTION delete_company(companyId varchar(255))
RETURNS void AS $$
BEGIN
DELETE FROM company_settings WHERE "company_id"=company_id;
DELETE FROM users WHERE "company_id"=companyId;
DELETE FROM companies WHERE id=companyId;
END;
$$ LANGUAGE plpgsql;
SELECT * FROM (
SELECT id, name, created_at FROM companies WHERE created_at < '2018-01-01'
) c, LATERAL delete_company(c.id);
That's the only way I know how to do this sort of thing in PostgreSQL.
The following snippet will print "REGISTER here"
$string = "REGISTER 11223344 here";
$result = preg_replace(
array('/(\d+)/'),
array(''),
$string
);
print_r($result);
The preg_replace() API usage us as given below.
$result = preg_replace(
array('/pattern1/', '/pattern2/'),
array('replace1', 'replace2'),
$input_string
);
Something like that should be what you need
private void button1_Click(object sender, RoutedEventArgs e)
{
// Create OpenFileDialog
Microsoft.Win32.OpenFileDialog dlg = new Microsoft.Win32.OpenFileDialog();
// Set filter for file extension and default file extension
dlg.DefaultExt = ".png";
dlg.Filter = "JPEG Files (*.jpeg)|*.jpeg|PNG Files (*.png)|*.png|JPG Files (*.jpg)|*.jpg|GIF Files (*.gif)|*.gif";
// Display OpenFileDialog by calling ShowDialog method
Nullable<bool> result = dlg.ShowDialog();
// Get the selected file name and display in a TextBox
if (result == true)
{
// Open document
string filename = dlg.FileName;
textBox1.Text = filename;
}
}
You can create an empty project by selecting the "Empty Project" from the "General" group of Visual C++ projects (maybe that project template isn't included in Express?).
To fix the problem in the project you already have, open the project properties and navigate to:
Configuration Properties | C/C++ | Precompiled Headers
And choose "Not using Precompiled Headers" for the "Precompiled Header" option.
In the Drupal content management system, 'hook' has a relatively specific meaning. When an internal event occurs (like content creation or user login, for example), modules can respond to the event by implementing a special "hook" function. This is done via naming convention -- [your-plugin-name]_user_login() for the User Login event, for example.
Because of this convention, the underlying events are referred to as "hooks" and appear with names like "hook_user_login" and "hook_user_authenticate()" in Drupal's API documentation.
The method you are trying to use checks if the button is active:
btnAdd.isEnabled()
When enabled, any component associated with this object is active and able to fire this object's actionPerformed method.
This method does not check if the button is pressed.
If i understand your question correctly, you want to disable your "Add" button after the user clicks "Check out".
Try disabling your button at start: btnAdd.setEnabled(false)
or after the user presses "Check out"
There are two types of WITH clauses:
Here is the FizzBuzz in SQL form, using a WITH common table expression (CTE).
;WITH mil AS (
SELECT TOP 1000000 ROW_NUMBER() OVER ( ORDER BY c.column_id ) [n]
FROM master.sys.all_columns as c
CROSS JOIN master.sys.all_columns as c2
)
SELECT CASE WHEN n % 3 = 0 THEN
CASE WHEN n % 5 = 0 THEN 'FizzBuzz' ELSE 'Fizz' END
WHEN n % 5 = 0 THEN 'Buzz'
ELSE CAST(n AS char(6))
END + CHAR(13)
FROM mil
Here is a select statement also using a WITH clause
SELECT * FROM orders WITH (NOLOCK) where order_id = 123
I would also recommend the Tao Framework. But one additional note:
Take a look at these tutorials: http://www.taumuon.co.uk/jabuka/
Vim:
Emacs:
Personally, I prefer vim - it is small, does what it's supposed to do, and when I wish a full blown IDE I open VS. Emacs's approach of being an editor which wants to be an IDE (or should I say, an OS), but is not quite, is IMHO, outdated. In the old days having a email client, ftp client, tetris, ... whatnot in one package (emacs) made some sense ... nowadays, it doesn't anymore.
Both are however a topic of religious discussions among the programmer and superuser community users, and in that respect, both are excellent for starting flame wars if put in contact (in the same sentence / question).
Additional information for modern (systemd) linux systems.
There are many resources about this of values that may need tweaking (such as How to increase maximum number of JVM threads (Linux 64bit)); however a new limit is imposed by way of the systemd "TasksMax" limit which sets pids.max on the cgroup.
For login sessions the UserTasksMax default is 33% of the kernel limit pids_max (usually 12,288) and can be override in /etc/systemd/logind.conf.
For services the DefaultTasksMax default is 15% of the kernel limit pids_max (usually 4,915). You can override it for the service by setting TasksMax in "systemctl edit" or update DefaultTasksMax in /etc/systemd/system.conf
Textpad also works well at opening files that size. I have done it many times when having to deal with extremely large log files in the 3-5gb range. Also, using grep to pull out the worthwhile lines and then look at those works great.
This question actually is not JSP related, it is HTTP related. you can just do:
window.location = window.location;
Array into table. Array into div. JSON into table. JSON into div.
All are nicely handle this class. Click here to get a class
How to use it?
Just get and object
$obj = new Arrayinto();
Create an array you want to convert
$obj->array_object = array("AAA" => "1111",
"BBB" => "2222",
"CCC" => array("CCC-1" => "123",
"CCC-2" => array("CCC-2222-A" => "CA2",
"CCC-2222=B" => "CB2"
)
)
);
If you want to convert Array into table. Call this.
$result = $obj->process_table();
If you want to convert Array into div. Call this.
$result = $obj->process_div();
Let suppose if you have a JSON
$obj->json_string = '{
"AAA":"11111",
"BBB":"22222",
"CCC":[
{
"CCC-1":"123"
},
{
"CCC-2":"456"
}
]
}
';
You can convert into table/div like this
$result = $obj->process_json('div');
OR
$result = $obj->process_json('table');
problem is, it is not converted to proper format. Use function "printPreview(binaryPDFData)" to get print preview dialog of binary pdf data. you can comment script part if you don't want print dialog open.
printPreview = (data, type = 'application/pdf') => {
let blob = null;
blob = this.b64toBlob(data, type);
const blobURL = URL.createObjectURL(blob);
const theWindow = window.open(blobURL);
const theDoc = theWindow.document;
const theScript = document.createElement('script');
function injectThis() {
window.print();
}
theScript.innerHTML = `window.onload = ${injectThis.toString()};`;
theDoc.body.appendChild(theScript);
};
b64toBlob = (content, contentType) => {
contentType = contentType || '';
const sliceSize = 512;
// method which converts base64 to binary
const byteCharacters = window.atob(content);
const byteArrays = [];
for (let offset = 0; offset < byteCharacters.length; offset += sliceSize) {
const slice = byteCharacters.slice(offset, offset + sliceSize);
const byteNumbers = new Array(slice.length);
for (let i = 0; i < slice.length; i++) {
byteNumbers[i] = slice.charCodeAt(i);
}
const byteArray = new Uint8Array(byteNumbers);
byteArrays.push(byteArray);
}
const blob = new Blob(byteArrays, {
type: contentType
}); // statement which creates the blob
return blob;
};
I do it like this, to launch the SendFreeTextActivity from a (custom) menu fragment that appears in multiple activities:
In the MenuFragment class:
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_menu, container, false);
final Button sendFreeTextButton = (Button) view.findViewById(R.id.sendFreeTextButton);
sendFreeTextButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Log.d(TAG, "sendFreeTextButton clicked");
Intent intent = new Intent(getActivity(), SendFreeTextActivity.class);
MenuFragment.this.startActivity(intent);
}
});
...
Try this:
public void ShowMain()
{
if(auth()) // a method that returns true when the user exists.
{
this.Close();
System.Threading.Thread t = new System.Threading.Thread(new System.Threading.ThreadStart(Main));
t.Start();
}
else
{
MessageBox.Show("Invalid login details.");
}
}
[STAThread]
public void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Main());
}
You must call the new form in a diferent thread apartment, if I not wrong, because of the call system of windows' API and COM interfaces.
One advice: this system is high insecure, because you can change the if condition (in MSIL) and it's "a children game" to pass out your security. You need a stronger system to secure your software like obfuscate or remote login or something like this.
Hope this helps.
I had this problem but didn't have a version conflict in my package.json.
My package-lock.json was somehow out of sync with package json though. Deleting and regenerating it worked for me.
That looks like the GitLab issue 5769.
In GitLab, since the repositories always end in
.git
, I must specify.git
at the end of the repository name to make it work, for example:import "example.org/myuser/mygorepo.git"
And:
$ go get example.org/myuser/mygorepo.git
Looks like GitHub solves this by appending
".git"
.
It is supposed to be resolved in “Added support for Go's repository retrieval. #5958”, provided the right meta tags are in place.
Although there is still an issue for Go itself: “cmd/go
: go get cannot discover meta tag in HTML5 documents”.
I think you can normalize the row elements sum to 1 by this:
new_matrix = a / a.sum(axis=1, keepdims=1)
.
And the column normalization can be done with new_matrix = a / a.sum(axis=0, keepdims=1)
. Hope this can hep.
As you see in an error UseCalls.java:27: error: cannot find symbol
return String.parseString(input);
there is no method parseString
in String
class. There is no need to parse it as long as JOptionPane.showInputDialog(prompt);
already returns a string.
You have probably defined $name
, $date
, $text
or $date2
to be a string, like:
$name = 'String';
Then if you treat it like an array it will give that fatal error:
$name[] = 'new value'; // fatal error
To solve your problem just add the following code at the beginning of the loop:
$name = array();
$date = array();
$text = array();
$date2 = array();
This will reset their value to array and then you'll able to use them as arrays.
you can always use functions: .ToLower(); .ToUpper();
convert your strings and then compare them...
Good Luck
You can just capture the output and pass it through a filter, something like:
mysql show processlist
| grep -v '^\+\-\-'
| grep -v '^| Id'
| sort -n -k12
The two greps strip out the header and trailer lines (others may be needed if there are other lines not containing useful information) and the sort is done based on the numeric field number 12 (I think that's right).
This one works for your immediate output:
mysql show processlist
| grep -v '^\+\-\-'
| grep -v '^| Id'
| grep -v '^[0-9][0-9]* rows in set '
| grep -v '^ '
| sort -n -k12
Sharding does more than just horizontal partitioning. According to the wikipedia article,
Horizontal partitioning splits one or more tables by row, usually within a single instance of a schema and a database server. It may offer an advantage by reducing index size (and thus search effort) provided that there is some obvious, robust, implicit way to identify in which partition a particular row will be found, without first needing to search the index, e.g., the classic example of the 'CustomersEast' and 'CustomersWest' tables, where their zip code already indicates where they will be found.
Sharding goes beyond this: it partitions the problematic table(s) in the same way, but it does this across potentially multiple instances of the schema. The obvious advantage would be that search load for the large partitioned table can now be split across multiple servers (logical or physical), not just multiple indexes on the same logical server.
Also,
Splitting shards across multiple isolated instances requires more than simple horizontal partitioning. The hoped-for gains in efficiency would be lost, if querying the database required both instances to be queried, just to retrieve a simple dimension table. Beyond partitioning, sharding thus splits large partitionable tables across the servers, while smaller tables are replicated as complete units
One can have separate application properties files according to the environment, if Spring Boot application is being created. For example - properties file for dev environment, application-dev.properties:
spring.hivedatasource.url=<hive dev data source url>
spring.hivedatasource.username=dev
spring.hivedatasource.password=dev
spring.hivedatasource.driver-class-name=org.apache.hive.jdbc.HiveDriver
application-test.properties:
spring.hivedatasource.url=<hive dev data source url>
spring.hivedatasource.username=test
spring.hivedatasource.password=test
spring.hivedatasource.driver-class-name=org.apache.hive.jdbc.HiveDriver
And a primary application.properties file to select the profile:
application.properties:
spring.profiles.active=dev
server.tomcat.max-threads = 10
spring.application.name=sampleApp
Define the DB Configuration as below:
@Configuration
@ConfigurationProperties(prefix="spring.hivedatasource")
public class DBConfig {
@Profile("dev")
@Qualifier("hivedatasource")
@Primary
@Bean
public DataSource devHiveDataSource() {
System.out.println("DataSource bean created for Dev");
return new BasicDataSource();
}
@Profile("test")
@Qualifier("hivedatasource")
@Primary
@Bean
public DataSource testHiveDataSource() {
System.out.println("DataSource bean created for Test");
return new BasicDataSource();
}
This will automatically create the BasicDataSource bean according to the active profile set in application.properties file. Run the Spring-boot application and test.
Note that this will create an empty bean initially until getConnection() is called. Once the connection is available you can get the url, driver-class, etc. using that DataSource bean.
You need to use JSON.stringify
to first serialize your object to JSON, and then specify the contentType
so your server understands it's JSON. This should do the trick:
$.ajax({
url: url,
type: "POST",
data: JSON.stringify(data),
contentType: "application/json",
complete: callback
});
Note that the JSON
object is natively available in browsers that support JavaScript 1.7 / ECMAScript 5 or later. If you need legacy support you can use json2.
One possible way to achieve this is to have static instances of a class within another class. For example:
class SystemParams
{
pageWidth: number = 8270;
pageHeight: number = 11690;
}
class DocLevelParams
{
totalPages: number = 0;
}
class Wrapper
{
static System: SystemParams = new SystemParams();
static DocLevel: DocLevelParams = new DocLevelParams();
}
Then parameters can be accessed using Wrapper, without having to declare an instance of it. For example:
Wrapper.System.pageWidth = 1234;
Wrapper.DocLevel.totalPages = 10;
So you get the benefits of the JavaScript type object (as described in the original question) but with the benefits of being able to add the TypeScript typing. Additionally, it avoids having to add 'static' in front of all the parameters in the class.
Let's dissect it. There are three parts:
cd
-- This is change directory command./d
-- This switch makes cd
change both drive and directory at once. Without it you would have to do cd %~d0 & cd %~p0
. (%~d0
Changs active drive, cd %~p0
change the directory).%~dp0
-- This can be dissected further into three parts:
%0
-- This represents zeroth parameter of your batch script. It expands into the name of the batch file itself.%~0
-- The ~
there strips double quotes ("
) around the expanded argument.%dp0
-- The d
and p
there are modifiers of the expansion. The d
forces addition of a drive letter and the p
adds full path.None of the solutions regarding packet size or timeouts made any difference for me. I needed to disable ssl
mysql -u -p -hmyhost.com --disable-ssl db < file.sql
https://dev.mysql.com/doc/refman/5.7/en/encrypted-connections.html
int sign(float n)
{
union { float f; std::uint32_t i; } u { n };
return 1 - ((u.i >> 31) << 1);
}
This function assumes:
Both certificates should exist prior to the connection. They're usually created by Certification Authorities (not necessarily the same). (There are alternative cases where verification can be done differently, but some verification will need to be made.)
The server certificate should be created by a CA that the client trusts (and following the naming conventions defined in RFC 6125).
The client certificate should be created by a CA that the server trusts.
It's up to each party to choose what it trusts.
There are online CA tools that will allow you to apply for a certificate within your browser and get it installed there once the CA has issued it. They need not be on the server that requests client-certificate authentication.
The certificate distribution and trust management is the role of the Public Key Infrastructure (PKI), implemented via the CAs. The SSL/TLS client and servers and then merely users of that PKI.
When the client connects to a server that requests client-certificate authentication, the server sends a list of CAs it's willing to accept as part of the client-certificate request. The client is then able to send its client certificate, if it wishes to and a suitable one is available.
The main advantages of client-certificate authentication are:
You may be interested in Advantages of client certificates for client authentication? (on Security.SE).
This must be a new feature or something, otherwise I'm not sure why it hasn't been mentioned.
You can access the value in a column in a DataRow
object using row["ColumnName"]
:
DataRow row = table.Rows[0];
string rowValue = row["ColumnName"].ToString();
Series.to_frame
can be used to convert a Series
to DataFrame
.
# The provided name (columnName) will substitute the series name
df = series.to_frame('columnName')
For example,
s = pd.Series(["a", "b", "c"], name="vals")
df = s.to_frame('newCol')
print(df)
newCol
0 a
1 b
2 c
You could also use a URI template. If you structured your request into a restful URL Spring could parse the provided value from the url.
HTML
<li>
<a id="byParameter"
class="textLink" href="<c:url value="/mapping/parameter/bar />">By path, method,and
presence of parameter</a>
</li>
Controller
@RequestMapping(value="/mapping/parameter/{foo}", method=RequestMethod.GET)
public @ResponseBody String byParameter(@PathVariable String foo) {
//Perform logic with foo
return "Mapped by path + method + presence of query parameter! (MappingController)";
}
You need URL Rewrite module, preferably v2 (I have no v1 installed, so cannot guarantee that it will work there, but it should).
Here is an example of such web.config -- it will force HTTPS for ALL resources (using 301 Permanent Redirect):
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<system.webServer>
<rewrite>
<rules>
<clear />
<rule name="Redirect to https" stopProcessing="true">
<match url=".*" />
<conditions>
<add input="{HTTPS}" pattern="off" ignoreCase="true" />
</conditions>
<action type="Redirect" url="https://{HTTP_HOST}{REQUEST_URI}" redirectType="Permanent" appendQueryString="false" />
</rule>
</rules>
</rewrite>
</system.webServer>
</configuration>
P.S. This particular solution has nothing to do with ASP.NET/PHP or any other technology as it's done using URL rewriting module only -- it is processed at one of the initial/lower levels -- before request gets to the point where your code gets executed.
It seems that you've omitted the value attribute in HTML markup.
Add it there as <input value="" ... >
.
In Access 2013 I've just tested this:
While ComboBox1.ListCount > 0
ComboBox1.RemoveItem 0
Wend
Interestingly, if you set the item list in Properties, this is not lost when you exit Form View and go back to Design View.
I was going to post my own solution, but checking if someone already posted it, I found that @Rodney almost did it. However, he missed it one last crucial that made it uniseful, at least in my case. I mean, I too took the same .fakeHover
class addition / removing via mouseenter
and mouseleave
event detection, but that alone, per se, acts almost exactly like "genuine" :hover
. I mean: when you tap on a element in your table, it won't detect that you have "leaved" it - thus keeping the "fakehover" state.
What I did was simply to listen on click
, too, so when I "tap" the button, I manually fire a mouseleave
.
Si this is my final code:
.fakeHover {
background-color: blue;
}
$(document).on('mouseenter', 'button.myButton',function(){
$(this).addClass('fakeHover');
});
$(document).on('mouseleave', 'button.myButton',function(){
$(this).removeClass('fakeHover');
});
$(document).on('button.myButton, 'click', function(){
$(this).mouseleave();
});
This way you keep your usual hover
functionality when using a mouse when simply "hovering" on your buttons. Well, almost all of it: the only drawback somehow is that, after clicking on the button with the mouse, it wont be in hover
state. Much like if you clicked and quickly took the pointer out of the button. But in my case I can live with that.
RewriteCond %{REQUEST_URI} foobar
RewriteRule .* index.php
Here's a slightly less complicated answer:
NSString *myString = @"abcdefg";
NSString *mySmallerString = [myString substringToIndex:4];
See also substringWithRange and substringFromIndex
Try this library, it supports shadow, there is minSdkVersion=7
and also supports android:elevation
attribute for API-21
implicitly.
Original post is here.
Looks like the question has been long ago answered but the solution did not work for me. When I was getting that error, I was able to fix the problem by downloading PyWin32
To summarize a few items here: There are some pixel-by-pixel options that, while being simple just aren't fast.
@Luis' comment linking to: (archived) https://web.archive.org/web/20110827032809/http://www.switchonthecode.com/tutorials/csharp-tutorial-convert-a-color-image-to-grayscale is superb.
He runs through three different options and includes timings for each.
You can use this plugin very easily. From the docs:
var timestamps = require('mongoose-timestamp');
var UserSchema = new Schema({
username: String
});
UserSchema.plugin(timestamps);
mongoose.model('User', UserSchema);
var User = mongoose.model('User', UserSchema)
And also set the name of the fields if you wish:
mongoose.plugin(timestamps, {
createdAt: 'created_at',
updatedAt: 'updated_at'
});
Use:
git reflog
to show all the living cycle of your repository in current folder. The branch name that first appear (from down to up) is the source that was created.
855a3ce HEAD@{0}: checkout: moving from development to feature-sut-46
855a3ce HEAD@{1}: checkout: moving from feature-sut-46 to development
855a3ce HEAD@{2}: checkout: moving from feature-jira35 to feature-sut-46
535dd9d HEAD@{3}: checkout: moving from feature-sut-46 to feature-jira35
855a3ce HEAD@{4}: checkout: moving from development to feature-sut-46
855a3ce HEAD@{5}: checkout: moving from feature-jira35 to development
535dd9d HEAD@{6}: commit: insert the format for vendor specific brower - screen.css
855a3ce HEAD@{7}: checkout: moving from development to feature-jira35
855a3ce HEAD@{8}: checkout: moving from master to development
That mean:
Branch development is created (checkout -b) from master
Branch feature-jira35 is created (checkout -b) from development
Branch feature-jira-sut-46 is created (checkout -b) from development
A = [1,2,3,4]
B = [2,5]
#A - B
x = list(set(A) - set(B))
#B - A
y = list(set(B) - set(A))
print x
print y
You should use Ctrl+shift+enter when using the =SUM(VLOOKUP(A9,A1:D5,{2,3,4,},FALSE)) that results in {=SUM(VLOOKUP(A9,A1:D5,{2,3,4,},FALSE))} en also works.
NSArray *_returnedArguments = [serverOutput componentsSeparatedByString:@":"];
_returnedArguments
is an array of NSStrings
which the UITextField text
property is expecting. No need to convert.
Syntax error:
[_appDelegate loggedIn:usernameField.text:passwordField.text:(int)[[_returnedArguments objectAtIndex:2] intValue]];
If your _appDelegate has a passwordField
property, then you can set the text using the following
[[_appDelegate passwordField] setText:[_returnedArguments objectAtIndex:2]];
You could try using "typeid".
This doesn't work for "object" name but YOU know the object name so you'll just have to store it somewhere. The Compiler doesn't care what you namned an object.
Its worth bearing in mind, though, that the output of typeid is a compiler specific thing so even if it produces what you are after on the current platform it may not on another. This may or may not be a problem for you.
The other solution is to create some kind of template wrapper that you store the class name in. Then you need to use partial specialisation to get it to return the correct class name for you. This has the advantage of working compile time but is significantly more complex.
Edit: Being more explicit
template< typename Type > class ClassName
{
public:
static std::string name()
{
return "Unknown";
}
};
Then for each class somethign liek the following:
template<> class ClassName<MyClass>
{
public:
static std::string name()
{
return "MyClass";
}
};
Which could even be macro'd as follows:
#define DefineClassName( className ) \
\
template<> class ClassName<className> \
{ \
public: \
static std::string name() \
{ \
return #className; \
} \
}; \
Allowing you to, simply, do
DefineClassName( MyClass );
Finally to Get the class name you'd do the following:
ClassName< MyClass >::name();
Edit2: Elaborating further you'd then need to put this "DefineClassName" macro in each class you make and define a "classname" function that would call the static template function.
Edit3: And thinking about it ... Its obviously bad posting first thing in the morning as you may as well just define a member function "classname()" as follows:
std::string classname()
{
return "MyClass";
}
which can be macro'd as follows:
DefineClassName( className ) \
std::string classname() \
{ \
return #className; \
}
Then you can simply just drop
DefineClassName( MyClass );
into the class as you define it ...
If you have to set your anchor tag inside the div, you can also use CSS to set the anchor to fill the div via display:block.
As such:
<div style="height: 80px"><a href="#" style="display: block">Text</a></div>
Now when the user floats their cursor in that div the anchor tag will fill the div.
I solved this by writing the explicit IP address defined in the Listener.ora file as the hostname.
So, instead of "localhost", I wrote "192.168.1.2" as the "Hostname" in the SQL Developer field.
In the below picture I highlighted the input boxes that I've modified:
This is an old question, but many anwsers don't perform well or overflow for big numbers. I think D. Nesterov answer is the best one: robust, simple and fast. I just want to add my two cents.
I played around with decimals and also checked out the source code. From the public Decimal (int lo, int mid, int hi, bool isNegative, byte scale)
constructor documentation.
The binary representation of a Decimal number consists of a 1-bit sign, a 96-bit integer number, and a scaling factor used to divide the integer number and specify what portion of it is a decimal fraction. The scaling factor is implicitly the number 10 raised to an exponent ranging from 0 to 28.
Knowing this, my first approach was to create another decimal
whose scale corresponds to the decimals that I wanted to discard, then truncate it and finally create a decimal with the desired scale.
private const int ScaleMask = 0x00FF0000;
public static Decimal Truncate(decimal target, byte decimalPlaces)
{
var bits = Decimal.GetBits(target);
var scale = (byte)((bits[3] & (ScaleMask)) >> 16);
if (scale <= decimalPlaces)
return target;
var temporalDecimal = new Decimal(bits[0], bits[1], bits[2], target < 0, (byte)(scale - decimalPlaces));
temporalDecimal = Math.Truncate(temporalDecimal);
bits = Decimal.GetBits(temporalDecimal);
return new Decimal(bits[0], bits[1], bits[2], target < 0, decimalPlaces);
}
This method is not faster than D. Nesterov's and it is more complex, so I played around a little bit more. My guess is that having to create an auxiliar decimal
and retrieving the bits twice is making it slower. On my second attempt, I manipulated the components returned by Decimal.GetBits(Decimal d) method myself. The idea is to divide the components by 10 as many times as needed and reduce the scale. The code is based (heavily) on the Decimal.InternalRoundFromZero(ref Decimal d, int decimalCount) method.
private const Int32 MaxInt32Scale = 9;
private const int ScaleMask = 0x00FF0000;
private const int SignMask = unchecked((int)0x80000000);
// Fast access for 10^n where n is 0-9
private static UInt32[] Powers10 = new UInt32[] {
1,
10,
100,
1000,
10000,
100000,
1000000,
10000000,
100000000,
1000000000
};
public static Decimal Truncate(decimal target, byte decimalPlaces)
{
var bits = Decimal.GetBits(target);
int lo = bits[0];
int mid = bits[1];
int hi = bits[2];
int flags = bits[3];
var scale = (byte)((flags & (ScaleMask)) >> 16);
int scaleDifference = scale - decimalPlaces;
if (scaleDifference <= 0)
return target;
// Divide the value by 10^scaleDifference
UInt32 lastDivisor;
do
{
Int32 diffChunk = (scaleDifference > MaxInt32Scale) ? MaxInt32Scale : scaleDifference;
lastDivisor = Powers10[diffChunk];
InternalDivRemUInt32(ref lo, ref mid, ref hi, lastDivisor);
scaleDifference -= diffChunk;
} while (scaleDifference > 0);
return new Decimal(lo, mid, hi, (flags & SignMask)!=0, decimalPlaces);
}
private static UInt32 InternalDivRemUInt32(ref int lo, ref int mid, ref int hi, UInt32 divisor)
{
UInt32 remainder = 0;
UInt64 n;
if (hi != 0)
{
n = ((UInt32)hi);
hi = (Int32)((UInt32)(n / divisor));
remainder = (UInt32)(n % divisor);
}
if (mid != 0 || remainder != 0)
{
n = ((UInt64)remainder << 32) | (UInt32)mid;
mid = (Int32)((UInt32)(n / divisor));
remainder = (UInt32)(n % divisor);
}
if (lo != 0 || remainder != 0)
{
n = ((UInt64)remainder << 32) | (UInt32)lo;
lo = (Int32)((UInt32)(n / divisor));
remainder = (UInt32)(n % divisor);
}
return remainder;
}
I haven't performed rigorous performance tests, but on a MacOS Sierra 10.12.6, 3,06 GHz Intel Core i3 processor and targeting .NetCore 2.1 this method seems to be much faster than D. Nesterov's (I won't give numbers since, as I have mentioned, my tests are not rigorous). It is up to whoever implements this to evaluate whether or not the performance gains pay off for the added code complexity.
You can also cast an array to a string like...
newStr = String(aa);
I also agree with Tor Valamo's answer, console.log should have no problem with arrays, no need to convert to a string unless you're debugging something or just curious.
Refering to the very first question, I am looking into the same. The result I get, recording a macro, is, starting by selecting cell A76:
Sub find_last_row()
Range("A76").Select
Range(Selection, Selection.End(xlDown)).Select
End Sub
Alternatively, if you have Node.js installed, you can use the following command:
npx degit GIT_REPO
npx
comes with Node, and it allows you to run binary node-based packages without installing them first (alternatively, you can first install degit
globally using npm i -g degit
).
Degit is a tool created by Rich Harris, the creator of Svelte and Rollup, which he uses to quickly create a new project by cloning a repository without keeping the git folder. But it can also be used to clone any repo once...
Your port 80 is being used by the system.
And from "Overview>>CPU" just Right click on that process and click "End Process Tree". If that process is system that might be a critical issue.
each_with_object
is your friend!
input = [:bla,:blubb,:bleh,:bla,:bleh,:bla,:blubb,:brrr]
# to get the counts of the elements in the array:
> input.each_with_object({}){|x,h| h[x] ||= 0; h[x] += 1}
=> {:bla=>3, :blubb=>2, :bleh=>2, :brrr=>1}
# to get only the counts of the non-unique elements in the array:
> input.each_with_object({}){|x,h| h[x] ||= 0; h[x] += 1}.reject{|k,v| v < 2}
=> {:bla=>3, :blubb=>2, :bleh=>2}
You have root, but you still need to remount /system to be read/write
$ adb shell
$ su
$ mount -o rw,remount -t yaffs2 /dev/block/mtdblock3 /system
Go here for more information: Mount a filesystem read-write.
I faced this issue today, and I resolved it by doing the following steps:
1) manually inserting that troubling user providing value of mandatory fields into mysql.user
mysql> insert into user(Host, User, Password, ssl_type)
values ('localhost', 'jack', 'jack', 'ANY');
2)
mysql> select * from user where User = 'jack';
1 row in set (0.00 sec)
3) A.
mysql> drop user jack;
Query OK, 0 rows affected (0.00 sec)
B. mysql> flush privileges;
Query OK, 0 rows affected (0.00 sec)
C. mysql> create user 'jack' identified by 'jack';
Query OK, 0 rows affected (0.00 sec)
D. mysql> select Host, User, Password, ssl_type from user where User = 'jack';
+-----------+-----------+-------------------------------------------+----------+
| Host | User | Password | ssl_type |
+-----------+-----------+-------------------------------------------+----------+
| localhost | jack | jack | ANY |
| % | jack | *45BB7035F11303D8F09B2877A00D2510DCE4D758 | |
+-----------+-----------+-------------------------------------------+----------+
2 rows in set (0.00 sec)
4) A.
mysql> delete from user
where User = 'nyse_user' and
Host = 'localhost' and
Password ='nyse';
Query OK, 1 row affected (0.00 sec)
B.
mysql> select Host, User, Password, ssl_type from user where User = 'jack';
+------+-----------+-------------------------------------------+----------+
| Host | User | Password | ssl_type |
+------+-----------+-------------------------------------------+----------+
| % | jack | *45BB7035F11303D8F09B2877A00D2510DCE4D758 | |
+------+-----------+-------------------------------------------+----------+
1 row in set (0.00 sec)
Hope this helps.
The following works fine for me in Excel 2007. It is simple, and performs a full copy (retains all formatting, etc.):
Sheets("Sheet1").Columns(1).Copy Destination:=Sheets("Sheet2").Columns(2)
"Columns" returns a Range object, and so this is utilizing the "Range.Copy" method. "Destination" is an option to this method - if not provided the default is to copy to the paste buffer. But when provided, it is an easy way to copy.
As when manually copying items in Excel, the size and geometry of the destination must support the range being copied.
This doesn't sound intuitive but select the column you're having the issue with and use "text to column" and just press finish. This is the suggested answer from Excel help as well. For some reason in converts text to numbers.
private void ExceptionTest()
{
try
{
int j = 0;
int i = 5;
i = 1 / j;
}
catch (Exception ex)
{
Console.WriteLine("Error: " + ex.Message);
var stList = ex.StackTrace.ToString().Split('\\');
Console.WriteLine("Exception occurred at " + stList[stList.Count() - 1]);
}
}
Seems to work for me
Answer has been updated
count
is a Collection method. The query builder returns an array. So in order to get the count, you would just count it like you normally would with an array:
$wordCount = count($wordlist);
If you have a wordlist model, then you can use Eloquent to get a Collection and then use the Collection's count
method. Example:
$wordlist = Wordlist::where('id', '<=', $correctedComparisons)->get();
$wordCount = $wordlist->count();
There is/was a discussion on having the query builder return a collection here: https://github.com/laravel/framework/issues/10478
However as of now, the query builder always returns an array.
Edit: As linked above, the query builder now returns a collection (not an array). As a result, what JP Foster was trying to do initially will work:
$wordlist = \DB::table('wordlist')->where('id', '<=', $correctedComparisons)
->get();
$wordCount = $wordlist->count();
However, as indicated by Leon in the comments, if all you want is the count, then querying for it directly is much faster than fetching an entire collection and then getting the count. In other words, you can do this:
// Query builder
$wordCount = \DB::table('wordlist')->where('id', '<=', $correctedComparisons)
->count();
// Eloquent
$wordCount = Wordlist::where('id', '<=', $correctedComparisons)->count();
The DataRow
has also an indexer:
Object cellValue = dt.Rows[i][j];
But i would prefer the strongly typed Field
extension method which also supports nullable types:
int number = dt.Rows[i].Field<int>(j);
or even more readable and less error-prone with the name of the column:
double otherNumber = dt.Rows[i].Field<double>("DoubleColumn");
I suggest using:
command $(echo $(tr '\n' ' ' < parameters.cfg))
Simply trim the end-line characters and replace them with spaces, and then push the resulting string as possible separate arguments with echo.
next() and nextLine() methods are associated with Scanner and is used for getting String inputs. Their differences are...
next() can read the input only till the space. It can't read two words separated by space. Also, next() places the cursor in the same line after reading the input.
nextLine() reads input including space between the words (that is, it reads till the end of line \n). Once the input is read, nextLine() positions the cursor in the next line.
Read article :Difference between next() and nextLine()
Replace your while loop with :
while(r.hasNext()) {
scan = r.next();
System.out.println(scan);
if(scan.length()==0) {continue;}
//treatment
}
Using hasNext()
and next()
methods will resolve the issue.
Incase you you're like me and you landed here trying to find a way to tell if your PowerShell variable is this particular flavor of non-existent:
COM object that has been separated from its underlying RCW cannot be used.
Then here's some code that worked for me:
function Count-RCW([__ComObject]$ComObj){
try{$iuk = [System.Runtime.InteropServices.Marshal]::GetIUnknownForObject($ComObj)}
catch{return 0}
return [System.Runtime.InteropServices.Marshal]::Release($iuk)-1
}
example usage:
if((Count-RCW $ExcelApp) -gt 0){[System.Runtime.InteropServices.Marshal]::FinalReleaseComObject($ExcelApp)}
mashed together from other peoples' better answers:
and some other cool things to know:
I had to fix this by decreasing the priority (making it higher). This caused an immediate response. Not what I was expecting, but it worked.
InputStream is;
try {
is = new FileInputStream("c://filename");
is.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return is;
You must create your own Pipe for array sorting, here is one example how can you do that.
<li *ngFor="#item of array | arraySort:'-date'">{{item.name}} {{item.date | date:'medium' }}</li>
puts true ? "true" : "false"
=> "true"
puts false ? "true" : "false"
=> "false"
Another simple way is to use a tuple:
// Declare a tuple type
let x: [string, number];
// Initialize it
x = ["hello", 10];
// Access elements
console.log("First: " + x["0"] + " Second: " + x["1"]);
Output:
First: hello Second: 10
Just check for it before you pass to your function. So you would pass:
thing.foo ? thing.foo.bar : undefined
Defining insertable=false, updatable=false
is useful when you need to map a field more than once in an entity, typically:
This is IMO not a semantical thing, but definitely a technical one.
this questions is linked with the question How to write binary data file on C and plot it using Gnuplot by CAMILO HG. I know that the real problem have two parts: 1) Write the binary data file, 2) Plot it using Gnuplot.
The first part has been very clearly answered here, so I do not have something to add.
For the second, the easy way is send the people to the Gnuplot manual, and I sure someone find a good answer, but I do not find it in the web, so I am going to explain one solution (which must be in the real question, but I new in stackoverflow and I can not answer there):
After write your binary data file using fwrite()
, you should create a very simple program in C, a reader. The reader only contains the same structure as the writer, but you use fread()
instead fwrite()
. So it is very ease to generate this program: copy in the reader.c
file the writing part of your original code and change write for read (and "wb" for "rb"). In addition, you could include some checks for the data, for example, if the length of the file is correct. And finally, your program need to print the data in the standard output using a printf()
.
For be clear: your program run like this
$ ./reader data.dat
X_position Y_position (it must be a comment for Gnuplot)*
1.23 2.45
2.54 3.12
5.98 9.52
Okey, with this program, in Gnuplot you only need to pipe the standard output of the reader to the Gnuplot, something like this:
plot '< ./reader data.dat'
This line, run the program reader, and the output is connected with Gnuplot and it plot the data.
*Because Gnuplot is going to read the output of the program, you must know what can Gnuplot read and plot and what can not.
Microsoft.Win32.OpenFileDialog is the standard dialog that any application on Windows uses. Your user won't be surprised by its appearance when you use WPF in .NET 4.0
The dialog was altered in Vista. WPF in .NET 3.0 and 3.5 still used the legacy dialog but that was fixed in .NET 4.0. I can only guess that you started this thread because you are seeing that old dialog. Which probably means you're actually running a program that is targeting 3.5. Yes, the Winforms wrapper did get the upgrade and shows the Vista version. System.Windows.Forms.OpenFileDialog class, you'll need to add a reference to System.Windows.Forms.
You can easily do this by:
::variableName.isInitialized
or
this::variableName.isInitialized
But if you are inside a listener or inner class, do this:
this@OuterClassName::variableName.isInitialized
Note: The above statements work fine if you are writing them in the same file(same class or inner class) where the variable is declared but this will not work if you want to check the variable of other class (which could be a superclass or any other class which is instantiated), for ex:
class Test {
lateinit var str:String
}
And to check if str is initialized:
What we are doing here: checking isInitialized
for field str
of Test
class in Test2
class.
And we get an error backing field of var is not accessible at this point.
Check a question already raised about this.
If you are using Talend MDM Server, the login is: login: admin password: talend
See more: http://wiki.glitchdata.com/index.php?title=TOS:_Accessing_the_Talend_MDM_Server
This differs from the default JBoss login of admin/admin The password setup file is also login-config.xml in this case.
Finally this is for Hibernate 5
in Tomcat
.
Compiled all the answers from the above and added my tips which works like a charm for Hibernate 5 and SQL Server 2014
.
<hibernate-configuration>
<session-factory>
<property name="hibernate.dialect">
org.hibernate.dialect.SQLServerDialect
</property>
<property name="hibernate.connection.driver_class">
com.microsoft.sqlserver.jdbc.SQLServerDriver
</property>
<property name="hibernate.connection.url">
jdbc:sqlserver://localhost\ServerInstanceOrServerName:1433;databaseName=DATABASE_NAME
</property>
<property name="hibernate.default_schema">theSchemaNameUsuallydbo</property>
<property name="hibernate.connection.username">
YourUsername
</property>
<property name="hibernate.connection.password">
YourPasswordForMSSQL
</property>
remember, SSL/TLS operates at the Transport Layer, so all the crypto goo happens under the application-layer HTTP stuff.
http://en.wikipedia.org/wiki/File:IP_stack_connections.svg
that's the long way of saying, "Yes!"
You can use an IF to test:
check:
@[ "${var}" ] || ( echo ">> var is not set"; exit 1 )
Result:
$ make check
>> var is not set
Makefile:2: recipe for target 'check' failed
make: *** [check] Error 1
Through values in dictionary can be object of any kind they can't be hashed or indexed other way. So finding key by the value is unnatural for this collection type. Any query like that can be executed in O(n) time only. So if this is frequent task you should take a look for some indexing of key like Jon sujjested or maybe even some spatial index (DB or http://pypi.python.org/pypi/Rtree/ ).
Try the following:
LD_LIBRARY_PATH=/usr/local/lib /usr/local/bin/python
Replace /usr/local/lib
with the folder where you have installed libpython2.7.so.1.0
if it is not in /usr/local/lib
.
If this works and you want to make the changes permanent, you have two options:
Add export LD_LIBRARY_PATH=/usr/local/lib
to your .profile
in your home directory (this works only if you are using a shell which loads this file when a new shell instance is started). This setting will affect your user only.
Add /usr/local/lib
to /etc/ld.so.conf
and run ldconfig
. This is a system-wide setting of course.
In ES6 standard there is a new spread operator ...
which does exactly that.
call_me(...x)
It is supported by all major browsers except for IE.
The spread operator can do many other useful things, and the linked documentation does a really good job at showing that.
What I would do is use this tool and step through where you are getting the exception
Read this it will tell you how to create PDB's so you do not have to have all your references setup.
http://www.cplotts.com/2011/01/14/net-reflector-pro-debugging-the-net-framework-source-code/
It is a trial and I am not related to redgate at all I just use there software.
Any component added to the GridLayout will be resized to the same size as the largest component added. If you want a component to remain at its preferred size, then wrap that component in a JPanel and then the panel will be resized:
JPanel displayPanel = new JPanel(new GridLayout(4, 2));
JTextField titleText = new JTextField("title");
JPanel wrapper = new JPanel( new FlowLayout(0, 0, FlowLayout.LEADING) );
wrapper.add( titleText );
displayPanel.add(wrapper);
//displayPanel.add(titleText);
export class Dashboard {
innerHeight: any;
innerWidth: any;
constructor() {
this.innerHeight = (window.screen.height) + "px";
this.innerWidth = (window.screen.width) + "px";
}
}
Alex Answer is pretty neat but when using context rotate it can be hard to trace x,y coordinates, so I have made a Demo showing how to keep track of that.
Basically I am using this function & giving it the angle & the amount of distance traveled in that angel before drawing object.
function rotCor(angle, length){
var cos = Math.cos(angle);
var sin = Math.sin(angle);
var newx = length*cos;
var newy = length*sin;
return {
x : newx,
y : newy
};
}
The Date
property will return the date at midnight.
One option could be to get the individual values (day/month/year) separately and store it in the type you want.
var dateAndTime = DateTime.Now;
int year = dateAndTime.Year;
int month = dateAndTime.Month;
int day = dateAndTime.Day;
string.Format("{0}/{1}/{2}", month, day, year);
Here is the small example
public class TryWithResource {
public static void main(String[] args) {
try (TestMe r = new TestMe()) {
r.generalTest();
} catch(Exception e) {
System.out.println("From Exception Block");
} finally {
System.out.println("From Final Block");
}
}
}
public class TestMe implements AutoCloseable {
@Override
public void close() throws Exception {
System.out.println(" From Close - AutoCloseable ");
}
public void generalTest() {
System.out.println(" GeneralTest ");
}
}
Here is the output:
GeneralTest
From Close - AutoCloseable
From Final Block
Windows 10 Home Edition does not have Local Users and Groups option so that is the reason you aren't able to see that in Computer Management.
You can use User Accounts by pressing Window
+R
, typing netplwiz
and pressing OK as described here.
Tcl has a builtin for this
$ tclsh
% string map {ab bc bc ab} abbc
bcab
This works by walking the string a character at a time doing string comparisons starting at the current position.
In perl:
perl -E '
sub string_map {
my ($str, %map) = @_;
my $i = 0;
while ($i < length $str) {
KEYS:
for my $key (keys %map) {
if (substr($str, $i, length $key) eq $key) {
substr($str, $i, length $key) = $map{$key};
$i += length($map{$key}) - 1;
last KEYS;
}
}
$i++;
}
return $str;
}
say string_map("abbc", "ab"=>"bc", "bc"=>"ab");
'
bcab
If its working when you are using a browser and then passing on your username and password for the first time - then this means that once authentication is done Request header of your browser is set with required authentication values, which is then passed on each time a request is made to hosting server.
So start with inspecting Request Header (this could be done using Web Developers tools), Once you established whats required in header then you could pass this within your HttpWebRequest Header.
Example with Digest Authentication:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Security.Cryptography;
using System.Text.RegularExpressions;
using System.Net;
using System.IO;
namespace NUI
{
public class DigestAuthFixer
{
private static string _host;
private static string _user;
private static string _password;
private static string _realm;
private static string _nonce;
private static string _qop;
private static string _cnonce;
private static DateTime _cnonceDate;
private static int _nc;
public DigestAuthFixer(string host, string user, string password)
{
// TODO: Complete member initialization
_host = host;
_user = user;
_password = password;
}
private string CalculateMd5Hash(
string input)
{
var inputBytes = Encoding.ASCII.GetBytes(input);
var hash = MD5.Create().ComputeHash(inputBytes);
var sb = new StringBuilder();
foreach (var b in hash)
sb.Append(b.ToString("x2"));
return sb.ToString();
}
private string GrabHeaderVar(
string varName,
string header)
{
var regHeader = new Regex(string.Format(@"{0}=""([^""]*)""", varName));
var matchHeader = regHeader.Match(header);
if (matchHeader.Success)
return matchHeader.Groups[1].Value;
throw new ApplicationException(string.Format("Header {0} not found", varName));
}
private string GetDigestHeader(
string dir)
{
_nc = _nc + 1;
var ha1 = CalculateMd5Hash(string.Format("{0}:{1}:{2}", _user, _realm, _password));
var ha2 = CalculateMd5Hash(string.Format("{0}:{1}", "GET", dir));
var digestResponse =
CalculateMd5Hash(string.Format("{0}:{1}:{2:00000000}:{3}:{4}:{5}", ha1, _nonce, _nc, _cnonce, _qop, ha2));
return string.Format("Digest username=\"{0}\", realm=\"{1}\", nonce=\"{2}\", uri=\"{3}\", " +
"algorithm=MD5, response=\"{4}\", qop={5}, nc={6:00000000}, cnonce=\"{7}\"",
_user, _realm, _nonce, dir, digestResponse, _qop, _nc, _cnonce);
}
public string GrabResponse(
string dir)
{
var url = _host + dir;
var uri = new Uri(url);
var request = (HttpWebRequest)WebRequest.Create(uri);
// If we've got a recent Auth header, re-use it!
if (!string.IsNullOrEmpty(_cnonce) &&
DateTime.Now.Subtract(_cnonceDate).TotalHours < 1.0)
{
request.Headers.Add("Authorization", GetDigestHeader(dir));
}
HttpWebResponse response;
try
{
response = (HttpWebResponse)request.GetResponse();
}
catch (WebException ex)
{
// Try to fix a 401 exception by adding a Authorization header
if (ex.Response == null || ((HttpWebResponse)ex.Response).StatusCode != HttpStatusCode.Unauthorized)
throw;
var wwwAuthenticateHeader = ex.Response.Headers["WWW-Authenticate"];
_realm = GrabHeaderVar("realm", wwwAuthenticateHeader);
_nonce = GrabHeaderVar("nonce", wwwAuthenticateHeader);
_qop = GrabHeaderVar("qop", wwwAuthenticateHeader);
_nc = 0;
_cnonce = new Random().Next(123400, 9999999).ToString();
_cnonceDate = DateTime.Now;
var request2 = (HttpWebRequest)WebRequest.Create(uri);
request2.Headers.Add("Authorization", GetDigestHeader(dir));
response = (HttpWebResponse)request2.GetResponse();
}
var reader = new StreamReader(response.GetResponseStream());
return reader.ReadToEnd();
}
}
Then you could call it:
DigestAuthFixer digest = new DigestAuthFixer(domain, username, password);
string strReturn = digest.GrabResponse(dir);
if Url is: http://xyz.rss.com/folder/rss then domain: http://xyz.rss.com (domain part) dir: /folder/rss (rest of the url)
you could also return it as stream and use XmlDocument Load() method.
There are ways you can mimic this by having your controller return a piece of data, which your view can then translate into a JavaScript call.
We do something like this to allow people to use RESTful URLs to share their jquery-rendered workspace view.
In our case we pass a list of components which need to be rendered and use Razor to translate these back into jquery calls.
function getBaseURL() {
var url = location.href; // entire url including querystring - also: window.location.href;
var baseURL = url.substring(0, url.indexOf('/', 14));
if (baseURL.indexOf('http://localhost') != -1) {
// Base Url for localhost
var url = location.href; // window.location.href;
var pathname = location.pathname; // window.location.pathname;
var index1 = url.indexOf(pathname);
var index2 = url.indexOf("/", index1 + 1);
var baseLocalUrl = url.substr(0, index2);
return baseLocalUrl + "/";
}
else {
// Root Url for domain name
return baseURL + "/";
}
}
You then can use it like this...
var str = 'http://en.wikipedia.org/wiki/Knopf?q=1&t=2';
var url = str.toUrl();
The value of url will be...
{
"original":"http://en.wikipedia.org/wiki/Knopf?q=1&t=2",<br/>"protocol":"http:",
"domain":"wikipedia.org",<br/>"host":"en.wikipedia.org",<br/>"relativePath":"wiki"
}
The "var url" also contains two methods.
var paramQ = url.getParameter('q');
In this case the value of paramQ will be 1.
var allParameters = url.getParameters();
The value of allParameters will be the parameter names only.
["q","t"]
Tested on IE,chrome and firefox.
There is an issue with placing using statements inside the namespace when you wish to use aliases. The alias doesn't benefit from the earlier using
statements and has to be fully qualified.
Consider:
namespace MyNamespace
{
using System;
using MyAlias = System.DateTime;
class MyClass
{
}
}
versus:
using System;
namespace MyNamespace
{
using MyAlias = DateTime;
class MyClass
{
}
}
This can be particularly pronounced if you have a long-winded alias such as the following (which is how I found the problem):
using MyAlias = Tuple<Expression<Func<DateTime, object>>, Expression<Func<TimeSpan, object>>>;
With using
statements inside the namespace, it suddenly becomes:
using MyAlias = System.Tuple<System.Linq.Expressions.Expression<System.Func<System.DateTime, object>>, System.Linq.Expressions.Expression<System.Func<System.TimeSpan, object>>>;
Not pretty.
You need to do something with the return value...
import java.util.Arrays;
public class trial1{
public static void main(String[] args){
int[] B = numbers();
System.out.println(Arrays.toString(B));
}
public static int[] numbers(){
int[] A = {1,2,3};
return A;
}
}
The best way to run shell on any particular device is to use:
adb -s << emulator UDID >> shell
For Example:
adb -s emulator-5554 shell
function final_submit1() {
var city = $("#city").val();
var airport = $("#airport").val();
var vehicle = $("#vehicle").val();
if(city && airport){
$.ajax({
type:"POST",
cache:false,
data:{"city": city,"airport": airport},
url:'http://airportLimo/ajax-car-list',
success: function (html) {
console.log(html);
//$('#add').val('data sent');
//$('#msg').html(html);
$('#pprice').html("Price: $"+html);
}
});
}
}
You might have made the same silly mistake that I did, by not removing the // making it a comment.
The line should be like this, but not as a comment.
$cfg['Servers'][$i]['AllowNoPassword'] = TRUE;
The main difference :
•Activity.dispatchTouchEvent(MotionEvent) - This allows your Activity to intercept all touch events before they are dispatched to the window.
•ViewGroup.onInterceptTouchEvent(MotionEvent) - This allows a ViewGroup to watch events as they are dispatched to child Views.
I do not agree and do not recommend to return a vector
:
vector <double> vectorial(vector <double> a, vector <double> b)
{
vector <double> c{ a[1] * b[2] - b[1] * a[2], -a[0] * b[2] + b[0] * a[2], a[0] * b[1] - b[0] * a[1] };
return c;
}
This is much faster:
void vectorial(vector <double> a, vector <double> b, vector <double> &c)
{
c[0] = a[1] * b[2] - b[1] * a[2]; c[1] = -a[0] * b[2] + b[0] * a[2]; c[2] = a[0] * b[1] - b[0] * a[1];
}
I tested on Visual Studio 2017 with the following results in release mode:
8.01 MOPs by reference
5.09 MOPs returning vector
In debug mode, things are much worse:
0.053 MOPS by reference
0.034 MOPs by return vector
Get process explorer from sysinternals (now Microsoft)
First understand that you have three languages working together.
PHP: Is only run by the server and responds to requests like clicking on a link (GET) or submitting a form (POST). HTML & Javascript: Is only run in someone's browser (excluding NodeJS) I'm assuming your file looks something like:
<?php
function the_function() {
echo 'I just ran a php function';
}
if (isset($_GET['hello'])) {
the_function();
}
?>
<html>
<a href='the_script.php?hello=true'>Run PHP Function</a>
</html>
Because PHP only responds to requests (GET, POST, PUT, PATCH, and DELETE via $_REQUEST) this is how you have to run a php function even though their in the same file. This gives you a level of security, "Should I run this script for this user or not?".
If you don't want to refresh the page you can make a request to PHP without refreshing via a method called Asynchronous Javascript and XML (AJAX).
Since this is a readability issue, I have used the following code:
MySql = ""
MySql = MySql & "SELECT myTable.id"
MySql = MySql & " FROM myTable"
MySql = MySql & " WHERE myTable.id_equipment = " & lblId.Text
use the built in float() function in a list comprehension.
A2 = [float(v.replace('"','').strip()) for v in A1]
What about the oldschool way?
class MyClass {
constructor(count){
this.countVar = 1 + count;
}
}
MyClass.prototype.foo = "foo";
MyClass.prototype.countVar = 0;
// ...
var o1 = new MyClass(2); o2 = new MyClass(3);
o1.foo = "newFoo";
console.log( o1.foo,o2.foo);
console.log( o1.countVar,o2.countVar);
In constructor you mention only those vars which have to be computed. I like prototype inheritance for this feature -- it can help to save a lot of memory(in case if there are a lot of never-assigned vars).
use Result Rows.
row() method returns a single result row.
$id = $this
-> db
-> select('id')
-> where('email', $email)
-> limit(1)
-> get('users')
-> row();
then, you can simply use as you want. :)
echo "ID is" . $id;
The problem is your dataType
and the format of your data
parameter. I just tested this in a sandbox and the following works:
C#
[HttpPost]
public string ConvertLogInfoToXml(string jsonOfLog)
{
return Convert.ToString(jsonOfLog);
}
javascript
<input type="button" onclick="test()"/>
<script type="text/javascript">
function test() {
data = { prop: 1, myArray: [1, "two", 3] };
//'data' is much more complicated in my real application
var jsonOfLog = JSON.stringify(data);
$.ajax({
type: 'POST',
dataType: 'text',
url: "Home/ConvertLogInfoToXml",
data: "jsonOfLog=" + jsonOfLog,
success: function (returnPayload) {
console && console.log("request succeeded");
},
error: function (xhr, ajaxOptions, thrownError) {
console && console.log("request failed");
},
processData: false,
async: false
});
}
</script>
Pay special attention to data
, when sending text, you need to send a variable that matches the name of your parameter. It's not pretty, but it will get you your coveted unformatted string.
When running this, jsonOfLog looks like this in the server function:
jsonOfLog "{\"prop\":1,\"myArray\":[1,\"two\",3]}" string
The HTTP POST header:
Key Value
Request POST /Home/ConvertLogInfoToXml HTTP/1.1
Accept text/plain, */*; q=0.01
Content-Type application/x-www-form-urlencoded; charset=UTF-8
X-Requested-With XMLHttpRequest
Referer http://localhost:50189/
Accept-Language en-US
Accept-Encoding gzip, deflate
User-Agent Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.2; WOW64; Trident/6.0)
Host localhost:50189
Content-Length 42
DNT 1
Connection Keep-Alive
Cache-Control no-cache
Cookie EnableSSOUser=admin
The HTTP POST body:
jsonOfLog={"prop":1,"myArray":[1,"two",3]}
The response header:
Key Value
Cache-Control private
Content-Type text/html; charset=utf-8
Date Fri, 28 Jun 2013 18:49:24 GMT
Response HTTP/1.1 200 OK
Server Microsoft-IIS/8.0
X-AspNet-Version 4.0.30319
X-AspNetMvc-Version 4.0
X-Powered-By ASP.NET
X-SourceFiles =?UTF-8?B?XFxwc2ZcaG9tZVxkb2N1bWVudHNcdmlzdWFsIHN0dWRpbyAyMDEyXFByb2plY3RzXE12YzRQbGF5Z3JvdW5kXE12YzRQbGF5Z3JvdW5kXEhvbWVcQ29udmVydExvZ0luZm9Ub1htbA==?=
The response body:
{"prop":1,"myArray":[1,"two",3]}
Answer suggested by @Stacy Simpson:
We are struggling with the issue described in these threads and none of the resolutions seem to work:
As I'm new to SO, I cannot post in either thread. (The first one is actually closed and I disagree with the localization reasoning...)
Anyway, we created a work-around using AppleScript that folks may be interested in. The script below should be executed asynchronously prior to launching your automated test:
osascript <script name> <password> &
Here is the script:
on run argv
# Delay for 10 seconds as this script runs asynchronously to the automation process and is kicked off first.
delay 10
# Inspect all running processes
tell application "System Events"
set ProcessList to name of every process
# Determine if authentication is being requested
if "SecurityAgent" is in ProcessList then
# Bring this dialogue to the front
tell application "SecurityAgent" to activate
# Enter provided password
keystroke item 1 of argv
keystroke return
end if
end tell
end run
Probably not very secure, but it's the best work-around we've come up with to allow tests to run without requiring user intervention.
Hopefully, I can get enough points to post the answer; or, someone can unprotect this question. Regards.
As @Sean said, fcntl()
is largely standardized, and therefore available across platforms. The ioctl()
function predates fcntl()
in Unix, but is not standardized at all. That the ioctl()
worked for you across all the platforms of relevance to you is fortunate, but not guaranteed. In particular, the names used for the second argument are arcane and not reliable across platforms. Indeed, they are often unique to the particular device driver that the file descriptor references. (The ioctl()
calls used for a bit-mapped graphics device running on an ICL Perq running PNX (Perq Unix) of twenty years ago never translated to anything else anywhere else, for example.)
You could use Mono for Android
:
http://xamarin.com/monoforandroid
An alternative is dot42
:
dot42 provides a free community licence as well as a professional licence for $399.
Another method is has_key()
(if still using Python 2.X):
>>> a={"1":"one","2":"two"}
>>> a.has_key("1")
True
malloc will do.
int rows = 20;
int cols = 20;
int *array;
array = malloc(rows * cols * sizeof(int));
Refer the below article for help:-
http://courses.cs.vt.edu/~cs2704/spring00/mcquain/Notes/4up/Managing2DArrays.pdf
Add this
node_modules/
to .gitignore
file to ignore all directories called node_modules
in current folder and any subfolders
EF Core 2.1+ :
Property:
public string[] Strings { get; set; }
OnModelCreating:
modelBuilder.Entity<YourEntity>()
.Property(e => e.Strings)
.HasConversion(
v => string.Join(',', v),
v => v.Split(',', StringSplitOptions.RemoveEmptyEntries));
The PostgreSQL has an array data type and the Npgsql EF Core provider does support that. So it will map your C# arrays and lists to the PostgreSQL array data type automatically and no extra config is required. Also you can operate on the array and the operation will be translated to SQL.
More information on this page.
Without conversion to string
import math
digits = int(math.log10(n))+1
To also handle zero and negative numbers
import math
if n > 0:
digits = int(math.log10(n))+1
elif n == 0:
digits = 1
else:
digits = int(math.log10(-n))+2 # +1 if you don't count the '-'
You'd probably want to put that in a function :)
Here are some benchmarks. The len(str())
is already behind for even quite small numbers
timeit math.log10(2**8)
1000000 loops, best of 3: 746 ns per loop
timeit len(str(2**8))
1000000 loops, best of 3: 1.1 µs per loop
timeit math.log10(2**100)
1000000 loops, best of 3: 775 ns per loop
timeit len(str(2**100))
100000 loops, best of 3: 3.2 µs per loop
timeit math.log10(2**10000)
1000000 loops, best of 3: 844 ns per loop
timeit len(str(2**10000))
100 loops, best of 3: 10.3 ms per loop
For the above issue, first of all if suppose tables contains more than 1 primary key then first remove all those primary keys and add first AUTO INCREMENT field as primary key then add another required primary keys which is removed earlier. Set AUTO INCREMENT option for required field from the option area.
If a class is declared as static then the variables and methods need to be declared as static.
A class can be declared static, indicating that it contains only static members. It is not possible to create instances of a static class using the new keyword. Static classes are loaded automatically by the .NET Framework common language runtime (CLR) when the program or namespace containing the class is loaded.
Use a static class to contain methods that are not associated with a particular object. For example, it is a common requirement to create a set of methods that do not act on instance data and are not associated to a specific object in your code. You could use a static class to hold those methods.
->The main features of a static class are:
Example
static class CollegeRegistration
{
//All static member variables
static int nCollegeId; //College Id will be same for all the students studying
static string sCollegeName; //Name will be same
static string sColegeAddress; //Address of the college will also same
//Member functions
public static int GetCollegeId()
{
nCollegeId = 100;
return (nCollegeID);
}
//similarly implementation of others also.
} //class end
public class student
{
int nRollNo;
string sName;
public GetRollNo()
{
nRollNo += 1;
return (nRollNo);
}
//similarly ....
public static void Main()
{
//Not required.
//CollegeRegistration objCollReg= new CollegeRegistration();
//<ClassName>.<MethodName>
int cid= CollegeRegistration.GetCollegeId();
string sname= CollegeRegistration.GetCollegeName();
} //Main end
}
$rootbeer = (float) $InvoicedUnits;
Should do it for you. Check out Type-Juggling. You should also read String conversion to Numbers.
These are not command line args. Run psql. Manage to log into database (so pass the hostname, port, user and database if needed). And then write it in the psql program.
Example (below are two commands, write the first one, press enter, wait for psql to login, write the second):
psql -h host -p 5900 -U username database
\pset format aligned
Im attempting this now, this is what i came up with;
placeholder = 1
while placeholder is not None:
try:
#Code
placeholder = None
except Exception as e:
print(str(datetime.time(datetime.now()))[:8] + str(e)) #To log the errors
placeholder = e
time.sleep(0.5)
continue