Two generic ways to do the same thing... I'm not aware of any specific open solutions to do this, but it'd be rather trivial to do.
You could write a daily or weekly cron/jenkins job to scrape the previous time period's email from the archive looking for your keyworkds/combinations. Sending a batch digest with what it finds, if anything.
But personally, I'd Setup a specific email account to subscribe to the various security lists you're interested in. Add a simple automated script to parse the new emails for various keywords or combinations of keywords, when it finds a match forward that email on to you/your team. Just be sure to keep the keywords list updated with new products you're using.
You could even do this with a gmail account and custom rules, which is what I currently do, but I have setup an internal inbox in the past with a simple python script to forward emails that were of interest.
A Record lets you create a new type from a Union. The values in the Union are used as attributes of the new type.
For example, say I have a Union like this:
type CatNames = "miffy" | "boris" | "mordred";
Now I want to create an object that contains information about all the cats, I can create a new type using the values in the CatName Union as keys.
type CatList = Record<CatNames, {age: number}>
If I want to satisfy this CatList, I must create an object like this:
const cats:CatList = {
miffy: { age:99 },
boris: { age:16 },
mordred: { age:600 }
}
You get very strong type safety:
I used this recently to create a Status component. The component would receive a status prop, and then render an icon. I've simplified the code quite a lot here for illustrative purposes
I had a union like this:
type Statuses = "failed" | "complete";
I used this to create an object like this:
const icons: Record<
Statuses,
{ iconType: IconTypes; iconColor: IconColors }
> = {
failed: {
iconType: "warning",
iconColor: "red"
},
complete: {
iconType: "check",
iconColor: "green"
};
I could then render by destructuring an element from the object into props, like so:
const Status = ({status}) => <Icon {...icons[status]} />
If the Statuses union is later extended or changed, I know my Status component will fail to compile and I'll get an error that I can fix immediately. This allows me to add additional error states to the app.
Note that the actual app had dozens of error states that were referenced in multiple places, so this type safety was extremely useful.
I tested this one and it works
// Map from firestore
// Using flutterfire package hence the returned data()
Map<String, dynamic> data = documentSnapshot.data();
DateTime _timestamp = data['timestamp'].toDate();
Test details can be found here: https://www.youtube.com/watch?v=W_X8J7uBPNw&feature=youtu.be
If you have a proper cors header in place. Your corporate network may be stripping off the cors header. If the website is externally accessible, try accessing it from outside your network to verify whether the network is causing the problem--a good idea regardless of the cause.
Here is the sample code, which is working in Android Oreo and less than Oreo.
NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
NotificationCompat.Builder builder = null;
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
int importance = NotificationManager.IMPORTANCE_DEFAULT;
NotificationChannel notificationChannel = new NotificationChannel("ID", "Name", importance);
notificationManager.createNotificationChannel(notificationChannel);
builder = new NotificationCompat.Builder(getApplicationContext(), notificationChannel.getId());
} else {
builder = new NotificationCompat.Builder(getApplicationContext());
}
builder = builder
.setSmallIcon(R.drawable.ic_notification_icon)
.setColor(ContextCompat.getColor(context, R.color.color))
.setContentTitle(context.getString(R.string.getTitel))
.setTicker(context.getString(R.string.text))
.setContentText(message)
.setDefaults(Notification.DEFAULT_ALL)
.setAutoCancel(true);
notificationManager.notify(requestCode, builder.build());
You can use ReactDOMServer to render your component to HTML and then use this on jsPDF.
First do the imports:
import React from "react";
import ReactDOMServer from "react-dom/server";
import jsPDF from 'jspdf';
then:
var doc = new jsPDF();
doc.fromHTML(ReactDOMServer.renderToStaticMarkup(this.render()));
doc.save("myDocument.pdf");
Prefer to use:
renderToStaticMarkup
instead of:
renderToString
As the former include HTML code that react relies on.
This was already pointed out in this comment, but I think that's too easy to overlook: You may run into an UnnecessaryStubbingException
if you simply convert a JUnit 4 test class to a JUnit 5 test class by replacing an existing @Before
with @BeforeEach
, and if you perform some stubbing in that setup method that is not realized by at least one of the test cases.
This Mockito thread has more information on that, basically there is a subtle difference in the test execution between @Before
and @BeforeEach
. With @Before
, it was sufficient if any test case realized the stubbings, with @BeforeEach
, all cases would have to.
If you don't want to break up the setup of @BeforeEach
into many small bits (as the comment cited above rightly points out), there's another option still instead of activating the lenient mode for the whole test class: you can merely make those stubbings in the @BeforeEach
method lenient individually using lenient()
.
I always use this code while converting Date
to String
. (Swift 3)
extension Date
{
func toString( dateFormat format : String ) -> String
{
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = format
return dateFormatter.string(from: self)
}
}
and call like this . .
let today = Date()
today.toString(dateFormat: "dd-MM")
I have faced same issue, it may be issue of administrator, so followed below steps to setup docker on
windows10
.
Docker Desktop Installer.exe
file will be downloaded.Docker Desktop Installer.exe
using Run as administrator
-> Mark windows container during installation else it will only install linux container. It will ask for Logout after logging out and login it shows docker desktop in menu.Run as administrator
function get() {_x000D_
var arrayOfRows = document.getElementById("ta").value.split("\n");_x000D_
var docfrag = document.createDocumentFragment();_x000D_
_x000D_
var p = document.getElementById("result");_x000D_
while (p.firstChild) {_x000D_
p.removeChild(p.firstChild);_x000D_
}_x000D_
_x000D_
arrayOfRows.forEach(function(row, index, array) {_x000D_
var span = document.createElement("span");_x000D_
span.textContent = row;_x000D_
docfrag.appendChild(span);_x000D_
if(index < array.length - 1) {_x000D_
docfrag.appendChild(document.createElement("br"));_x000D_
}_x000D_
});_x000D_
_x000D_
p.appendChild(docfrag);_x000D_
}
_x000D_
<textarea id="ta" rows=3></textarea><br>_x000D_
<button onclick="get()">get</button>_x000D_
<p id="result"></p>
_x000D_
You can split textarea rows into array:
var arrayOfRows = postText.value.split("\n");
Then use it to generate, maybe, more p tags...
I think the main difference I can describe relates to record oriented vs. column oriented formats. Record oriented formats are what we're all used to -- text files, delimited formats like CSV, TSV. AVRO is slightly cooler than those because it can change schema over time, e.g. adding or removing columns from a record. Other tricks of various formats (especially including compression) involve whether a format can be split -- that is, can you read a block of records from anywhere in the dataset and still know it's schema? But here's more detail on columnar formats like Parquet.
Parquet, and other columnar formats handle a common Hadoop situation very efficiently. It is common to have tables (datasets) having many more columns than you would expect in a well-designed relational database -- a hundred or two hundred columns is not unusual. This is so because we often use Hadoop as a place to denormalize data from relational formats -- yes, you get lots of repeated values and many tables all flattened into a single one. But it becomes much easier to query since all the joins are worked out. There are other advantages such as retaining state-in-time data. So anyway it's common to have a boatload of columns in a table.
Let's say there are 132 columns, and some of them are really long text fields, each different column one following the other and use up maybe 10K per record.
While querying these tables is easy with SQL standpoint, it's common that you'll want to get some range of records based on only a few of those hundred-plus columns. For example, you might want all of the records in February and March for customers with sales > $500.
To do this in a row format the query would need to scan every record of the dataset. Read the first row, parse the record into fields (columns) and get the date and sales columns, include it in your result if it satisfies the condition. Repeat. If you have 10 years (120 months) of history, you're reading every single record just to find 2 of those months. Of course this is a great opportunity to use a partition on year and month, but even so, you're reading and parsing 10K of each record/row for those two months just to find whether the customer's sales are > $500.
In a columnar format, each column (field) of a record is stored with others of its kind, spread all over many different blocks on the disk -- columns for year together, columns for month together, columns for customer employee handbook (or other long text), and all the others that make those records so huge all in their own separate place on the disk, and of course columns for sales together. Well heck, date and months are numbers, and so are sales -- they are just a few bytes. Wouldn't it be great if we only had to read a few bytes for each record to determine which records matched our query? Columnar storage to the rescue!
Even without partitions, scanning the small fields needed to satisfy our query is super-fast -- they are all in order by record, and all the same size, so the disk seeks over much less data checking for included records. No need to read through that employee handbook and other long text fields -- just ignore them. So, by grouping columns with each other, instead of rows, you can almost always scan less data. Win!
But wait, it gets better. If your query only needed to know those values and a few more (let's say 10 of the 132 columns) and didn't care about that employee handbook column, once it had picked the right records to return, it would now only have to go back to the 10 columns it needed to render the results, ignoring the other 122 of the 132 in our dataset. Again, we skip a lot of reading.
(Note: for this reason, columnar formats are a lousy choice when doing straight transformations, for example, if you're joining all of two tables into one big(ger) result set that you're saving as a new table, the sources are going to get scanned completely anyway, so there's not a lot of benefit in read performance, and because columnar formats need to remember more about the where stuff is, they use more memory than a similar row format).
One more benefit of columnar: data is spread around. To get a single record, you can have 132 workers each read (and write) data from/to 132 different places on 132 blocks of data. Yay for parallelization!
And now for the clincher: compression algorithms work much better when it can find repeating patterns. You could compress AABBBBBBCCCCCCCCCCCCCCCC
as 2A6B16C
but ABCABCBCBCBCCCCCCCCCCCCCC
wouldn't get as small (well, actually, in this case it would, but trust me :-) ). So once again, less reading. And writing too.
So we read a lot less data to answer common queries, it's potentially faster to read and write in parallel, and compression tends to work much better.
Columnar is great when your input side is large, and your output is a filtered subset: from big to little is great. Not as beneficial when the input and outputs are about the same.
But in our case, Impala took our old Hive queries that ran in 5, 10, 20 or 30 minutes, and finished most in a few seconds or a minute.
Hope this helps answer at least part of your question!
This way you can create Observable from data, in my case I need to maintain shopping cart:
service.ts
export class OrderService {
cartItems: BehaviorSubject<Array<any>> = new BehaviorSubject([]);
cartItems$ = this.cartItems.asObservable();
// I need to maintain cart, so add items in cart
addCartData(data) {
const currentValue = this.cartItems.value; // get current items in cart
const updatedValue = [...currentValue, data]; // push new item in cart
if(updatedValue.length) {
this.cartItems.next(updatedValue); // notify to all subscribers
}
}
}
Component.ts
export class CartViewComponent implements OnInit {
cartProductList: any = [];
constructor(
private order: OrderService
) { }
ngOnInit() {
this.order.cartItems$.subscribe(items => {
this.cartProductList = items;
});
}
}
docker ps -a | grep training/webapp | cut -d ' ' -f 1 | xargs docker rm
- ps -a: list all containers
- grep training/webapp : filter out everything but the containers started from the training/webapp image
- cut -d ' ' -f 1: list only the container ids (first field when delimited by space)
- xargs docker rm : send the container id list output to the docker rm command to remove the container
None of these answers worked for me. This answer doesn't solve OP's issue but since this post is the only one that shows up on googling this issue, I'm sharing my answer here.
I came across this issue while writing unit tests for Android. The issue was that the activity that I was testing extended AppCompatActivity
instead of Activity
. To fix this, I was able to just replace AppCompatActivity
with Activity
since I didn't really need it. This might not be a viable solution for everyone, but hopefully knowing the root cause will help someone.
I just found my own solution to this problem, or at least my problem.
I was using justify-content: space-around
instead of justify-content: space-between;
.
This way the end elements will stick to the top and bottom, and you could have custom margins if you wanted.
For your first method change ws.Range("A")
to ws.Range("A:A")
which will search the entirety of column a, like so:
Sub Find_Bingo()
Dim wb As Workbook
Dim ws As Worksheet
Dim FoundCell As Range
Set wb = ActiveWorkbook
Set ws = ActiveSheet
Const WHAT_TO_FIND As String = "Bingo"
Set FoundCell = ws.Range("A:A").Find(What:=WHAT_TO_FIND)
If Not FoundCell Is Nothing Then
MsgBox (WHAT_TO_FIND & " found in row: " & FoundCell.Row)
Else
MsgBox (WHAT_TO_FIND & " not found")
End If
End Sub
For your second method, you are using Bingo
as a variable instead of a string literal. This is a good example of why I add Option Explicit
to the top of all of my code modules, as when you try to run the code it will direct you to this "variable" which is undefined and not intended to be a variable at all.
Additionally, when you are using With...End With
you need a period .
before you reference Cells
, so Cells
should be .Cells
. This mimics the normal qualifying behavior (i.e. Sheet1.Cells.Find..)
Change Bingo
to "Bingo"
and change Cells
to .Cells
With Sheet1
Set FoundCell = .Cells.Find(What:="Bingo", After:=.Cells(1, 1), _
LookIn:=xlValues, lookat:=xlPart, SearchOrder:=xlByRows, _
SearchDirection:=xlNext, MatchCase:=False, SearchFormat:=False)
End With
If Not FoundCell Is Nothing Then
MsgBox ("""Bingo"" found in row " & FoundCell.Row)
Else
MsgBox ("Bingo not found")
End If
In my
With Sheet1
.....
End With
The Sheet1
refers to a worksheet's code name, not the name of the worksheet itself. For example, say I open a new blank Excel workbook. The default worksheet is just Sheet1
. I can refer to that in code either with the code name of Sheet1
or I can refer to it with the index of Sheets("Sheet1")
. The advantage to using a codename is that it does not change if you change the name of the worksheet.
Continuing this example, let's say I renamed Sheet1
to Data
. Using Sheet1
would continue to work, as the code name doesn't change, but now using Sheets("Sheet1")
would return an error and that syntax must be updated to the new name of the sheet, so it would need to be Sheets("Data")
.
In the VB Editor you would see something like this:
Notice how, even though I changed the name to Data
, there is still a Sheet1
to the left. That is what I mean by codename.
The Data
worksheet can be referenced in two ways:
Debug.Print Sheet1.Name
Debug.Print Sheets("Data").Name
Both should return Data
More discussion on worksheet code names can be found here.
I would like to recommend:
Microsoft Edge Run Wrapper
https://github.com/mihula/RunEdge
You run it this way:
RunEdge.exe [URL]
Examples:
RunEdge.exe http://google.com
RunEdge.exe www.stackoverflow.com
It is not exactly new way how to do it, but it is wrapped as exe file, which could be useful in some situations. For me it is way how to start Edge from IBM Notes Basic client.
So here is the controller code.
public IActionResult AddURLTest()
{
return ViewComponent("AddURL");
}
You can load it using JQuery load method.
$(document).ready (function(){
$("#LoadSignIn").click(function(){
$('#UserControl').load("/Home/AddURLTest");
});
});
source code link
Above things are really helpful.
While creating web services, If you will take case of services consumer will greatly appreciated. I tried to maintain uniformity of the output. Also you can give remark or actual error message. The web service consumer can only check IsSuccess true or not else will sure there is problem, and act as per situation.
public class Response
{
/// <summary>
/// Gets or sets a value indicating whether this instance is success.
/// </summary>
/// <value>
/// <c>true</c> if this instance is success; otherwise, <c>false</c>.
/// </value>
public bool IsSuccess { get; set; } = false;
/// <summary>
/// Actual response if succeed
/// </summary>
/// <value>
/// Actual response if succeed
/// </value>
public object Data { get; set; } = null;
/// <summary>
/// Remark if anythig to convey
/// </summary>
/// <value>
/// Remark if anythig to convey
/// </value>
public string Remark { get; set; } = string.Empty;
/// <summary>
/// Gets or sets the error message.
/// </summary>
/// <value>
/// The error message.
/// </value>
public object ErrorMessage { get; set; } = null;
}
[HttpGet]
public IHttpActionResult Employees()
{
Response _res = new Response();
try
{
DalTest objDal = new DalTest();
_res.Data = objDal.GetTestData();
_res.IsSuccess = true;
return Ok<Response>(_res);
}
catch (Exception ex)
{
_res.IsSuccess = false;
_res.ErrorMessage = ex;
return ResponseMessage(Request.CreateResponse(HttpStatusCode.InternalServerError, _res ));
}
}
You are welcome to give suggestion if any :)
This is a development storage
part of Tomas M answer for Chrome. We must add listener
window.addEventListener("storage", (e)=> { console.log(e) } );
Load/save item in storage not runt this event - we MUST trigger it manually by
window.dispatchEvent( new Event('storage') ); // THIS IS IMPORTANT ON CHROME
and now, all open tab-s will receive event
Swift 4,
private func callNumber(phoneNumber:String) {
if let phoneCallURL = URL(string: "telprompt://\(phoneNumber)") {
let application:UIApplication = UIApplication.shared
if (application.canOpenURL(phoneCallURL)) {
if #available(iOS 10.0, *) {
application.open(phoneCallURL, options: [:], completionHandler: nil)
} else {
// Fallback on earlier versions
application.openURL(phoneCallURL as URL)
}
}
}
}
demo - http://jsfiddle.net/victor_007/ywevz8ra/
added border for better view (testing)
more info about white-space
table{
width:100%;
}
table td{
white-space: nowrap; /** added **/
}
table td:last-child{
width:100%;
}
table {_x000D_
width: 100%;_x000D_
}_x000D_
table td {_x000D_
white-space: nowrap;_x000D_
}_x000D_
table td:last-child {_x000D_
width: 100%;_x000D_
}
_x000D_
<table border="1">_x000D_
<thead>_x000D_
<tr>_x000D_
<th>Column A</th>_x000D_
<th>Column B</th>_x000D_
<th>Column C</th>_x000D_
<th class="absorbing-column">Column D</th>_x000D_
</tr>_x000D_
</thead>_x000D_
<tbody>_x000D_
<tr>_x000D_
<td>Data A.1 lorem</td>_x000D_
<td>Data B.1 ip</td>_x000D_
<td>Data C.1 sum l</td>_x000D_
<td>Data D.1</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>Data A.2 ipsum</td>_x000D_
<td>Data B.2 lorem</td>_x000D_
<td>Data C.2 some data</td>_x000D_
<td>Data D.2 a long line of text that is long</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>Data A.3</td>_x000D_
<td>Data B.3</td>_x000D_
<td>Data C.3</td>_x000D_
<td>Data D.3</td>_x000D_
</tr>_x000D_
</tbody>_x000D_
</table>
_x000D_
I don't think desc
takes an na.rm
argument... I'm actually surprised it doesn't throw an error when you give it one. If you just want to remove NA
s, use na.omit
(base) or tidyr::drop_na
:
outcome.df %>%
na.omit() %>%
group_by(Hospital, State) %>%
arrange(desc(HeartAttackDeath)) %>%
head()
library(tidyr)
outcome.df %>%
drop_na() %>%
group_by(Hospital, State) %>%
arrange(desc(HeartAttackDeath)) %>%
head()
If you only want to remove NA
s from the HeartAttackDeath column, filter with is.na
, or use tidyr::drop_na
:
outcome.df %>%
filter(!is.na(HeartAttackDeath)) %>%
group_by(Hospital, State) %>%
arrange(desc(HeartAttackDeath)) %>%
head()
outcome.df %>%
drop_na(HeartAttackDeath) %>%
group_by(Hospital, State) %>%
arrange(desc(HeartAttackDeath)) %>%
head()
As pointed out at the dupe, complete.cases
can also be used, but it's a bit trickier to put in a chain because it takes a data frame as an argument but returns an index vector. So you could use it like this:
outcome.df %>%
filter(complete.cases(.)) %>%
group_by(Hospital, State) %>%
arrange(desc(HeartAttackDeath)) %>%
head()
You can use a scope watch:
$scope.$watch('user', function(newValue, oldValue) {
// access new and old value here
console.log("Your former user.name was "+oldValue.name+", you're current user name is "+newValue.name+".");
});
https://docs.angularjs.org/api/ng/type/$rootScope.Scope#$watch
Navigate to the emulator folder located within Android SDK folder
/ emulator
cd ${ANDROID_HOME}/emulator
Then type these command to open emulator without android studio:
$ ./emulator -list-avds
$ ./emulator -avd Nexus_5X_API_28_x86
Nexus_5X_API_28_x86
is My AVD you need to give your AVD name
com.nhaarman.mockitokotlin2.mock {}
This error occurs when, for example, we create a mock inside another mock
mock {
on { x() } doReturn mock {
on { y() } doReturn z()
}
}
The solution to this is to create the child mock in a variable and use the variable in the scope of the parent mock to prevent the mock creation from being explicitly nested.
val liveDataMock = mock {
on { y() } doReturn z()
}
mock {
on { x() } doReturn liveDataMock
}
GL
I'm getting an index out of range error with the accepted answer solution. Reason: When range start, it is not iterate value one by one, it is iterate by index. If you modified a slice while it is in range, it will induce some problem.
Old Answer:
chars := []string{"a", "a", "b"}
for i, v := range chars {
fmt.Printf("%+v, %d, %s\n", chars, i, v)
if v == "a" {
chars = append(chars[:i], chars[i+1:]...)
}
}
fmt.Printf("%+v", chars)
Expected :
[a a b], 0, a
[a b], 0, a
[b], 0, b
Result: [b]
Actual:
// Autual
[a a b], 0, a
[a b], 1, b
[a b], 2, b
Result: [a b]
Correct Way (Solution):
chars := []string{"a", "a", "b"}
for i := 0; i < len(chars); i++ {
if chars[i] == "a" {
chars = append(chars[:i], chars[i+1:]...)
i-- // form the remove item index to start iterate next item
}
}
fmt.Printf("%+v", chars)
Source: https://dinolai.com/notes/golang/golang-delete-slice-item-in-range-problem.html
Swift uses the same cocoa-touch API. You can call all the same methods, but they will use Swift's syntax. In this example you can do something like this:
self.simpleLabel.text = "message"
Note the setText method isn't available. Setting the label's text with = will automatically call the setter in swift.
If Your issue is when you touch/tap on android and whole div covered by blue transparent color! Then you need to just change the
CURSOR : POINTER; to CURSOR : DEFAULT;
use mediaQuery to hide in mobile phone/Tablet.
This works for me.
By commenting it out this part on my web.config solved my problem:
<dependentAssembly>
<assemblyIdentity name="Newtonsoft.Json" publicKeyToken="30ad4fe6b2a6aeed" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-6.0.0.0" newVersion="6.0.0.0" />
</dependentAssembly>
But of course you need to make sure you have updated or you have the right version by doing this in your package manager console:
update-package Newtonsoft.Json -reinstall
just remove class 'fade' from modal
Below is a class which will accomplish the very basics of what you want to do when reading data from a MySQL database into a JTable
in Java.
import java.awt.*;
import java.sql.*;
import java.util.*;
import javax.swing.*;
import javax.swing.table.*;
public class TableFromMySqlDatabase extends JFrame
{
public TableFromMySqlDatabase()
{
ArrayList columnNames = new ArrayList();
ArrayList data = new ArrayList();
// Connect to an MySQL Database, run query, get result set
String url = "jdbc:mysql://localhost:3306/yourdb";
String userid = "root";
String password = "sesame";
String sql = "SELECT * FROM animals";
// Java SE 7 has try-with-resources
// This will ensure that the sql objects are closed when the program
// is finished with them
try (Connection connection = DriverManager.getConnection( url, userid, password );
Statement stmt = connection.createStatement();
ResultSet rs = stmt.executeQuery( sql ))
{
ResultSetMetaData md = rs.getMetaData();
int columns = md.getColumnCount();
// Get column names
for (int i = 1; i <= columns; i++)
{
columnNames.add( md.getColumnName(i) );
}
// Get row data
while (rs.next())
{
ArrayList row = new ArrayList(columns);
for (int i = 1; i <= columns; i++)
{
row.add( rs.getObject(i) );
}
data.add( row );
}
}
catch (SQLException e)
{
System.out.println( e.getMessage() );
}
// Create Vectors and copy over elements from ArrayLists to them
// Vector is deprecated but I am using them in this example to keep
// things simple - the best practice would be to create a custom defined
// class which inherits from the AbstractTableModel class
Vector columnNamesVector = new Vector();
Vector dataVector = new Vector();
for (int i = 0; i < data.size(); i++)
{
ArrayList subArray = (ArrayList)data.get(i);
Vector subVector = new Vector();
for (int j = 0; j < subArray.size(); j++)
{
subVector.add(subArray.get(j));
}
dataVector.add(subVector);
}
for (int i = 0; i < columnNames.size(); i++ )
columnNamesVector.add(columnNames.get(i));
// Create table with database data
JTable table = new JTable(dataVector, columnNamesVector)
{
public Class getColumnClass(int column)
{
for (int row = 0; row < getRowCount(); row++)
{
Object o = getValueAt(row, column);
if (o != null)
{
return o.getClass();
}
}
return Object.class;
}
};
JScrollPane scrollPane = new JScrollPane( table );
getContentPane().add( scrollPane );
JPanel buttonPanel = new JPanel();
getContentPane().add( buttonPanel, BorderLayout.SOUTH );
}
public static void main(String[] args)
{
TableFromMySqlDatabase frame = new TableFromMySqlDatabase();
frame.setDefaultCloseOperation( EXIT_ON_CLOSE );
frame.pack();
frame.setVisible(true);
}
}
In the NetBeans IDE which you are using - you will need to add the MySQL JDBC Driver in Project Properties as I display here:
Otherwise the code will throw an SQLException
stating that the driver cannot be found.
Now in my example, yourdb
is the name of the database and animals
is the name of the table that I am performing a query against.
Here is what will be output:
Parting note:
You stated that you were a novice and needed some help understanding some of the basic classes and concepts of Java. I will list a few here, but remember you can always browse the docs on Oracle's site.
Here is an alternate solution for version 4.x of Select2. You can use listeners to catch the focus event and then open the select.
$('#test').select2({
// Initialisation here
}).data('select2').listeners['*'].push(function(name, target) {
if(name == 'focus') {
$(this.$element).select2("open");
}
});
Find the working example here based the exampel created by @tonywchen
Try this method to convert a 'string that could potentially contain html code' to 'text format':
$msg = "<div></div>";
$safe_msg = htmlspecialchars($msg, ENT_QUOTES);
echo $safe_msg;
Hope this helps!
If you use several projects on a solution, and call method in one project to another project, make sure that all projects (called project and caller project) use the unique 'System.Net.Http'
version.
I think this may solve your problem:
in config/application.rb:
config.autoload_paths << Rails.root.join('lib')
and keep the right naming convention in lib.
in lib/foo.rb:
class Foo
end
in lib/foo/bar.rb:
class Foo::Bar
end
if you really wanna do some monkey patches in file like lib/extensions.rb, you may manually require it:
in config/initializers/require.rb:
require "#{Rails.root}/lib/extensions"
P.S.
Rails 3 Autoload Modules/Classes by Bill Harding.
And to understand what does Rails exactly do about auto-loading?
read Rails autoloading — how it works, and when it doesn't by Simon Coffey.
To get your radio button to list horizontally , just add
RepeatDirection="Horizontal"
to your .aspx file where the asp:radiobuttonlist is being declared.
OK, this is a bad thing to be doing. Don't mock a list; instead, mock the individual objects inside the list. See Mockito: mocking an arraylist that will be looped in a for loop for how to do this.
Also, why are you using PowerMock? You don't seem to be doing anything that requires PowerMock.
But the real cause of your problem is that you are using when
on two different objects, before you complete the stubbing. When you call when
, and provide the method call that you are trying to stub, then the very next thing you do in either Mockito OR PowerMock is to specify what happens when that method is called - that is, to do the thenReturn
part. Each call to when
must be followed by one and only one call to thenReturn
, before you do any more calls to when
. You made two calls to when
without calling thenReturn
- that's your error.
s = "BINGO"
print(s.replace("", " ")[1: -1])
Timings below
$ python -m timeit -s's = "BINGO"' 's.replace(""," ")[1:-1]'
1000000 loops, best of 3: 0.584 usec per loop
$ python -m timeit -s's = "BINGO"' '" ".join(s)'
100000 loops, best of 3: 1.54 usec per loop
In batch you could do it like this:
@echo off
setlocal EnableDelayedExpansion
set "string_list=str1 str2 str3 ... str10"
for %%s in (%string_list%) do (
set "var=%%sxyz"
svn co "!var!"
)
If you don't need the variable !var!
elsewhere in the loop, you could simplify that to
@echo off
setlocal
set "string_list=str1 str2 str3 ... str10"
for %%s in (%string_list%) do svn co "%%sxyz"
However, like C.B. I'd prefer PowerShell if at all possible:
$string_list = 'str1', 'str2', 'str3', ... 'str10'
$string_list | ForEach-Object {
$var = "${_}xyz" # alternatively: $var = $_ + 'xyz'
svn co $var
}
Again, this could be simplified if you don't need $var
elsewhere in the loop:
$string_list = 'str1', 'str2', 'str3', ... 'str10'
$string_list | ForEach-Object { svn co "${_}xyz" }
First give your input type submit a name, like this name='submitform'
.
and then put this in your php file
if (isset($_POST['submitform']))
{
?>
<script type="text/javascript">
window.location = "http://www.google.com/";
</script>
<?php
}
Don't forget to change the url to yours.
Solution tested with https://httpbin.org/ and inline bash script
1. For variables without spaces in it i.e. 1
:
Simply add '
before and after $variable
when replacing desired
string
for i in {1..3}; do \
curl -X POST -H "Content-Type: application/json" -d \
'{"number":"'$i'"}' "https://httpbin.org/post"; \
done
2. For input with spaces:
Wrap variable with additional "
i.e. "el a"
:
declare -a arr=("el a" "el b" "el c"); for i in "${arr[@]}"; do \
curl -X POST -H "Content-Type: application/json" -d \
'{"elem":"'"$i"'"}' "https://httpbin.org/post"; \
done
Wow works :)
Please try this approach. It worked for me.
<head>
<script type="text/javascript" src='./d3.v4.min.js'></script>
</head>
<body>
<div id="jschart41448" style="color:red">
Hi red
</div>
<div id="jschart41449" style="color:blueviolet">
Hi blueviolet
</div>
<script type="text/javascript" >
d3.select("#jschart41448").style('color', 'green' , null);
d3.select("#jschart41449").style('color', 'yellow', null);
</script>
</body>
this line should work for your 3 examples:
sed -r 's#\?(page)=([^&]*)&#/\1/\2#g' a.txt
-r
to save some escaping .test with your example (a.txt):
kent$ echo "?page=one&
?page=two&
?page=three&"|sed -r 's#\?(page)=([^&]*)&#/\1/\2#g'
/page/one
/page/two
/page/three
Your solution is correct, but your outer loop is still longer than needed. You don't need to compare the last element with anything else because it's been already compared with all the others in the previous iterations. Your inner loop still prevents that, but since we're talking about collision detection you can save the unnecessary check.
Using the same language you used to illustrate your algorithm, you'd come with something like this:
for (int i = 0, i < mylist.size() - 1; ++i)
for (int j = i + 1, j < mylist.size(); --j)
compare(mylist[i], mylist[j])
A method taking into consideration
it takes such a multi-line string which may be messy e.g.
test_str = '\nhej ho \n aaa\r\n a\n '
and produces nice one-line string
>>> ' '.join([line.strip() for line in test_str.strip().splitlines()])
'hej ho aaa a'
UPDATE: To fix multiple new-line character producing redundant spaces:
' '.join([line.strip() for line in test_str.strip().splitlines() if line.strip()])
This works for the following too
test_str = '\nhej ho \n aaa\r\n\n\n\n\n a\n '
I have met the same problem as I install it globally, then I try to install it locally, and it work.
The general consensus is that you do not (should not) need to dispose of HttpClient.
Many people who are intimately involved in the way it works have stated this.
See Darrel Miller's blog post and a related SO post: HttpClient crawling results in memory leak for reference.
I'd also strongly suggest that you read the HttpClient chapter from Designing Evolvable Web APIs with ASP.NET for context on what is going on under the hood, particularly the "Lifecycle" section quoted here:
Although HttpClient does indirectly implement the IDisposable interface, the standard usage of HttpClient is not to dispose of it after every request. The HttpClient object is intended to live for as long as your application needs to make HTTP requests. Having an object exist across multiple requests enables a place for setting DefaultRequestHeaders and prevents you from having to re-specify things like CredentialCache and CookieContainer on every request as was necessary with HttpWebRequest.
Or even open up DotPeek.
Although the original post had other issues (i.e. the missing "-d"), the error message is more generic.
curl: (3) [globbing] nested braces not supported at pos X
This is because curly braces {} and square brackets [] are special globbing characters in curl. To turn this globbing off, use the "-g" option.
As an example, the following Solr facet query will fail without the "-g" to turn off curl globbing:
curl -g 'http://localhost:8983/solr/query?json.facet={x:{terms:"myfield"}}'
In my case, it was because I was not pointing to the correct package where I kept my feature (cucumber) file(s). This was a case of wrong path specification. See code snippet below:
import org.junit.runner.RunWith;
import io.cucumber.junit.CucumberOptions;
import io.cucumber.junit.Cucumber;
@RunWith(Cucumber.class)
@CucumberOptions(
features = "src/test/features",
glue = "stepDefinitions"
)
Below is the Stack Trace in the console:
The final solution was I had to change the path to the correct package where my feature files were kept.
package cucumberOptions;
import org.junit.runner.RunWith;
import io.cucumber.junit.CucumberOptions;
import io.cucumber.junit.Cucumber;
@RunWith(Cucumber.class)
@CucumberOptions(
features = "src/test/java/features",
glue = "stepDefinitions"
)
public class TestRunner {
}
I faced similar problem on windows server 2012 STD 64 bit , my problem is resolved after updating windows with all available windows updates.
Using obtrusive JavaScript (i.e. inline code) as in your example, you can attach the click event handler to the div
element with the onclick
attribute like so:
<div id="some-id" class="some-class" onclick="slideonlyone('sms_box');">
...
</div>
However, the best practice is unobtrusive JavaScript which you can easily achieve by using jQuery's on()
method or its shorthand click()
. For example:
$(document).ready( function() {
$('.some-class').on('click', slideonlyone('sms_box'));
// OR //
$('.some-class').click(slideonlyone('sms_box'));
});
Inside your handler function (e.g. slideonlyone()
in this case) you can reference the element that triggered the event (e.g. the div
in this case) with the $(this)
object. For example, if you need its ID, you can access it with $(this).attr('id')
.
EDIT
After reading your comment to @fmsf below, I see you also need to dynamically reference the target element to be toggled. As @fmsf suggests, you can add this information to the div
with a data-attribute like so:
<div id="some-id" class="some-class" data-target="sms_box">
...
</div>
To access the element's data-attribute you can use the attr()
method as in @fmsf's example, but the best practice is to use jQuery's data()
method like so:
function slideonlyone() {
var trigger_id = $(this).attr('id'); // This would be 'some-id' in our example
var target_id = $(this).data('target'); // This would be 'sms_box'
...
}
Note how data-target
is accessed with data('target')
, without the data-
prefix. Using data-attributes you can attach all sorts of information to an element and jQuery would automatically add them to the element's data object.
The hamcrest-core-1.3.jar available on maven repository is deprecated.
Download working hamcrest-core-1.3.jar
from official Junit4 github link .
If you want to download from maven repository, use latest hamcrest-XX.jar
.
<dependency>
<groupId>org.hamcrest</groupId>
<artifactId>hamcrest</artifactId>
<version>2.2</version>
<scope>test</scope>
</dependency>
jQuery.i18n is a lightweight jQuery plugin for enabling internationalization in your web pages. It allows you to package custom resource strings in ‘.properties’ files, just like in Java Resource Bundles. It loads and parses resource bundles (.properties) based on provided language or language reported by browser.
to know more about this take a look at the How to internationalize your pages using JQuery?
Add a span
with the style="float: right"
element inside the h1
element. So you can add a "goto top of the page" link, with a unicode arrow link button.
<h1 id="myAnchor">Headline Text
<span style="float: right"><a href="#top" aria-hidden="true">?</a></span>
</h1>
If you don't want to include the full path, you can do
add_executable(main main.cpp)
target_link_libraries(main bingitup)
bingitup
is the same name you'd give a target if you create the static library in a CMake project:
add_library(bingitup STATIC bingitup.cpp)
CMake automatically adds the lib
to the front and the .a
at the end on Linux, and .lib
at the end on Windows.
If the library is external, you might want to add the path to the library using
link_directories(/path/to/libraries/)
C also does a good job at not making anything ambiguous.
Sure the dot could be overloaded to mean both things, but the arrow makes sure that the programmer knows that he's operating on a pointer, just like when the compiler won't let you mix two incompatible types.
In my case (Windows 10 + IIS 10) i had to open "Turn Windows Features On or Off" and then go to Internet Information Services > World Wide Web Services > Application Development Features > and check ASP.NET 4.6
All of the above answers are wrong because they fail to handle the OPTIONS preflight request, the solution is to override the mux router's interface. See AngularJS $http get request failed with custom header (alllowed in CORS)
func main() {
r := mux.NewRouter()
r.HandleFunc("/save", saveHandler)
http.Handle("/", &MyServer{r})
http.ListenAndServe(":8080", nil);
}
type MyServer struct {
r *mux.Router
}
func (s *MyServer) ServeHTTP(rw http.ResponseWriter, req *http.Request) {
if origin := req.Header.Get("Origin"); origin != "" {
rw.Header().Set("Access-Control-Allow-Origin", origin)
rw.Header().Set("Access-Control-Allow-Methods", "POST, GET, OPTIONS, PUT, DELETE")
rw.Header().Set("Access-Control-Allow-Headers",
"Accept, Content-Type, Content-Length, Accept-Encoding, X-CSRF-Token, Authorization")
}
// Stop here if its Preflighted OPTIONS request
if req.Method == "OPTIONS" {
return
}
// Lets Gorilla work
s.r.ServeHTTP(rw, req)
}
IntelliJ IDEA 2018.3.6
Using macOS Mojave Version 10.14.4 and pressing ?F12(Alt+F12) will open Sound preferences.
A solution without changing the current keymap is to use the command above with the key fn.
fn ? F12(fn+Alt+F12) will open the Terminal. And you can use ShiftEsc to close it.
It sounds like you want the object parameter to be optional, and also each of the properties in the object to be optional. In the example, as provided, overload syntax isn't needed. I wanted to point out some bad practices in some of the answers here. Granted, it's not the smallest possible expression of essentially writing box = { x: 0, y: 87, width: 4, height: 0 }
, but this provides all the code hinting niceties you could possibly want from the class as described. This example allows you to call a function with one, some, all, or none of the parameters and still get default values.
/** @class */
class Box {
public x?: number;
public y?: number;
public height?: number;
public width?: number;
constructor(params: Box = {} as Box) {
// Define the properties of the incoming `params` object here.
// Setting a default value with the `= 0` syntax is optional for each parameter
let {
x = 0,
y = 0,
height = 1,
width = 1
} = params;
// If needed, make the parameters publicly accessible
// on the class ex.: 'this.var = var'.
/** Use jsdoc comments here for inline ide auto-documentation */
this.x = x;
this.y = y;
this.height = height;
this.width = width;
}
}
Need to add methods? A verbose but more extendable alternative:
The Box
class above can work double-duty as the interface since they are identical. If you choose to modify the above class, you will need to define and reference a new interface for the incoming parameters object since the Box
class no longer would look exactly like the incoming parameters. Notice where the question marks (?:
) denoting optional properties move in this case. Since we're setting default values within the class, they are guaranteed to be present, yet they are optional within the incoming parameters object:
interface BoxParams {
x?: number;
// Add Parameters ...
}
class Box {
public x: number;
// Copy Parameters ...
constructor(params: BoxParams = {} as BoxParams) {
let { x = 0 } = params;
this.x = x;
}
doSomething = () => {
return this.x + this.x;
}
}
Whichever way you choose to define your class, this technique offers the guardrails of type safety, yet the flexibility write any of these:
const box1 = new Box();
const box2 = new Box({});
const box3 = new Box({x:0});
const box4 = new Box({x:0, height:10});
const box5 = new Box({x:0, y:87,width:4,height:0});
// Correctly reports error in TypeScript, and in js, box6.z is undefined
const box6 = new Box({z:0});
Compiled, you see how the default settings are only used if an optional value is undefined; it avoids the pitfalls of a widely used (but error-prone) fallback syntax of var = isOptional || default;
by checking against void 0
, which is shorthand for undefined
:
var Box = (function () {
function Box(params) {
if (params === void 0) { params = {}; }
var _a = params.x, x = _a === void 0 ? 0 : _a, _b = params.y, y = _b === void 0 ? 0 : _b, _c = params.height, height = _c === void 0 ? 1 : _c, _d = params.width, width = _d === void 0 ? 1 : _d;
this.x = x;
this.y = y;
this.height = height;
this.width = width;
}
return Box;
}());
||
(or) operatorConsider the danger of ||
/or operators when setting default fallback values as shown in some other answers. This code below illustrates the wrong way to set defaults. You can get unexpected results when evaluating against falsey values like 0, '', null, undefined, false, NaN:
var myDesiredValue = 0;
var result = myDesiredValue || 2;
// This test will correctly report a problem with this setup.
console.assert(myDesiredValue === result && result === 0, 'Result should equal myDesiredValue. ' + myDesiredValue + ' does not equal ' + result);
In my tests, using es6/typescript destructured object can be 15-90% faster than Object.assign. Using a destructured parameter only allows methods and properties you've assigned to the object. For example, consider this method:
class BoxTest {
public x?: number = 1;
constructor(params: BoxTest = {} as BoxTest) {
Object.assign(this, params);
}
}
If another user wasn't using TypeScript and attempted to place a parameter that didn't belong, say, they might try putting a z
property
var box = new BoxTest({x: 0, y: 87, width: 4, height: 0, z: 7});
// This test will correctly report an error with this setup. `z` was defined even though `z` is not an allowed property of params.
console.assert(typeof box.z === 'undefined')
Marking the document as HTML5 by the proper doctype on the first line, solved my issue.
<!DOCTYPE html>
<html>...
Assuming the following method to test:
public boolean doSomething(SomeClass arg);
Mockito documentation says that you should not use captor in this way:
when(someObject.doSomething(argumentCaptor.capture())).thenReturn(true);
assertThat(argumentCaptor.getValue(), equalTo(expected));
Because you can just use matcher during stubbing:
when(someObject.doSomething(eq(expected))).thenReturn(true);
But verification is a different story. If your test needs to ensure that this method was called with a specific argument, use ArgumentCaptor
and this is the case for which it is designed:
ArgumentCaptor<SomeClass> argumentCaptor = ArgumentCaptor.forClass(SomeClass.class);
verify(someObject).doSomething(argumentCaptor.capture());
assertThat(argumentCaptor.getValue(), equalTo(expected));
We can use below Curl command in Windows Command prompt to send the request.
Use the Curl command below, replace single quote with double quotes, remove quotes where they are not there in below format and use the ^
symbol.
curl http://localhost:7101/module/url ^
-d @D:/request.xml ^
-H "Content-Type: text/xml" ^
-H "SOAPAction: process" ^
-H "Authorization: Basic xyz" ^
-X POST
.delegate is the only one that is working to me with jQuery JavaScript Library v2.1.1
$(document).delegate('#textareaID','change', function() {
console.log("change!");
});
So simple. In Nuget Package Manager Console:
Update-Package Microsoft.AspNet.Mvc -Reinstall
You don't really need the MockitoAnnotations.initMocks(this);
if you're using mockito 1.9 ( or newer ) - all you need is this:
@InjectMocks
private MyTestObject testObject;
@Mock
private MyDependentObject mockedObject;
The @InjectMocks
annotation will inject all your mocks to the MyTestObject
object.
Use substr()
with a negative number for the 2nd argument.
$newstring = substr($dynamicstring, -7);
From the php docs:
string substr ( string $string , int $start [, int $length ] )
If start is negative, the returned string will start at the start'th character from the end of string.
In addition, if you want to see Sources and Console on one window, go to:
"Customize and control DevTools -> "Show console drawer"
You can also see it here at the right corner:
Here is a small example for those who want to peruse quickly
object ApplyExample01 extends App {
class Greeter1(var message: String) {
println("A greeter-1 is being instantiated with message " + message)
}
class Greeter2 {
def apply(message: String) = {
println("A greeter-2 is being instantiated with message " + message)
}
}
val g1: Greeter1 = new Greeter1("hello")
val g2: Greeter2 = new Greeter2()
g2("world")
}
output
A greeter-1 is being instantiated with message hello
A greeter-2 is being instantiated with message world
Simple, use absolute positioning, and instead of specifying a top and a left, specify a top and a right!
For example:
#logo_image {
width:80px;
height:80px;
top:10px;
right:10px;
z-index: 3;
position:absolute;
}
adding to the top answer: here is some sample code from PHP and Jquery:
$("#button").click(function () {
$.ajax({
type: "POST",
url: "handler.php",
data: dataString,
success: function(data) {
if(data.status == "success"){
/* alert("Thank you for subscribing!");*/
$(".title").html("");
$(".message").html(data.message)
.hide().fadeIn(1000, function() {
$(".message").append("");
}).delay(1000).fadeOut("fast");
/* setTimeout(function() {
window.location.href = "myhome.php";
}, 2500);*/
}
else if(data.status == "error"){
alert("Error on query!");
}
}
});
return false;
}
});
PHP - send custom message / status:
$response_array['status'] = 'success'; /* match error string in jquery if/else */
$response_array['message'] = 'RFQ Sent!'; /* add custom message */
header('Content-type: application/json');
echo json_encode($response_array);
This should work in most versions of PHP 4+. Array map using anonymous functions is not supported below 5.3.
Also the foreach examples will throw a warning when using strict PHP error handling.
Here is a small multi-dimensional key renaming function. It can also be used to process arrays to have the correct keys for integrity throughout your app. It will not throw any errors when a key does not exist.
function multi_rename_key(&$array, $old_keys, $new_keys)
{
if(!is_array($array)){
($array=="") ? $array=array() : false;
return $array;
}
foreach($array as &$arr){
if (is_array($old_keys))
{
foreach($new_keys as $k => $new_key)
{
(isset($old_keys[$k])) ? true : $old_keys[$k]=NULL;
$arr[$new_key] = (isset($arr[$old_keys[$k]]) ? $arr[$old_keys[$k]] : null);
unset($arr[$old_keys[$k]]);
}
}else{
$arr[$new_keys] = (isset($arr[$old_keys]) ? $arr[$old_keys] : null);
unset($arr[$old_keys]);
}
}
return $array;
}
Usage is simple. You can either change a single key like in your example:
multi_rename_key($tags, "url", "value");
or a more complex multikey
multi_rename_key($tags, array("url","name"), array("value","title"));
It uses similar syntax as preg_replace() where the amount of $old_keys and $new_keys should be the same. However when they are not a blank key is added. This means you can use it to add a sort if schema to your array.
Use this all the time, hope it helps!
A very good plugin management system to use. The included vimrc file is good enough for python programming and can be easily configured to your needs. See http://spf13.com/project/spf13-vim/
I am surprised that no-one else has mentioned this so I am sharing in case none of the above help (my case).
What was happening was that an VBCSCompiler.exe instance was somehow stuck and was in fact not releasing the file handles to allow new instances to correctly write the new files and was causing the issue. This became apparent when I tried to delete the "bin" folder and it was complaining that another process was using files in there.
Closed VS, opened task manager, looked and terminated all VBCSCompiler instances and deleted the "bin" folder to get back to where I was.
Just add another join:
SELECT dashboard_data.headline,
dashboard_data.message,
dashboard_messages.image_id,
images.filename
FROM dashboard_data
INNER JOIN dashboard_messages
ON dashboard_message_id = dashboard_messages.id
INNER JOIN images
ON dashboard_messages.image_id = images.image_id
Globbing uses brackets, hence the need to escape them with a slash \
. Alternatively, the following command-line switch will disable globbing:
--globoff
(or the short-option version: -g
)
Ex:
curl --globoff https://www.google.com?test[]=1
To use Objectid method you don't need to import it. It is already on the mongodb object.
var ObjectId = new db.ObjectId('58c85d1b7932a14c7a0a320d');_x000D_
db.yourCollection.findOne({ _id: ObjectId }, function (err, info) {_x000D_
console.log(info)_x000D_
});_x000D_
_x000D_
Another avenue that hasn't been considered is that your postgres was installed by pgvm
(Postgres Version Manager).
Uninstall with pgvm uninstall 9.0.3
Here's a cross browser function I have in my standard library:
function getCursorPos(input) {
if ("selectionStart" in input && document.activeElement == input) {
return {
start: input.selectionStart,
end: input.selectionEnd
};
}
else if (input.createTextRange) {
var sel = document.selection.createRange();
if (sel.parentElement() === input) {
var rng = input.createTextRange();
rng.moveToBookmark(sel.getBookmark());
for (var len = 0;
rng.compareEndPoints("EndToStart", rng) > 0;
rng.moveEnd("character", -1)) {
len++;
}
rng.setEndPoint("StartToStart", input.createTextRange());
for (var pos = { start: 0, end: len };
rng.compareEndPoints("EndToStart", rng) > 0;
rng.moveEnd("character", -1)) {
pos.start++;
pos.end++;
}
return pos;
}
}
return -1;
}
Use it in your code like this:
var cursorPosition = getCursorPos($('#myTextarea')[0])
Here's its complementary function:
function setCursorPos(input, start, end) {
if (arguments.length < 3) end = start;
if ("selectionStart" in input) {
setTimeout(function() {
input.selectionStart = start;
input.selectionEnd = end;
}, 1);
}
else if (input.createTextRange) {
var rng = input.createTextRange();
rng.moveStart("character", start);
rng.collapse();
rng.moveEnd("character", end - start);
rng.select();
}
}
I recently found and modified this snippet from an existing SO post that I have not been able to find again but I've found it very useful
// specify any elements you've attached listeners to here
const nodes = [document]
// https://developer.mozilla.org/en-US/docs/Web/Events
const logBrowserEvents = () => {
const AllEvents = {
AnimationEvent: ['animationend', 'animationiteration', 'animationstart'],
AudioProcessingEvent: ['audioprocess'],
BeforeUnloadEvent: ['beforeunload'],
CompositionEvent: [
'compositionend',
'compositionstart',
'compositionupdate',
],
ClipboardEvent: ['copy', 'cut', 'paste'],
DeviceLightEvent: ['devicelight'],
DeviceMotionEvent: ['devicemotion'],
DeviceOrientationEvent: ['deviceorientation'],
DeviceProximityEvent: ['deviceproximity'],
DragEvent: [
'drag',
'dragend',
'dragenter',
'dragleave',
'dragover',
'dragstart',
'drop',
],
Event: [
'DOMContentLoaded',
'abort',
'afterprint',
'beforeprint',
'cached',
'canplay',
'canplaythrough',
'change',
'chargingchange',
'chargingtimechange',
'checking',
'close',
'dischargingtimechange',
'downloading',
'durationchange',
'emptied',
'ended',
'error',
'fullscreenchange',
'fullscreenerror',
'input',
'invalid',
'languagechange',
'levelchange',
'loadeddata',
'loadedmetadata',
'noupdate',
'obsolete',
'offline',
'online',
'open',
'open',
'orientationchange',
'pause',
'play',
'playing',
'pointerlockchange',
'pointerlockerror',
'ratechange',
'readystatechange',
'reset',
'seeked',
'seeking',
'stalled',
'submit',
'success',
'suspend',
'timeupdate',
'updateready',
'visibilitychange',
'volumechange',
'waiting',
],
FocusEvent: [
'DOMFocusIn',
'DOMFocusOut',
'Unimplemented',
'blur',
'focus',
'focusin',
'focusout',
],
GamepadEvent: ['gamepadconnected', 'gamepaddisconnected'],
HashChangeEvent: ['hashchange'],
KeyboardEvent: ['keydown', 'keypress', 'keyup'],
MessageEvent: ['message'],
MouseEvent: [
'click',
'contextmenu',
'dblclick',
'mousedown',
'mouseenter',
'mouseleave',
'mousemove',
'mouseout',
'mouseover',
'mouseup',
'show',
],
// https://developer.mozilla.org/en-US/docs/Web/Guide/Events/Mutation_events
MutationNameEvent: ['DOMAttributeNameChanged', 'DOMElementNameChanged'],
MutationEvent: [
'DOMAttrModified',
'DOMCharacterDataModified',
'DOMNodeInserted',
'DOMNodeInsertedIntoDocument',
'DOMNodeRemoved',
'DOMNodeRemovedFromDocument',
'DOMSubtreeModified',
],
OfflineAudioCompletionEvent: ['complete'],
OtherEvent: ['blocked', 'complete', 'upgradeneeded', 'versionchange'],
UIEvent: [
'DOMActivate',
'abort',
'error',
'load',
'resize',
'scroll',
'select',
'unload',
],
PageTransitionEvent: ['pagehide', 'pageshow'],
PopStateEvent: ['popstate'],
ProgressEvent: [
'abort',
'error',
'load',
'loadend',
'loadstart',
'progress',
],
SensorEvent: ['compassneedscalibration', 'Unimplemented', 'userproximity'],
StorageEvent: ['storage'],
SVGEvent: [
'SVGAbort',
'SVGError',
'SVGLoad',
'SVGResize',
'SVGScroll',
'SVGUnload',
],
SVGZoomEvent: ['SVGZoom'],
TimeEvent: ['beginEvent', 'endEvent', 'repeatEvent'],
TouchEvent: [
'touchcancel',
'touchend',
'touchenter',
'touchleave',
'touchmove',
'touchstart',
],
TransitionEvent: ['transitionend'],
WheelEvent: ['wheel'],
}
const RecentlyLoggedDOMEventTypes = {}
Object.keys(AllEvents).forEach((DOMEvent) => {
const DOMEventTypes = AllEvents[DOMEvent]
if (Object.prototype.hasOwnProperty.call(AllEvents, DOMEvent)) {
DOMEventTypes.forEach((DOMEventType) => {
const DOMEventCategory = `${DOMEvent} ${DOMEventType}`
nodes.forEach((node) => {
node.addEventListener(
DOMEventType,
(e) => {
if (RecentlyLoggedDOMEventTypes[DOMEventCategory]) return
RecentlyLoggedDOMEventTypes[DOMEventCategory] = true
// NOTE: throttle continuous events
setTimeout(() => {
RecentlyLoggedDOMEventTypes[DOMEventCategory] = false
}, 1000)
const isActive = e.target === document.activeElement
// https://developer.mozilla.org/en-US/docs/Web/API/DocumentOrShadowRoot/activeElement
const hasActiveElement = document.activeElement !== document.body
const msg = [
DOMEventCategory,
'target:',
e.target,
...(hasActiveElement
? ['active:', document.activeElement]
: []),
]
if (isActive) {
console.info(...msg)
}
},
true,
)
})
})
}
})
}
logBrowserEvents()
// export default logBrowserEvents
Enclose <img>
in <a>
tag.
<a href="http://www.google.com.pk"><img src="smiley.gif"></a>
it will open link on same tab, and if you want to open link on new tab then use target="_blank"
<a href="http://www.google.com.pk" target="_blank"><img src="smiley.gif"></a>
You can't modify the members of a CSS class on the fly. However, you could introduce a new <style>
tag on the page with your new css class implementation, and then switch out the class. Example:
Sample.css
.someClass { border: 1px solid black; font-size: 20px; }
You want to change that class entirely, so you create a new style element:
<style>
.someClassReplacement { border: 1px solid white; font-size: 14px; }
</style>
You then do a simple replacement via jQuery:
$('.someClass').removeClass('someClass').addClass('someClassReplacement');
I keep hearing people say they're forking code in git. Git "fork" sounds suspiciously like git "clone" plus some (meaningless) psychological willingness to forgo future merges. There is no fork command in git, right?
"Forking" is a concept, not a command specifically supported by any version control system.
The simplest kind of forking is synonymous with branching. Every time you create a branch, regardless of your VCS, you've "forked". These forks are usually pretty easy to merge back together.
The kind of fork you're talking about, where a separate party takes a complete copy of the code and walks away, necessarily happens outside the VCS in a centralized system like Subversion. A distributed VCS like Git has much better support for forking the entire codebase and effectively starting a new project.
Git (not GitHub) natively supports "forking" an entire repo (ie, cloning it) in a couple of ways:
origin
is created for youorigin
equivalentsGit makes contributing changes back to the source of the fork as simple as asking someone from the original project to pull from you, or requesting write access to push changes back yourself. This is the part that GitHub makes easier, and standardizes.
Any angst over Github extending git in this direction? Or any rumors of git absorbing the functionality?
There is no angst because your assumption is wrong. GitHub "extends" the forking functionality of Git with a nice GUI and a standardized way of issuing pull requests, but it doesn't add the functionality to Git. The concept of full-repo-forking is baked right into distributed version control at a fundamental level. You could abandon GitHub at any point and still continue to push/pull projects you've "forked".
//Do this
int IS_NULL_PTR(char *k){
memset(&k, k, sizeof k);
if(k) { return 71; } ;
return 72;
}
int PRINT_PTR_SAFE(char *KR){
char *E=KR;;
if (IS_NULL_PTR(KR)==71){
printf("%s\r\n",KR);
} else {
printf("%s","(null)\r\n");
}
}
int main(int argc,char *argv[]){
int i=0;
char *A=malloc(sizeof(char)*9);
;strcpy(A,"hello world");
for (i=((int)(A))-10;i<1e+40;i++){
PRINT_PTR_SAFE(i);
}
}
//Then watch the show!
//Edit as you wish. Just credit me if you really want more of this.
I prefer this
WHERE CASE WHEN my_col LIKE '%val1%' THEN 1
WHEN my_col LIKE '%val2%' THEN 1
WHEN my_col LIKE '%val3%' THEN 1
ELSE 0
END = 1
I'm not saying it's optimal but it works and it's easily understood. Most of my queries are adhoc used once so performance is generally not an issue for me.
I am using an ImageView in an RelativeLayout that overlays with my normal layout. No code required. It sizes the image to the full height of the screen (or any other layout you use) and then crops the picture left and right to fit the width. In my case, if the user turns the screen, the picture may be a tiny bit too small. Therefore I use match_parent, which will make the image stretch in width if too small.
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<ImageView
android:id="@+id/main_backgroundImage"
android:layout_width="match_parent"
//comment: Stretches picture in the width if too small. Use "wrap_content" does not stretch, but leaves space
android:layout_height="match_parent"
//in my case I always want the height filled
android:layout_alignParentTop="true"
android:scaleType="centerCrop"
//will crop picture left and right, so it fits in height and keeps aspect ratio
android:contentDescription="@string/image"
android:src="@drawable/your_image" />
<LinearLayout
android:id="@+id/main_root"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
</LinearLayout>
</RelativeLayout>
Use 'q'
as the the optional argument to getline
.
#include <iostream>
#include <sstream>
int main() {
std::string numbers_str;
getline( std::cin, numbers_str, 'q' );
int number;
for ( std::istringstream numbers_iss( numbers_str );
numbers_iss >> number; ) {
std::cout << number << ' ';
}
}
I think move
would probably be the closest standard cursor value for what you're doing:
move
Indicates something is to be moved.
You can resave the image and literally find the src file of your project and add it to that when you save. For me I had to go to netbeans and found my project and when that comes up it had 3 files src was the last. Don't click on any of them just save your pic there. That should work. Now resizing it may be a different issue and one I'm working on now lol
This is such a common problem, especially in GUI applications, that I'm surprised there isn't a BCL class to do this out of the box. Here's how I do it.
public static class ReflectiveEnumerator
{
static ReflectiveEnumerator() { }
public static IEnumerable<T> GetEnumerableOfType<T>(params object[] constructorArgs) where T : class, IComparable<T>
{
List<T> objects = new List<T>();
foreach (Type type in
Assembly.GetAssembly(typeof(T)).GetTypes()
.Where(myType => myType.IsClass && !myType.IsAbstract && myType.IsSubclassOf(typeof(T))))
{
objects.Add((T)Activator.CreateInstance(type, constructorArgs));
}
objects.Sort();
return objects;
}
}
A few notes:
Assembly.GetAssembly(typeof(T))
because your base class might be in a different assembly. type.IsClass
and !type.IsAbstract
because it'll throw an exception if you try to instantiate an interface or abstract class.IComparable
so that they can be sorted.If you need Jenkins to access more then 1 project you will need to:
1. add public key to one github user account
2. add this user as Owner (to access all projects) or as a Collaborator in every project.
Many public keys for one system user will not work because GitHub will find first matched deploy key and will send back error like "ERROR: Permission to user/repo2 denied to user/repo1"
After read all Answers I came up with elegant way:
public class MyActivity extends ActionBarActivity {
Fragment fragment ;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
FragmentManager fm = getSupportFragmentManager();
fragment = fm.findFragmentByTag("myFragmentTag");
if (fragment == null) {
FragmentTransaction ft = fm.beginTransaction();
fragment =new MyFragment();
ft.add(android.R.id.content,fragment,"myFragmentTag");
ft.commit();
}
}
basically you don't need to add a frameLayout as container of your fragment instead you can add straight the fragment into the android root View container
IMPORTANT: don't use replace fragment as most of the approach shown here, unless you don't mind to lose fragment variable instance state during onrecreation process.
Websockets use sockets in their implementation. Websockets are based on a standard protocol (now in final call, but not yet final) that defines a connection "handshake" and message "frame." The two sides go through the handshake procedure to mutually accept a connection and then use the standard message format ("frame") to pass messages back and forth.
I'm developing a framework that will allow you to communicate directly machine to machine with installed software. It might suit your purpose. You can follow my blog if you wish: http://highlevellogic.blogspot.com/2011/09/websocket-server-demonstration_26.html
Simple Console Span/Fill/Pad/Padding with automatic scaling/resizing Method and Example.
function create-console-spanner() {
# 1: left-side-text, 2: right-side-text
local spanner="";
eval printf -v spanner \'"%0.1s"\' "-"{1..$[$(tput cols)- 2 - ${#1} - ${#2}]}
printf "%s %s %s" "$1" "$spanner" "$2";
}
Example: create-console-spanner "loading graphics module" "[success]"
Now here is a full-featured-color-character-terminal-suite that does everything in regards to printing a color and style formatted string with a spanner.
# Author: Triston J. Taylor <[email protected]>
# Date: Friday, October 19th, 2018
# License: OPEN-SOURCE/ANY (NO-PRODUCT-LIABILITY OR WARRANTIES)
# Title: paint.sh
# Description: color character terminal driver/controller/suite
declare -A PAINT=([none]=`tput sgr0` [bold]=`tput bold` [black]=`tput setaf 0` [red]=`tput setaf 1` [green]=`tput setaf 2` [yellow]=`tput setaf 3` [blue]=`tput setaf 4` [magenta]=`tput setaf 5` [cyan]=`tput setaf 6` [white]=`tput setaf 7`);
declare -i PAINT_ACTIVE=1;
function paint-replace() {
local contents=$(cat)
echo "${contents//$1/$2}"
}
source <(cat <<EOF
function paint-activate() {
echo "\$@" | $(for k in ${!PAINT[@]}; do echo -n paint-replace \"\&$k\;\" \"\${PAINT[$k]}\" \|; done) cat;
}
EOF
)
source <(cat <<EOF
function paint-deactivate(){
echo "\$@" | $(for k in ${!PAINT[@]}; do echo -n paint-replace \"\&$k\;\" \"\" \|; done) cat;
}
EOF
)
function paint-get-spanner() {
(( $# == 0 )) && set -- - 0;
declare -i l=$(( `tput cols` - ${2}))
eval printf \'"%0.1s"\' "${1:0:1}"{1..$l}
}
function paint-span() {
local left_format=$1 right_format=$3
local left_length=$(paint-format -l "$left_format") right_length=$(paint-format -l "$right_format")
paint-format "$left_format";
paint-get-spanner "$2" $(( left_length + right_length));
paint-format "$right_format";
}
function paint-format() {
local VAR="" OPTIONS='';
local -i MODE=0 PRINT_FILE=0 PRINT_VAR=1 PRINT_SIZE=2;
while [[ "${1:0:2}" =~ ^-[vl]$ ]]; do
if [[ "$1" == "-v" ]]; then OPTIONS=" -v $2"; MODE=$PRINT_VAR; shift 2; continue; fi;
if [[ "$1" == "-l" ]]; then OPTIONS=" -v VAR"; MODE=$PRINT_SIZE; shift 1; continue; fi;
done;
OPTIONS+=" --"
local format="$1"; shift;
if (( MODE != PRINT_SIZE && PAINT_ACTIVE )); then
format=$(paint-activate "$format&none;")
else
format=$(paint-deactivate "$format")
fi
printf $OPTIONS "${format}" "$@";
(( MODE == PRINT_SIZE )) && printf "%i\n" "${#VAR}" || true;
}
function paint-show-pallette() {
local -i PAINT_ACTIVE=1
paint-format "Normal: &red;red &green;green &blue;blue &magenta;magenta &yellow;yellow &cyan;cyan &white;white &black;black\n";
paint-format " Bold: &bold;&red;red &green;green &blue;blue &magenta;magenta &yellow;yellow &cyan;cyan &white;white &black;black\n";
}
To print a color, that's simple enough: paint-format "&red;This is %s\n" red
And you might want to get bold later on: paint-format "&bold;%s!\n" WOW
The -l
option to the paint-format
function measures the text so you can do console font metrics operations.
The -v
option to the paint-format
function works the same as printf
but cannot be supplied with -l
Now for the spanning!
paint-span "hello " . " &blue;world"
[note: we didn't add newline terminal sequence, but the text fills the terminal, so the next line only appears to be a newline terminal sequence]
and the output of that is:
hello ............................. world
I like Alfonso Tienda responce from HTTP status code for update and delete?
Here are some Tips:
DELETE
200 (if you want send some additional data in the Response) or 204 (recommended).
202 Operation deleted has not been committed yet.
If there's nothing to delete, use 204 or 404 (DELETE operation is idempotent, delete an already deleted item is operation successful, so you can return 204, but it's true that idempotent doesn't necessarily imply the same response)
Other errors:
- 400 Bad Request (Malformed syntax or a bad query is strange but possible).
- 401 Unauthorized Authentication failure
- 403 Forbidden: Authorization failure or invalid Application ID.
- 405 Not Allowed. Sure.
- 409 Resource Conflict can be possible in complex systems.
- And 501, 502 in case of errors.
PUT
If you're updating an element of a collection
- 200/204 with the same reasons as DELETE above.
- 202 if the operation has not been commited yet.
The referenced element doesn't exists:
PUT can be 201 (if you created the element because that is your behaviour)
404 If you don't want to create elements via PUT.
400 Bad Request (Malformed syntax or a bad query more common than in case of DELETE).
401 Unauthorized
403 Forbidden: Authentication failure or invalid Application ID.
405 Not Allowed. Sure.
409 Resource Conflict can be possible in complex systems, as in DELETE.
422 Unprocessable entity It helps to distinguish between a "Bad request" (e.g. malformed XML/JSON) and invalid field values
And 501, 502 in case of errors.
I was following this video: https://www.youtube.com/watch?v=WHPPQGOyy_Y but failed to run the test. After that, I deleted all the downloaded files and add the Junit using the step in the picture.
I tried most of the answers but still couldn't get it to work. This worked for me:
right click on reference -> properties -> change 'Specific Version' to false.
Hope this Helps.
This works in latest Chrome, FireFox and Edge, but not IE11:
document.evaluate('//option[text()="Yahoo"]', document).iterateNext().selected = 'selected';
And if you want to ignore spaces around the title:
document.evaluate('//option[normalize-space(text())="Yahoo"]', document).iterateNext().selected = 'selected'
Interesting if maddening puzzle...but here's the best I could get:
The data seems to repeat every 8 bytes or so.
import struct
import base64
target = \
r'''Q5YACgAAAABDlgAbAAAAAEOWAC0AAAAAQ5YAPwAAAABDlgdNAAAAAEOWB18AAAAAQ5YH
[snip.]
ZAAAAABExxniAAAAAETH/rQAAAAARMf/MwAAAABEx/+yAAAAAETIADEAAAAA'''
data = base64.b64decode(target)
cleaned_data = []
struct_format = ">ff"
for i in range(len(data) // 8):
cleaned_data.append(struct.unpack_from(struct_format, data, 8*i))
That gives output like the following (a sampling of lines from the first 100 or so):
(300.00030517578125, 0.0)
(300.05975341796875, 241.93943786621094)
(301.05612182617187, 0.0)
(301.05667114257812, 8.7439727783203125)
(326.9617919921875, 0.0)
(326.96826171875, 0.0)
(328.34432983398438, 280.55218505859375)
That first number does seem to monotonically increase through the entire set. If you plot it:
import matplotlib.pyplot as plt
f, ax = plt.subplots()
ax.plot(*zip(*cleaned_data))
format = 'hhhh'
(possibly with various paddings/directions (e.g. '<hhhh'
, '<xhhhh'
) also might be worth a look (again, random lines):
(-27069, 2560, 0, 0)
(-27069, 8968, 0, 0)
(-27069, 13576, 3139, -18487)
(-27069, 18184, 31043, -5184)
(-27069, -25721, -25533, -8601)
(-27069, -7289, 0, 0)
(-25533, 31066, 0, 0)
(-25533, -29350, 0, 0)
(-25533, 25179, 0, 0)
(-24509, -1888, 0, 0)
(-24509, -4447, 0, 0)
(-23741, -14725, 32067, 27475)
(-23741, -3973, 0, 0)
(-23485, 4908, -29629, -20922)
following is my understanding...
if you create test objects locally and feed your local service with that, you are using mock object. this will give a test for the method you implemented in your local service. it is used to verify behaviors
when you get the test data from the real service provider, though from a test version of interface and get a test version of the object, you are working with stubs the stub can have logic to accept certain input and give corresponding output to help you perform state verification...
A solution is to create your own jquery plugin that take the json map and populate the select with it.
(function($) {
$.fn.fillValues = function(options) {
var settings = $.extend({
datas : null,
complete : null,
}, options);
this.each( function(){
var datas = settings.datas;
if(datas !=null) {
$(this).empty();
for(var key in datas){
$(this).append('<option value="'+key+'"+>'+datas[key]+'</option>');
}
}
if($.isFunction(settings.complete)){
settings.complete.call(this);
}
});
}
}(jQuery));
You can call it by doing this :
$("#select").fillValues({datas:your_map,});
The advantages is that anywhere you will face the same problem you just call
$("....").fillValues({datas:your_map,});
Et voila !
You can add functions in your plugin as you like
function wndsize(){
var w = 0;var h = 0;
//IE
if(!window.innerWidth){
if(!(document.documentElement.clientWidth == 0)){
//strict mode
w = document.documentElement.clientWidth;h = document.documentElement.clientHeight;
} else{
//quirks mode
w = document.body.clientWidth;h = document.body.clientHeight;
}
} else {
//w3c
w = window.innerWidth;h = window.innerHeight;
}
return {width:w,height:h};
}
function wndcent(){
var hWnd = (arguments[0] != null) ? arguments[0] : {width:0,height:0};
var _x = 0;var _y = 0;var offsetX = 0;var offsetY = 0;
//IE
if(!window.pageYOffset){
//strict mode
if(!(document.documentElement.scrollTop == 0)){offsetY = document.documentElement.scrollTop;offsetX = document.documentElement.scrollLeft;}
//quirks mode
else{offsetY = document.body.scrollTop;offsetX = document.body.scrollLeft;}}
//w3c
else{offsetX = window.pageXOffset;offsetY = window.pageYOffset;}_x = ((wndsize().width-hWnd.width)/2)+offsetX;_y = ((wndsize().height-hWnd.height)/2)+offsetY;
return{x:_x,y:_y};
}
var center = wndcent({width:350,height:350});
document.write(center.x+';<br>');
document.write(center.y+';<br>');
document.write('<DIV align="center" id="rich_ad" style="Z-INDEX: 10; left:'+center.x+'px;WIDTH: 350px; POSITION: absolute; TOP: '+center.y+'px; HEIGHT: 350px"><!--? ?????????, ? ??? ?? ?????????? flash ?????.--></div>');
I started to use
git show-branch --no-name <hash>
It seems to be faster than
git show -s --format=%s <hash>
Both give the same result
I actually wrote a small tool to see the status of all my repos. You can find it on github.
pip won't install binary packages and isn't well tested on Windows.
As Windows doesn't come with a compiler by default pip often can't be used there. easy_install can install binary packages for Windows.
You didn't specify how the order is determined, but this will give you a rank value in MySQL:
SELECT t.*,
@rownum := @rownum +1 AS rank
FROM TBL_FOO t
JOIN (SELECT @rownum := 0) r
WHERE t.name = 'sarmen'
Then you can pick out what rows you want, based on the rank value.
To get and show the user's current location, you could also use MyLocationOverlay
. Suppose you have a mapView
field in your activity. All you would need to do to show the user location is the following:
myLocationOverlay = new MyLocationOverlay(this, mapView);
myLocationOverlay.enableMyLocation();
mapView.getOverlays().add(myLocationOverlay);
This gets the current location from either the GPS or the network. If both fail, enableMyLocation()
will return false
.
As for the locations of things around the area, an ItemizedOverlay
should do the trick.
I hope I haven't misunderstood your question. Good luck.
SPListItem item;
DataRow dr = datatable.NewRow();
dr["ID"] = (!Object.Equals(item["ID"], null)) ? item["ID"].ToString() : string.Empty;
As already stated, enum instances should be uppercase according to the docs on the Oracle website (http://docs.oracle.com/javase/tutorial/java/javaOO/enum.html).
However, while looking through a JavaEE7 tutorial on the Oracle website (http://www.oracle.com/technetwork/java/javaee/downloads/index.html), I stumbled across the "Duke's bookstore" tutorial and in a class (tutorial\examples\case-studies\dukes-bookstore\src\main\java\javaeetutorial\dukesbookstore\components\AreaComponent.java
), I found the following enum definition:
private enum PropertyKeys {
alt, coords, shape, targetImage;
}
According to the conventions, it should have looked like:
public enum PropertyKeys {
ALT("alt"), COORDS("coords"), SHAPE("shape"), TARGET_IMAGE("targetImage");
private final String val;
private PropertyKeys(String val) {
this.val = val;
}
@Override
public String toString() {
return val;
}
}
So it seems even the guys at Oracle sometimes trade convention with convenience.
Simple solution :-
List<String> list = new ArrayList<String>(Arrays.asList("a", "b", "d", "c"));
List<String> list2 = new ArrayList<String>(Arrays.asList("b", "f", "c"));
list.retainAll(list2);
list2.removeAll(list);
System.out.println("similiar " + list);
System.out.println("different " + list2);
Output :-
similiar [b, c]
different [f]
Or if the Boolean value is not been returned, you can do something like this:
bool boolValue = (returnValue == "1");
Also, the Common function config_item()
works pretty much everywhere throughout the CodeIgniter instance. Controllers, models, views, libraries, helpers, hooks, whatever.
The first line of a paragraph is indented by default, thus whether or not you have \indent
there won't make a difference. \indent
and \noindent
can be used to override default behavior. You can see this by replacing your line with the following:
Now we are engaged in a great civil war.\\
\indent this is indented\\
this isn't indented
\noindent override default indentation (not indented)\\
asdf
use the
innerHTML
property and access the td
using getElementById()
as always.
Here is an example of how to convert a number of any base to another base.
from collections import namedtuple
Test = namedtuple("Test", ["n", "from_base", "to_base", "expected"])
def convert(n: int, from_base: int, to_base: int) -> int:
digits = []
while n:
(n, r) = divmod(n, to_base)
digits.append(r)
return sum(from_base ** i * v for i, v in enumerate(digits))
if __name__ == "__main__":
tests = [
Test(32, 16, 10, 50),
Test(32, 20, 10, 62),
Test(1010, 2, 10, 10),
Test(8, 10, 8, 10),
Test(150, 100, 1000, 150),
Test(1500, 100, 10, 1050000),
]
for test in tests:
result = convert(*test[:-1])
assert result == test.expected, f"{test=}, {result=}"
print("PASSED!!!")
My Dark Color scheme for QtCreator is at:
https://github.com/borzh/qt-creator-css/blob/master/qt-creator.css
To use with Vim (dark) scheme.
Hope it is useful for someone.
<div class="apple-monkey"></div>
<div class="apple-horse"></div>
<div class="cow-apple-brick"></div>
in this case as question Josh Stodola answer is correct Classes that start with "apple-" plus classes that contain " apple-"
$("div[class^='apple-'],div[class*=' apple-']")
but if element have multiple classes like this
<div class="some-class apple-monkey"></div>
<div class="some-class apple-horse"></div>
<div class="some-class cow-apple-brick"></div>
then Josh Stodola's solution will do not work
for this have to do some thing like this
$('.some-parent-class div').filter(function () {
return this.className.match(/\bapple-/);// this is for start with
//return this.className.match(/apple-/g);// this is for contain selector
}).css("color","red");
may be it helps some one else thanks
Let me at least answer a part of your question. With an example of how the Linux ABI affects the systemcalls, and why that is usefull.
A systemcall is a way for a userspace program to ask the kernelspace for something. It works by putting the numeric code for the call and the argument in a certain register and triggering an interrupt. Than a switch occurs to kernelspace and the kernel looks up the numeric code and the argument, handles the request, puts the result back into a register and triggers a switch back to userspace. This is needed for example when the application wants to allocate memory or open a file (syscalls "brk" and "open").
Now the syscalls have short names "brk", etc. and corresponding opcodes, these are defined in a system specific header file. As long as these opcodes stay the same you can run the same compiled userland programs with different updated kernels without having to recompile. So you have an interface used by precompiled binarys, hence ABI.
A reusable isEmpty( <selector> )
function.
You can also run it toward a collection of elements (see example)
const isEmpty = sel =>_x000D_
![... document.querySelectorAll(sel)].some(el => el.innerHTML.trim() !== "");_x000D_
_x000D_
console.log(_x000D_
isEmpty("#one"), // false_x000D_
isEmpty("#two"), // true_x000D_
isEmpty(".foo"), // false_x000D_
isEmpty(".bar") // true_x000D_
);
_x000D_
<div id="one">_x000D_
foo_x000D_
</div>_x000D_
_x000D_
<div id="two">_x000D_
_x000D_
</div>_x000D_
_x000D_
<div class="foo"></div>_x000D_
<div class="foo"><p>foo</p></div>_x000D_
<div class="foo"></div>_x000D_
_x000D_
<div class="bar"></div>_x000D_
<div class="bar"></div>_x000D_
<div class="bar"></div>
_x000D_
returns true
(and exits loop) as soon one element has any kind of content beside spaces or newlines.
I would suggest (as a first pass) that PUT
should only be used for updating existing entities. POST
should be used for creating new ones. i.e.
/api/users when called with PUT, creates user record
doesn't feel right to me. The rest of your first section (re. verb usage) looks logical, however.
The story of %2F
vs /
was that, according to the initial W3C recommendations, slashes «must imply a hierarchical structure»:
The slash ("/", ASCII 2F hex) character is reserved for the delimiting of substrings whose relationship is hierarchical. This enables partial forms of the URI.
Example 2
The URIs
http://www.w3.org/albert/bertram/marie-claude
and
http://www.w3.org/albert/bertram%2Fmarie-claude
are NOT identical, as in the second case the encoded slash does not have hierarchical significance.
The idea is that the response body gives you a page that links you to the thing:
201 Created
The 201 (Created) status code indicates that the request has been fulfilled and has resulted in one or more new resources being created. The primary resource created by the request is identified by either a Location header field in the response or, if no Location field is received, by the effective request URI.
This means that you would include a Location
in the response header that gives the URL of where you can find the newly created thing:
HTTP/1.1 201 Created
Date: Sat, 02 Apr 2016 12:22:40 GMT
Location: http://stackoverflow.com/a/36373586/12597
They then go on to mention what you should include in the response body:
The 201 response payload typically describes and links to the resource(s) created.
For the human using the browser, you give them something they can look at, and click, to get to their newly created resource:
HTTP/1.1 201 Created
Date: Sat, 02 Apr 2016 12:22:40 GMT
Location: http://stackoverflow.com/a/36373586/12597
Content-Type: text/html
Your answer has been saved!
Click <A href="/a/36373586/12597">here</A> to view it.
If the page will only be used by a robot, the it makes sense to have the response be computer readable:
HTTP/1.1 201 Created
Date: Sat, 02 Apr 2016 12:22:40 GMT
Location: http://stackoverflow.com/a/36373586/12597
Content-Type: application/xml
<createdResources>
<questionID>1860645</questionID>
<answerID>36373586</answerID>
<primary>/a/36373586/12597</primary>
<additional>
<resource>http://stackoverflow.com/questions/1860645/create-request-with-post-which-response-codes-200-or-201-and-content/36373586#36373586</resource>
<resource>http://stackoverflow.com/a/1962757/12597</resource>
</additional>
</createdResource>
Or, if you prefer:
HTTP/1.1 201 Created
Date: Sat, 02 Apr 2016 12:22:40 GMT
Location: http://stackoverflow.com/a/36373586/12597
Content-Type: application/json
{
"questionID": 1860645,
"answerID": 36373586,
"primary": "/a/36373586/12597",
"additional": [
"http://stackoverflow.com/questions/1860645/create-request-with-post-which-response-codes-200-or-201-and-content/36373586#36373586",
"http://stackoverflow.com/a/36373586/12597"
]
}
The response is entirely up to you; it's arbitrarily what you'd like.
Finally there's the optimization that I can pre-cache the created resource (because I already have the content; I just uploaded it). The server can return a date or ETag which I can store with the content I just uploaded:
See Section 7.2 for a discussion of the meaning and purpose of validator header fields, such as ETag and Last-Modified, in a 201 response.
HTTP/1.1 201 Created
Date: Sat, 02 Apr 2016 12:22:40 GMT
Location: http://stackoverflow.com/a/23704283/12597
Content-Type: text/html
ETag: JF2CA53BOMQGU5LTOQQGC3RAMV4GC3LQNRSS4
Last-Modified: Sat, 02 Apr 2016 12:22:39 GMT
Your answer has been saved!
Click <A href="/a/36373586/12597">here</A> to view it.
And ETag
s are purely arbitrary values. Having them be different when a resource changes (and caches need to be updated) is all that matters. The ETag is usually a hash (e.g. SHA2). But it can be a database rowversion
, or an incrementing revision number. Anything that will change when the thing changes.
location.hash is not safe for IE , in case of IE ( including IE9 ) , if your page contains iframe , then after manual refresh inside iframe content get location.hash value is old( value for first page load ). while manual retrieved value is different than location.hash so always retrieve it through document.URL
var hash = document.URL.substr(document.URL.indexOf('#')+1)
For those looking for an SCSS mixin instead, including woff2:
@mixin fface($path, $family, $type: '', $weight: 400, $svg: '', $style: normal) {
@font-face {
font-family: $family;
@if $svg == '' {
// with OTF without SVG and EOT
src: url('#{$path}#{$type}.otf') format('opentype'), url('#{$path}#{$type}.woff2') format('woff2'), url('#{$path}#{$type}.woff') format('woff'), url('#{$path}#{$type}.ttf') format('truetype');
} @else {
// traditional src inclusions
src: url('#{$path}#{$type}.eot');
src: url('#{$path}#{$type}.eot?#iefix') format('embedded-opentype'), url('#{$path}#{$type}.woff2') format('woff2'), url('#{$path}#{$type}.woff') format('woff'), url('#{$path}#{$type}.ttf') format('truetype'), url('#{$path}#{$type}.svg##{$svg}') format('svg');
}
font-weight: $weight;
font-style: $style;
}
}
// ========================================================importing
$dir: '/assets/fonts/';
$famatic: 'AmaticSC';
@include fface('#{$dir}amatic-sc-v11-latin-regular', $famatic, '', 400, $famatic);
$finter: 'Inter';
// adding specific types of font-weights
@include fface('#{$dir}#{$finter}', $finter, '-Thin-BETA', 100);
@include fface('#{$dir}#{$finter}', $finter, '-Regular', 400);
@include fface('#{$dir}#{$finter}', $finter, '-Medium', 500);
@include fface('#{$dir}#{$finter}', $finter, '-Bold', 700);
// ========================================================usage
.title {
font-family: Inter;
font-weight: 700; // Inter-Bold font is loaded
}
.special-title {
font-family: AmaticSC;
font-weight: 700; // default font is loaded
}
The $type
parameter is useful for stacking related families with different weights.
The @if
is due to the need of supporting the Inter font (similar to Roboto), which has OTF but doesn't have SVG and EOT types at this time.
If you get a can't resolve error, remember to double check your fonts directory ($dir
).
It leaves blank pages so that a new part or chapter start on the right-hand side. You can fix this with the "openany" option for the document class. ;)
For AMPPS, I have to add this is my phpMyAdmin/config.inc.php
$cfg['Servers'][$i]['user'] = 'root';
$cfg['Servers'][$i]['password'] = '';
$cfg['Servers'][$i]['AllowNoPassword'] = true;
Note: In Ubuntu, I had to locate where the file is and I used locate config.inc.php
This answer is only meant for local, development purposes :)
The problem is that you are using SingleOrDefault
. This method will only succeed when the collections contains exactly 0 or 1 element. I believe you are looking for FirstOrDefault
which will succeed no matter how many elements are in the collection.
This should do it:
$("label[for=comedyclubs]")
If you have non alphanumeric characters in your id then you must surround the attr value with quotes:
$("label[for='comedy-clubs']")
this is my sample you can use:
public static string GetFileNameValidChar(string fileName)
{
foreach (var item in System.IO.Path.GetInvalidFileNameChars())
{
fileName = fileName.Replace(item.ToString(), "");
}
return fileName;
}
public static string GetFileNameFromUrl(string url)
{
string fileName = "";
if (Uri.TryCreate(url, UriKind.Absolute, out Uri uri))
{
fileName = GetFileNameValidChar(Path.GetFileName(uri.AbsolutePath));
}
string ext = "";
if (!string.IsNullOrEmpty(fileName))
{
ext = Path.GetExtension(fileName);
if (string.IsNullOrEmpty(ext))
ext = ".html";
else
ext = "";
return GetFileNameValidChar(fileName + ext);
}
fileName = Path.GetFileName(url);
if (string.IsNullOrEmpty(fileName))
{
fileName = "noName";
}
ext = Path.GetExtension(fileName);
if (string.IsNullOrEmpty(ext))
ext = ".html";
else
ext = "";
fileName = fileName + ext;
if (!fileName.StartsWith("?"))
fileName = fileName.Split('?').FirstOrDefault();
fileName = fileName.Split('&').LastOrDefault().Split('=').LastOrDefault();
return GetFileNameValidChar(fileName);
}
Usage:
var fileName = GetFileNameFromUrl("http://cdn.p30download.com/?b=p30dl-software&f=Mozilla.Firefox.v58.0.x86_p30download.com.zip");
This is how it worked for me:
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("DELETE");
int responseCode = connection.getResponseCode();
I have been hasseling with that as other folks have.
I used the criteria;
=countif(matchingList,C2)=0
where matchingList is the list that i am using as a filter.
have a look at this
http://www.youtube.com/watch?v=x47VFMhRLnM&list=PL63A7644FE57C97F4&index=30
The trick i found is that normally you would have the column heading in the criteria matching the data column heading. this will not work for criteria that is a formula.
What I found was if I left the column heading blank for only the criteria that has the countif
formula in the advanced filter works. If I have the column heading i.e. the column heading for column C2 in my formula example then the filter return no output.
Hope this helps
There is an issue with simple usage of:
org.apache.commons.io.FileUtils.copyURLToFile(URL, File)
if you need to download and save very large files, or in general if you need automatic retries in case connection is dropped.
What I suggest in such cases is Apache HttpClient along with org.apache.commons.io.FileUtils. For example:
GetMethod method = new GetMethod(resource_url);
try {
int statusCode = client.executeMethod(method);
if (statusCode != HttpStatus.SC_OK) {
logger.error("Get method failed: " + method.getStatusLine());
}
org.apache.commons.io.FileUtils.copyInputStreamToFile(
method.getResponseBodyAsStream(), new File(resource_file));
} catch (HttpException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
method.releaseConnection();
}
For Drupal 8 you can do this :
$url = 'YOUR_URL';
$url = \Drupal\Core\Url::fromUserInput('/' . $url, array('absolute' => 'true'))->toString();
You can use the script from http://technet.microsoft.com/en-us/library/ee692772.aspx#EBAA to access the registry and list applications using WMI.
I like the style of Mike Woodhouse's answer on the other page you mentioned. It's especially concise when the thing being maximised over is just a single column, in which case the subquery can just use MAX(some_col)
and GROUP BY
the other columns, but in your case you have a 2-part quantity to be maximised, you can still do so by using ORDER BY
plus LIMIT 1
instead (as done by Quassnoi):
SELECT *
FROM lives outer
WHERE (usr_id, time_stamp, trans_id) IN (
SELECT usr_id, time_stamp, trans_id
FROM lives sq
WHERE sq.usr_id = outer.usr_id
ORDER BY trans_id, time_stamp
LIMIT 1
)
I find using the row-constructor syntax WHERE (a, b, c) IN (subquery)
nice because it cuts down on the amount of verbiage needed.
Well, you can compute the height of a tree with the following recursive function:
int height(struct tree *t) {
if (t == NULL)
return 0;
else
return max(height(t->left), height(t->right)) + 1;
}
with an appropriate definition of max()
and struct tree
. You should take the time to figure out why this corresponds to the definition based on path-length that you quote. This function uses zero as the height of the empty tree.
However, for something like an AVL tree, I don't think you actually compute the height each time you need it. Instead, each tree node is augmented with a extra field that remembers the height of the subtree rooted at that node. This field has to be kept up-to-date as the tree is modified by insertions and deletions.
I suspect that, if you compute the height each time instead of caching it within the tree like suggested above, that the AVL tree shape will be correct, but it won't have the expected logarithmic performance.
Automatically fill all form fields from an array
http://jsfiddle.net/brynner/wf0rk7tz/2/
JS
function fill(a){
for(var k in a){
$('[name="'+k+'"]').val(a[k]);
}
}
array_example = {"God":"Jesus","Holy":"Spirit"};
fill(array_example);
HTML
<form>
<input name="God">
<input name="Holy">
</form>
You have to be careful using the destructor. This will get called on the GC Finalizer thread. In some cases the resources that your freeing may not like being released on a different thread from the one they were created on.
Rope: It's a string that allows for cheap prepends, substrings, middle insertions and appends. I've really only had use for it once, but no other structure would have sufficed. Regular strings and arrays prepends were just far too expensive for what we needed to do, and reversing everthing was out of the question.
Use the replace
function in js:
var emailAdd = $(this).text().replace(/ /g,'');
That will remove all the spaces
If you want to remove the leading and trailing whitespace only, use the jQuery $.trim method :
var emailAdd = $.trim($(this).text());
I prefer to use tuples whenever a tuple feels "natural"; coordinates are a typical example, where the separate objects can stand on their own, e.g. in one-axis only scaling calculations, and the order is important. Note: if I can sort or shuffle the items without an adverse effect to the meaning of the group, then I probably shouldn't use a tuple.
I use dictionaries as a return value only when the grouped objects aren't always the same. Think optional email headers.
For the rest of the cases, where the grouped objects have inherent meaning inside the group or a fully-fledged object with its own methods is needed, I use a class.
Copying and pasting from the MS-DOS tree
command might also work for you. Examples:
tree
C:\Foobar>tree
C:.
+---FooScripts
+---barconfig
+---Baz
¦ +---BadBaz
¦ +---Drop
...
tree /F
C:\Foobar>tree
C:.
+---FooScripts
¦ foo.sh
+---barconfig
¦ bar.xml
+---Baz
¦ +---BadBaz
¦ ¦ badbaz.xml
¦ +---Drop
...
tree /A
C:\Foobar>tree /A
C:.
+---FooScripts
+---barconfig
+---Baz
¦ +---BadBaz
¦ \---Drop
...
tree /F /A
C:\Foobar>tree /A
C:.
+---FooScripts
¦ foo.sh
+---barconfig
¦ bar.xml
+---Baz
¦ +---BadBaz
¦ ¦ badbaz.xml
¦ \---Drop
...
tree
[drive:
][path
] [/F
] [/A
]
drive:\path
— Drive and directory containing disk for display of directory structure, without listing files.
/F
— Include all files living in every directory.
/A
— Replace graphic characters used for linking lines with ext characters , instead of graphic characters./a
is used with code pages that do not support graphic characters and to send output to printers that do not properly interpret graphic characters.
Stub - an object that provides predefined answers to method calls.
Mock - an object on which you set expectations.
Fake - an object with limited capabilities (for the purposes of testing), e.g. a fake web service.
Test Double is the general term for stubs, mocks and fakes. But informally, you'll often hear people simply call them mocks.
To call a web service from a mobile device (especially on an Android phone), I have used a very simple way to do it. I have not used any web service client API in attempt to call the web service. My approach is as follows to make a call.
HttpURLConnection
.getResonseCode
).ErrorInput
stream on
same HTTPobject and receive the
error if any.I have implemented this procedure for the Android phone, and it is successfully running. I am able to parse the response even if it is more than 700 KB.
If you use json_decode($string, true)
, you will get no objects, but everything as an associative or number indexed array. Way easier to handle, as the stdObject provided by PHP is nothing but a dumb container with public properties, which cannot be extended with your own functionality.
$array = json_decode($string, true);
echo $array['trends'][0]['name'];
Because interfaces are in inheritance structure, and static methods don't inherit well.
This is the pattern I usually follow when setting up a harness for testing an abstract class:
public abstract class MyBase{
/*...*/
public abstract void VoidMethod(object param1);
public abstract object MethodWithReturn(object param1);
/*,,,*/
}
And the version I use under test:
public class MyBaseHarness : MyBase{
/*...*/
public Action<object> VoidMethodFunction;
public override void VoidMethod(object param1){
VoidMethodFunction(param1);
}
public Func<object, object> MethodWithReturnFunction;
public override object MethodWithReturn(object param1){
return MethodWihtReturnFunction(param1);
}
/*,,,*/
}
If the abstract methods are called when I don't expect it, the tests fail. When arranging the tests, I can easily stub out the abstract methods with lambdas that perform asserts, throw exceptions, return different values, etc.
I've been using the following with great success:
(["'])(?:(?=(\\?))\2.)*?\1
It supports nested quotes as well.
For those who want a deeper explanation of how this works, here's an explanation from user ephemient:
([""'])
match a quote;((?=(\\?))\2.)
if backslash exists, gobble it, and whether or not that happens, match a character;*?
match many times (non-greedily, as to not eat the closing quote);\1
match the same quote that was use for opening.
'Inside the Enter event
TextBox1.SelectAll();
Ok, after trying it here is what you want:
This selected all the text on entry, but allowed me to highlight part of the text afterwards, or allow you to highlight on the first click.
By request:
bool entered = false;
private void textBox1_Enter(object sender, EventArgs e)
{
entered = true;
textBox1.SelectAll(); //From Jakub's answer.
}
private void textBox1_Click(object sender, EventArgs e)
{
if (entered) textBox1.SelectAll();
entered = false;
}
private void textBox1_MouseMove(object sender, MouseEventArgs e)
{
if (entered) entered = false;
}
For me, the tabbing into the control selects all the text.
My experience in Visual Studio 2010 is that there are two changes needed so as to not need DLL's. From the project property page (right click on the project name in the Solution Explorer window):
Under Configuration Properties --> General, change the "Use of MFC" field to "Use MFC in a Static Library".
Under Configuration Properties --> C/C++ --> Code Generation, change the "Runtime Library" field to "Multi-Threaded (/MT)"
Not sure why both were needed. I used this to remove a dependency on glut32.dll.
Added later: When making these changes to the configurations, you should make them to "All Configurations" --- you can select this at the top of the Properties window. If you make the change to just the Debug configuration, it won't apply to the Release configuration, and vice-versa.
change the name of the image folder to img and then use the HTML code
There is a nice writeup here.
Configuring this in nginx/apache is a mistake.
If you are using a hosting company you can't configure the edge.
If you are using Docker, the app should be self contained.
Note that some examples use connectHandlers
but this only sets headers on the doc. Using rawConnectHandlers
applies to all assets served (fonts/css/etc).
// HSTS only the document - don't function over http.
// Make sure you want this as it won't go away for 30 days.
WebApp.connectHandlers.use(function(req, res, next) {
res.setHeader('Strict-Transport-Security', 'max-age=2592000; includeSubDomains'); // 2592000s / 30 days
next();
});
// CORS all assets served (fonts/etc)
WebApp.rawConnectHandlers.use(function(req, res, next) {
res.setHeader('Access-Control-Allow-Origin', '*');
return next();
});
This would be a good time to look at browser policy like framing, etc.
As I understand, you want the average value for each id at each pass. The solution is
SELECT id, pass, avg(value) FROM data_r1
GROUP BY id, pass;
For jQuery you can try this. I always do the following and it works.
$(function () {
$("#multiSelect").attr("size",$("#multiSelect option").length);
});
You can add atom beauty package for formatting text in atom..
file --> setting --> Install
then you type atom-beautify in search area.
then click Package button.. select atom beuty and install it.
next you can format your text using (Alt + ctrl + b) or right click and select beautify editor contents
std::remove
does not actually erase the element from the container, but it does return the new end iterator which can be passed to container_type::erase
to do the REAL removal of the extra elements that are now at the end of the container:
std::vector<int> vec;
// .. put in some values ..
int int_to_remove = n;
vec.erase(std::remove(vec.begin(), vec.end(), int_to_remove), vec.end());
I needed encoding of an UTF-8 string as base64 for a project of mine. Most of the answers here don't seem to properly handle UTF-16 surrogate pairs when converting to UTF-8 so, for completion sake, I will post my solution:
function strToUTF8Base64(str) {
function decodeSurrogatePair(hi, lo) {
var resultChar = 0x010000;
resultChar += lo - 0xDC00;
resultChar += (hi - 0xD800) << 10;
return resultChar;
}
var bytes = [0, 0, 0];
var byteIndex = 0;
var result = [];
function output(s) {
result.push(s);
}
function emitBase64() {
var digits =
'ABCDEFGHIJKLMNOPQRSTUVWXYZ' +
'abcdefghijklmnopqrstuvwxyz' +
'0123456789+/';
function toDigit(value) {
return digits[value];
}
// --Byte 0-- --Byte 1-- --Byte 2--
// 1111 1122 2222 3333 3344 4444
var d1 = toDigit(bytes[0] >> 2);
var d2 = toDigit(
((bytes[0] & 0x03) << 4) |
(bytes[1] >> 4));
var d3 = toDigit(
((bytes[1] & 0x0F) << 2) |
(bytes[2] >> 6));
var d4 = toDigit(
bytes[2] & 0x3F);
if (byteIndex === 1) {
output(d1 + d2 + '==');
}
else if (byteIndex === 2) {
output(d1 + d2 + d3 + '=');
}
else {
output(d1 + d2 + d3 + d4);
}
}
function emit(chr) {
bytes[byteIndex++] = chr;
if (byteIndex == 3) {
emitBase64();
bytes[0] = 0;
bytes[1] = 0;
bytes[2] = 0;
byteIndex = 0;
}
}
function emitLast() {
if (byteIndex > 0) {
emitBase64();
}
}
// Converts the string to UTF8:
var i, chr;
var hi, lo;
for (i = 0; i < str.length; i++) {
chr = str.charCodeAt(i);
// Test and decode surrogate pairs in the string
if (chr >= 0xD800 && chr <= 0xDBFF) {
hi = chr;
lo = str.charCodeAt(i + 1);
if (lo >= 0xDC00 && lo <= 0xDFFF) {
chr = decodeSurrogatePair(hi, lo);
i++;
}
}
// Encode the character as UTF-8.
if (chr < 0x80) {
emit(chr);
}
else if (chr < 0x0800) {
emit((chr >> 6) | 0xC0);
emit(((chr >> 0) & 0x3F) | 0x80);
}
else if (chr < 0x10000) {
emit((chr >> 12) | 0xE0);
emit(((chr >> 6) & 0x3F) | 0x80);
emit(((chr >> 0) & 0x3F) | 0x80);
}
else if (chr < 0x110000) {
emit((chr >> 18) | 0xF0);
emit(((chr >> 12) & 0x3F) | 0x80);
emit(((chr >> 6) & 0x3F) | 0x80);
emit(((chr >> 0) & 0x3F) | 0x80);
}
}
emitLast();
return result.join('');
}
Note that the code is not thoroughly tested. I tested some inputs, including things like strToUTF8Base64('????')
and compared with the output of an online encoding tool (https://www.base64encode.org/).
Using ng serve --host 0.0.0.0
will allow you to connect to the ng serve
using your ip instead of localhost
.
EDIT
In newer versions of the cli, you have to provide your local ip address instead
EDIT 2
In newer versions of the cli (I think v5 and up) you can use 0.0.0.0
as the ip again to host it for anyone on your network to talk to.
I use another Eclipse plugin to import existing gradle projects.
You can install the Builship Gradle Gntegration 2.0 using the Eclipse Marketplace client.
Then you choose FIle ? Import ? Existing Gradle Project.
Finially, indicate your project root directory and click finish.
In my case, the issue was with another instance of Tomcat was running. I stopped it from services and the issue got resolved
The syntax is
EXEC mySchema.myPackage.myProcedure@myRemoteDB( 'someParameter' );
$ gcc test.c -o testc $ file testc testc: ELF 64-bit LSB executable, x86-64, version 1 (SYSV), dynamically linked (uses shared libs), for GNU/Linux 2.6.9, not stripped $ ldd testc linux-vdso.so.1 => (0x00007fff227ff000) libc.so.6 => /lib64/libc.so.6 (0x000000391f000000) /lib64/ld-linux-x86-64.so.2 (0x000000391ec00000) $ gcc -m32 test.c -o testc $ file testc testc: ELF 32-bit LSB executable, Intel 80386, version 1 (SYSV), dynamically linked (uses shared libs), for GNU/Linux 2.6.9, not stripped $ ldd testc linux-gate.so.1 => (0x009aa000) libc.so.6 => /lib/libc.so.6 (0x00780000) /lib/ld-linux.so.2 (0x0075b000)
In short: use the -m32
flag to compile a 32-bit binary.
Also, make sure that you have the 32-bit versions of all required libraries installed (in my case all I needed on Fedora was glibc-devel.i386)
If you want to target a specific class and ID in CSS, then use a format like div.x#y {}
.
While this is sort of a follow up to the previous answer, it adds a little (hopefully).
Mainly what I want to clarify is that usually we think of drawing things like draw a rectangle at 10, 3
.
So if we think about that like this: move origin to 10, 3
, then draw rectangle at 0, 0
.
Then all we have to do is add a rotate in between.
Another big point is the alignment of the text. It's easiest to draw the text at 0, 0, so using the correct alignment can allow us to do that without measuring the text width.
We should still move the text by an amount to get it centered vertically, and unfortunately canvas does not have great line height support, so that's a guess and check thing ( correct me if there is something better ).
I've created 3 examples that provide a point and a text with 3 alignments, to show what the actual point on the screen is where the font will go.
var font, lineHeight, x, y;
x = 100;
y = 100;
font = 20;
lineHeight = 15; // this is guess and check as far as I know
this.context.font = font + 'px Arial';
// Right Aligned
this.context.save();
this.context.translate(x, y);
this.context.rotate(-Math.PI / 4);
this.context.textAlign = 'right';
this.context.fillText('right', 0, lineHeight / 2);
this.context.restore();
this.context.fillStyle = 'red';
this.context.fillRect(x, y, 2, 2);
// Center
this.context.fillStyle = 'black';
x = 150;
y = 100;
this.context.save();
this.context.translate(x, y);
this.context.rotate(-Math.PI / 4);
this.context.textAlign = 'center';
this.context.fillText('center', 0, lineHeight / 2);
this.context.restore();
this.context.fillStyle = 'red';
this.context.fillRect(x, y, 2, 2);
// Left
this.context.fillStyle = 'black';
x = 200;
y = 100;
this.context.save();
this.context.translate(x, y);
this.context.rotate(-Math.PI / 4);
this.context.textAlign = 'left';
this.context.fillText('left', 0, lineHeight / 2);
this.context.restore();
this.context.fillStyle = 'red';
this.context.fillRect(x, y, 2, 2);
The line this.context.fillText('right', 0, lineHeight / 2);
is basically 0, 0
, except we move slightly for the text to be centered near the point
Try the following
var myData = [['2013-01-22', 0], ['2013-01-29', 1], ['2013-02-05', 21]];_x000D_
_x000D_
var myTotal = 0; // Variable to hold your total_x000D_
_x000D_
for(var i = 0, len = myData.length; i < len; i++) {_x000D_
myTotal += myData[i][1]; // Iterate over your first array and then grab the second element add the values up_x000D_
}_x000D_
_x000D_
document.write(myTotal); // 22 in this instance
_x000D_
Suppose if I have GetAllEmployees.cshtml
<h2>GetAllEmployees</h2>
<p>
<a asp-action="Create">Create New</a>
</p>
<table class="table">
<thead>
// do something ...
</thead>
<tbody>
// do something ...
</tbody>
</table>
//Added my custom scripts in the scripts sections
@section Scripts
{
<script src="~/js/customScripts.js"></script>
}
And another view "GetEmployeeDetails.cshtml" with no scripts
<h2>GetEmployeeByDetails</h2>
@Model.PageTitle
<p>
<a asp-action="Create">Create New</a>
</p>
<table class="table">
<thead>
// do something ...
</thead>
<tbody>
// do something ...
</tbody>
</table>
And my layout page "_layout.cshtml"
@RenderSection("Scripts", required: true)
So, when I navigate to GetEmployeeDetails.cshtml. I get the error that there is no section scripts to be rendered in GetEmployeeDetails.cshtml.
If I change the flag in @RenderSection()
from required : true
to ``required : false`. It means render the scripts defined in the @section scripts of the views if present.Else, do nothing.
And the refined approach would be in _layout.cshtml
@if (IsSectionDefined("Scripts"))
{
@RenderSection("Scripts", required: true)
}
"""
This function check if set is empty or not.
>>> c = set([])
>>> set_is_empty(c)
True
:param some_set: set to check if he empty or not.
:return True if empty, False otherwise.
"""
def set_is_empty(some_set):
return some_set == set()
In case you want to compress a PDF which contains a lot of selectable text, on Windows you can use NicePDF Compressor - choose "Flate" option. After trying everything (cpdf, pdftk, gs) it finally helped me to compress my 1360 pages PDF from 500 MB down to 10 MB.
Connect your javascript clientside controller and php serverside controller using sending and receiving opcodes with binded data. So your php code can send as response functional delta for js recepient/listener
see https://github.com/ArtNazarov/LazyJs
Sorry for my bad English
I created a Fiddle for the answer to this question because the accepted answer is incorrect plus this is the first StackOverflow thread returned from Google regarding this question.
To break out of a $.each you must use return false;
Here is a Fiddle proving it:
height
of your label to the same height
as the multiline textbox.Add the cssClass .alignTop{vertical-align: middle;}
for the label control.
<p>
<asp:Label ID="DescriptionLabel" runat="server" Text="Description: " Width="70px" Height="200px" CssClass="alignTop"></asp:Label>
<asp:Textbox id="DescriptionTextbox" runat="server" Width="400px" Height="200px" TextMode="MultiLine"></asp:Textbox>
<asp:RequiredFieldValidator id="DescriptionRequiredFieldValidator" runat="server" ForeColor="Red"
ControlToValidate="DescriptionTextbox" ErrorMessage="Description is a required field.">
</asp:RequiredFieldValidator>
I was facing the same issue, and it drove me up the wall. The issue ended up to be that the .idea folder was ALREADY commited into the repo previously, and so they were being tracked by git regardless of whether you ignored them or not. I would recommend the following, after closing RubyMine/IntelliJ or whatever IDE you are using:
mv .idea ../.idea_backup
rm .idea # in case you forgot to close your IDE
git rm -r .idea
git commit -m "Remove .idea from repo"
mv ../.idea_backup .idea
After than make sure to ignore .idea in your .gitignore
Although it is sufficient to ignore it in the repository's .gitignore, I would suggest that you ignore your IDE's dotfiles globally.
Otherwise you will have to add it to every .gitgnore for every project you work on. Also, if you collaborate with other people, then its best practice not to pollute the project's .gitignore with private configuation that are not specific to the source-code of the project.
For showing Forbidden error then include these lines in your .htaccess file:
Options -Indexes
If we want to index our files and showing them with some information, then use:
IndexOptions -FancyIndexing
If we want for some particular extension not to show, then:
IndexIgnore *.zip *.css
If you don't want to use the url helper, you can get the same results by using the following variable:
$this->config->config['base_url']
It will return the base url for you with no extra steps required.
I think the problem is with the datatype of the data you are passing Caused by: java.sql.SQLException: Invalid column type: 1111
check the datatypes you pass with the actual column datatypes may be there can be some mismatch or some constraint violation with null
If your cascading deletes nuke a product because it was a member of a category that was killed, then you've set up your foreign keys improperly. Given your example tables, you should have the following table setup:
CREATE TABLE categories (
id int unsigned not null primary key,
name VARCHAR(255) default null
)Engine=InnoDB;
CREATE TABLE products (
id int unsigned not null primary key,
name VARCHAR(255) default null
)Engine=InnoDB;
CREATE TABLE categories_products (
category_id int unsigned not null,
product_id int unsigned not null,
PRIMARY KEY (category_id, product_id),
KEY pkey (product_id),
FOREIGN KEY (category_id) REFERENCES categories (id)
ON DELETE CASCADE
ON UPDATE CASCADE,
FOREIGN KEY (product_id) REFERENCES products (id)
ON DELETE CASCADE
ON UPDATE CASCADE
)Engine=InnoDB;
This way, you can delete a product OR a category, and only the associated records in categories_products will die alongside. The cascade won't travel farther up the tree and delete the parent product/category table.
e.g.
products: boots, mittens, hats, coats
categories: red, green, blue, white, black
prod/cats: red boots, green mittens, red coats, black hats
If you delete the 'red' category, then only the 'red' entry in the categories table dies, as well as the two entries prod/cats: 'red boots' and 'red coats'.
The delete will not cascade any farther and will not take out the 'boots' and 'coats' categories.
comment followup:
you're still misunderstanding how cascaded deletes work. They only affect the tables in which the "on delete cascade" is defined. In this case, the cascade is set in the "categories_products" table. If you delete the 'red' category, the only records that will cascade delete in categories_products are those where category_id = red
. It won't touch any records where 'category_id = blue', and it would not travel onwards to the "products" table, because there's no foreign key defined in that table.
Here's a more concrete example:
categories: products:
+----+------+ +----+---------+
| id | name | | id | name |
+----+------+ +----+---------+
| 1 | red | | 1 | mittens |
| 2 | blue | | 2 | boots |
+---++------+ +----+---------+
products_categories:
+------------+-------------+
| product_id | category_id |
+------------+-------------+
| 1 | 1 | // red mittens
| 1 | 2 | // blue mittens
| 2 | 1 | // red boots
| 2 | 2 | // blue boots
+------------+-------------+
Let's say you delete category #2 (blue):
DELETE FROM categories WHERE (id = 2);
the DBMS will look at all the tables which have a foreign key pointing at the 'categories' table, and delete the records where the matching id is 2. Since we only defined the foreign key relationship in products_categories
, you end up with this table once the delete completes:
+------------+-------------+
| product_id | category_id |
+------------+-------------+
| 1 | 1 | // red mittens
| 2 | 1 | // red boots
+------------+-------------+
There's no foreign key defined in the products
table, so the cascade will not work there, so you've still got boots and mittens listed. There's just no 'blue boots' and no 'blue mittens' anymore.
you could also try: instance_of?
p 1.instance_of? Fixnum #=> True
p "1".instance_of? String #=> True
p [1,2].instance_of? Array #=> True
I believe Double.NaN might be able to cover this. That is the only 'null' value double contains.
If you are using the Genymotion emulator:
Make sure that the SDK path used for Genymotion is also the same path used for the Eclipse.
This error also occurs if those two paths are different.
A working example for OSX (tested right now on Catalina 10.15). Not portable to linux/windows obviously. Probably it will be usefull to somebody.
In the "Mew-exception" string you can use backtrace and/or backtrace_symbols functions
#include <stdexcept>
#include <typeinfo>
#include <dlfcn.h>
extern "C" void __cxa_throw(void *thrown_object, std::type_info *tinfo, void (*dest)(void *));
static void (*__cxa_throw_orig)(void *thrown_object, std::type_info *tinfo, void (*dest)(void *));
extern "C" void luna_cxa_throw(void *thrown_object, std::type_info *tinfo, void (*dest)(void *))
{
printf("Mew-exception you can catch your backtrace here!");
__cxa_throw_orig(thrown_object, tinfo, dest);
}
//__attribute__ ((used))
//__attribute__ ((section ("__DATA,__interpose")))
static struct replace_pair_t {
void *replacement, *replacee;
} replace_pair = { (void*)luna_cxa_throw, (void*)__cxa_throw };
extern "C" const struct mach_header __dso_handle;
extern "C" void dyld_dynamic_interpose(const struct mach_header*,
const replace_pair_t replacements[],
size_t count);
int fn()
{
int a = 10; ++a;
throw std::runtime_error("Mew!");
}
int main(int argc, const char * argv[]) {
__cxa_throw_orig = (void (*)(void *thrown_object, std::type_info *tinfo, void (*dest)(void *)))dlsym(RTLD_DEFAULT, "__cxa_throw");
dyld_dynamic_interpose(&__dso_handle, &replace_pair, 1);
fn();
return 0;
}
Try if that works
sc = spark.sparkContext
# Infer the schema, and register the DataFrame as a table.
schemaPeople = spark.createDataFrame(RddName)
schemaPeople.createOrReplaceTempView("RddName")
For loading weights, you need to have a model first. It must be:
existingModel.save_weights('weightsfile.h5')
existingModel.load_weights('weightsfile.h5')
If you want to save and load the entire model (this includes the model's configuration, it's weights and the optimizer states for further training):
model.save_model('filename')
model = load_model('filename')
Try using the property ForeColor. Like this :
TextBox1.ForeColor = Color.Red;
Just copy the image and paste into Eclipse in the res/drawable
directory. Note that the image name should be in lowercase, otherwise it will end up with an error.
Create an Android app using Eclipse.
Create a layout that has a <WebView>
control.
Move your HTML code to /assets
folder.
Load webview with your file:///android_asset/ file.
And you have an android app!
Take a look at the ISNULL function. It helps you replace NULL values for other values. http://msdn.microsoft.com/en-us/library/ms184325.aspx
Put them in brackets []
:
var cleanString = dirtyString.replace(/[\|&;\$%@"<>\(\)\+,]/g, "");
You can use the following method to get the width and height of the view, For example,
int height = yourView.getLayoutParams().height;
int width = yourView.getLayoutParams().width;
This gives the converted value of the view which specified in the XML layout.
Say if the specified value for height is 53dp in XML, you will get the converted value in integer as 80.
When I want to display an empty date value I do this
if (sStrDate != "")
{
dateCreated.Value = DateTime.Parse(sStrDate);
}
else
{
dateCreated.CustomFormat = " ";
dateCreated.Format = DateTimePickerFormat.Custom;
}
Then when the user clicks on the control I have this:
private void dateControl_MouseDown(object sender, MouseEventArgs e)
{
((DateTimePicker)sender).Format = DateTimePickerFormat.Long;
}
This allows you to display and use an empty date value, but still allow the user to be able to change the date to something when they wish.
Keep in mind that sStrDate has already been validated as a valid date string.
var currentDateTime = dateTime.Now();
var date=currentDateTime.Date;
How about std::cin.get();
?
Also, if you're using Visual Studio, you can run without debugging (CTRL-F5 by default) and it won't close the console at the end. If you run it with debugging, you could always put a breakpoint at the closing brace of main()
.
I got the same error.
On my view I was overriding get_form_kwargs() like this:
class UserAccountView(FormView):
form_class = UserAccountForm
success_url = '/'
template_name = 'user_account/user-account.html'
def get_form_kwargs(self):
kwargs = super(UserAccountView, self).get_form_kwargs()
kwargs.update({'user': self.request.user})
return kwargs
But on my form I failed to override the init() method. Once I did it. Problem solved
class UserAccountForm(forms.Form):
first_name = forms.CharField(label='Your first name', max_length=30)
last_name = forms.CharField(label='Your last name', max_length=30)
email = forms.EmailField(max_length=75)
def __init__(self, *args, **kwargs):
user = kwargs.pop('user')
super(UserAccountForm, self).__init__(*args, **kwargs)
you can use rdd.coalesce(1, true).saveAsTextFile(path)
it will store data as singile file in path/part-00000
To enable zoom controls in a WebView, add the following line:
webView.getSettings().setBuiltInZoomControls(true);
With this line of code, you get the zoom enabled in your WebView, if you want to remove the zoom in and zoom out buttons provided, add the following line of code:
webView.getSettings().setDisplayZoomControls(false);
Based on @Spider's solution, my non JQuery version is this:
// Get the container element's bounding box
var sides = document.getElementById("container").getBoundingClientRect();
// Apply the mouse event listener
document.getElementById("canvas").onmousemove = (e) => {
// Here 'self' is simply the current window's context
var x = (e.clientX - sides.left) + self.pageXOffset;
var y = (e.clientY - sides.top) + self.pageYOffset;
}
This works both with scrolling and zooming (in which case sometimes it returns floats).
Well the data src attribute is just used for binding data for example ASP.NET ...
In C# it is not possible to call another constructor from inside the method body. You can call a base constructor this way: foo(args):base() as pointed out yourself. You can also call another constructor in the same class: foo(args):this().
When you want to do something before calling a base constructor, it seems the construction of the base is class is dependant of some external things. If so, you should through arguments of the base constructor, not by setting properties of the base class or something like that
If you plot in IPython console (where you can't use %matplotlib inline
) instead of Jupyter notebook, and don't want to run plt.show()
repeatedly, you can start IPython console with ipython --pylab
:
$ ipython --pylab
Python 3.6.6 |Anaconda custom (64-bit)| (default, Jun 28 2018, 17:14:51)
Type 'copyright', 'credits' or 'license' for more information
IPython 7.0.1 -- An enhanced Interactive Python. Type '?' for help.
Using matplotlib backend: Qt5Agg
In [1]: import seaborn as sns
In [2]: tips = sns.load_dataset("tips")
In [3]: sns.relplot(x="total_bill", y="tip", data=tips) # you can see the plot now
For a different approach, I would suggest using the XeTeX or LuaTex system. They allow you to access system fonts (TrueType, OpenType, etc) and set font features. In a typical LaTeX document, you just need to include this in your headers:
\usepackage{fontspec}
\defaultfontfeatures{Mapping=tex-text,Scale=MatchLowercase}
\setmainfont{Times}
\setmonofont{Lucida Sans Typewriter}
It's the fontspec
package that allows for \setmainfont
and \setmonofont
. The ability to choose a multitude of font features is beyond my expertise, but I would suggest looking up some examples and seeing if this would suit your needs.
Just don't forget to replace your favorite latex compiler by the appropriate one (xelatex or lualatex).
regarding to Imran answer from Sep 1th 2008 at 12:33 there is a missing : in the pattern the correct patterns are
preg_match('/\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}/', '2008-09-01 12:35:45', $m1);
print_r( $m1 );
preg_match('/\d{4}-\d{2}-\d{2} \d{1,2}:\d{2}:\d{2}/', '2008-09-01 12:35:45', $m2);
print_r( $m2 );
preg_match('/^\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}$/', '2008-09-01 12:35:45', $m3);
print_r( $m3 );
this returns
Array ( [0] => 2008-09-01 12:35:45 )
Array ( [0] => 2008-09-01 12:35:45 )
Array ( [0] => 2008-09-01 12:35:45 )
var ItemSchema = new Schema({
name : { type: String }
});
ItemSchema.set('timestamps', true); // this will add createdAt and updatedAt timestamps
These are the methods I know:
ichramm@NOTPARALLEL ~$ i=10; echo $i;
10
ichramm@NOTPARALLEL ~$ ((i+=1)); echo $i;
11
ichramm@NOTPARALLEL ~$ ((i=i+1)); echo $i;
12
ichramm@NOTPARALLEL ~$ i=`expr $i + 1`; echo $i;
13
Note the spaces in the last example, also note that's the only one that uses $i
.
def replace_line(file_name, line_num, text):
lines = open(file_name, 'r').readlines()
lines[line_num] = text
out = open(file_name, 'w')
out.writelines(lines)
out.close()
And then:
replace_line('stats.txt', 0, 'Mage')
Apache Commons I/O provides FileUtils#readLines(), which should be fine for all but huge files: http://commons.apache.org/io/api-release/index.html. The 2.1 distribution includes FileUtils.lineIterator(), which would be suitable for large files. Google's Guava libraries include similar utilities.
Do you have Bitnami installed? If so it is most likely one of those installations check by opening command prompt as admin or terminal in linux, enter this...
netstat -b
This will give an application name to those processes and ports in use. Look for :80 or :443
I know this is a really old post, but I found it in searching for a solution to the same problem. I don't want a nested if-statement, and Switch is apparently newer than the version of Excel I'm using. I figured out what was going wrong with my code, so I figured I'd share here in case it helps someone else.
I remembered that VLOOKUP requires the source table to be sorted alphabetically/numerically for it to work. I was initially trying to do this...
=LOOKUP(LOWER(LEFT($T$3, 1)), {"s","l","m"}, {-1,1,0})
and it started working when I did this...
=LOOKUP(LOWER(LEFT($T$3, 1)), {"l","m","s"}, {1,0,-1})
I was initially thinking the last value might turn out to be a default, so I wanted the zero at the last place. That doesn't seem to be the behavior anyway, so I just put the possible matches in order, and it worked.
Edit: As a final note, I see that the example in the original post has letters in alphabetical order, but I imagine the real use case might have been different if the error was happening and the letters A, B, and C were just examples.
Add spacer span between two elements, then make it unvisible:
<img src="#" />
<span class="spacer">---</span>
<span>Text TEXT</span>
.spacer {
visibility: hidden
}
Update: 22.01.2019, 13.41 I optimized the solution by jhay, which also supports closing and opening same or different dialogs when for example stepping from one detail data to another forwards or backwards.
(function ($, window) {
'use strict';
var MultiModal = function (element) {
this.$element = $(element);
this.modalIndex = 0;
};
MultiModal.BASE_ZINDEX = 1040;
/* Max index number. When reached just collate the zIndexes */
MultiModal.MAX_INDEX = 5;
MultiModal.prototype.show = function (target) {
var that = this;
var $target = $(target);
// Bootstrap triggers the show event at the beginning of the show function and before
// the modal backdrop element has been created. The timeout here allows the modal
// show function to complete, after which the modal backdrop will have been created
// and appended to the DOM.
// we only want one backdrop; hide any extras
setTimeout(function () {
/* Count the number of triggered modal dialogs */
that.modalIndex++;
if (that.modalIndex >= MultiModal.MAX_INDEX) {
/* Collate the zIndexes of every open modal dialog according to its order */
that.collateZIndex();
}
/* Modify the zIndex */
$target.css('z-index', MultiModal.BASE_ZINDEX + (that.modalIndex * 20) + 10);
/* we only want one backdrop; hide any extras */
if (that.modalIndex > 1)
$('.modal-backdrop').not(':first').addClass('hidden');
that.adjustBackdrop();
});
};
MultiModal.prototype.hidden = function (target) {
this.modalIndex--;
this.adjustBackdrop();
if ($('.modal.in').length === 1) {
/* Reset the index to 1 when only one modal dialog is open */
this.modalIndex = 1;
$('.modal.in').css('z-index', MultiModal.BASE_ZINDEX + 10);
var $modalBackdrop = $('.modal-backdrop:first');
$modalBackdrop.removeClass('hidden');
$modalBackdrop.css('z-index', MultiModal.BASE_ZINDEX);
}
};
MultiModal.prototype.adjustBackdrop = function () {
$('.modal-backdrop:first').css('z-index', MultiModal.BASE_ZINDEX + (this.modalIndex * 20));
};
MultiModal.prototype.collateZIndex = function () {
var index = 1;
var $modals = $('.modal.in').toArray();
$modals.sort(function(x, y)
{
return (Number(x.style.zIndex) - Number(y.style.zIndex));
});
for (i = 0; i < $modals.length; i++)
{
$($modals[i]).css('z-index', MultiModal.BASE_ZINDEX + (index * 20) + 10);
index++;
};
this.modalIndex = index;
this.adjustBackdrop();
};
function Plugin(method, target) {
return this.each(function () {
var $this = $(this);
var data = $this.data('multi-modal-plugin');
if (!data)
$this.data('multi-modal-plugin', (data = new MultiModal(this)));
if (method)
data[method](target);
});
}
$.fn.multiModal = Plugin;
$.fn.multiModal.Constructor = MultiModal;
$(document).on('show.bs.modal', function (e) {
$(document).multiModal('show', e.target);
});
$(document).on('hidden.bs.modal', function (e) {
$(document).multiModal('hidden', e.target);
});}(jQuery, window));
final Properties properties = new Properties();
try (final InputStream stream =
this.getClass().getResourceAsStream("foo.properties")) {
properties.load(stream);
/* or properties.loadFromXML(...) */
}
there any rule I can follow to be sure that my app executes my own code just in the main thread?
Typically you wouldn't need to do anything to ensure this — your list of things is usually enough. Unless you're interacting with some API that happens to spawn a thread and run your code in the background, you'll be running on the main thread.
If you want to be really sure, you can do things like
[self performSelectorOnMainThread:@selector(myMethod:) withObject:anObj waitUntilDone:YES];
to execute a method on the main thread. (There's a GCD equivalent too.)
When using git rm, the removal will part of your next commit. So if you want to push the change you should use git rm
Just use the sys.getsizeof function defined in the sys
module.
sys.getsizeof(object[, default])
:Return the size of an object in bytes. The object can be any type of object. All built-in objects will return correct results, but this does not have to hold true for third-party extensions as it is implementation specific.
Only the memory consumption directly attributed to the object is accounted for, not the memory consumption of objects it refers to.
The
default
argument allows to define a value which will be returned if the object type does not provide means to retrieve the size and would cause aTypeError
.
getsizeof
calls the object’s__sizeof__
method and adds an additional garbage collector overhead if the object is managed by the garbage collector.See recursive sizeof recipe for an example of using
getsizeof()
recursively to find the size of containers and all their contents.
Usage example, in python 3.0:
>>> import sys
>>> x = 2
>>> sys.getsizeof(x)
24
>>> sys.getsizeof(sys.getsizeof)
32
>>> sys.getsizeof('this')
38
>>> sys.getsizeof('this also')
48
If you are in python < 2.6 and don't have sys.getsizeof
you can use this extensive module instead. Never used it though.
You can set this at boot by adding the "elevator" parameter to the kernel cmdline (such as in grub.cfg)
Example:
elevator=deadline
This will make "deadline" the default I/O scheduler for all block devices.
If you'd like to query or change the scheduler after the system has booted, or would like to use a different scheduler for a specific block device, I recommend installing and use the tool ioschedset to make this easy.
https://github.com/kata198/ioschedset
If you're on Archlinux it's available in aur:
https://aur.archlinux.org/packages/ioschedset
Some example usage:
# Get i/o scheduler for all block devices
[username@hostname ~]$ io-get-sched
sda: bfq
sr0: bfq
# Query available I/O schedulers
[username@hostname ~]$ io-set-sched --list
mq-deadline kyber bfq none
# Set sda to use "kyber"
[username@hostname ~]$ io-set-sched kyber /dev/sda
Must be root to set IO Scheduler. Rerunning under sudo...
[sudo] password for username:
+ Successfully set sda to 'kyber'!
# Get i/o scheduler for all block devices to assert change
[username@hostname ~]$ io-get-sched
sda: kyber
sr0: bfq
# Set all block devices to use 'deadline' i/o scheduler
[username@hostname ~]$ io-set-sched deadline
Must be root to set IO Scheduler. Rerunning under sudo...
+ Successfully set sda to 'deadline'!
+ Successfully set sr0 to 'deadline'!
# Get the current block scheduler just for sda
[username@hostname ~]$ io-get-sched sda
sda: mq-deadline
Usage should be self-explanatory. The tools are standalone and only require bash.
Hope this helps!
EDIT: Disclaimer, these are scripts I wrote.
Another option is to update the Microsoft.AspnNet.Mvc NuGet package. Be careful, because NuGet update does not update the Web.Config. You should update all previous version numbers to updated number. For example if you update from asp.net MVC 4.0.0.0 to 5.0.0.0, then this should be replaced in the Web.Config:
<sectionGroup name="system.web.webPages.razor" type="System.Web.WebPages.Razor.Configuration.RazorWebSectionGroup, System.Web.WebPages.Razor, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35">
<section name="host" type="System.Web.WebPages.Razor.Configuration.HostSection, System.Web.WebPages.Razor, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" />
<section name="pages" type="System.Web.WebPages.Razor.Configuration.RazorPagesSection, System.Web.WebPages.Razor, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" />
</sectionGroup>
</configSections>
<host factoryType="System.Web.Mvc.MvcWebRazorHostFactory, System.Web.Mvc, Version=5.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
<pages
validateRequest="false"
pageParserFilterType="System.Web.Mvc.ViewTypeParserFilter, System.Web.Mvc, Version=5.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"
pageBaseType="System.Web.Mvc.ViewPage, System.Web.Mvc, Version=5.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"
userControlBaseType="System.Web.Mvc.ViewUserControl, System.Web.Mvc, Version=5.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35">
<controls>
<add assembly="System.Web.Mvc, Version=5.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" namespace="System.Web.Mvc" tagPrefix="mvc" />
</controls>
</pages>
You'll need to tweak registry. First, configure a PSDrive for HKEY_CLASSES_ROOT since this isn’t set up by default. The command for this is:
New-PSDrive HKCR Registry HKEY_CLASSES_ROOT
Now you can navigate and edit registry keys and values in HKEY_CLASSES_ROOT just like you would in the regular HKCU and HKLM PSDrives.
To configure double-clicking to launch PowerShell scripts directly:
Set-ItemProperty HKCR:\Microsoft.PowerShellScript.1\Shell '(Default)' 0
To configure double-clicking to open PowerShell scripts in the PowerShell ISE:
Set-ItemProperty HKCR:\Microsoft.PowerShellScript.1\Shell '(Default)' 'Edit'
To restore the default value (sets double-click to open PowerShell scripts in Notepad):
Set-ItemProperty HKCR:\Microsoft.PowerShellScript.1\Shell '(Default)' 'Open'
As HungryDB said the easier way for do that is:
$mystring = json_encode($my_json,JSON_UNESCAPED_SLASHES);
Have a look at your php version because this parameter has been added in version 5.4.0
I spent a day messing with CSS before I found anataliocs tip. Add wmode=transparent
as a parameter to the YouTube URL:
<iframe title=<your frame title goes here>
src="http://www.youtube.com/embed/K3j9taoTd0E?wmode=transparent"
scrolling="no"
frameborder="0"
width="640"
height="390"
style="border:none;">
</iframe>
This allows the iframe to inherit the z-index of its container so your opaque <div>
would be in front of the iframe.
I would like to return two values from a function in two separate variables.
What would you expect it to look like on the calling end? You can't write a = select_choice(); b = select_choice()
because that would call the function twice.
Values aren't returned "in variables"; that's not how Python works. A function returns values (objects). A variable is just a name for a value in a given context. When you call a function and assign the return value somewhere, what you're doing is giving the received value a name in the calling context. The function doesn't put the value "into a variable" for you, the assignment does (never mind that the variable isn't "storage" for the value, but again, just a name).
When i tried to to use
return i, card
, it returns atuple
and this is not what i want.
Actually, it's exactly what you want. All you have to do is take the tuple
apart again.
And i want to be able to use these values separately.
So just grab the values out of the tuple
.
The easiest way to do this is by unpacking:
a, b = select_choice()
I was getting same kinda error but after copying the ojdbc14.jar into lib folder, no more exception.(copy ojdbc14.jar from somewhere and paste it into lib folder inside WebContent.)
File.GetLastWriteTime Method
Returns the date and time the specified file or directory was last written to.
string path = @"c:\Temp\MyTest.txt";
DateTime dt = File.GetLastWriteTime(path);
For create time File.GetCreationTime Method
DateTime fileCreatedDate = File.GetCreationTime(@"C:\Example\MyTest.txt");
Console.WriteLine("file created: " + fileCreatedDate);
It obtains a reference to the class object with the FQCN (fully qualified class name) oracle.jdbc.driver.OracleDriver
.
It doesn't "do" anything in terms of connecting to a database, aside from ensure that the specified class is loaded by the current classloader. There is no fundamental difference between writing
Class<?> driverClass = Class.forName("oracle.jdbc.driver.OracleDriver");
// and
Class<?> stringClass = Class.forName("java.lang.String");
Class.forName("com.example.some.jdbc.driver")
calls show up in legacy code that uses JDBC because that is the legacy way of loading a JDBC driver.
From The Java Tutorial:
In previous versions of JDBC, to obtain a connection, you first had to initialize your JDBC driver by calling the method
Class.forName
. This methods required an object of typejava.sql.Driver
. Each JDBC driver contains one or more classes that implements the interfacejava.sql.Driver
.
...
Any JDBC 4.0 drivers that are found in your class path are automatically loaded. (However, you must manually load any drivers prior to JDBC 4.0 with the methodClass.forName
.)
You can simply save your data in a variable and use find(to get single object of records) or filter(to get single array of records) method of JavaScript.
For example :-
let data = {
"list": [
{"name":"my Name","id":12,"type":"car owner"},
{"name":"my Name2","id":13,"type":"car owner2"},
{"name":"my Name4","id":14,"type":"car owner3"},
{"name":"my Name4","id":15,"type":"car owner5"}
]}
and now use below command onkeyup or enter
to get single object
data.list.find( record => record.name === "my Name")
to get single array object
data.list.filter( record => record.name === "my Name")
Unity added JsonUtility to their API after 5.3.3 Update. Forget about all the 3rd party libraries unless you are doing something more complicated. JsonUtility is faster than other Json libraries. Update to Unity 5.3.3 version or above then try the solution below.
JsonUtility
is a lightweight API. Only simple types are supported. It does not support collections such as Dictionary. One exception is List
. It supports List
and List
array!
If you need to serialize a Dictionary
or do something other than simply serializing and deserializing simple datatypes, use a third-party API. Otherwise, continue reading.
Example class to serialize:
[Serializable]
public class Player
{
public string playerId;
public string playerLoc;
public string playerNick;
}
1. ONE DATA OBJECT (NON-ARRAY JSON)
Serializing Part A:
Serialize to Json with the public static string ToJson(object obj);
method.
Player playerInstance = new Player();
playerInstance.playerId = "8484239823";
playerInstance.playerLoc = "Powai";
playerInstance.playerNick = "Random Nick";
//Convert to JSON
string playerToJson = JsonUtility.ToJson(playerInstance);
Debug.Log(playerToJson);
Output:
{"playerId":"8484239823","playerLoc":"Powai","playerNick":"Random Nick"}
Serializing Part B:
Serialize to Json with the public static string ToJson(object obj, bool prettyPrint);
method overload. Simply passing true
to the JsonUtility.ToJson
function will format the data. Compare the output below to the output above.
Player playerInstance = new Player();
playerInstance.playerId = "8484239823";
playerInstance.playerLoc = "Powai";
playerInstance.playerNick = "Random Nick";
//Convert to JSON
string playerToJson = JsonUtility.ToJson(playerInstance, true);
Debug.Log(playerToJson);
Output:
{
"playerId": "8484239823",
"playerLoc": "Powai",
"playerNick": "Random Nick"
}
Deserializing Part A:
Deserialize json with the public static T FromJson(string json);
method overload.
string jsonString = "{\"playerId\":\"8484239823\",\"playerLoc\":\"Powai\",\"playerNick\":\"Random Nick\"}";
Player player = JsonUtility.FromJson<Player>(jsonString);
Debug.Log(player.playerLoc);
Deserializing Part B:
Deserialize json with the public static object FromJson(string json, Type type);
method overload.
string jsonString = "{\"playerId\":\"8484239823\",\"playerLoc\":\"Powai\",\"playerNick\":\"Random Nick\"}";
Player player = (Player)JsonUtility.FromJson(jsonString, typeof(Player));
Debug.Log(player.playerLoc);
Deserializing Part C:
Deserialize json with the public static void FromJsonOverwrite(string json, object objectToOverwrite);
method. When JsonUtility.FromJsonOverwrite
is used, no new instance of that Object you are deserializing to will be created. It will simply re-use the instance you pass in and overwrite its values.
This is efficient and should be used if possible.
Player playerInstance;
void Start()
{
//Must create instance once
playerInstance = new Player();
deserialize();
}
void deserialize()
{
string jsonString = "{\"playerId\":\"8484239823\",\"playerLoc\":\"Powai\",\"playerNick\":\"Random Nick\"}";
//Overwrite the values in the existing class instance "playerInstance". Less memory Allocation
JsonUtility.FromJsonOverwrite(jsonString, playerInstance);
Debug.Log(playerInstance.playerLoc);
}
2. MULTIPLE DATA(ARRAY JSON)
Your Json contains multiple data objects. For example playerId
appeared more than once. Unity's JsonUtility
does not support array as it is still new but you can use a helper class from this person to get array working with JsonUtility
.
Create a class called JsonHelper
. Copy the JsonHelper directly from below.
public static class JsonHelper
{
public static T[] FromJson<T>(string json)
{
Wrapper<T> wrapper = JsonUtility.FromJson<Wrapper<T>>(json);
return wrapper.Items;
}
public static string ToJson<T>(T[] array)
{
Wrapper<T> wrapper = new Wrapper<T>();
wrapper.Items = array;
return JsonUtility.ToJson(wrapper);
}
public static string ToJson<T>(T[] array, bool prettyPrint)
{
Wrapper<T> wrapper = new Wrapper<T>();
wrapper.Items = array;
return JsonUtility.ToJson(wrapper, prettyPrint);
}
[Serializable]
private class Wrapper<T>
{
public T[] Items;
}
}
Serializing Json Array:
Player[] playerInstance = new Player[2];
playerInstance[0] = new Player();
playerInstance[0].playerId = "8484239823";
playerInstance[0].playerLoc = "Powai";
playerInstance[0].playerNick = "Random Nick";
playerInstance[1] = new Player();
playerInstance[1].playerId = "512343283";
playerInstance[1].playerLoc = "User2";
playerInstance[1].playerNick = "Rand Nick 2";
//Convert to JSON
string playerToJson = JsonHelper.ToJson(playerInstance, true);
Debug.Log(playerToJson);
Output:
{
"Items": [
{
"playerId": "8484239823",
"playerLoc": "Powai",
"playerNick": "Random Nick"
},
{
"playerId": "512343283",
"playerLoc": "User2",
"playerNick": "Rand Nick 2"
}
]
}
Deserializing Json Array:
string jsonString = "{\r\n \"Items\": [\r\n {\r\n \"playerId\": \"8484239823\",\r\n \"playerLoc\": \"Powai\",\r\n \"playerNick\": \"Random Nick\"\r\n },\r\n {\r\n \"playerId\": \"512343283\",\r\n \"playerLoc\": \"User2\",\r\n \"playerNick\": \"Rand Nick 2\"\r\n }\r\n ]\r\n}";
Player[] player = JsonHelper.FromJson<Player>(jsonString);
Debug.Log(player[0].playerLoc);
Debug.Log(player[1].playerLoc);
Output:
Powai
User2
If this is a Json array from the server and you did not create it by hand:
You may have to Add {"Items":
in front of the received string then add }
at the end of it.
I made a simple function for this:
string fixJson(string value)
{
value = "{\"Items\":" + value + "}";
return value;
}
then you can use it:
string jsonString = fixJson(yourJsonFromServer);
Player[] player = JsonHelper.FromJson<Player>(jsonString);
3.Deserialize json string without class && De-serializing Json with numeric properties
This is a Json that starts with a number or numeric properties.
For example:
{
"USD" : {"15m" : 1740.01, "last" : 1740.01, "buy" : 1740.01, "sell" : 1744.74, "symbol" : "$"},
"ISK" : {"15m" : 179479.11, "last" : 179479.11, "buy" : 179479.11, "sell" : 179967, "symbol" : "kr"},
"NZD" : {"15m" : 2522.84, "last" : 2522.84, "buy" : 2522.84, "sell" : 2529.69, "symbol" : "$"}
}
Unity's JsonUtility
does not support this because the "15m" property starts with a number. A class variable cannot start with an integer.
Download SimpleJSON.cs
from Unity's wiki.
To get the "15m" property of USD:
var N = JSON.Parse(yourJsonString);
string price = N["USD"]["15m"].Value;
Debug.Log(price);
To get the "15m" property of ISK:
var N = JSON.Parse(yourJsonString);
string price = N["ISK"]["15m"].Value;
Debug.Log(price);
To get the "15m" property of NZD:
var N = JSON.Parse(yourJsonString);
string price = N["NZD"]["15m"].Value;
Debug.Log(price);
The rest of the Json properties that doesn't start with a numeric digit can be handled by Unity's JsonUtility.
4.TROUBLESHOOTING JsonUtility:
Problems when serializing with JsonUtility.ToJson
?
Getting empty string or "{}
" with JsonUtility.ToJson
?
A. Make sure that the class is not an array. If it is, use the helper class above with JsonHelper.ToJson
instead of JsonUtility.ToJson
.
B. Add [Serializable]
to the top of the class you are serializing.
C. Remove property from the class. For example, in the variable, public string playerId { get; set; }
remove { get; set; }
. Unity cannot serialize this.
Problems when deserializing with JsonUtility.FromJson
?
A. If you get Null
, make sure that the Json is not a Json array. If it is, use the helper class above with JsonHelper.FromJson
instead of JsonUtility.FromJson
.
B. If you get NullReferenceException
while deserializing, add [Serializable]
to the top of the class.
C.Any other problems, verify that your json is valid. Go to this site here and paste the json. It should show you if the json is valid. It should also generate the proper class with the Json. Just make sure to remove remove { get; set; }
from each variable and also add [Serializable]
to the top of each class generated.
Newtonsoft.Json:
If for some reason Newtonsoft.Json must be used then check out the forked version for Unity here. Note that you may experience crash if certain feature is used. Be careful.
To answer your question:
Your original data is
[{"playerId":"1","playerLoc":"Powai"},{"playerId":"2","playerLoc":"Andheri"},{"playerId":"3","playerLoc":"Churchgate"}]
Add {"Items":
in front of it then add }
at the end of it.
Code to do this:
serviceData = "{\"Items\":" + serviceData + "}";
Now you have:
{"Items":[{"playerId":"1","playerLoc":"Powai"},{"playerId":"2","playerLoc":"Andheri"},{"playerId":"3","playerLoc":"Churchgate"}]}
To serialize the multiple data from php as arrays, you can now do
public player[] playerInstance;
playerInstance = JsonHelper.FromJson<player>(serviceData);
playerInstance[0]
is your first data
playerInstance[1]
is your second data
playerInstance[2]
is your third data
or data inside the class with playerInstance[0].playerLoc
, playerInstance[1].playerLoc
, playerInstance[2].playerLoc
......
You can use playerInstance.Length
to check the length before accessing it.
NOTE: Remove { get; set; }
from the player
class. If you have { get; set; }
, it won't work. Unity's JsonUtility
does NOT work with class members that are defined as properties.
.nav-menu li:not(:last-child){
// write some style here
}
this code should apply the style to all
In ASCII text file each character is just one byte
Extra Tips:
Multiple "nots", input that is NOT hidden and NOT disabled:
:not([type="hidden"]):not([disabled])
Also did you know you can do this:
node.parentNode.querySelectorAll('div');
This is equivelent to jQuery's:
$(node).parent().find('div');
Which will effectively find all divs in "node" and below recursively, HOT DAMN!
I mean a prompt script would work if the variable was not needed for the HTML aspect, even then in certain situations, a function could be used.
var save_user_input = prompt('what needs to be saved?');
//^ makes a variable of the prompt's answer
if (save_user_input == null) {
//^ if the answer is null, it is nothing
//however, if it is nothing, it is cancelled (as seen below). If it is "null" it is what the user said, then assigned to the variable(i think), but also null as in nothing in the prompt answer window, but ok pressed. So you cant do an or "null" (which would look like: if (save_user_input == null || "null") {)because (I also don't really know if this is right) the variable is "null". Very confusing
alert("cancelled");
//^ alerts the user the cancel button was pressed. No long explanation this time.
}
//^ is an end for the if (i got stumped as to why it wasn’t working and then realised this. very important to remember.)
else {
alert(save_user_input + " is what you said");
//^ alerts the user the variable and adds the string " is what you said" on the end
}
_x000D_
I created a simple extension for this (Swift 3)
extension String {
func substring(location: Int, length: Int) -> String? {
guard characters.count >= location + length else { return nil }
let start = index(startIndex, offsetBy: location)
let end = index(startIndex, offsetBy: location + length)
return substring(with: start..<end)
}
}
$(document).ready(function(){
$('.lbOn').click();
});
Suppose this would work too.
I encountered this issue on my Windows 7 64-bit development machine when running Android Studio 2.1.x and Android Studio 2.2.x side-by-side.
I had deployed an application via the 2.2.x instance the previous day and had left that IDE running. The next day I deployed a different application from the 2.1.x IDE and this is when I encountered the issue.
Shutting down both IDEs and then restarting the 2.1.x IDE resolved the issue for me.
$("#mydropdownlist").val("thevalue");
just make sure the value in the options tags matches the value in the val method.
<input type="image" name="your_image_name" src="your_image_url.png" />
This will send the your_image_name.x
and your_image_name.y
values as it submits the form, which are the x and y coordinates of the position the user clicked the image.
If you want to create dynamically/runtime data table in VB.Net then you should follow these steps as mentioned below :
For eg.
Dim dt As New DataTable
dt.Columns.Add("Id", GetType(Integer))
dt.Columns.Add("FirstName", GetType(String))
dt.Columns.Add("LastName", GetType(String))
dt.Rows.Add(1, "Test", "data")
dt.Rows.Add(15, "Robert", "Wich")
dt.Rows.Add(18, "Merry", "Cylon")
dt.Rows.Add(30, "Tim", "Burst")
Generally it means that you are providing an index for which a list element does not exist.
E.g, if your list was [1, 3, 5, 7]
, and you asked for the element at index 10, you would be well out of bounds and receive an error, as only elements 0 through 3 exist.
Donno how or why but i manage to find this around and it works for me, i had the problem I wanted to return the result of executing a bash
$ while true; do { echo -e 'HTTP/1.1 200 OK\r\n'; sh test; } | nc -l 8080; done
NOTE: This command was taken from: http://www.razvantudorica.com/08/web-server-in-one-line-of-bash
this executes bash script test and return the result to a browser client connecting to the server running this command on port 8080
My script does this ATM
$ nano test
#!/bin/bash
echo "************PRINT SOME TEXT***************\n"
echo "Hello World!!!"
echo "\n"
echo "Resources:"
vmstat -S M
echo "\n"
echo "Addresses:"
echo "$(ifconfig)"
echo "\n"
echo "$(gpio readall)"
and my web browser is showing
************PRINT SOME TEXT***************
Hello World!!!
Resources:
procs -----------memory---------- ---swap-- -----io---- -system-- ----cpu----
r b swpd free buff cache si so bi bo in cs us sy id wa
0 0 0 314 18 78 0 0 2 1 306 31 0 0 100 0
Addresses:
eth0 Link encap:Ethernet HWaddr b8:27:eb:86:e8:c5
inet addr:192.168.1.83 Bcast:192.168.1.255 Mask:255.255.255.0
UP BROADCAST RUNNING MULTICAST MTU:1500 Metric:1
RX packets:27734 errors:0 dropped:0 overruns:0 frame:0
TX packets:26393 errors:0 dropped:0 overruns:0 carrier:0
collisions:0 txqueuelen:1000
RX bytes:1924720 (1.8 MiB) TX bytes:3841998 (3.6 MiB)
lo Link encap:Local Loopback
inet addr:127.0.0.1 Mask:255.0.0.0
UP LOOPBACK RUNNING MTU:65536 Metric:1
RX packets:0 errors:0 dropped:0 overruns:0 frame:0
TX packets:0 errors:0 dropped:0 overruns:0 carrier:0
collisions:0 txqueuelen:0
RX bytes:0 (0.0 B) TX bytes:0 (0.0 B)
GPIOs:
+----------+-Rev2-+------+--------+------+-------+
| wiringPi | GPIO | Phys | Name | Mode | Value |
+----------+------+------+--------+------+-------+
| 0 | 17 | 11 | GPIO 0 | IN | Low |
| 1 | 18 | 12 | GPIO 1 | IN | Low |
| 2 | 27 | 13 | GPIO 2 | IN | Low |
| 3 | 22 | 15 | GPIO 3 | IN | Low |
| 4 | 23 | 16 | GPIO 4 | IN | Low |
| 5 | 24 | 18 | GPIO 5 | IN | Low |
| 6 | 25 | 22 | GPIO 6 | IN | Low |
| 7 | 4 | 7 | GPIO 7 | IN | Low |
| 8 | 2 | 3 | SDA | IN | High |
| 9 | 3 | 5 | SCL | IN | High |
| 10 | 8 | 24 | CE0 | IN | Low |
| 11 | 7 | 26 | CE1 | IN | Low |
| 12 | 10 | 19 | MOSI | IN | Low |
| 13 | 9 | 21 | MISO | IN | Low |
| 14 | 11 | 23 | SCLK | IN | Low |
| 15 | 14 | 8 | TxD | ALT0 | High |
| 16 | 15 | 10 | RxD | ALT0 | High |
| 17 | 28 | 3 | GPIO 8 | ALT2 | Low |
| 18 | 29 | 4 | GPIO 9 | ALT2 | Low |
| 19 | 30 | 5 | GPIO10 | ALT2 | Low |
| 20 | 31 | 6 | GPIO11 | ALT2 | Low |
+----------+------+------+--------+------+-------+
simply amazing!
it must be changed whenever anything changes that affects the serialization (additional fields, removed fields, change of field order, ...)
That's not correct, and you will be unable to cite an authoriitative source for that claim. It should be changed whenever you make a change that is incompatible under the rules given in the Versioning of Serializable Objects section of the Object Serialization Specification, which specifically does not include additional fields or change of field order, and when you haven't provided readObject(), writeObject(),
and/or readResolve()
or /writeReplace()
methods and/or a serializableFields
declaration that could cope with the change.
To also remove the trailing newline at the end of the file
python -c "s=open('filename','r').read();open('filename', 'w').write(s.replace('\n',''))"
One easy way to understand "ABI" is to compare it to "API".
You are already familiar with the concept of an API. If you want to use the features of, say, some library or your OS, you will program against an API. The API consists of data types/structures, constants, functions, etc that you can use in your code to access the functionality of that external component.
An ABI is very similar. Think of it as the compiled version of an API (or as an API on the machine-language level). When you write source code, you access the library through an API. Once the code is compiled, your application accesses the binary data in the library through the ABI. The ABI defines the structures and methods that your compiled application will use to access the external library (just like the API did), only on a lower level. Your API defines the order in which you pass arguments to a function. Your ABI defines the mechanics of how these arguments are passed (registers, stack, etc.). Your API defines which functions are part of your library. Your ABI defines how your code is stored inside the library file, so that any program using your library can locate the desired function and execute it.
ABIs are important when it comes to applications that use external libraries. Libraries are full of code and other resources, but your program has to know how to locate what it needs inside the library file. Your ABI defines how the contents of a library are stored inside the file, and your program uses the ABI to search through the file and find what it needs. If everything in your system conforms to the same ABI, then any program is able to work with any library file, no matter who created them. Linux and Windows use different ABIs, so a Windows program won't know how to access a library compiled for Linux.
Sometimes, ABI changes are unavoidable. When this happens, any programs that use that library will not work unless they are re-compiled to use the new version of the library. If the ABI changes but the API does not, then the old and new library versions are sometimes called "source compatible". This implies that while a program compiled for one library version will not work with the other, source code written for one will work for the other if re-compiled.
For this reason, developers tend to try to keep their ABI stable (to minimize disruption). Keeping an ABI stable means not changing function interfaces (return type and number, types, and order of arguments), definitions of data types or data structures, defined constants, etc. New functions and data types can be added, but existing ones must stay the same. If, for instance, your library uses 32-bit integers to indicate the offset of a function and you switch to 64-bit integers, then already-compiled code that uses that library will not be accessing that field (or any following it) correctly. Accessing data structure members gets converted into memory addresses and offsets during compilation and if the data structure changes, then these offsets will not point to what the code is expecting them to point to and the results are unpredictable at best.
An ABI isn't necessarily something you will explicitly provide unless you are doing very low-level systems design work. It isn't language-specific either, since (for example) a C application and a Pascal application can use the same ABI after they are compiled.
Edit: Regarding your question about the chapters regarding the ELF file format in the SysV ABI docs: The reason this information is included is because the ELF format defines the interface between operating system and application. When you tell the OS to run a program, it expects the program to be formatted in a certain way and (for example) expects the first section of the binary to be an ELF header containing certain information at specific memory offsets. This is how the application communicates important information about itself to the operating system. If you build a program in a non-ELF binary format (such as a.out or PE), then an OS that expects ELF-formatted applications will not be able to interpret the binary file or run the application. This is one big reason why Windows apps cannot be run directly on a Linux machine (or vice versa) without being either re-compiled or run inside some type of emulation layer that can translate from one binary format to another.
IIRC, Windows currently uses the Portable Executable (or, PE) format. There are links in the "external links" section of that Wikipedia page with more information about the PE format.
Also, regarding your note about C++ name mangling: When locating a function in a library file, the function is typically looked up by name. C++ allows you to overload function names, so name alone is not sufficient to identify a function. C++ compilers have their own ways of dealing with this internally, called name mangling. An ABI can define a standard way of encoding the name of a function so that programs built with a different language or compiler can locate what they need. When you use extern "c"
in a C++ program, you're instructing the compiler to use a standardized way of recording names that's understandable by other software.
Simple Solution from ascending to descending and vice versa is:
STRINGS
str = ['ravi', 'aravind', 'joker', 'poker']
asc_string = str.sort # => ["aravind", "joker", "poker", "ravi"]
asc_string.reverse # => ["ravi", "poker", "joker", "aravind"]
DIGITS
digit = [234,45,1,5,78,45,34,9]
asc_digit = digit.sort # => [1, 5, 9, 34, 45, 45, 78, 234]
asc_digit.reverse # => [234, 78, 45, 45, 34, 9, 5, 1]
const static int newvals[] = {34,2,4,5,6};
std::copy(newvals, newvals+sizeof(newvals)/sizeof(newvals[0]), array);
add this to your form:
<form id="regform" action="insert.php" method="post">
add this to your function:
<script>
function myFunction() {
var pass1 = document.getElementById("pass1").value;
var pass2 = document.getElementById("pass2").value;
if (pass1 != pass2) {
//alert("Passwords Do not match");
document.getElementById("pass1").style.borderColor = "#E34234";
document.getElementById("pass2").style.borderColor = "#E34234";
}
else {
alert("Passwords Match!!!");
document.getElementById("regForm").submit();
}
}
</script>
Windows 7 x32 I found that no matter what I did, the driver being used dated back to 2006. It would not update, in fact Windows appears to be preferring the old driver to the new. I eventually found a way to sort it.
The Device Manager contains 'ghost' drivers that need to be deleted (if you have the same problem as I). To see them requires setting a variable in the registry, restarting and then deleting the likely redundant drivers.
Open the Device Manager from the command line use devmgmt.msc There are other ways, but this is easiest to describe. Currently it shows only 'current' drivers.
Open the System Properties box. Via Command line use sysdm.cpl
** Be aware that playing with area of your computer can break it. Back away if you are at all unsure of this. **
Re-open the Device Manager, under view click Show Hidden Devices.
From here delete what you think are the problems then follow the advise you will have read elsewhere. On two seperate computers I have done this and found all I needed to do following this was download and install the standard google drivers as per user3079537's answer above. Good luck.
ref: http://www.petri.co.il/removing-old-drivers-from-vista-and-windows7.htm#
I faced similar problem. I solved it without using onload handler.I was working on AngularJs project so i used $interval and $ timeout. U can also use setTimeout and setInterval.Here's the code:
var stopPolling;
var doIframePolling;
$scope.showIframe = true;
doIframePolling = $interval(function () {
if(document.getElementById('UrlIframe') && document.getElementById('UrlIframe').contentDocument.head && document.getElementById('UrlIframe').contentDocument.head.innerHTML != ''){
$interval.cancel(doIframePolling);
doIframePolling = undefined;
$timeout.cancel(stopPolling);
stopPolling = undefined;
$scope.showIframe = true;
}
},400);
stopPolling = $timeout(function () {
$interval.cancel(doIframePolling);
doIframePolling = undefined;
$timeout.cancel(stopPolling);
stopPolling = undefined;
$scope.showIframe = false;
},5000);
$scope.$on("$destroy",function() {
$timeout.cancel(stopPolling);
$interval.cancel(doIframePolling);
});
Every 0.4 Seconds keep checking the head of iFrame Document. I somthing is present.Loading was not stopped by CORS as CORS error shows blank page. If nothing is present after 5 seconds there was some error (Cors policy) etc.. Show suitable message.Thanks. I hope it solves your problem.
0 for input, 1 for stdout and 2 for stderr.
One Tip:
somecmd >1.txt 2>&1
is correct, while somecmd 2>&1 >1.txt
is totally wrong with no effect!
Strings can be deep copied with
List<String> b = new ArrayList<String>(a);
because they are immutable. Every other Object not --> you need to iterate and do a copy by yourself.
You might want to try one of the following ways:
createNativeQuery(sqlString, resultClass)
Native queries can also be defined dynamically using the EntityManager.createNativeQuery()
API.
String sql = "SELECT USER.* FROM USER_ AS USER WHERE ID = ?";
Query query = em.createNativeQuery(sql, User.class);
query.setParameter(1, id);
User user = (User) query.getSingleResult();
@NamedNativeQuery
Native queries are defined through the @NamedNativeQuery
and @NamedNativeQueries
annotations, or <named-native-query>
XML element.
@NamedNativeQuery(
name="complexQuery",
query="SELECT USER.* FROM USER_ AS USER WHERE ID = ?",
resultClass=User.class
)
public class User { ... }
Query query = em.createNamedQuery("complexQuery", User.class);
query.setParameter(1, id);
User user = (User) query.getSingleResult();
You can read more in the excellent open book Java Persistence (available in PDF).
-------
NOTE: With regard to use of getSingleResult()
, see Why you should never use getSingleResult()
in JPA.
Ok, I solved it by adding the url for the background image at the end of the line.
Here's my working code:
.css {_x000D_
background: -moz-linear-gradient(top, rgba(0, 0, 0, 0) 0%, rgba(0, 0, 0, 0) 59%, rgba(0, 0, 0, 0.65) 100%), url('https://cdn.sstatic.net/Sites/stackoverflow/company/img/logos/so/so-icon.png?v=c78bd457575a') no-repeat;_x000D_
background: -webkit-gradient(linear, left top, left bottom, color-stop(0%, rgba(0, 0, 0, 0)), color-stop(59%, rgba(0, 0, 0, 0)), color-stop(100%, rgba(0, 0, 0, 0.65))), url('https://cdn.sstatic.net/Sites/stackoverflow/company/img/logos/so/so-icon.png?v=c78bd457575a') no-repeat;_x000D_
background: -webkit-linear-gradient(top, rgba(0, 0, 0, 0) 0%, rgba(0, 0, 0, 0) 59%, rgba(0, 0, 0, 0.65) 100%), url('https://cdn.sstatic.net/Sites/stackoverflow/company/img/logos/so/so-icon.png?v=c78bd457575a') no-repeat;_x000D_
background: -o-linear-gradient(top, rgba(0, 0, 0, 0) 0%, rgba(0, 0, 0, 0) 59%, rgba(0, 0, 0, 0.65) 100%), url('https://cdn.sstatic.net/Sites/stackoverflow/company/img/logos/so/so-icon.png?v=c78bd457575a') no-repeat;_x000D_
background: -ms-linear-gradient(top, rgba(0, 0, 0, 0) 0%, rgba(0, 0, 0, 0) 59%, rgba(0, 0, 0, 0.65) 100%), url('https://cdn.sstatic.net/Sites/stackoverflow/company/img/logos/so/so-icon.png?v=c78bd457575a') no-repeat;_x000D_
background: linear-gradient(to bottom, rgba(0, 0, 0, 0) 0%, rgba(0, 0, 0, 0) 59%, rgba(0, 0, 0, 0.65) 100%), url('https://cdn.sstatic.net/Sites/stackoverflow/company/img/logos/so/so-icon.png?v=c78bd457575a') no-repeat;_x000D_
height: 200px;_x000D_
_x000D_
}
_x000D_
<div class="css"></div>
_x000D_
Check out jquery-ui-bootstrap. From the README:
Twitter's Bootstrap was one of my favorite projects to come out of 2011, but having used it regularly it left me wanting two things:
The ability to work side-by-side with jQuery UI (something which caused a number of widgets to break visually) The ability to theme jQuery UI widgets using Bootstrap styles. Whilst I love jQuery UI, I (like others) find some of the current themes to look a little dated. My hope is that this theme provides a decent alternative for others that feel the same. To clarify, this project doesn't aim or intend to replace Twitter Bootstrap. It merely provides a jQuery UI-compatible theme inspired by Bootstrap's design. It also provides a version of Bootstrap CSS with a few (minor) sections commented out which enable the theme to work along-side it.
If the error message only occurs locally, try opening the sql file and press the play button.
If you don't want the event to be continuous (if you want the user to have to release the key each time), change onkeydown
to onkeyup
window.onkeydown = function (e) {
var code = e.keyCode ? e.keyCode : e.which;
if (code === 38) { //up key
alert('up');
} else if (code === 40) { //down key
alert('down');
}
};
Depends on what the while loop is doing. If there is a chance that it will block for a long time, use TimerTask
to schedule a task to set a stopExecution
flag, and also .interrupt()
your thread.
With just a time condition in the loop, it could sit there forever waiting for input or a lock (then again, may not be a problem for you).
To hide from the UI, use Format > Sheet > Hide
To hide programatically, use the Visible
property of the Worksheet
object. If you do it programatically, you can set the sheet as "very hidden", which means it cannot be unhidden through the UI.
ActiveWorkbook.Sheets("Name").Visible = xlSheetVeryHidden
' or xlSheetHidden or xlSheetVisible
You can also set the Visible property through the properties pane for the worksheet in the VBA IDE (ALT+F11).
I've did a "Update-Package –reinstall Microsoft.AspNet.Mvc" to fix it in Visual Studio 2015.
My case may not be typical but what I wanted to do was to have certain columns in a TABLE
completely "inert": impossible to tab into them, and impossible to select anything in them. I had found class "unselectable" from other SO answers:
.unselectable {
-webkit-touch-callout: none;
-webkit-user-select: none;
-khtml-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
user-select: none;
}
This actually prevents the user using the mouse to put the focus in the TD
... but I couldn't find a way on SO to prevent tabbing into cells. The TDs
in my TABLE
actually each has a DIV
as their sole child, and using console.log
I found that in fact the DIVs
would get the focus (without the focus first being obtained by the TDs
).
My solution involves keeping track of the "previously focused" element (anywhere on the page):
window.currFocus = document;
//Catch any bubbling focusin events (focus does not bubble)
$(window).on('focusin', function () {
window.prevFocus = window.currFocus;
window.currFocus = document.activeElement;
});
I can't really see how you'd get by without a mechanism of this kind... jolly useful for all sorts of purposes ... and of course it'd be simple to transform it into a stack of recently focused elements, if you wanted that...
The simplest answer is then just to do this (to the sole DIV
child in every newly created TD
):
...
jqNewCellDiv[ 0 ].classList.add( 'unselectable' );
jqNewCellDiv.focus( function() {
window.prevFocus.focus();
});
So far so good. It should be clear that this would work if you just have a TD
(with no DIV
child).
Slight issue: this just stops tabbing dead in its tracks. Clearly if the table has any more cells on that row or rows below the most obvious action you'd want is to making tabbing tab to the next non-unselectable cell ... either on the same row or, if there are other rows, on the row below. If it's the very end of the table it gets a bit more tricky: i.e. where should tabbing go then. But all good clean fun.
You will figure out that setOnPageChangeListener is deprecated, use addOnPageChangeListener, as below:
ViewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
@Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
@Override
public void onPageSelected(int position) {
if(position == 1){ // if you want the second page, for example
//Your code here
}
}
@Override
public void onPageScrollStateChanged(int state) {
}
});
The error you quote has nothing to do with pg_hba.conf
; it's failing to connect, not failing to authorize the connection.
Do what the error message says:
Check that the hostname and port are correct and that the postmaster is accepting TCP/IP connections
You haven't shown the command that produces the error. Assuming you're connecting on localhost
port 5432
(the defaults for a standard PostgreSQL install), then either:
PostgreSQL isn't running
PostgreSQL isn't listening for TCP/IP connections (listen_addresses
in postgresql.conf
)
PostgreSQL is only listening on IPv4 (0.0.0.0
or 127.0.0.1
) and you're connecting on IPv6 (::1
) or vice versa. This seems to be an issue on some older Mac OS X versions that have weird IPv6 socket behaviour, and on some older Windows versions.
PostgreSQL is listening on a different port to the one you're connecting on
(unlikely) there's an iptables
rule blocking loopback connections
(If you are not connecting on localhost
, it may also be a network firewall that's blocking TCP/IP connections, but I'm guessing you're using the defaults since you didn't say).
So ... check those:
ps -f -u postgres
should list postgres
processes
sudo lsof -n -u postgres |grep LISTEN
or sudo netstat -ltnp | grep postgres
should show the TCP/IP addresses and ports PostgreSQL is listening on
BTW, I think you must be on an old version. On my 9.3 install, the error is rather more detailed:
$ psql -h localhost -p 12345
psql: could not connect to server: Connection refused
Is the server running on host "localhost" (::1) and accepting
TCP/IP connections on port 12345?
The byte1 & 0xff
ensures that only the 8 least significant bits of byte1
can be non-zero.
if byte1
is already an unsigned type that has only 8 bits (e.g., char
in some cases, or unsigned char
in most) it won't make any difference/is completely unnecessary.
If byte1
is a type that's signed or has more than 8 bits (e.g., short
, int
, long
), and any of the bits except the 8 least significant is set, then there will be a difference (i.e., it'll zero those upper bits before or
ing with the other variable, so this operand of the or
affects only the 8 least significant bits of the result).
for out
@Test
void it_prints_out() {
PrintStream save_out=System.out;final ByteArrayOutputStream out = new ByteArrayOutputStream();System.setOut(new PrintStream(out));
System.out.println("Hello World!");
assertEquals("Hello World!\r\n", out.toString());
System.setOut(save_out);
}
for err
@Test
void it_prints_err() {
PrintStream save_err=System.err;final ByteArrayOutputStream err= new ByteArrayOutputStream();System.setErr(new PrintStream(err));
System.err.println("Hello World!");
assertEquals("Hello World!\r\n", err.toString());
System.setErr(save_err);
}
For eclipse here is how I solved my problem:
Preferences --> Compiler --> Compiler Complainer Level (Change to 1.8)
Rebuild via maven using Run as maven build.
It shouldn't show you the invalid target error anymore.
Note: I didn't have to set or change any other variables in my terminal.
Hope this helps.
The answer appears to be solely related to application size. I created a simple "hello world" app with nothing special in the manifest file, uploaded it to the Play store, and it was reported as compatible with my device.
I changed nothing in this app except for adding more content into the res/drawable
directory. When the .apk
size reached about 32 MB, the Play store started reporting that my app was incompatible with my phone.
I will attempt to contact Google developer support and ask for clarification on the reason for this limit.
UPDATE: Here is Google developer support response to this:
Thank you for your note. Currently the maximum file size limit for an app upload to Google Play is approximately 50 MB.
However, some devices may have smaller than 50 MB cache partition making the app unavailable for users to download. For example, some of HTC Wildfire devices are known for having 35-40 MB cache partitions. If Google Play is able to identify such device that doesn't have cache large enough to store the app, it may filter it from appearing for the user.
I ended up solving my problem by converting all the PNG files to JPG, with a small loss of quality. The .apk
file is now 28 MB, which is below whatever threshold Google Play is enforcing for my phone.
I also removed all the <uses-feature>
stuff, and now have just this:
<uses-sdk android:minSdkVersion="4" android:targetSdkVersion="15" />
Disclamer: This is just a wild guess
I know everybody loves an easy-to-read list:
toBe(<value>)
- The returned value is the same as <value>
toBeTrue()
- Checks if the returned value is true
toBeTruthy()
- Check if the value, when cast to a boolean, will be a truthy value
Truthy values are all values that aren't 0
, ''
(empty string), false
, null
, NaN
, undefined
or []
(empty array)*.
* Notice that when you run !![]
, it returns true
, but when you run [] == false
it also returns true
. It depends on how it is implemented. In other words: (!![]) === ([] == false)
On your example, toBe(true)
and toBeTrue()
will yield the same results.
Out of all the combinations you tried, %ld
and %lu
are the only ones which are valid printf format specifiers at all. %lu
(long unsigned decimal), %lx
or %lX
(long hex with lowercase or uppercase letters), and %lo
(long octal) are the only valid format specifiers for a variable of type unsigned long (of course you can add field width, precision, etc modifiers between the %
and the l
).
For anyone still having an issue I made mine work by doing this probably not the best fix but it worked for me..
I uninstalled all Java's that i current had installed, reinstalled the latest one and changed the install directory to C:/Windows/jre (Basically where it kept saying there was no config file)
HTA works like a normal windows application.
You write HTML code, and save it as an .hta file.
However, there are, at least, one drawback: The browser can't open an .hta file; it's handled as a normal .exe program. So, if you place a link to an .hta onto your web page, it will open a download dialog, asking of you want to open or save the HTA file. If its not a problem for you, you can click "Open" and it will open a new window (that have no toolbars, so no Back button, neither address bar, neither menubar).
I needed to do something very similar to what you want, but instead of iframes
, I used a real frameset
.
The main page need to be a .hta file; the other should be a normal .htm page (or .php or whatever).
Here's an example of a HTA page with 2 frames, where the top one have a button and a text field, that contains the second frame URL; the button updates the field:
<html>
<head>
<title>HTA Example</title>
<HTA:APPLICATION id="frames" border="thin" caption="yes" icon="http://www.google.com/favicon.ico" showintaskbar="yes" singleinstance="no" sysmenu="yes" navigable="yes" contextmenu="no" innerborder="no" scroll="auto" scrollflat="yes" selection="yes" windowstate="normal"></HTA:APPLICATION>
</head>
<frameset rows="60px, *">
<frame src="topo.htm" name="topo" id="topo" application="yes" />
<frame src="http://www.google.com" name="conteudo" id="conteudo" application="yes" />
</frameset>
</html>
HTA:APPLICATION
tag that sets some properties to the file; it's good to have, but it isn't a must.application="yes"
at the frames' tags. It says they belongs to the program too and should have access to all data (if you don't, the frames will still show the error you had before). <html>
<head>
<title>Topo</title>
<script type="text/javascript">
function copia_url() {
campo.value = parent.conteudo.location;
}
</script>
</head>
<body style="background: lightBlue;" onload="copia_url()">
<input type="button" value="Copiar URL" onclick="copia_url()" />
<input type="text" size="120" id="campo" />
</body>
</html>
I hope this help you, and others that get to this question. It solved my problem, that looks like to be the same as you have.
You can found more information here: http://www.irt.org/articles/js191/index.htm
Enjoy =]
They can be considered as equivalent. The limits in size are the same:
There is also the DBCLOBs, for double byte characters.
References:
You may find it easier to use the is
keyword:
if (mycontrol is TextBox)
You could use SysInternal's PsExec.
Defining array with multiple types in TypeScript
Use a union type (string|number)[]
demo:
const foo: (string|number)[] = [ 1, "message" ];
I have an array of the form: [ 1, "message" ].
If you are sure that there are always only two elements [number, string]
then you can declare it as a tuple:
const foo: [number, string] = [ 1, "message" ];
if you use .Values while creating the matrix X and Y vectors it will fix the problem.
y=dataset.iloc[:, 4].values
X=dataset.iloc[:, 0:4].values
when you use .Values it creates a Object representation of the created matrix will be returned with the axes removed. Check the below link for more information
https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.values.html
Just a caveat to add about DateDiff, it counts the number of times you pass the boundary you specify as your units, so is subject to problems if you are looking for a precise timespan. e.g.
select datediff (m, '20100131', '20100201')
gives an answer of 1, because it crossed the boundary from January to February, so even though the span is 2 days, datediff would return a value of 1 - it crossed 1 date boundary.
select datediff(mi, '2010-01-22 15:29:55.090' , '2010-01-22 15:30:09.153')
Gives a value of 1, again, it passed the minute boundary once, so even though it is approx 14 seconds, it would be returned as a single minute when using Minutes as the units.
You can set focus to element. It works better than scrollIntoView
node.setAttribute('tabindex', '-1')
node.focus()
node.removeAttribute('tabindex')
Another way would be creating a mutable integer:
class MutableInt {
int value = 0;
public void inc () { ++value; }
public int get () { return value; }
}
...
Map<String,MutableInt> map = new HashMap<String,MutableInt> ();
MutableInt value = map.get (key);
if (value == null) {
value = new MutableInt ();
map.put (key, value);
} else {
value.inc ();
}
of course this implies creating an additional object but the overhead in comparison to creating an Integer (even with Integer.valueOf) should not be so much.
public static class SerializerDeserializerExtensions
{
public static byte[] Serializer(this object _object)
{
byte[] bytes;
using (var _MemoryStream = new MemoryStream())
{
IFormatter _BinaryFormatter = new BinaryFormatter();
_BinaryFormatter.Serialize(_MemoryStream, _object);
bytes = _MemoryStream.ToArray();
}
return bytes;
}
public static T Deserializer<T>(this byte[] _byteArray)
{
T ReturnValue;
using (var _MemoryStream = new MemoryStream(_byteArray))
{
IFormatter _BinaryFormatter = new BinaryFormatter();
ReturnValue = (T)_BinaryFormatter.Deserialize(_MemoryStream);
}
return ReturnValue;
}
}
You can use it like below code.
DataTable _DataTable = new DataTable();
_DataTable.Columns.Add(new DataColumn("Col1"));
_DataTable.Columns.Add(new DataColumn("Col2"));
_DataTable.Columns.Add(new DataColumn("Col3"));
for (int i = 0; i < 10; i++) {
DataRow _DataRow = _DataTable.NewRow();
_DataRow["Col1"] = (i + 1) + "Column 1";
_DataRow["Col2"] = (i + 1) + "Column 2";
_DataRow["Col3"] = (i + 1) + "Column 3";
_DataTable.Rows.Add(_DataRow);
}
byte[] ByteArrayTest = _DataTable.Serializer();
DataTable dt = ByteArrayTest.Deserializer<DataTable>();
You have set #slider
as absolute
, which means that it "is positioned relative to the nearest positioned ancestor" (confusing, right?). Meanwhile, #content
div is placed relative, which means "relative to its normal position". So the position of the 2 divs is not related.
You can read about CSS positioning here
If you set both to relative
, the divs will be one after the other, as shown here:
#slider {
position:relative;
left:0;
height:400px;
border-style:solid;
border-width:5px;
}
#slider img {
width:100%;
}
#content {
position:relative;
}
#content #text {
position:relative;
width:950px;
height:215px;
color:red;
}
So I was having a similar issue and I managed to solve it by putting the script tag with my JS file after the closing body tag.
I assume it's because it makes sure there's something to reference, but I am not entirely sure.
Try this, it works!
<div class="row">
<div class="center">
<div class="col-xs-12 col-sm-4">
<p>hi 1!</p>
</div>
<div class="col-xs-12 col-sm-4">
<p>hi 2!</p>
</div>
<div class="col-xs-12 col-sm-4">
<p>hi 3!</p>
</div>
</div>
</div>
Then, in css define the width of center div and center in a document:
.center {
margin: 0 auto;
width: 80%;
}
I got the same message but my files are decrypted as expected. Please check in your destination path if you could see the output file file.
To check whether a Byte array is empty, the simplest way is to use the VBA function StrPtr()
.
If the Byte array is empty, StrPtr()
returns 0
; otherwise, it returns a non-zero value (however, it's not the address to the first element).
Dim ar() As Byte
Debug.Assert StrPtr(ar) = 0
ReDim ar(0 to 3) As Byte
Debug.Assert StrPtr(ar) <> 0
However, it only works with Byte array.
export
is a built-in command of the bash
shell and other Bourne shell variants. It is used to mark a shell variable for export to child processes.
The time difference b/w to time will be shown use this method.
private void HoursCalculator()
{
var t1 = txtfromtime.Text.Trim();
var t2 = txttotime.Text.Trim();
var Fromtime = t1.Substring(6);
var Totime = t2.Substring(6);
if (Fromtime == "M")
{
Fromtime = t1.Substring(5);
}
if (Totime == "M")
{
Totime = t2.Substring(5);
}
if (Fromtime=="PM" && Totime=="AM" )
{
var dt1 = DateTime.Parse("1900-01-01 " + txtfromtime.Text.Trim());
var dt2 = DateTime.Parse("1900-01-02 " + txttotime.Text.Trim());
var t = dt1.Subtract(dt2);
//int temp = Convert.ToInt32(t.Hours);
//temp = temp / 2;
lblHours.Text =t.Hours.ToString() + ":" + t.Minutes.ToString();
}
else if (Fromtime == "AM" && Totime == "PM")
{
var dt1 = DateTime.Parse("1900-01-01 " + txtfromtime.Text.Trim());
var dt2 = DateTime.Parse("1900-01-01 " + txttotime.Text.Trim());
TimeSpan t = (dt2.Subtract(dt1));
lblHours.Text = t.Hours.ToString() + ":" + t.Minutes.ToString();
}
else
{
var dt1 = DateTime.Parse("1900-01-01 " + txtfromtime.Text.Trim());
var dt2 = DateTime.Parse("1900-01-01 " + txttotime.Text.Trim());
TimeSpan t = (dt2.Subtract(dt1));
lblHours.Text = t.Hours.ToString() + ":" + t.Minutes.ToString();
}
}
use your field id's
var t1 captures a value of 4:00AM
check this code may be helpful to someone.
All you need is a control that you can set the text of, and an UpdatePanel if the exception occurs during a postback.
If occurs during a postback: markup:
<ajax:UpdatePanel id="ErrorUpdatePanel" runat="server" UpdateMode="Coditional">
<ContentTemplate>
<asp:TextBox id="ErrorTextBox" runat="server" />
</ContentTemplate>
</ajax:UpdatePanel>
code:
try
{
do something
}
catch(YourException ex)
{
this.ErrorTextBox.Text = ex.Message;
this.ErrorUpdatePanel.Update();
}
This response isn't about macro war, but producing error if no matching platform is found.
#ifdef LINUX_KEY_WORD
... // linux code goes here.
#elif WINDOWS_KEY_WORD
... // windows code goes here.
#else
#error Platform not supported
#endif
If #error
is not supported, you may use static_assert (C++0x) keyword. Or you may implement custom STATIC_ASSERT, or just declare an array of size 0, or have switch that has duplicate cases. In short, produce error at compile time and not at runtime
'raw string' means it is stored as it appears. For example, '\'
is just a backslash instead of an escaping.
Need help reading and writing text file using vbscript - Dev Shed
VBScript - FileSystemObject
http://ezinearticles.com/?VBScript---FileSystemObject&id=294348
I don't think there's ever a reason not to use pull --rebase
-- I added code to Git specifically to allow my git pull
command to always rebase against upstream commits.
When looking through history, it is just never interesting to know when the guy/gal working on the feature stopped to synchronise up. It might be useful for the guy/gal while he/she is doing it, but that's what reflog
is for. It's just adding noise for everyone else.
You can use Date.getTime()
function, or the Date
object itself which when divided returns the time in milliseconds.
var d = new Date();
d/1000
> 1510329641.84
d.getTime()/1000
> 1510329641.84
ArrayList bkgrefs = new ArrayList();
foreach (GridViewRow rowd in grdOptionExtraDetails.Rows)
{
CheckBox cbf = (CheckBox)rowd.Cells[1].FindControl("chkbulk");
if (cbf.Checked)
{
rowd.Visible = true;
bkgrefs.Add(Convert.ToString(grdOptionExtraDetails.Data.Rows[rowd.RowIndex]["OptionID"]));
}
else
{
grdOptionExtraDetails.Data.Rows.RemoveAt(rowd.DataItemIndex);
rowd.Visible = false;
}
}
You can access rails app path using variable RAILS_ROOT
.
For example:
render :file => "#{RAILS_ROOT}/public/layouts/mylayout.html.erb"
The Math.round function is overloaded When it receives a float value, it will give you an int. For example this would work.
int a=Math.round(1.7f);
When it receives a double value, it will give you a long, therefore you have to typecast it to int.
int a=(int)Math.round(1.7);
This is done to prevent loss of precision. Your double value is 64bit, but then your int variable can only store 32bit so it just converts it to long, which is 64bit but you can typecast it to 32bit as explained above.
You will want to use the String class' Split() method and pass in a regular expression of "\D+" which will match at least one non-number.
myString.split("\\D+");
Here's a variation that ignores and preserves case:
jQuery.fn.highlight = function (str, className) {
var regex = new RegExp("\\b"+str+"\\b", "gi");
return this.each(function () {
this.innerHTML = this.innerHTML.replace(regex, function(matched) {return "<span class=\"" + className + "\">" + matched + "</span>";});
});
};
Searching with leading and trailing wildcards is going to be extremely slow on a large index. If you want to be able to search by word prefix, remove leading wildcard. If you really need to find a substring in a middle of a word, you would be better of using ngram tokenizer.
Well one way to do it is set the height of your body to the height
that you want your page
to be. In this example I did 600px
.
Then set your wrapper
height to a percentage of the body here I did 70%
This will adjust your table so that it does not fill up the whole screen but in stead just takes up a percentage of the specified page height.
body {
padding-top: 70px;
border:1px solid black;
height:600px;
}
.mygrid-wrapper-div {
border: solid red 5px;
overflow: scroll;
height: 70%;
}
Update How about a jQuery approach.
$(function() {
var window_height = $(window).height(),
content_height = window_height - 200;
$('.mygrid-wrapper-div').height(content_height);
});
$( window ).resize(function() {
var window_height = $(window).height(),
content_height = window_height - 200;
$('.mygrid-wrapper-div').height(content_height);
});
In Swift, iOS 8+ project I like to make an extension on UIScreen
, like:
extension UIScreen {
var isPhone4: Bool {
return self.nativeBounds.size.height == 960;
}
var isPhone5: Bool {
return self.nativeBounds.size.height == 1136;
}
var isPhone6: Bool {
return self.nativeBounds.size.height == 1334;
}
var isPhone6Plus: Bool {
return self.nativeBounds.size.height == 2208;
}
}
(NOTE: nativeBounds
is in pixels).
And then the code will be like:
if UIScreen.mainScreen().isPhone4 {
// do smth on the smallest screen
}
So the code makes it clear that this is a check for the main screen, not for the device model.
As another answer says, you can take advantage of truthy/falsy evaluations if you know that 0
is the only falsy element possibly in your array. All elements in an array are falsy iff there are not any truthy elements in it.*
>>> a = np.zeros(10)
>>> not np.any(a)
True
However, the answer claimed that any
was faster than other options due partly to short-circuiting. As of 2018, Numpy's all
and any
do not short-circuit.
If you do this kind of thing often, it's very easy to make your own short-circuiting versions using numba
:
import numba as nb
# short-circuiting replacement for np.any()
@nb.jit(nopython=True)
def sc_any(array):
for x in array.flat:
if x:
return True
return False
# short-circuiting replacement for np.all()
@nb.jit(nopython=True)
def sc_all(array):
for x in array.flat:
if not x:
return False
return True
These tend to be faster than Numpy's versions even when not short-circuiting. count_nonzero
is the slowest.
Some input to check performance:
import numpy as np
n = 10**8
middle = n//2
all_0 = np.zeros(n, dtype=int)
all_1 = np.ones(n, dtype=int)
mid_0 = np.ones(n, dtype=int)
mid_1 = np.zeros(n, dtype=int)
np.put(mid_0, middle, 0)
np.put(mid_1, middle, 1)
# mid_0 = [1 1 1 ... 1 0 1 ... 1 1 1]
# mid_1 = [0 0 0 ... 0 1 0 ... 0 0 0]
Check:
## count_nonzero
%timeit np.count_nonzero(all_0)
# 220 ms ± 8.73 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
%timeit np.count_nonzero(all_1)
# 150 ms ± 4.56 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)
### all
# np.all
%timeit np.all(all_1)
%timeit np.all(mid_0)
%timeit np.all(all_0)
# 56.8 ms ± 3.41 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)
# 57.4 ms ± 1.76 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)
# 55.9 ms ± 2.13 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)
# sc_all
%timeit sc_all(all_1)
%timeit sc_all(mid_0)
%timeit sc_all(all_0)
# 44.4 ms ± 2.49 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)
# 22.7 ms ± 599 µs per loop (mean ± std. dev. of 7 runs, 10 loops each)
# 288 ns ± 6.36 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)
### any
# np.any
%timeit np.any(all_0)
%timeit np.any(mid_1)
%timeit np.any(all_1)
# 60.7 ms ± 1.38 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)
# 60 ms ± 287 µs per loop (mean ± std. dev. of 7 runs, 10 loops each)
# 57.7 ms ± 1.12 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)
# sc_any
%timeit sc_any(all_0)
%timeit sc_any(mid_1)
%timeit sc_any(all_1)
# 41.7 ms ± 1.24 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)
# 22.4 ms ± 1.51 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)
# 287 ns ± 12.7 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)
* Helpful all
and any
equivalences:
np.all(a) == np.logical_not(np.any(np.logical_not(a)))
np.any(a) == np.logical_not(np.all(np.logical_not(a)))
not np.all(a) == np.any(np.logical_not(a))
not np.any(a) == np.all(np.logical_not(a))
I would like to add a design pattern that has been applied in Android Framework. This is Half Sync Half Async pattern used in the Asynctask implementation. See my discussion at
https://docs.google.com/document/d/1_zihWXAwgTAdJc013-bOLUHPMrjeUBZnDuPkzMxEEj0/edit?usp=sharing
1.Set the Path of Git in environment variables. 2.From Windows command prompt, run cd Project\folder\Path\ run the command: bower install
If you are using the excellent
simply tap Apple-Shift-N (as in "new window")
Drag whatever you want there.
I know this is in the above answers, but my point is that I think all you need is
new Date(collectionDate);
if your goal is to convert a date string into a date (as per the OP "How do I convert it to a date object?").
In angular 1.4 +, in addition to adding the dependency
angular.module('myApp', ['ngRoute'])
,we also need to reference the separate angular-route.js file
<script src="angular.js">
<script src="angular-route.js">
You need an assignment operator so that:
arrayOfAs[i] = A(3);
works as it should.
var a = [1,2,3,4,5,6,7,8,9];
var isSixInArray = a.filter(function(item){return item==6}).length ? true : false;
var isSixInArray = a.indexOf(6)>=0;
To get the number of element in any iterable object, your goto method in Python is len()
eg.
a = range(1000) # range
b = 'abcdefghijklmnopqrstuvwxyz' # string
c = [10, 20, 30] # List
d = (30, 40, 50, 60, 70) # tuple
e = {11, 21, 31, 41} # set
len()
method can work on all the above data types because they are iterable i.e You can iterate over them.
all_var = [a, b, c, d, e] # All variables are stored to a list
for var in all_var:
print(len(var))
Rough estimate of the len() method
def len(iterable, /):
total = 0
for i in iterable:
total += 1
return total
matches();
does not buffer, but find()
buffers. find()
searches to the end of the string first, indexes the result, and return the boolean value and corresponding index.
That is why when you have a code like
1:Pattern.compile("[a-z]");
2:Pattern.matcher("0a1b1c3d4");
3:int count = 0;
4:while(matcher.find()){
5:count++: }
At 4: The regex engine using the pattern structure will read through the whole of your code (index to index as specified by the regex[single character]
to find at least one match. If such match is found, it will be indexed then the loop will execute based on the indexed result else if it didn't do ahead calculation like which matches()
; does not. The while statement would never execute since the first character of the matched string is not an alphabet.
If you have multiple projects in solution, then setUp project as started where you have your truth App.config.
You can use JQuery also
$(document).ready(function () {
$('#personlist').val("10");
}
Microsoft Visual Studio 2008 Service Pack 1 (iso)
http://www.microsoft.com/en-us/download/details.aspx?id=13276
Version: SP1 File Name: VS2008SP1ENUX1512962.iso Date Published: 8/11/2008 File Size: 831.3 MB
Supported Operating System
Windows Server 2003, Windows Server 2008, Windows Vista, Windows XP
Minimum: 1.6 GHz CPU, 384 MB RAM, 1024x768 display, 5400 RPM hard disk
Recommended: 2.2 GHz or higher CPU, 1024 MB or more RAM, 1280x1024 display, 7200 RPM or higher hard disk
On Windows Vista: 2.4 GHz CPU, 768 MB RAM
Maintain Internet connectivity during the installation of the service pack until seeing the “Installation Completed Successfully” message before disconnecting.
You've already got it: A if test else B
is a valid Python expression. The only problem with your dict comprehension as shown is that the place for an expression in a dict comprehension must have two expressions, separated by a colon:
{ (some_key if condition else default_key):(something_if_true if condition
else something_if_false) for key, value in dict_.items() }
The final if
clause acts as a filter, which is different from having the conditional expression.
I would extend this question with a NDIS driver example on getting time. As one knows, KeQuerySystemTime (mimicked under NdisGetCurrentSystemTime) has a low resolution above milliseconds, and there are some processes like network packets or other IRPs which may need a better timestamp;
The example is just as simple:
LONG_INTEGER data, frequency;
LONGLONG diff;
data = KeQueryPerformanceCounter((LARGE_INTEGER *)&frequency)
diff = data.QuadPart / (Frequency.QuadPart/$divisor)
where divisor is 10^3, or 10^6 depending on required resolution.
Given you use JQuery, you can do something like below :
<form id="myform">
syn<input type="checkbox" name="checkfield" id="g01-01" onclick="doalert()"/>
</form>
function doalert() {
if ($("#g01-01").is(":checked")) {
alert ("hi");
} else {
alert ("bye");
}
}
Here are conversion method for both ways. this = instance of your class
public string ToXML()
{
using(var stringwriter = new System.IO.StringWriter())
{
var serializer = new XmlSerializer(this.GetType());
serializer.Serialize(stringwriter, this);
return stringwriter.ToString();
}
}
public static YourClass LoadFromXMLString(string xmlText)
{
using(var stringReader = new System.IO.StringReader(xmlText))
{
var serializer = new XmlSerializer(typeof(YourClass ));
return serializer.Deserialize(stringReader) as YourClass ;
}
}
See ?order
. You just need the last index (or first, in decreasing order), so this should do the trick:
order(matrix[,2],decreasing=T)[1]
You can simply do it by using:
Object.prototype.extend = function(object) {
// loop through object
for (var i in object) {
// check if the extended object has that property
if (object.hasOwnProperty(i)) {
// mow check if the child is also and object so we go through it recursively
if (typeof this[i] == "object" && this.hasOwnProperty(i) && this[i] != null) {
this[i].extend(object[i]);
} else {
this[i] = object[i];
}
}
}
return this;
};
update: I checked for
this[i] != null
sincenull
is an object
Then use it like:
var options = {
foo: 'bar',
baz: 'dar'
}
var defaults = {
foo: false,
baz: 'car',
nat: 0
}
defaults.extend(options);
This well result in:
// defaults will now be
{
foo: 'bar',
baz: 'dar',
nat: 0
}
If I understand well, you want to Join ScheduleRequest
with User
and apply the in
clause to the userName
property of the entity User
.
I'd need to work a bit on this schema. But you can try with this trick, that is much more readable than the code you posted, and avoids the Join
part (because it handles the Join
logic outside the Criteria Query).
List<String> myList = new ArrayList<String> ();
for (User u : usersList) {
myList.add(u.getUsername());
}
Expression<String> exp = scheduleRequest.get("createdBy");
Predicate predicate = exp.in(myList);
criteria.where(predicate);
In order to write more type-safe code you could also use Metamodel by replacing this line:
Expression<String> exp = scheduleRequest.get("createdBy");
with this:
Expression<String> exp = scheduleRequest.get(ScheduleRequest_.createdBy);
If it works, then you may try to add the Join
logic into the Criteria Query
. But right now I can't test it, so I prefer to see if somebody else wants to try.
Not a perfect answer though may be code snippets might help.
public <T> List<T> findListWhereInCondition(Class<T> clazz,
String conditionColumnName, Serializable... conditionColumnValues) {
QueryBuilder<T> queryBuilder = new QueryBuilder<T>(clazz);
addWhereInClause(queryBuilder, conditionColumnName,
conditionColumnValues);
queryBuilder.select();
return queryBuilder.getResultList();
}
private <T> void addWhereInClause(QueryBuilder<T> queryBuilder,
String conditionColumnName, Serializable... conditionColumnValues) {
Path<Object> path = queryBuilder.root.get(conditionColumnName);
In<Object> in = queryBuilder.criteriaBuilder.in(path);
for (Serializable conditionColumnValue : conditionColumnValues) {
in.value(conditionColumnValue);
}
queryBuilder.criteriaQuery.where(in);
}
To prevent recopy the array every time which isn't efficient
What about using Stack
csharp> var i = new Stack<byte>();
csharp> i.Push(1);
csharp> i.Push(2);
csharp> i.Push(3);
csharp> i; { 3, 2, 1 }
csharp> foreach(var x in i) {
> Console.WriteLine(x);
> }
3 2 1
For showing a particular trigger in a particular schema you can try the following:
select * from information_schema.triggers where
information_schema.triggers.trigger_name like '%trigger_name%' and
information_schema.triggers.trigger_schema like '%data_base_name%'
Have to uncheck the Reuse types in all referenced assemblies from Configure service reference option
Is this what you're looking for?
if (request instanceof HttpServletRequest) {
String url = ((HttpServletRequest)request).getRequestURL().toString();
String queryString = ((HttpServletRequest)request).getQueryString();
}
To Reconstruct:
System.out.println(url + "?" + queryString);
Info on HttpServletRequest.getRequestURL()
and HttpServletRequest.getQueryString()
.
You can use numpy's slicing, simply start:stop:step
.
>>> xs
array([1, 2, 3, 4, 1, 2, 3, 4, 1, 2, 3, 4])
>>> xs[1::4]
array([2, 2, 2])
This creates a view of the the original data, so it's constant time. It'll also reflect changes to the original array and keep the whole original array in memory:
>>> a
array([1, 2, 3, 4, 5])
>>> b = a[::2] # O(1), constant time
>>> b[:] = 0 # modifying the view changes original array
>>> a # original array is modified
array([0, 2, 0, 4, 0])
so if either of the above things are a problem, you can make a copy explicitly:
>>> a
array([1, 2, 3, 4, 5])
>>> b = a[::2].copy() # explicit copy, O(n)
>>> b[:] = 0 # modifying the copy
>>> a # original is intact
array([1, 2, 3, 4, 5])
This isn't constant time, but the result isn't tied to the original array. The copy also contiguous in memory, which can make some operations on it faster.
To get the modified date on a single file try:
$lastModifiedDate = (Get-Item "C:\foo.tmp").LastWriteTime
To compare with another:
$dateA= $lastModifiedDate
$dateB= (Get-Item "C:\other.tmp").LastWriteTime
if ($dateA -ge $dateB) {
Write-Host("C:\foo.tmp was modified at the same time or after C:\other.tmp")
} else {
Write-Host("C:\foo.tmp was modified before C:\other.tmp")
}
The code looks strange because the printf are not in any function blocks.
To anyone else who tried most of the solutions and still having problems.
My solution is different from the others, which is located at the bottom of this post, but before you try it make sure you have exhausted the following lists. To be sure, I have tried all of them but to no avail.
Recompile and redeploy from scratch, don't update the existing app. SO Answer
Grant IIS_IUSRS full access to the directory "C:\Windows\Microsoft.NET\Framework\v4.0.30319\Temporary ASP.NET Files"
Keep in mind the framework version you are using. If your app is using impersonation, use that identity instead of IIS_IUSRS
Delete all contents of the directory "C:\Windows\Microsoft.NET\Framework\v4.0.30319\Temporary ASP.NET Files".
Keep in mind the framework version you are using
Change the identity of the AppPool that your app is using, from ApplicatonPoolIdentity to NetworkService.
IIS > Application Pools > Select current app pool > Advance Settings > Identity.
SO Answer (please restore to default if it doesn't work)
Verify IIS Version and AppPool .NET version compatibility with your app. Highly applicable to first time deployments. SO Answer
Verify impersonation configuration if applicable. SO Answer
My Solution:
I found out that certain anti-virus softwares are actively blocking compilations of DLLs within the directory "Temporary ASP.NET Files", mine was McAfee, the IT people failed to notify me of the installation.
As per advice by both McAfee experts and Microsoft, you need to exclude the directory "Temporary ASP.NET Files" in the real time scanning.
Sources:
Don't disable the Anti-Virus because it is only doing its job. Don't manually copy missing DLL files in the directory \Temporary ASP.NET Files{project name} because thats duct taping.
If you have another program running in the JVM and you use System.exit, that second program will be closed, too. Imagine for example that you run a java job on a cluster node and that the java program that manages the cluster node runs in the same JVM. If the job would use System.exit it would not only quit the job but also "shut down the complete node". You would not be able to send another job to that cluster node since the management program has been closed accidentally.
Therefore, do not use System.exit if you want to be able to control your program from another java program within the same JVM.
Use System.exit if you want to close the complete JVM on purpose and if you want to take advantage of the possibilities that have been described in the other answers (e.g. shut down hooks: Java shutdown hook, non-zero return value for command line calls: How to get the exit status of a Java program in Windows batch file).
Also have a look at Runtime Exceptions: System.exit(num) or throw a RuntimeException from main?
mkdir B && touch B/myfile.txt
Alternatively, create a function:
mkfile() { mkdir -p -- "$1" && touch -- "$1"/"$2" }
Execute it with 2 arguments: path to create and filename. Saying:
mkfile B/C/D myfile.txt
would create the file myfile.txt
in the directory B/C/D
.
BOOST_VERSION is defined in the boost header file version.hpp.
<resource>
<string name="your_string_here">This is an <u>underline</u>.</string>
</resources>
If it does not work then
<resource>
<string name="your_string_here">This is an <u>underline</u>.</string>
Because "<" could be a keyword at some time.
And for Displaying
TextView textView = (TextView) view.findViewById(R.id.textview);
textView.setText(Html.fromHtml(getString(R.string.your_string_here)));
You can use GETUTCDATE() function to get UTC datetime Probably you can select difference between GETUTCDATE() and GETDATE() and use this difference to ajust your dates to UTC
But I agree with previous message, that it is much easier to control right datetime in the business layer (in .NET, for example).
Basename wild cards were introduced in Java 6; i.e. "foo/*" means all ".jar" files in the "foo" directory.
In earlier versions of Java that do not support wildcard classpaths, I have resorted to using a shell wrapper script to assemble a Classpath by 'globbing' a pattern and mangling the results to insert ':' characters at the appropriate points. This would be hard to do in a BAT file ...
I know the reason why it is the way it is has already been addressed, but when it comes to "custom" boolean formatting, I've got two extension methods that I can't live without anymore :-)
public static class BoolExtensions
{
public static string ToString(this bool? v, string trueString, string falseString, string nullString="Undefined") {
return v == null ? nullString : v.Value ? trueString : falseString;
}
public static string ToString(this bool v, string trueString, string falseString) {
return ToString(v, trueString, falseString, null);
}
}
Usage is trivial. The following converts various bool values to their Portuguese representations:
string verdadeiro = true.ToString("verdadeiro", "falso");
string falso = false.ToString("verdadeiro", "falso");
bool? v = null;
string nulo = v.ToString("verdadeiro", "falso", "nulo");
data
will return you a string representation of a list, but it is actually still a string. Just check the type of data
with type(data)
. That means if you try using indexing on this string representation of a list as such data['fruits'][0]
, it will return you "[" as it is the first character of data['fruits']
You can do json.loads(data['fruits'])
to convert it back to a Python list so that you can interact with regular list indexing. There are 2 other ways you can convert it back to a Python list suggested here
userType = (user.Type == 0) ? "Admin" : (user.type == 1) ? "User" : "Admin";
should do the trick.
I had problems, if the file contained German Umlauts (ä,ö,ü). I could solve the problem by using:
ec = Encoding::Converter.new('iso-8859-1', 'utf-8')
...
f << ec.convert(seg)
...
You can create a generic style and re-use it on multiple textviews like the one below:
textView.setTextAppearance(this, R.style.MyTextStyle);
Edit: this refers to Context
position: relative act as a parent element position: absolute act a child of relative position. you can see the below example
.postion-element{
position:relative;
width:200px;
height:200px;
background-color:green;
}
.absolute-element{
position:absolute;
top:10px;
left:10px;
background-color:blue;
}
Make sure that you really need it. Do a google search for "singleton anti-pattern" to see some arguments against it.
There's nothing inherently wrong with it I suppose, but it's just a mechanism for exposing some global resource/data so make sure that this is the best way. In particular, I've found dependency injection (DI) more useful particularly if you are also using unit tests, because DI allows you to use mocked resources for testing purposes.
In bash, if you don't need decimals in your division, you can do:
>echo $((5+6))
11
>echo $((10/2))
5
>echo $((10/3))
3
In my case, this issue was resolved by updating maven's dependencies:
Another easy way to circumvent google's check is to use another compression algorithm with tar, like bz2:
tar -cvjf my.tar.bz2 dir/
Note that 'j' (for bz2 compression) is used above instead of 'z' (gzip compression).
i import the material design dialog module , so i created aboutcomponent for dialog the call this component from openDialog method then i got this error , i just put this
declarations: [
AppComponent,
ExampleDialogComponent
],
entryComponents: [
ExampleDialogComponent
],
You can construct it:
#modal-select-your-position li {
/* handle multiline */
overflow: visible;
padding-left: 17px;
position: relative;
}
#modal-select-your-position li:before {
/* your own marker in content */
content: "—";
left: 0;
position: absolute;
}
Here's a solution using C#:
void DrawCirclePoints(int points, double radius, Point center)
{
double slice = 2 * Math.PI / points;
for (int i = 0; i < points; i++)
{
double angle = slice * i;
int newX = (int)(center.X + radius * Math.Cos(angle));
int newY = (int)(center.Y + radius * Math.Sin(angle));
Point p = new Point(newX, newY);
Console.WriteLine(p);
}
}
Sample output from DrawCirclePoints(8, 10, new Point(0,0));
:
{X=10,Y=0}
{X=7,Y=7}
{X=0,Y=10}
{X=-7,Y=7}
{X=-10,Y=0}
{X=-7,Y=-7}
{X=0,Y=-10}
{X=7,Y=-7}
Good luck!
I would look at the Join operator:
from r in list join i in listofIds on r.Id equals i select r
I'm not sure how this would be optimized over the Contains methods, but at least it gives the compiler a better idea of what you're trying to do. It's also sematically closer to what you're trying to achieve.
Edit: Extension method syntax for completeness (now that I've figured it out):
var results = listofIds.Join(list, i => i, r => r.Id, (i, r) => r);
Late answer, but I figured it's worth keeping this updated. Expanding on Andrea Turri answer to reflect updated jQuery API and .success/.error deprecated methods.
As of jQuery 1.8.* the preferred way of doing this is to use .done() and .fail(). Jquery Docs
e.g.
$('#my_get_related_keywords').click(function() {
var ajaxRequest = $.ajax({
type: "POST",
url: "HERE PUT THE PATH OF YOUR SERVICE OR PAGE",
data: '{"HERE YOU CAN PUT DATA TO PASS AT THE SERVICE"}',
contentType: "application/json; charset=utf-8",
dataType: "json"});
//When the request successfully finished, execute passed in function
ajaxRequest.done(function(msg){
//do something
});
//When the request failed, execute the passed in function
ajaxRequest.fail(function(jqXHR, status){
//do something else
});
});
You can combine attribute selectors this way:
$("[attr1=val][attr2=val]")...
so that an element has to satisfy both conditions. Of course you can use this for more than two. Also, don't do [type=checkbox]
. jQuery has a selector for that, namely :checkbox
so the end result is:
$("input:checkbox[name=ProductCode]")...
Attribute selectors are slow however so the recommended approach is to use ID and class selectors where possible. You could change your markup to:
<input type="checkbox" class="ProductCode" name="ProductCode"value="396P4">
<input type="checkbox" class="ProductCode" name="ProductCode"value="401P4">
<input type="checkbox" class="ProductCode" name="ProductCode"value="F460129">
allowing you to use the much faster selector of:
$("input.ProductCode")...
Another example for vertically and horizontally centered div or any object(s):
var obj = $("#divID");
var halfsc = $(window).height()/2;
var halfh = $(obj).height() / 2;
var halfscrn = screen.width/2;
var halfobj =$(obj).width() / 2;
var goRight = halfscrn - halfobj ;
var goBottom = halfsc - halfh;
$(obj).css({marginLeft: goRight }).css({marginTop: goBottom });