I had this error recently. Turns out that my cookie settings were incorrect in config.yml. Adding the cookie_path
and cookie_domain
settings to framework.session
fixed it.
This error may also occur if trying to run a script and the shebang is misspelled. Make sure it reads #!/bin/sh
, #!/bin/bash
, or whichever interpreter you're using.
Suppose your drop down list is:
<asp:DropDownList runat="server" id="ddl">
<asp:ListItem Value="0" text="Select a Value">
....
</asp:DropDownList>
There are two ways:
<asp:RequiredFieldValidator ID="re1" runat="Server" InitialValue="0" />
the 2nd way is to use a compare validator:
<asp:CompareValidator ID="re1" runat="Server" ValueToCompare="0" ControlToCompare="ddl" Operator="Equal" />
$Machinedispatch =
$this->Machinedispatch->find('first',array('order'=>array('Machinedispatch.id DESC')));
Simplest way of finding last inserted row. For me getLastInsertId() this not works.
You need to look at the explain plans, but unless there is an INDEX or PARTITION on COL_A, you are looking at a FULL TABLE SCAN on both tables.
With that in mind, your first example is throwing out some of the data as it does the FULL TABLE SCAN. That result is being sorted by the UNION, then duplicate data is dropped. This gives you your result set.
In the second example, you are pulling the full contents of both tables. That result is likely to be larger. So the UNION is sorting more data, then dropping the duplicate stuff. Then the filter is being applied to give you the result set you are after.
As a general rule, the earlier you filter away data, the smaller the data set, and the faster you will get your results. As always, your milage may vary.
navigator.userLanguage
for IE
window.navigator.language
for firefox/opera/safari
It's an old question, but if you wanted to catch a backspace event on input, and not keydown, keypress, or keyup—as I've noticed any one of these break certain functions I've written and cause awkward delays with automated text formatting—you can catch a backspace using inputType:
document.getElementsByTagName('input')[0].addEventListener('input', function(e) {
if (e.inputType == "deleteContentBackward") {
// your code here
}
});
A bit verbose, but it's the standard way of parsing and formatting dates in Java:
DateFormat formatter = new SimpleDateFormat("HH:mm:ss");
try {
Date dt = formatter.parse("08:19:12");
Calendar cal = Calendar.getInstance();
cal.setTime(dt);
int hour = cal.get(Calendar.HOUR);
int minute = cal.get(Calendar.MINUTE);
int second = cal.get(Calendar.SECOND);
} catch (ParseException e) {
// This can happen if you are trying to parse an invalid date, e.g., 25:19:12.
// Here, you should log the error and decide what to do next
e.printStackTrace();
}
Buttons can be added to frozen rows as images. Assigning a function within the attached script to the button makes it possible to run the function. The comment which says you can not is of course a very old comment, possibly things have changed now.
In C int foo()
and int foo(void)
are different functions. int foo()
accepts an arbitrary number of arguments, while int foo(void)
accepts 0 arguments. In C++ they mean the same thing. I suggest that you use void
consistently when you mean no arguments.
If you have a variable a
, extern int a;
is a way to tell the compiler that a
is a symbol that might be present in a different translation unit (C compiler speak for source file), don't resolve it until link time. On the other hand, symbols which are function names are anyway resolved at link time. The meaning of a storage class specifier on a function (extern
, static
) only affects its visibility and extern
is the default, so extern
is actually unnecessary.
I suggest removing the extern
, it is extraneous and is usually omitted.
A node
is the generic name for any type of object in the DOM hierarchy. A node
could be one of the built-in DOM elements such as document
or document.body
, it could be an HTML tag specified in the HTML such as <input>
or <p>
or it could be a text node that is created by the system to hold a block of text inside another element. So, in a nutshell, a node
is any DOM object.
An element
is one specific type of node
as there are many other types of nodes (text nodes, comment nodes, document nodes, etc...).
The DOM consists of a hierarchy of nodes where each node can have a parent, a list of child nodes and a nextSibling and previousSibling. That structure forms a tree-like hierarchy. The document
node has the html
node as its child.
The html
node has its list of child nodes (the head
node and the body
node). The body
node would have its list of child nodes (the top level elements in your HTML page) and so on.
So, a nodeList
is simply an array-like list of nodes
.
An element is a specific type of node, one that can be directly specified in the HTML with an HTML tag and can have properties like an id
or a class
. can have children, etc... There are other types of nodes such as comment nodes, text nodes, etc... with different characteristics. Each node has a property .nodeType
which reports what type of node it is. You can see the various types of nodes here (diagram from MDN):
You can see an ELEMENT_NODE
is one particular type of node where the nodeType
property has a value of 1
.
So document.getElementById("test")
can only return one node and it's guaranteed to be an element (a specific type of node). Because of that it just returns the element rather than a list.
Since document.getElementsByClassName("para")
can return more than one object, the designers chose to return a nodeList
because that's the data type they created for a list of more than one node. Since these can only be elements (only elements typically have a class name), it's technically a nodeList
that only has nodes of type element in it and the designers could have made a differently named collection that was an elementList
, but they chose to use just one type of collection whether it had only elements in it or not.
EDIT: HTML5 defines an HTMLCollection
which is a list of HTML Elements (not any node, only Elements). A number of properties or methods in HTML5 now return an HTMLCollection
. While it is very similar in interface to a nodeList
, a distinction is now made in that it only contains Elements, not any type of node.
The distinction between a nodeList
and an HTMLCollection
has little impact on how you use one (as far as I can tell), but the designers of HTML5 have now made that distinction.
For example, the element.children
property returns a live HTMLCollection.
In my case, I noticed that the routing logic was kicking in if I modified the $location.hash()
. The following trick worked..
$scope.scrollTo = function(id) {
var old = $location.hash();
$location.hash(id);
$anchorScroll();
//reset to old to keep any additional routing logic from kicking in
$location.hash(old);
};
This is for the worst-case scenario of exiting Vim if you just want out, have no idea what you've done and you don't care what will happen to the files you opened.
Ctrl-cEnterEntervi
EnterCtrl-\Ctrl-n:qa!
Enter
This should get you out most of the time.
Some interesting cases where you need something like this:
i
Ctrl-ovg
(you enter insert mode, then visual mode and then operator pending mode)
Qappend
Enter
i
Ctrl-ogQ
Ctrl-r=
Ctrl-k (thanks to porges for this case)
:set insertmode
(this is a case when Ctrl-\Ctrl-n returns you to normal mode)
Edit: This answer was corrected due to cases above. It used to be:
EscEscEsc:qa!
Enter
However, that doesn't work if you have entered Ex mode. In that case you would need to do:
vi
Enter:qa!
Enter
So a complete command for "I don't want to know what I've done and I don't want to save anything, I just want out now!" would be
vi
EnterEscEscEsc:qa!
Enter
I had a similar issue when migrating over to React-Router v4 so I'll try to explain my solution below.
Please do not consider this answer as the right way to solve the problem, I imagine there's a good chance something better will arise as React Router v4 becomes more mature and leaves beta (It may even already exist and I just didn't discover it).
For context, I had this problem because I occasionally use Redux-Saga
to programmatically change the history object (say when a user successfully authenticates).
In the React Router docs, take a look at the <Router>
component and you can see you have the ability to pass your own history object via a prop. This is the essence of the solution - we supply the history object to React-Router
from a global module.
yarn add history
or npm install history --save
create a file called history.js
in your App.js
level folder (this was my preference)
// src/history.js
import createHistory from 'history/createBrowserHistory';
export default createHistory();`
Add this history object to your Router component like so
// src/App.js
import history from '../your/path/to/history.js;'
<Router history={history}>
// Route tags here
</Router>
Adjust the URL just like before by importing your global history object:
import history from '../your/path/to/history.js;'
history.push('new/path/here/');
Everything should stay synced up now, and you also have access to a way of setting the history object programmatically and not via a component/container.
I personally use both cookies and session.
Cookies only used when user click on "remember me" checkbox. and also cookies are encrypted and data only decrypt on the server. If anyone tries to edit cookies our decrypter able to detect it and refuse the request.
I have seen so many sites where login info are stored in cookies, anyone can just simply change the user's id and username in cookies to access anyone account.
Thanks,
Special thanks to the answer here for more-or-less the same question.
For me, all I needed was setlocale(LC_ALL, "en_US.UTF-8");
Then, I could use even raw wchar_t
characters.
If you convert a Bash script into a function, you typically replace exit N
with return N
. The code that calls the function will treat the return value the same as it would an exit code from a subprocess.
Using exit
inside the function will force the entire script to end.
In my case the contents of my cell is HTML as result of a formatter. I want the value inside anchor tag. By fetching the cell contents and then creating an element out of the html via jQuery I am able to then access the raw value by calling .text() on my newly created element.
var cellContents = grid.getCell(rowid, 'ColNameHere');
console.log($(cellContents));
//in my case logs <h3><a href="#">The Value I'm After</a></h3>
var cellRawValue = $(cellContents).text();
console.log(cellRawValue); //outputs "The Value I'm After!"
my answer is based on @LLQ answer, but since in my case my cellContents isn't an input I needed to use .text()
instead of .val()
to access the raw value so I thought I'd post this in case anyone else is looking for a way to access the raw value of a formatted jqGrid cell.
Simple Demo for checking and setting a check box.
$('.attr-value-name').click(function() {
if($(this).parent().find('input[type="checkbox"]').is(':checked'))
{
$(this).parent().find('input[type="checkbox"]').prop('checked', false);
}
else
{
$(this).parent().find('input[type="checkbox"]').prop('checked', true);
}
});
A simple graphic makes this clearer:
git diff
Shows the changes between the working directory and the index. This shows what has been changed, but is not staged for a commit.
git diff --cached
Shows the changes between the index and the HEAD (which is the last commit on this branch). This shows what has been added to the index and staged for a commit.
git diff HEAD
Shows all the changes between the working directory and HEAD (which includes changes in the index). This shows all the changes since the last commit, whether or not they have been staged for commit or not.
Also:
There is a bit more detail on 365Git.
A new paper has been released with several tests against reCAPTCHA:
Some highlights:
Google has already fixed the cookie vulnerability and is probably restricting some behaviors based on IPs.
Another interesting finding is that Google runs a VM in JavaScript that obfuscates much of reCAPTCHA code and behavior. This VM is known as botguard and is used to protect other services besides reCAPTCHA:
https://github.com/neuroradiology/InsideReCaptcha
UPDATE 2017
A recent paper (from August) was published on WOOT 2017 achieving 85% accuracy in solving noCAPTCHA reCAPTCHA audio challenges:
http://uncaptcha.cs.umd.edu/papers/uncaptcha_woot17.pdf
UPDATE 2018
Google is introducing reCAPTCHA v3, which looks like a "human score prediction engine" that is calibrated per website. It can be installed into different pages of a website (working like a Google Analytics script) to help reCAPTCHA and the website owner to understand the behaviour of humans vs. bots before filling a reCAPTCHA.
This one works!
floor(loge(n) / loge(2)) + 1
To include negative numbers, you can add an extra bit to specify the sign.
floor(loge(abs(n)) / loge(2)) + 2
This function reads a CSV file of 15MB and copies its content into a sheet in about 3 secs. What is probably taking a lot of time in your code is the fact that you copy data cell by cell instead of putting the whole content at once.
Option Explicit
Public Sub test()
copyDataFromCsvFileToSheet "C:\temp\test.csv", ",", "Sheet1"
End Sub
Private Sub copyDataFromCsvFileToSheet(parFileName As String, parDelimiter As String, parSheetName As String)
Dim data As Variant
data = getDataFromFile(parFileName, parDelimiter)
If Not isArrayEmpty(data) Then
With Sheets(parSheetName)
.Cells.ClearContents
.Cells(1, 1).Resize(UBound(data, 1), UBound(data, 2)) = data
End With
End If
End Sub
Public Function isArrayEmpty(parArray As Variant) As Boolean
'Returns false if not an array or dynamic array that has not been initialised (ReDim) or has been erased (Erase)
If IsArray(parArray) = False Then isArrayEmpty = True
On Error Resume Next
If UBound(parArray) < LBound(parArray) Then isArrayEmpty = True: Exit Function Else: isArrayEmpty = False
End Function
Private Function getDataFromFile(parFileName As String, parDelimiter As String, Optional parExcludeCharacter As String = "") As Variant
'parFileName is supposed to be a delimited file (csv...)
'parDelimiter is the delimiter, "," for example in a comma delimited file
'Returns an empty array if file is empty or can't be opened
'number of columns based on the line with the largest number of columns, not on the first line
'parExcludeCharacter: sometimes csv files have quotes around strings: "XXX" - if parExcludeCharacter = """" then removes the quotes
Dim locLinesList() As Variant
Dim locData As Variant
Dim i As Long
Dim j As Long
Dim locNumRows As Long
Dim locNumCols As Long
Dim fso As Variant
Dim ts As Variant
Const REDIM_STEP = 10000
Set fso = CreateObject("Scripting.FileSystemObject")
On Error GoTo error_open_file
Set ts = fso.OpenTextFile(parFileName)
On Error GoTo unhandled_error
'Counts the number of lines and the largest number of columns
ReDim locLinesList(1 To 1) As Variant
i = 0
Do While Not ts.AtEndOfStream
If i Mod REDIM_STEP = 0 Then
ReDim Preserve locLinesList(1 To UBound(locLinesList, 1) + REDIM_STEP) As Variant
End If
locLinesList(i + 1) = Split(ts.ReadLine, parDelimiter)
j = UBound(locLinesList(i + 1), 1) 'number of columns
If locNumCols < j Then locNumCols = j
i = i + 1
Loop
ts.Close
locNumRows = i
If locNumRows = 0 Then Exit Function 'Empty file
ReDim locData(1 To locNumRows, 1 To locNumCols + 1) As Variant
'Copies the file into an array
If parExcludeCharacter <> "" Then
For i = 1 To locNumRows
For j = 0 To UBound(locLinesList(i), 1)
If Left(locLinesList(i)(j), 1) = parExcludeCharacter Then
If Right(locLinesList(i)(j), 1) = parExcludeCharacter Then
locLinesList(i)(j) = Mid(locLinesList(i)(j), 2, Len(locLinesList(i)(j)) - 2) 'If locTempArray = "", Mid returns ""
Else
locLinesList(i)(j) = Right(locLinesList(i)(j), Len(locLinesList(i)(j)) - 1)
End If
ElseIf Right(locLinesList(i)(j), 1) = parExcludeCharacter Then
locLinesList(i)(j) = Left(locLinesList(i)(j), Len(locLinesList(i)(j)) - 1)
End If
locData(i, j + 1) = locLinesList(i)(j)
Next j
Next i
Else
For i = 1 To locNumRows
For j = 0 To UBound(locLinesList(i), 1)
locData(i, j + 1) = locLinesList(i)(j)
Next j
Next i
End If
getDataFromFile = locData
Exit Function
error_open_file: 'returns empty variant
unhandled_error: 'returns empty variant
End Function
class()
function is the equivalent of typeof()
You can also use isa()
to check if a variable is of a particular type.
If you want to be even more specific, you can use ischar()
, isfloat()
, iscell()
, etc.
Please make a backup for the script.bs1 file
What works for me was deleting the script.bs1 file and running the execution command.
There is no reliable way to do this in pure Java. Setting the user.dir
property via System.setProperty()
or java -Duser.dir=...
does seem to affect subsequent creations of Files
, but not e.g. FileOutputStreams
.
The File(String parent, String child)
constructor can help if you build up your directory path separately from your file path, allowing easier swapping.
An alternative is to set up a script to run Java from a different directory, or use JNI native code as suggested below.
The relevant Sun bug was closed in 2008 as "will not fix".
I ran into a similar problem, and I know that is not an answer to the question, but it can be of help to someone with this kind of problem:
if there is need to put the elements of two or more forms in a given sequence, the HTML5 <input> form
attribute can be the solution.
From http://www.w3schools.com/tags/att_input_form.asp:
- The form attribute is new in HTML5.
- Specifies which
<form>
element an<input>
element belongs to. The value of this attribute must be the id attribute of a<form>
element in the same document.
Scenario:
Implementation:
<form id="Form1" action="Action1.php" method="post"></form>
<form id="Form2" action="Action2.php" method="post"></form>
<input type="text" name="input_Form1_n1" form="Form1" />
<input type="text" name="input_Form2_n1" form="Form2" />
<input type="text" name="input_Form1_n2" form="Form1" />
<input type="text" name="input_Form2_n2" form="Form2" />
<input type="submit" name="button1" value="buttonVal1" form="Form1" />
<input type="submit" name="button2" value="buttonVal2" form="Form2" />
Here you'll find browser's compatibility.
Try to install in your project the NuGet Package: Microsoft.AspNet.WebApi.Client:
Install-Package Microsoft.AspNet.WebApi.Client
I have achieved this by a http API node
request which returns required object from node object for HTML
page at client ,
for eg: API: localhost:3000/username
returns logged in user from cache by node App object .
node route file,
app.get('/username', function(req, res) {
res.json({ udata: req.session.user });
});
I guess this is what you want:
var data = '{"count" : 1, "stack" : "sometext\\n\\n"}';
(You need to escape the "\" in your string (turning it into a double-"\"), otherwise it will become a newline in the JSON source, not the JSON data.)
EDIT: Only after posting this, did I realize that @350D's answer does the exact same thing.
Surprisingly, this can be done in just 4 lines of code:
const canvas = document.getElementById("canvas"),
preview = document.getElementById("preview"),
ctx = canvas.getContext("2d");
canvas.width = 1;
canvas.height = 1;
preview.width = 400;
preview.height = 400;
function getDominantColor(imageObject) {
//draw the image to one pixel and let the computer find the dominant color
ctx.drawImage(imageObject, 0, 0, 1, 1);
//get pixel color
const i = ctx.getImageData(0, 0, 1, 1).data;
console.log(`rgba(${i[0]},${i[1]},${i[2]},${i[3]})`);
console.log("#" + ((1 << 24) + (i[0] << 16) + (i[1] << 8) + i[2]).toString(16).slice(1));
}
// vvv all of this is to just get the uploaded image vvv
const input = document.getElementById("input");
input.type = "file";
input.accept = "image/*";
input.onchange = event => {
const file = event.target.files[0];
const reader = new FileReader();
reader.onload = readerEvent => {
const image = new Image();
image.onload = function() {
//shows preview of uploaded image
preview.getContext("2d").drawImage(
image,
0,
0,
preview.width,
preview.height,
);
getDominantColor(image);
};
image.src = readerEvent.target.result;
};
reader.readAsDataURL(file, "UTF-8");
};
_x000D_
canvas {
width: 200px;
height: 200px;
outline: 1px solid #000000;
}
_x000D_
<canvas id="preview"></canvas>
<canvas id="canvas"></canvas>
<input id="input" type="file" />
_x000D_
How it works:
Create the canvas context
const context = document.createElement("canvas").getContext("2d");
This will draw the image to only one canvas pixel, making the browser find the dominant color for you.
context.drawImage(imageObject, 0, 0, 1, 1);
After that, just get the image data for the pixel:
const i = context.getImageData(0, 0, 1, 1).data;
Finally, convert to rgba
or HEX
:
const rgba = `rgba(${i[0]},${i[1]},${i[2]},${i[3]})`;
const HEX = "#" + ((1 << 24) + (i[0] << 16) + (i[1] << 8) + i[2]).toString(16).slice(1);
There is one problem with this method though, and that is that getImageData
will sometimes throw errors Unable to get image data from canvas because the canvas has been tainted by cross-origin data.
, which is the reason you need to upload images in the demo instead of inputting a URL for example.
This method can also be used for pixelating images by increasing the width and height to draw the image.
This works on chrome but may not on other browsers.
I prefer this way, not using a cell but a range
Dim cell_to_test As Range, cells_changed As Range
Set cells_changed = Target(1, 1)
Set cell_to_test = Range( RANGE_OF_CELLS_TO_DETECT )
If Not Intersect(cells_changed, cell_to_test) Is Nothing Then
Macro
End If
Another implementation, while recursive is very fast and uses single inline function. It hits the javascript 64-bit number precision limit, starting 80th sequence (as do all other algorithms): For example if you want the 78th term (78 goes in the last parenthesis):
(function (n,i,p,r){p=(p||0)+r||1;i=i?i+1:1;return i<=n?arguments.callee(n,i,r,p):r}(78));
will return: 8944394323791464
This is backwards compatible all the way to ECMASCRIPT4 - I tested it with IE7 and it works!
I came across this question and found Adams answer the most helpful https://stackoverflow.com/a/765862/2964689
But there was no python example of his method but here's what I ended up using.
input: datetime object
output: integer age in whole years
def age(birthday):
birthday = birthday.date()
today = date.today()
years = today.year - birthday.year
if (today.month < birthday.month or
(today.month == birthday.month and today.day < birthday.day)):
years = years - 1
return years
To answer this point:
I want Sleep to be an async method so it can await other methods
you can maybe rewrite the Sleep
function like this:
private static async Task<int> Sleep(int ms)
{
Console.WriteLine("Sleeping for " + ms);
var task = Task.Run(() => Thread.Sleep(ms));
await task;
Console.WriteLine("Sleeping for " + ms + "END");
return ms;
}
static void Main(string[] args)
{
Console.WriteLine("Starting");
var task1 = Sleep(2000);
var task2 = Sleep(1000);
int totalSlept = task1.Result +task2.Result;
Console.WriteLine("Slept for " + totalSlept + " ms");
Console.ReadKey();
}
running this code will output :
Starting
Sleeping for 2000
Sleeping for 1000
*(one second later)*
Sleeping for 1000END
*(one second later)*
Sleeping for 2000END
Slept for 3000 ms
By default, a grid item cannot be smaller than the size of its content.
Grid items have an initial size of min-width: auto
and min-height: auto
.
You can override this behavior by setting grid items to min-width: 0
, min-height: 0
or overflow
with any value other than visible
.
From the spec:
6.6. Automatic Minimum Size of Grid Items
To provide a more reasonable default minimum size for grid items, this specification defines that the
auto
value ofmin-width
/min-height
also applies an automatic minimum size in the specified axis to grid items whoseoverflow
isvisible
. (The effect is analogous to the automatic minimum size imposed on flex items.)
Here's a more detailed explanation covering flex items, but it applies to grid items, as well:
This post also covers potential problems with nested containers and known rendering differences among major browsers.
To fix your layout, make these adjustments to your code:
.month-grid {
display: grid;
grid-template: repeat(6, 1fr) / repeat(7, 1fr);
background: #fff;
grid-gap: 2px;
min-height: 0; /* NEW */
min-width: 0; /* NEW; needed for Firefox */
}
.day-item {
padding: 10px;
background: #DFE7E7;
overflow: hidden; /* NEW */
min-width: 0; /* NEW; needed for Firefox */
}
1fr
vs minmax(0, 1fr)
The solution above operates at the grid item level. For a container level solution, see this post:
Please see my answer here:
https://stackoverflow.com/a/24844618/2293304
It's a long and ugly, but reliable and efficient solution.
It resolves a few problems which are not addressed by the other answerers:
shutil.rmtree()
on a symbolic link (which will pass the os.path.isdir()
test if it links to a directory).A mix of BeautifulSoup and Selenium works very well for me.
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from bs4 import BeautifulSoup as bs
driver = webdriver.Firefox()
driver.get("http://somedomain/url_that_delays_loading")
try:
element = WebDriverWait(driver, 10).until(
EC.presence_of_element_located((By.ID, "myDynamicElement"))) #waits 10 seconds until element is located. Can have other wait conditions such as visibility_of_element_located or text_to_be_present_in_element
html = driver.page_source
soup = bs(html, "lxml")
dynamic_text = soup.find_all("p", {"class":"class_name"}) #or other attributes, optional
else:
print("Couldnt locate element")
P.S. You can find more wait conditions here
you can't use dataSourceClassName approach in application.properties configurations as said by @Andy Wilkinson. if you want to have dataSourceClassName anyway you can use Java Config as:
@Configuration
@ComponentScan
class DataSourceConfig {
@Value("${spring.datasource.username}")
private String user;
@Value("${spring.datasource.password}")
private String password;
@Value("${spring.datasource.url}")
private String dataSourceUrl;
@Value("${spring.datasource.dataSourceClassName}")
private String dataSourceClassName;
@Value("${spring.datasource.poolName}")
private String poolName;
@Value("${spring.datasource.connectionTimeout}")
private int connectionTimeout;
@Value("${spring.datasource.maxLifetime}")
private int maxLifetime;
@Value("${spring.datasource.maximumPoolSize}")
private int maximumPoolSize;
@Value("${spring.datasource.minimumIdle}")
private int minimumIdle;
@Value("${spring.datasource.idleTimeout}")
private int idleTimeout;
@Bean
public DataSource primaryDataSource() {
Properties dsProps = new Properties();
dsProps.put("url", dataSourceUrl);
dsProps.put("user", user);
dsProps.put("password", password);
dsProps.put("prepStmtCacheSize",250);
dsProps.put("prepStmtCacheSqlLimit",2048);
dsProps.put("cachePrepStmts",Boolean.TRUE);
dsProps.put("useServerPrepStmts",Boolean.TRUE);
Properties configProps = new Properties();
configProps.put("dataSourceClassName", dataSourceClassName);
configProps.put("poolName",poolName);
configProps.put("maximumPoolSize",maximumPoolSize);
configProps.put("minimumIdle",minimumIdle);
configProps.put("minimumIdle",minimumIdle);
configProps.put("connectionTimeout", connectionTimeout);
configProps.put("idleTimeout", idleTimeout);
configProps.put("dataSourceProperties", dsProps);
HikariConfig hc = new HikariConfig(configProps);
HikariDataSource ds = new HikariDataSource(hc);
return ds;
}
}
reason you cannot use dataSourceClassName because it will throw and exception
Caused by: java.lang.IllegalStateException: both driverClassName and dataSourceClassName are specified, one or the other should be used.
which mean spring boot infers from spring.datasource.url property the Driver and at the same time setting the dataSourceClassName creates this exception. To make it right your application.properties should look something like this for HikariCP datasource:
# hikariCP
spring.jpa.databasePlatform=org.hibernate.dialect.MySQLDialect
spring.datasource.url=jdbc:mysql://localhost:3306/exampledb
spring.datasource.username=root
spring.datasource.password=
spring.datasource.poolName=SpringBootHikariCP
spring.datasource.maximumPoolSize=5
spring.datasource.minimumIdle=3
spring.datasource.maxLifetime=2000000
spring.datasource.connectionTimeout=30000
spring.datasource.idleTimeout=30000
spring.datasource.pool-prepared-statements=true
spring.datasource.max-open-prepared-statements=250
Note: Please check if there is any tomcat-jdbc.jar or commons-dbcp.jar in your classpath added most of the times by transitive dependency. If these are present in classpath Spring Boot will configure the Datasource using default connection pool which is tomcat. HikariCP will only be used to create the Datasource if there is no other provider in classpath. there is a fallback sequence from tomcat -> to HikariCP -> to Commons DBCP.
On CENTOS 6 /etc/my.cnf , under [mysqld] section the correct syntax is:
[mysqld]
# added to avoid err "Got a packet bigger than 'max_allowed_packet' bytes"
#
net_buffer_length=1000000
max_allowed_packet=1000000000
#
if myString?.startIndex != myString?.endIndex {}
<xsl:template match="element3">
<xsl:value-of select="element4,element5" separator="."/>
</xsl:template>
If you want to have a different icon for each list-item, I suggest adding icons in HTML instead of using a pseudo element to keep your CSS down. It can be done quite simply as follows:
<ul>
<li><span><i class="mdi mdi-lightbulb-outline"></i></span>An electric light with a wire filament heated to such a high temperature that it glows with visible light</li>
<li><span><i class="mdi mdi-clipboard-check-outline"></i></span>A thin, rigid board with a clip at the top for holding paper in place.</li>
<li><span><i class="mdi mdi-finance"></i></span>A graphical representation of data, in which the data is represented by symbols, such as bars in a bar chart, lines in a line chart, or slices in a pie chart.</li>
<li><span><i class="mdi mdi-server"></i></span>A system that responds to requests across a computer network worldwide to provide, or help to provide, a network or data service.</li>
</ul>
-
ul {
list-style-type: none;
margin-left: 2.5em;
padding-left: 0;
}
ul>li {
position: relative;
}
span {
left: -2em;
position: absolute;
text-align: center;
width: 2em;
line-height: inherit;
}
In this case I used Material Design Icons
the strtok runtime function works like this
the first time you call strtok you provide a string that you want to tokenize
char s[] = "this is a string";
in the above string space seems to be a good delimiter between words so lets use that:
char* p = strtok(s, " ");
what happens now is that 's' is searched until the space character is found, the first token is returned ('this') and p points to that token (string)
in order to get next token and to continue with the same string NULL is passed as first argument since strtok maintains a static pointer to your previous passed string:
p = strtok(NULL," ");
p now points to 'is'
and so on until no more spaces can be found, then the last string is returned as the last token 'string'.
more conveniently you could write it like this instead to print out all tokens:
for (char *p = strtok(s," "); p != NULL; p = strtok(NULL, " "))
{
puts(p);
}
EDIT:
If you want to store the returned values from strtok
you need to copy the token to another buffer e.g. strdup(p);
since the original string (pointed to by the static pointer inside strtok
) is modified between iterations in order to return the token.
The shortest way, I think, is the following:
import struct
val = 0x11223344
val = struct.unpack("<I", struct.pack(">I", val))[0]
print "%08x" % val
This converts an integer to a byte-swapped integer.
just select '0' as the value for the desired column
It is possible by using the legend tag. Refer to http://www.w3schools.com/html5/tag_legend.asp
If you're using the mysql native driver (common since php 5.3), and the mysqli extension, you can accomplish this with an asynchronous query:
<?php
// Here's an example query that will take a long time to execute.
$sql = "
select *
from information_schema.tables t1
join information_schema.tables t2
join information_schema.tables t3
join information_schema.tables t4
join information_schema.tables t5
join information_schema.tables t6
join information_schema.tables t7
join information_schema.tables t8
";
$mysqli = mysqli_connect('localhost', 'root', '');
$mysqli->query($sql, MYSQLI_ASYNC | MYSQLI_USE_RESULT);
$links = $errors = $reject = [];
$links[] = $mysqli;
// wait up to 1.5 seconds
$seconds = 1;
$microseconds = 500000;
$timeStart = microtime(true);
if (mysqli_poll($links, $errors, $reject, $seconds, $microseconds) > 0) {
echo "query finished executing. now we start fetching the data rows over the network...\n";
$result = $mysqli->reap_async_query();
if ($result) {
while ($row = $result->fetch_row()) {
// print_r($row);
if (microtime(true) - $timeStart > 1.5) {
// we exceeded our time limit in the middle of fetching our result set.
echo "timed out while fetching results\n";
var_dump($mysqli->close());
break;
}
}
}
} else {
echo "timed out while waiting for query to execute\n";
var_dump($mysqli->close());
}
The flags I'm giving to mysqli_query accomplish important things. It tells the client driver to enable asynchronous mode, while forces us to use more verbose code, but lets us use a timeout(and also issue concurrent queries if you want!). The other flag tells the client not to buffer the entire result set into memory.
By default, php configures its mysql client libraries to fetch the entire result set of your query into memory before it lets your php code start accessing rows in the result. This can take a long time to transfer a large result. We disable it, otherwise we risk that we might time out while waiting for the buffering to complete.
Note that there's two places where we need to check for exceeding a time limit:
You can accomplish similar in the PDO and regular mysql extension. They don't support asynchronous queries, so you can't set a timeout on the query execution time. However, they do support unbuffered result sets, and so you can at least implement a timeout on the fetching of the data.
For many queries, mysql is able to start streaming the results to you almost immediately, and so unbuffered queries alone will allow you to somewhat effectively implement timeouts on certain queries. For example, a
select * from tbl_with_1billion_rows
can start streaming rows right away, but,
select sum(foo) from tbl_with_1billion_rows
needs to process the entire table before it can start returning the first row to you. This latter case is where the timeout on an asynchronous query will save you. It will also save you from plain old deadlocks and other stuff.
ps - I didn't include any timeout logic on the connection itself.
After going down the rabbit-hole of trying to do this myself by copy-pasting various code-snippets from Stack Overflow, I would highly recommend just using the InteractJS library, which allows you to create a draggable and resizable div (somewhat) easily.
I have been there, like so many of us. There are so many confusing words like Web API, REST, RESTful, HTTP, SOAP, WCF, Web Services... and many more around this topic. But I am going to give brief explanation of only those which you have asked.
It is neither an API nor a framework. It is just an architectural concept. You can find more details here.
I have not come across any formal definition of RESTful anywhere. I believe it is just another buzzword for APIs to say if they comply with REST specifications.
EDIT: There is another trending open source initiative OpenAPI Specification (OAS) (formerly known as Swagger) to standardise REST APIs.
It in an open source framework for writing HTTP APIs. These APIs can be RESTful or not. Most HTTP APIs we write are not RESTful. This framework implements HTTP protocol specification and hence you hear terms like URIs, request/response headers, caching, versioning, various content types(formats).
Note: I have not used the term Web Services deliberately because it is a confusing term to use. Some people use this as a generic concept, I preferred to call them HTTP APIs. There is an actual framework named 'Web Services' by Microsoft like Web API. However it implements another protocol called SOAP.
Like this?
public static void Test()
{
using (var image = Image.FromFile(@"c:\logo.png"))
using (var newImage = ScaleImage(image, 300, 400))
{
newImage.Save(@"c:\test.png", ImageFormat.Png);
}
}
public static Image ScaleImage(Image image, int maxWidth, int maxHeight)
{
var ratioX = (double)maxWidth / image.Width;
var ratioY = (double)maxHeight / image.Height;
var ratio = Math.Min(ratioX, ratioY);
var newWidth = (int)(image.Width * ratio);
var newHeight = (int)(image.Height * ratio);
var newImage = new Bitmap(newWidth, newHeight);
using (var graphics = Graphics.FromImage(newImage))
graphics.DrawImage(image, 0, 0, newWidth, newHeight);
return newImage;
}
I am looking for a way to create a select without repeating the conditional query.
I'm assuming that you don't want to repeat Foo-stuff+bar
. You could put your calculation into a derived table:
SELECT CASE WHEN a.TestValue > 2 THEN a.TestValue ELSE 'Fail' END
FROM (SELECT (Foo-stuff+bar) AS TestValue FROM MyTable) AS a
A common table expression would work just as well:
WITH a AS (SELECT (Foo-stuff+bar) AS TestValue FROM MyTable)
SELECT CASE WHEN a.TestValue > 2 THEN a.TestValue ELSE 'Fail' END
FROM a
Also, each part of your switch should return the same datatype, so you may have to cast one or more cases.
You can wrap those elements in anchor tag
like this
<a href="your link here"> <i class="fa fa-dribbble fa-4x"></i></a>
<a href="your link here"> <i class="fa fa-behance-square fa-4x"></i></a>
<a href="your link here"> <i class="fa fa-linkedin-square fa-4x"></i></a>
<a href="your link here"> <i class="fa fa-twitter-square fa-4x"></i></a>
<a href="your link here"> <i class="fa fa-facebook-square fa-4x"></i></a>
Note: Replace href="your link here"
with your desired link e.g. href="https://www.stackoverflow.com"
.
Here is a one-liner: str.replace(/[|\\{}()[\]^$+*?.]/g, '\\$&')
I got it from the escape-string-regexp NPM module.
Trying it out:
escapeStringRegExp.matchOperatorsRe = /[|\\{}()[\]^$+*?.]/g;
function escapeStringRegExp(str) {
return str.replace(escapeStringRegExp.matchOperatorsRe, '\\$&');
}
console.log(new RegExp(escapeStringRegExp('example.com')));
// => /example\.com/
Using tagged template literals with flags support:
function str2reg(flags = 'u') {
return (...args) => new RegExp(escapeStringRegExp(evalTemplate(...args))
, flags)
}
function evalTemplate(strings, ...values) {
let i = 0
return strings.reduce((str, string) => `${str}${string}${
i < values.length ? values[i++] : ''}`, '')
}
console.log(str2reg()`example.com`)
// => /example\.com/u
As far as I see it's currently not possible to sort a Map properly.
The other solutions where the Map is converted into an array and sorted this way have the following bug:
var a = new Map([[1, 2], [3,4]])
console.log(a); // a = Map(2) {1 => 2, 3 => 4}
var b = a;
console.log(b); // b = Map(2) {1 => 2, 3 => 4}
a = new Map(); // this is when the sorting happens
console.log(a, b); // a = Map(0) {} b = Map(2) {1 => 2, 3 => 4}
The sorting creates a new object and all other pointers to the unsorted object get broken.
Using the int value 1002
seems to work for PHP 5.3.0:
public static function createDB() {
$dbHost="localhost";
$dbName="project";
$dbUser="admin";
$dbPassword="whatever";
$dbOptions=array(1002 => 'SET NAMES utf8',);
return new DB($dbHost, $dbName, $dbUser, $dbPassword,$dbOptions);
}
function createConnexion() {
return new PDO(
"mysql:host=$this->dbHost;dbname=$this->dbName",
$this->dbUser,
$this->dbPassword,
$this->dbOptions);
}
You can use "ELSE IF" using conditional operator in expression language as below:
<p:outputLabel value="#{transaction.status.equals('PNDNG')?'Pending':
transaction.status.equals('RJCTD')?'Rejected':
transaction.status.equals('CNFRMD')?'Confirmed':
transaction.status.equals('PSTD')?'Posted':''}"/>
try this:
ls -ltraR |egrep -v '\.$|\.\.|\.:|\.\/|total' |sed '/^$/d'
use ilio: (inline io):
just one function call instead of file open(), read(), close().
from ilio import read
content = read('filename')
In addition to the other answers to this question, using an anonymous namespace can also improve performance. As symbols within the namespace do not need any external linkage, the compiler is freer to perform aggressive optimization of the code within the namespace. For example, a function which is called multiple times once in a loop can be inlined without any impact on the code size.
For example, on my system the following code takes around 70% of the run time if the anonymous namespace is used (x86-64 gcc-4.6.3 and -O2; note that the extra code in add_val makes the compiler not want to include it twice).
#include <iostream>
namespace {
double a;
void b(double x)
{
a -= x;
}
void add_val(double x)
{
a += x;
if(x==0.01) b(0);
if(x==0.02) b(0.6);
if(x==0.03) b(-0.1);
if(x==0.04) b(0.4);
}
}
int main()
{
a = 0;
for(int i=0; i<1000000000; ++i)
{
add_val(i*1e-10);
}
std::cout << a << '\n';
return 0;
}
Just in case anyone is trying to do this without java 8, there is a pretty good trick. List.toString() already returns a collection that looks like this:
[1,2,3]
Depending on your specific requirements, this can be post-processed to whatever you want as long as your list items don't contain [] or , .
For instance:
list.toString().replace("[","").replace("]","")
or if your data might contain square brackets this:
String s=list.toString();
s = s.substring(1,s.length()-1)
will get you a pretty reasonable output.
One array item on each line can be created like this:
list.toString().replace("[","").replace("]","").replaceAll(",","\r\n")
I used this technique to make html tooltips from a list in a small app, with something like:
list.toString().replace("[","<html>").replace("]","</html>").replaceAll(",","<br>")
If you have an array then start with Arrays.asList(list).toString() instead
I'll totally own the fact that this is not optimal, but it's not as inefficient as you might think and is pretty straightforward to read and understand. It is, however, quite inflexible--in particular don't try to separate the elements with replaceAll if your data might contain commas and use the substring version if you have square brackets in your data, but for an array of numbers it's pretty much perfect.
You can try : Yolk
For install yolk, try:
easy_install yolk
Yolk is a Python tool for obtaining information about installed Python packages and querying packages avilable on PyPI (Python Package Index).
You can see which packages are active, non-active or in development mode and show you which have newer versions available by querying PyPI.
In case that you still can't use "import" here is how I handled it: Just translate it to a node friendly require. Example:
import { parse } from 'node-html-parser';
Is the same as:
const parse = require('node-html-parser').parse;
Remove existing origin and add new origin to your project directory
>$ git remote show origin
>$ git remote rm origin
>$ git add .
>$ git commit -m "First commit"
>$ git remote add origin Copied_origin_url
>$ git remote show origin
>$ git push origin master
In docker, this worked for me:
head --lines=-N file_path >> file_path
0xe0434352 is the SEH code for a CLR exception. If you don't understand what that means, stop and read A Crash Course on the Depths of Win32™ Structured Exception Handling. So your process is not handling a CLR exception. Don't shoot the messenger, KERNELBASE.DLL is just the unfortunate victim. The perpetrator is MyApp.exe.
There should be a minidump of the crash in DrWatson folders with a full stack, it will contain everything you need to root cause the issue.
I suggest you wire up, in your myapp.exe code, AppDomain.UnhandledException
and Application.ThreadException
, as appropriate.
I wrote one for use with C++, it's very fast, works with streams, free, and open source:
https://tmplusplus.svn.sourceforge.net/svnroot/tmplusplus/trunk/src/
Feel free to use it if it fits your purpose.
Edit: Added code inline by request.
The performance boost is acieved by using a lookup table for encoding and decoding. _UINT8
is an unsigned char
on most OS's.
/** Static Base64 character encoding lookup table */
const char CBase64::encodeCharacterTable[65] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
/** Static Base64 character decoding lookup table */
const char CBase64::decodeCharacterTable[256] = {
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1
,-1,62,-1,-1,-1,63,52,53,54,55,56,57,58,59,60,61,-1,-1,-1,-1,-1,-1,-1,0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21
,22,23,24,25,-1,-1,-1,-1,-1,-1,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1
,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1};
/*!
\brief Encodes binary data to base 64 character data
\param in The data to encode
\param out The encoded data as characters
*/
void CBase64::Encode(std::istream &in, std::ostringstream &out)
{
char buff1[3];
char buff2[4];
_UINT8 i=0, j;
while(in.readsome(&buff1[i++], 1))
if (i==3)
{
out << encodeCharacterTable[(buff1[0] & 0xfc) >> 2];
out << encodeCharacterTable[((buff1[0] & 0x03) << 4) + ((buff1[1] & 0xf0) >> 4)];
out << encodeCharacterTable[((buff1[1] & 0x0f) << 2) + ((buff1[2] & 0xc0) >> 6)];
out << encodeCharacterTable[buff1[2] & 0x3f];
i=0;
}
if (--i)
{
for(j=i;j<3;j++) buff1[j] = '\0';
buff2[0] = (buff1[0] & 0xfc) >> 2;
buff2[1] = ((buff1[0] & 0x03) << 4) + ((buff1[1] & 0xf0) >> 4);
buff2[2] = ((buff1[1] & 0x0f) << 2) + ((buff1[2] & 0xc0) >> 6);
buff2[3] = buff1[2] & 0x3f;
for (j=0;j<(i+1);j++) out << encodeCharacterTable[buff2[j]];
while(i++<3) out << '=';
}
}
/*!
\brief Decodes base 64 character data to binary data
\param in The character data to decode
\param out The decoded data
*/
void CBase64::Decode(std::istringstream &in, std::ostream &out)
{
char buff1[4];
char buff2[4];
_UINT8 i=0, j;
while(in.readsome(&buff2[i], 1) && buff2[i] != '=')
{
if (++i==4)
{
for (i=0;i!=4;i++)
buff2[i] = decodeCharacterTable[buff2[i]];
out << (char)((buff2[0] << 2) + ((buff2[1] & 0x30) >> 4));
out << (char)(((buff2[1] & 0xf) << 4) + ((buff2[2] & 0x3c) >> 2));
out << (char)(((buff2[2] & 0x3) << 6) + buff2[3]);
i=0;
}
}
if (i)
{
for (j=i;j<4;j++) buff2[j] = '\0';
for (j=0;j<4;j++) buff2[j] = decodeCharacterTable[buff2[j]];
buff1[0] = (buff2[0] << 2) + ((buff2[1] & 0x30) >> 4);
buff1[1] = ((buff2[1] & 0xf) << 4) + ((buff2[2] & 0x3c) >> 2);
buff1[2] = ((buff2[2] & 0x3) << 6) + buff2[3];
for (j=0;j<(i-1); j++) out << (char)buff1[j];
}
}
Acked Unseen sample
Hi guys! Just some observations from what I just found in my capture:
On many occasions, the packet capture reports “ACKed segment that wasn't captured” on the client side, which alerts of the condition that the client PC has sent a data packet, the server acknowledges receipt of that packet, but the packet capture made on the client does not include the packet sent by the client
Initially, I thought it indicates a failure of the PC to record into the capture a packet it sends because “e.g., machine which is running Wireshark is slow” (https://osqa-ask.wireshark.org/questions/25593/tcp-previous-segment-not-captured-is-that-a-connectivity-issue)
However, then I noticed every time I see this “ACKed segment that wasn't captured” alert I can see a record of an “invalid” packet sent by the client PC
In the capture example above, frame 67795 sends an ACK for 10384
Even though wireshark reports Bogus IP length (0), frame 67795 is reported to have length 13194
if you are going to do a query you can join in your Inline Table Valued function like:
SELECT
a.*,b.*
FROM AAAA a
INNER JOIN MyNS.GetUnshippedOrders() b ON a.z=b.z
it will incur little overhead and run fine.
if you try to use your the Multi Statement Table Valued in a similar query, you will have performance issues:
SELECT
x.a,x.b,x.c,(SELECT OrderQty FROM MyNS.GetLastShipped(x.CustomerID)) AS Qty
FROM xxxx x
because you will execute the function 1 time for each row returned, as the result set gets large, it will run slower and slower.
The event
attribute of <f:ajax>
can hold at least all supported DOM events of the HTML element which is been generated by the JSF component in question. An easy way to find them all out is to check all on*
attribues of the JSF input component of interest in the JSF tag library documentation and then remove the "on" prefix. For example, the <h:inputText>
component which renders <input type="text">
lists the following on*
attributes (of which I've already removed the "on" prefix so that it ultimately becomes the DOM event type name):
blur
change
click
dblclick
focus
keydown
keypress
keyup
mousedown
mousemove
mouseout
mouseover
mouseup
select
Additionally, JSF has two more special event names for EditableValueHolder
and ActionSource
components, the real HTML DOM event being rendered depends on the component type:
valueChange
(will render as change
on text/select inputs and as click
on radio/checkbox inputs)action
(will render as click
on command links/buttons)The above two are the default events for the components in question.
Some JSF component libraries have additional customized event names which are generally more specialized kinds of valueChange
or action
events, such as PrimeFaces <p:ajax>
which supports among others tabChange
, itemSelect
, itemUnselect
, dateSelect
, page
, sort
, filter
, close
, etc depending on the parent <p:xxx>
component. You can find them all in the "Ajax Behavior Events" subsection of each component's chapter in PrimeFaces Users Guide.
Yes, people use these terms interchangeably with regard to MySQL. Though oftentimes you will hear people inappropriately refer to the entire database server as the database.
Inline elements:
Block elements:
Inline-block elements:
From W3Schools:
An inline element has no line break before or after it, and it tolerates HTML elements next to it.
A block element has some whitespace above and below it and does not tolerate any HTML elements next to it.
An inline-block element is placed as an inline element (on the same line as adjacent content), but it behaves as a block element.
When you visualize this, it looks like this:
The image is taken from this page, which also talks some more about this subject.
Essentially equivalent to the xargs answer, but in case you want parallel execution:
parallel -q cp file1 ::: /foo/ /bar/
So, for example, to copy file1 into all subdirectories of current folder (including recursion):
parallel -q cp file1 ::: `find -mindepth 1 -type d`
N.B.: This probably only conveys any noticeable speed gains for very specific use cases, e.g. if each target directory is a distinct disk.
It is also functionally similar to the '-P' argument for xargs.
Short for Dimension. It's a type of variable. You declare (or "tell" Visual Basic) that you are setting up a variable with this word.
I'll jump in with the notorious "Do you really want to do that" answer.
It seems like your focus is on playing with Java and seeing what it can do. However, if you want to actually develop a web app, you should be aware that, although Java is used in web applications (and in serious ones), there are other technology options which might be more adequate.
Personally, I like (and use) Java for powerful, portable backend services on a server. I've never tried building websites with it, because it never seemed the most obvious ting to do. After growing tired of PHP (which I have been using for years), I lately fell in love with Django, a Python-based web framework.
The Ruby on Rails people have a number of very funny videos on youtube comparing different web technologies to RoR. Of course, these are obviously exaggerated and maybe slightly biased, but I'd say there's more than one grain of truth in each of them. The one about Java is here. ;-)
Here's the simplest solution that doesn't even use any loops.
public class olleHdlroW {
static String reverse(String in, String out) {
return (in.isEmpty()) ? out :
(in.charAt(0) == ' ')
? out + ' ' + reverse(in.substring(1), "")
: reverse(in.substring(1), in.charAt(0) + out);
}
public static void main(String args[]) {
System.out.println(reverse("Hello World", ""));
}
}
Even if this is homework, feel free to copy it and submit it as your own. You'll either get an extra credit (if you can explain how it works) or get caught for plagiarism (if you can't).
Debug and Release are just labels for different solution configurations. You can add others if you want. A project I once worked on had one called "Debug Internal" which was used to turn on the in-house editing features of the application. You can see this if you go to Configuration Manager...
(it's on the Build
menu). You can find more information on MSDN Library under Configuration Manager Dialog Box.
Each solution configuration then consists of a bunch of project configurations. Again, these are just labels, this time for a collection of settings for your project. For example, our C++ library projects have project configurations called "Debug", "Debug_Unicode", "Debug_MT", etc.
The available settings depend on what type of project you're building. For a .NET project, it's a fairly small set: #define
s and a few other things. For a C++ project, you get a much bigger variety of things to tweak.
In general, though, you'll use "Debug" when you want your project to be built with the optimiser turned off, and when you want full debugging/symbol information included in your build (in the .PDB file, usually). You'll use "Release" when you want the optimiser turned on, and when you don't want full debugging information included.
The correct character to use in this case is a full colon (:
), not a semicolon (;
).
First, the class must implements the click listenener :
implements OnItemClickListener
Then set a listener to the ListView
yourList.setOnItemclickListener(this);
And finally, create the clic method:
@Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
Toast.makeText(MainActivity.this, "You Clicked at ",
Toast.LENGTH_SHORT).show();
}
Depending on your needs, this function will calculate the difference between the 2 days, and return a result in days decimal.
// This one returns a signed decimal. The sign indicates past or future.
this.getDateDiff = function(date1, date2) {
return (date1.getTime() - date2.getTime()) / (1000 * 60 * 60 * 24);
}
// This one always returns a positive decimal. (Suggested by Koen below)
this.getDateDiff = function(date1, date2) {
return Math.abs((date1.getTime() - date2.getTime()) / (1000 * 60 * 60 * 24));
}
One more reason, maybe your url include some hiden characters, such as '\n'.
If you define your url like below, this exception will raise:
url = '''
http://google.com
'''
because there are '\n' hide in the string. The url in fact become:
\nhttp://google.com\n
I am not sure if the above CSV generation code is so great as it appears to skip th
cells and also did not appear to allow for commas in the value. So here is my CSV generation code that might be useful.
It does assume you have the $table
variable which is a jQuery object (eg. var $table = $('#yourtable');
)
$rows = $table.find('tr');
var csvData = "";
for(var i=0;i<$rows.length;i++){
var $cells = $($rows[i]).children('th,td'); //header or content cells
for(var y=0;y<$cells.length;y++){
if(y>0){
csvData += ",";
}
var txt = ($($cells[y]).text()).toString().trim();
if(txt.indexOf(',')>=0 || txt.indexOf('\"')>=0 || txt.indexOf('\n')>=0){
txt = "\"" + txt.replace(/\"/g, "\"\"") + "\"";
}
csvData += txt;
}
csvData += '\n';
}
If you're doing shell commands and you (like I) have a fetish for pipelining, this one is good:
seq 1 $END | xargs -I {} echo {}
You should try and avoid jQuery in ReactJS. But if you really want to use it, you'd put it in componentDidMount() lifecycle function of the component.
e.g.
class App extends React.Component {
componentDidMount() {
// Jquery here $(...)...
}
// ...
}
Ideally, you'd want to create a reusable Accordion component. For this you could use Jquery, or just use plain javascript + CSS.
class Accordion extends React.Component {
constructor() {
super();
this._handleClick = this._handleClick.bind(this);
}
componentDidMount() {
this._handleClick();
}
_handleClick() {
const acc = this._acc.children;
for (let i = 0; i < acc.length; i++) {
let a = acc[i];
a.onclick = () => a.classList.toggle("active");
}
}
render() {
return (
<div
ref={a => this._acc = a}
onClick={this._handleClick}>
{this.props.children}
</div>
)
}
}
Then you can use it in any component like so:
class App extends React.Component {
render() {
return (
<div>
<Accordion>
<div className="accor">
<div className="head">Head 1</div>
<div className="body"></div>
</div>
</Accordion>
</div>
);
}
}
Codepen link here: https://codepen.io/jzmmm/pen/JKLwEA?editors=0110 (I changed this link to https ^)
Pretty strange, it should work out of the box as the ".modal-backdrop" class is defined top-level in the css.
<div class="modal-backdrop"></div>
Made a small demo: http://jsfiddle.net/PfBnq/
I think there is an error in the trigger code. As you want to delete all rows with the deleted patron ID, you have to use old.id (Otherwise it would delete other IDs)
Try this as the new trigger:
CREATE TRIGGER log_patron_delete AFTER DELETE on patrons
FOR EACH ROW
BEGIN
DELETE FROM patron_info
WHERE patron_info.pid = old.id;
END
Dont forget the ";" on the delete query. Also if you are entering the TRIGGER code in the console window, make use of the delimiters also.
I have problem with this error handling approach: In case of web.config:
<customErrors mode="On"/>
The error handler is searching view Error.shtml and the control flow step in to Application_Error global.asax only after exception
System.InvalidOperationException: The view 'Error' or its master was not found or no view engine supports the searched locations. The following locations were searched: ~/Views/home/Error.aspx ~/Views/home/Error.ascx ~/Views/Shared/Error.aspx ~/Views/Shared/Error.ascx ~/Views/home/Error.cshtml ~/Views/home/Error.vbhtml ~/Views/Shared/Error.cshtml ~/Views/Shared/Error.vbhtml at System.Web.Mvc.ViewResult.FindView(ControllerContext context) ....................
So
Exception exception = Server.GetLastError();
Response.Clear();
HttpException httpException = exception as HttpException;
httpException is always null then
customErrors mode="On"
:(
It is misleading
Then <customErrors mode="Off"/>
or <customErrors mode="RemoteOnly"/>
the users see customErrors html,
Then customErrors mode="On" this code is wrong too
Another problem of this code that
Response.Redirect(String.Format("~/Error/{0}/?message={1}", action, exception.Message));
Return page with code 302 instead real error code(402,403 etc)
I fixed the problem with deleting .vs folder on project folder.
VS will generate new config for this project.
What solved it for me was using :
regasm.exe 'xx.dll' /tlb /codebase /register
It is however, important to understand the difference between regasm.exe and regsvr.exe:
What is difference between RegAsm.exe and regsvr32? How to generate a tlb file using regsvr32?
A sub class is a small file of a program that extends from some other class. For example you make a class about cars in general and have basic information that holds true for all cars with your constructors and stuff then you have a class that extends from that on a more specific car or line of cars that would have new variables/methods. I see you already have plenty of examples of code from above by the time I get to post this but I hope this description helps.
Probably a stupid mistake; but, I experienced this problem and the issue turned out to be that "pip3 install sqlalchemy" installs libraries in user specific directories.
On my Linux machine, I was logged in as user1 executing a python script in user2's directory. I installed sqlalchemy as user1 and it by default placed the files in user1's directory. After installing sqlalchemy in user2's directory the problem went away.
A static variable declared in a header file outside of the class would be file-scoped
in every .c file which includes the header. That means separate copy of a variable with same name is accessible in each of the .c files where you include the header file.
A static class variable on the other hand is class-scoped
and the same static variable is available to every compilation unit that includes the header containing the class with static variable.
On Windows install http://chocolatey.org/ then
choco install python
Open a new cmd-window with the updated PATH. Next, do
choco install pip
After that you can
pip install pyside
pip install ipython
...
After making the id
unique across the document
,You have to use event delegation
$("#container").on("click", "buttonid", function () {
alert("Hi");
});
To rename a table in SQL Server, use the sp_rename
command:
exec sp_rename 'schema.old_table_name', 'new_table_name'
rimraf is an package for simulate linux command [rm -rf] in windows. which is useful for cross platform support. for install its CLI:
npm install rimraf -g
For me, this turned out to be an unimplemented parcelable class with no datatype [Any]; due to which there was a TODO() constructor created in parcelable implementation of model class.
Hope it helps someone.
@SerializedName("firstTxnDetails")
var firstTxnDetails: Any? = Any()
//in parcelable implementation :
constructor(parcel: Parcel) : this(
parcel.readInt(),
parcel.readLong(),
parcel.readInt(),
parcel.readDouble(),
parcel.readLong(),
TODO("firstTxnDetails"), // -> correct this
parcel.readString(),
parcel.readLong(),
parcel.readParcelable(MasterSavingPlan::class.java.classLoader),
parcel.readInt(),
parcel.readString(),
parcel.readString()) {
}
The heredoc solutions are certainly the most common way to do this. Other common solutions are:
echo 'line 1, '"${kernel}"' line 2, line 3, '"${distro}"' line 4' > /etc/myconfig.conf
and
exec 3>&1 # Save current stdout exec > /etc/myconfig.conf echo line 1, ${kernel} echo line 2, echo line 3, ${distro} ... exec 1>&3 # Restore stdout
as HTMLInputElement
works for me
try following statement
Uri myuri = new Uri(System.Web.HttpContext.Current.Request.Url.AbsoluteUri);
string pathQuery = myuri.PathAndQuery;
string hostName = myuri.ToString().Replace(pathQuery , "");
Example1
Input : http://localhost:4366/Default.aspx?id=notlogin
Ouput : http://localhost:4366
Example2
Input : http://support.domain.com/default.aspx?id=12345
Output: support.domain.com
unfortunately I don't think there is a direct way, however I think you can write an extension method for the array class to do this
class Program
{
static void Main(string[] args)
{
int[] arr = new int[1000];
arr.Init(10);
Array.ForEach(arr, Console.WriteLine);
}
}
public static class ArrayExtensions
{
public static void Init<T>(this T[] array, T defaultVaue)
{
if (array == null)
return;
for (int i = 0; i < array.Length; i++)
{
array[i] = defaultVaue;
}
}
}
Remove System.Web.Http and System.Net.Http.Formatting from your references and Add references back in by browsing to your bin folder (where they were copied to by nuget) Now the file version says 5.0.0.0
"Unable to load the requested file"
Can be also caused by access permissions under linux , make sure you set the correct read permissions for the directory "views/home"
packed
means it will use the smallest possible space for struct Ball
- i.e. it will cram fields together without paddingaligned
means each struct Ball
will begin on a 4 byte boundary - i.e. for any struct Ball
, its address can be divided by 4These are GCC extensions, not part of any C standard.
You can't rewrite a line without rewriting the entire file (unless the lines happen to be the same length). If your files are small then reading the entire target file into memory and then writing it out again might make sense. You can do that like this:
using System;
using System.IO;
class Program
{
static void Main(string[] args)
{
int line_to_edit = 2; // Warning: 1-based indexing!
string sourceFile = "source.txt";
string destinationFile = "target.txt";
// Read the appropriate line from the file.
string lineToWrite = null;
using (StreamReader reader = new StreamReader(sourceFile))
{
for (int i = 1; i <= line_to_edit; ++i)
lineToWrite = reader.ReadLine();
}
if (lineToWrite == null)
throw new InvalidDataException("Line does not exist in " + sourceFile);
// Read the old file.
string[] lines = File.ReadAllLines(destinationFile);
// Write the new file over the old file.
using (StreamWriter writer = new StreamWriter(destinationFile))
{
for (int currentLine = 1; currentLine <= lines.Length; ++currentLine)
{
if (currentLine == line_to_edit)
{
writer.WriteLine(lineToWrite);
}
else
{
writer.WriteLine(lines[currentLine - 1]);
}
}
}
}
}
If your files are large it would be better to create a new file so that you can read streaming from one file while you write to the other. This means that you don't need to have the whole file in memory at once. You can do that like this:
using System;
using System.IO;
class Program
{
static void Main(string[] args)
{
int line_to_edit = 2;
string sourceFile = "source.txt";
string destinationFile = "target.txt";
string tempFile = "target2.txt";
// Read the appropriate line from the file.
string lineToWrite = null;
using (StreamReader reader = new StreamReader(sourceFile))
{
for (int i = 1; i <= line_to_edit; ++i)
lineToWrite = reader.ReadLine();
}
if (lineToWrite == null)
throw new InvalidDataException("Line does not exist in " + sourceFile);
// Read from the target file and write to a new file.
int line_number = 1;
string line = null;
using (StreamReader reader = new StreamReader(destinationFile))
using (StreamWriter writer = new StreamWriter(tempFile))
{
while ((line = reader.ReadLine()) != null)
{
if (line_number == line_to_edit)
{
writer.WriteLine(lineToWrite);
}
else
{
writer.WriteLine(line);
}
line_number++;
}
}
// TODO: Delete the old file and replace it with the new file here.
}
}
You can afterwards move the file once you are sure that the write operation has succeeded (no excecption was thrown and the writer is closed).
Note that in both cases it is a bit confusing that you are using 1-based indexing for your line numbers. It might make more sense in your code to use 0-based indexing. You can have 1-based index in your user interface to your program if you wish, but convert it to a 0-indexed before sending it further.
Also, a disadvantage of directly overwriting the old file with the new file is that if it fails halfway through then you might permanently lose whatever data wasn't written. By writing to a third file first you only delete the original data after you are sure that you have another (corrected) copy of it, so you can recover the data if the computer crashes halfway through.
A final remark: I noticed that your files had an xml extension. You might want to consider if it makes more sense for you to use an XML parser to modify the contents of the files instead of replacing specific lines.
I use this function datetime_to_local_timezone()
, which seems overly convoluted but I found no simpler version of a function that converts a datetime
instance to the local time zone, as configured in the operating system, with the UTC offset that was in effect at that time:
import time, datetime
def datetime_to_local_timezone(dt):
epoch = dt.timestamp() # Get POSIX timestamp of the specified datetime.
st_time = time.localtime(epoch) # Get struct_time for the timestamp. This will be created using the system's locale and it's time zone information.
tz = datetime.timezone(datetime.timedelta(seconds = st_time.tm_gmtoff)) # Create a timezone object with the computed offset in the struct_time.
return dt.astimezone(tz) # Move the datetime instance to the new time zone.
utc = datetime.timezone(datetime.timedelta())
dt1 = datetime.datetime(2009, 7, 10, 18, 44, 59, 193982, utc) # DST was in effect
dt2 = datetime.datetime(2009, 1, 10, 18, 44, 59, 193982, utc) # DST was not in effect
print(dt1)
print(datetime_to_local_timezone(dt1))
print(dt2)
print(datetime_to_local_timezone(dt2))
This example prints four dates. For two moments in time, one in January and one in July 2009, each, it prints the timestamp once in UTC and once in the local time zone. Here, where CET (UTC+01:00) is used in the winter and CEST (UTC+02:00) is used in the summer, it prints the following:
2009-07-10 18:44:59.193982+00:00
2009-07-10 20:44:59.193982+02:00
2009-01-10 18:44:59.193982+00:00
2009-01-10 19:44:59.193982+01:00
Using grep
on the results of ps
is a bad idea in a script, since some proportion of the time it will also match the grep process you've just invoked. The command pgrep
avoids this problem, so if you need to know the process ID, that's a better option. (Note that, of course, there may be many processes matched.)
However, in your example, you could just use the similar command pkill
to kill all matching processes:
pkill ruby
Incidentally, you should be aware that using -9
is overkill (ho ho) in almost every case - there's some useful advice about that in the text of the "Useless Use of kill -9
form letter ":
No no no. Don't use
kill -9
.It doesn't give the process a chance to cleanly:
- shut down socket connections
- clean up temp files
- inform its children that it is going away
- reset its terminal characteristics
and so on and so on and so on.
Generally, send 15, and wait a second or two, and if that doesn't work, send 2, and if that doesn't work, send 1. If that doesn't, REMOVE THE BINARY because the program is badly behaved!
Don't use
kill -9
. Don't bring out the combine harvester just to tidy up the flower pot.
"==" always compare the memory location or object references of the values. equals method always compare the values. But equals also indirectly uses the "==" operator to compare the values.
Integer uses Integer cache to store the values from -128 to +127. If == operator is used to check for any values between -128 to 127 then it returns true. for other than these values it returns false .
Refer the link for some additional info
I liked the look of WenhaoWuI's idea above, but I needed to identify the div with class .ui-tree
in the PrimeNG tree component to set the height dynamically.
All the answers I could find required the div to be named (ie #treediv) to enable the use of @ViewChild()
, @ViewChildren()
, @ContentChild()
, @ContentChilden()
etc. This was messy with a third party component.
I finally found a snippet from Günter Zöchbauer :
ngAfterViewInit() {
this.elRef.nativeElement.querySelector('.myClass');
}
This made it easy:
@Input() height: number;
treeheight: number = 400; //default value
constructor(private renderer: Renderer2, private elRef: ElementRef) { }
ngOnInit() {
this.loading = true;
if (this.height != null) {
this.treeheight = this.height;
}
}
ngAfterViewInit() {
this.renderer.setStyle(this.elRef.nativeElement.querySelector('.ui-tree'), 'height', this.treeheight + "px");
}
I suspect you're facing the issue where your package.json
file is not in the same directory as your Gruntfile.js
. When you run your grunt xxx
commands, you get error an message like:
Local Npm module "xxx" not found. Is it installed?
For now, the solution is:
npm install
to load them locallyIMHO, it is sad that we cannot have grunt resolve modules loaded from a parent npm module (i.e. package.json in a parent directory within the same project). The discussion here seems to indicate that it was done to avoid loading "global" modules but I think what we want is loading from "my project" modules instead.
def common_start(sa, sb):
""" returns the longest common substring from the beginning of sa and sb """
def _iter():
for a, b in zip(sa, sb):
if a == b:
yield a
else:
return
return ''.join(_iter())
>>> common_start("apple pie available", "apple pies")
'apple pie'
Or a slightly stranger way:
def stop_iter():
"""An easy way to break out of a generator"""
raise StopIteration
def common_start(sa, sb):
return ''.join(a if a == b else stop_iter() for a, b in zip(sa, sb))
Which might be more readable as
def terminating(cond):
"""An easy way to break out of a generator"""
if cond:
return True
raise StopIteration
def common_start(sa, sb):
return ''.join(a for a, b in zip(sa, sb) if terminating(a == b))
'DD/MM/YYYY hh:mm A' => 12 hours 'DD/MM/YYYY HH:mm A' => 24 hours
This is because you have wrong selector. According to your markup, .ui-icon
and .ui-icon-circle-triangle-w"
should point to the same <span>
element. So you should use:
$(".ui-icon.ui-icon-circle-triangle-w").html("<<");
or
$(".ui-datepicker-prev .ui-icon").html("<<");
or
$(".ui-datepicker-prev span").html("<<");
For me, the user was mongod
instead of mongodb
sudo chown mongod:mongod /newlocation
You can see the logs for errors if the service fails:
/var/log/mongodb/mongod.log
In angular v10 I did something like this, first created a master.scss
file and included the following variables:
master.scss
file:
$theme: blue;
$button_color: red;
$label_color: gray;
Then I imported the master.scss
file in my style.scss
at the top:
style.scss file:
@use './master' as m;
Make sure you import the master.scss
at the top.
m
is an alias for the namespace;
Use @use
instead of @import
according to the official docs below:
https://sass-lang.com/documentation/at-rules/import
Then in your styles.scss
file you can use any variable which is defined in master.scss
like below:
someClass {
backgroud-color: m.$theme;
color: m.$button_color;
}
Hope it 'll help...
Happy Coding :)
If you're going across machines, you either need to be using NETWORK SERVICE, LOCAL SYSTEM, a domain account, or a SQL 2008 R2 (if you have it) Managed Service Account (which is my preference if you had such an infrastructure). You can not use an account which is not visible to the Active Directory domain.
You can use Sass' transparentize
.
I found it to be the most useful and plain to use.
transparentize(rgba(0, 0, 0, 0.5), 0.1) => rgba(0, 0, 0, 0.4)
transparentize(rgba(0, 0, 0, 0.8), 0.2) => rgba(0, 0, 0, 0.6)
See more: #transparentize($color, $amount) ? Sass::Script::Value::Color
The previous answers did not work for me.
I used this code. If you are using OSX make sure to use the correct format.
Options +FollowSymLinks -MultiViews
RewriteEngine on
RewriteCond %{HTTP_HOST} ^(www\.)?OLDDOMAIN\.com$ [NC]
RewriteRule (.*) http://www.NEWDOMAIN.com/ [R=301,L]
It is possible to have multiple or nested views. But not by ng-view.
The primary routing module in angular does not support multiple views. But you can use ui-router. This is a third party module which you can get via Github, angular-ui/ui-router, https://github.com/angular-ui/ui-router . Also a new version of ngRouter (ngNewRouter) currently, is being developed. It is not stable at the moment. So I provide you a simple start up example with ui-router. Using it you can name views and specify which templates and controllers should be used for rendering them. Using $stateProvider you should specify how view placeholders should be rendered for specific state.
<body ng-app="main">
<script type="text/javascript">
angular.module('main', ['ui.router'])
.config(['$locationProvider', '$stateProvider', function ($locationProvider, $stateProvider) {
$stateProvider
.state('home', {
url: '/',
views: {
'header': {
templateUrl: '/app/header.html'
},
'content': {
templateUrl: '/app/content.html'
}
}
});
}]);
</script>
<a ui-sref="home">home</a>
<div ui-view="header">header</div>
<div ui-view="content">content</div>
<div ui-view="bottom">footer</div>
<script src="bower_components/angular/angular.js"></script>
<script src="bower_components/angular-ui-router/release/angular-ui-router.js">
</body>
You need referencing angularjs, and angular-ui.router for this sample.
$ bower install angular-ui-router
In window form c#. If you use Enter event it will not work. try to use MouseUp event
bool FlagEntered;
private void textBox1_MouseUp(object sender, MouseEventArgs e)
{
if ((sender as TextBox).SelectedText == "" && !FlagEntered)
{
(sender as TextBox).SelectAll();
FlagEntered = true;
}
}
private void textBox1_Leave(object sender, EventArgs e)
{
FlagEntered = false;
}
This is how I do it...
public class ThreadA {
public ThreadA(object[] args) {
...
}
public void Run() {
while (true) {
Thread.sleep(1000); // wait 1 second for something to happen.
doStuff();
if(conditionToExitReceived) // what im waiting for...
break;
}
//perform cleanup if there is any...
}
}
Then to run this in its own thread... ( I do it this way because I also want to send args to the thread)
private void FireThread(){
Thread thread = new Thread(new ThreadStart(this.startThread));
thread.start();
}
private void (startThread){
new ThreadA(args).Run();
}
The thread is created by calling "FireThread()"
The newly created thread will run until its condition to stop is met, then it dies...
You can signal the "main" with delegates, to tell it when the thread has died.. so you can then start the second one...
Best to read through : This MSDN Article
>>> import re
>>> s = "start foo end"
>>> s = re.sub("foo", "replaced", s)
>>> s
'start replaced end'
>>> s = re.sub("(?<= )(.+)(?= )", lambda m: "can use a callable for the %s text too" % m.group(1), s)
>>> s
'start can use a callable for the replaced text too end'
>>> help(re.sub)
Help on function sub in module re:
sub(pattern, repl, string, count=0)
Return the string obtained by replacing the leftmost
non-overlapping occurrences of the pattern in string by the
replacement repl. repl can be either a string or a callable;
if a callable, it's passed the match object and must return
a replacement string to be used.
You can easily solve this by doing
delete mongoose.connection.models['users'];
const usersSchema = mongoose.Schema({...});
export default mongoose.model('users', usersSchema);
see 15.22.2 of the JLS. For boolean operands, the &
operator is boolean, not bitwise. The only difference between &&
and &
for boolean operands is that for &&
it is short circuited (meaning that the second operand isn't evaluated if the first operand evaluates to false).
So in your case, if b
is a primitive, a = a && b
, a = a & b
, and a &= b
all do the same thing.
For installing Composer below steps worked me:(WAMP version 2.4 x64bit)
edit ->
**C:\wamp\bin\php\php5.4.12\php.ini**
;;uncomment below line or remove the semicolons ';'
extension=php_openssl.dll
**C:\wamp\bin\apache\Apache2.4.4\bin\php.ini**
extension=php_openssl.dll
Here's how I interpret it:
int *something[n];
Note on precedence: array subscript operator (
[]
) has higher priority than dereference operator (*
).
So, here we will apply the []
before *
, making the statement equivalent to:
int *(something[i]);
Note on how a declaration makes sense:
int num
meansnum
is anint
,int *ptr
orint (*ptr)
means, (value atptr
) is anint
, which makesptr
a pointer toint
.
This can be read as, (value of the (value at ith index of the something)) is an integer. So, (value at the ith index of something) is an (integer pointer), which makes the something an array of integer pointers.
In the second one,
int (*something)[n];
To make sense out of this statement, you must be familiar with this fact:
Note on pointer representation of array:
somethingElse[i]
is equivalent to*(somethingElse + i)
So, replacing somethingElse
with (*something)
, we get *(*something + i)
, which is an integer as per declaration. So, (*something)
given us an array, which makes something equivalent to (pointer to an array).
One important note, the solution mentioned above will not work on local host, you have to upload your code to server and then it will work. I was getting no error, than bad request, the problem was I was using localhost (test.dev,myproject.git). Both solution above work, the solution that uses SSL cert is recommended.
Go to https://curl.haxx.se/docs/caextract.html, download the latest cacert.pem. Store is somewhere (not in public folder - but will work regardless)
Use this code
".$result; //echo "
Path:".$_SERVER['DOCUMENT_ROOT'] . "/ssl/cacert.pem"; // this is for troubleshooting only ?>
Node.js doesn't enforce any file naming conventions (except index.js
). And the Javascript language in general doesn't either. You can find dozens of threads here which suggest camelCase, hyphens and underscores, any of which work perfectly well. So its up to you. Choose one and stick with it.
I found an easy resolution for this issue was to add source /etc/profile to the top of the script.sh file I was trying to run on the target system. On the systems here, this caused the environmental variables which were needed by script.sh to be configured as if running from a login shell.
In one of the prior responses it was suggested that ~/.bashr_profile etc... be used. I didn't spend much time on this but, the problem with this is if you ssh to a different user on the target system than the shell on the source system from which you log in it appeared to me that this causes the source system user name to be used for the ~.
not sure if anyone notice it may be correct to return a 301 but browsers choke on it to doing
rewrite ^(.*)$ https://yoursite.com$1;
is faster than:
return 301 $scheme://yoursite.com$request_uri;
//JUST little bit modified the answer of giuseppe which returns array of table columns
+(NSMutableArray*)tableInfo:(NSString *)table{
sqlite3_stmt *sqlStatement;
NSMutableArray *result = [NSMutableArray array];
const char *sql = [[NSString stringWithFormat:@"PRAGMA table_info('%@')",table] UTF8String];
if(sqlite3_prepare(md.database, sql, -1, &sqlStatement, NULL) != SQLITE_OK)
{
NSLog(@"Problem with prepare statement tableInfo %@",
[NSString stringWithUTF8String:(const char *)sqlite3_errmsg(md.database)]);
}
while (sqlite3_step(sqlStatement)==SQLITE_ROW)
{
[result addObject:
[NSString stringWithUTF8String:(char*)sqlite3_column_text(sqlStatement, 1)]];
}
return result;
}
Here's an easier way:
sudo apt-get install maven
More details are here.
You can't just change the delimiters from ---- BEGIN SSH2 PUBLIC KEY ----
to -----BEGIN RSA PUBLIC KEY-----
and expect that it will be sufficient to convert from one format to another (which is what you've done in your example).
This article has a good explanation about both formats.
What you get in an RSA PUBLIC KEY
is closer to the content of a PUBLIC KEY
, but you need to offset the start of your ASN.1 structure to reflect the fact that PUBLIC KEY
also has an indicator saying which type of key it is (see RFC 3447). You can see this using openssl asn1parse
and -strparse 19
, as described in this answer.
EDIT: Following your edit, your can get the details of your RSA PUBLIC KEY
structure using grep -v -- ----- | tr -d '\n' | base64 -d | openssl asn1parse -inform DER
:
0:d=0 hl=4 l= 266 cons: SEQUENCE
4:d=1 hl=4 l= 257 prim: INTEGER :FB1199FF0733F6E805A4FD3B36CA68E94D7B974621162169C71538A539372E27F3F51DF3B08B2E111C2D6BBF9F5887F13A8DB4F1EB6DFE386C92256875212DDD00468785C18A9C96A292B067DDC71DA0D564000B8BFD80FB14C1B56744A3B5C652E8CA0EF0B6FDA64ABA47E3A4E89423C0212C07E39A5703FD467540F874987B209513429A90B09B049703D54D9A1CFE3E207E0E69785969CA5BF547A36BA34D7C6AEFE79F314E07D9F9F2DD27B72983AC14F1466754CD41262516E4A15AB1CFB622E651D3E83FA095DA630BD6D93E97B0C822A5EB4212D428300278CE6BA0CC7490B854581F0FFB4BA3D4236534DE09459942EF115FAA231B15153D67837A63
265:d=1 hl=2 l= 3 prim: INTEGER :010001
To decode the SSH key format, you need to use the data format specification in RFC 4251 too, in conjunction with RFC 4253:
The "ssh-rsa" key format has the following specific encoding: string "ssh-rsa" mpint e mpint n
For example, at the beginning, you get 00 00 00 07 73 73 68 2d 72 73 61
. The first four bytes (00 00 00 07
) give you the length. The rest is the string itself: 73=s, 68=h, ... -> 73 73 68 2d 72 73 61
=ssh-rsa
, followed by the exponent of length 1 (00 00 00 01 25
) and the modulus of length 256 (00 00 01 00 7f ...
).
Here is a simple and more update format of getting the data:
$now = new \DateTime('now');
$month = $now->format('m');
$year = $now->format('Y');
margin
to align images:Since we wanted the image
to be left-aligned
, we added:
img {
margin-right: auto;
}
Similarly for image
to be right-aligned
, we can add margin-right: auto;
. The snippet shows a demo for both types of alignment.
Good Luck...
div {_x000D_
display:flex; _x000D_
flex-direction:column;_x000D_
border: 2px black solid;_x000D_
}_x000D_
_x000D_
h1 {_x000D_
text-align: center;_x000D_
}_x000D_
hr {_x000D_
border: 1px black solid;_x000D_
width: 100%_x000D_
}_x000D_
img.one {_x000D_
margin-right: auto;_x000D_
}_x000D_
_x000D_
img.two {_x000D_
margin-left: auto;_x000D_
}
_x000D_
<div>_x000D_
<h1>Flex Box</h1>_x000D_
_x000D_
<hr />_x000D_
_x000D_
<img src="https://via.placeholder.com/80x80" class="one" _x000D_
/>_x000D_
_x000D_
_x000D_
<img src="https://via.placeholder.com/80x80" class="two" _x000D_
/>_x000D_
_x000D_
<hr />_x000D_
</div>
_x000D_
Using some of the above recommendations, the following function and code is working for search a date range:
Set date with the time component set to 00:00:00
public static DateTime GetDateZeroTime(DateTime date)
{
return new DateTime(date.Year, date.Month, date.Day, 0, 0, 0);
}
Usage
var modifieddatebegin = Tools.Utilities.GetDateZeroTime(form.modifieddatebegin);
var modifieddateend = Tools.Utilities.GetDateZeroTime(form.modifieddateend.AddDays(1));
For namespace and Library
@using NameSpace_Name
For Model
@model Application_Name.Models.Model_Name
For Iterate the list on Razor Page (You Have to use foreach loop for access the list items)
@model List<Application_Name.Models.Model_Name>
@foreach (var item in Model)
{
<tr>
<td>@item.srno</td>
<td>@item.name</td>
</tr>
}
Just an improvement to the nice answer given by @vuhung3990. I implemented the solution and works great but if I touch one radio button it will be selected and nothing happens.
I suggest to also change page when a radio button is tapped. To do this, simply add a listener to the radioGroup:
mPager = (ViewPager) findViewById(R.id.pager);
final RadioGroup radioGroup = (RadioGroup)findViewById(R.id.radiogroup);
radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
switch (checkedId) {
case R.id.radioButton :
mPager.setCurrentItem(0, true);
break;
case R.id.radioButton2 :
mPager.setCurrentItem(1, true);
break;
case R.id.radioButton3 :
mPager.setCurrentItem(2, true);
break;
}
}
});
KEY or INDEX refers to a normal non-unique index. Non-distinct values for the index are allowed, so the index may contain rows with identical values in all columns of the index. These indexes don't enforce any restraints on your data so they are used only for access - for quickly reaching certain ranges of records without scanning all records.
UNIQUE refers to an index where all rows of the index must be unique. That is, the same row may not have identical non-NULL values for all columns in this index as another row. As well as being used to quickly reach certain record ranges, UNIQUE indexes can be used to enforce restraints on data, because the database system does not allow the distinct values rule to be broken when inserting or updating data.
Your database system may allow a UNIQUE index to be applied to columns which allow NULL values, in which case two rows are allowed to be identical if they both contain a NULL value (the rationale here is that NULL is considered not equal to itself). Depending on your application, however, you may find this undesirable: if you wish to prevent this, you should disallow NULL values in the relevant columns.
PRIMARY acts exactly like a UNIQUE index, except that it is always named 'PRIMARY', and there may be only one on a table (and there should always be one; though some database systems don't enforce this). A PRIMARY index is intended as a primary means to uniquely identify any row in the table, so unlike UNIQUE it should not be used on any columns which allow NULL values. Your PRIMARY index should be on the smallest number of columns that are sufficient to uniquely identify a row. Often, this is just one column containing a unique auto-incremented number, but if there is anything else that can uniquely identify a row, such as "countrycode" in a list of countries, you can use that instead.
Some database systems (such as MySQL's InnoDB) will store a table's records on disk in the order in which they appear in the PRIMARY index.
FULLTEXT indexes are different from all of the above, and their behaviour differs significantly between database systems. FULLTEXT indexes are only useful for full text searches done with the MATCH() / AGAINST() clause, unlike the above three - which are typically implemented internally using b-trees (allowing for selecting, sorting or ranges starting from left most column) or hash tables (allowing for selection starting from left most column).
Where the other index types are general-purpose, a FULLTEXT index is specialised, in that it serves a narrow purpose: it's only used for a "full text search" feature.
All of these indexes may have more than one column in them.
With the exception of FULLTEXT, the column order is significant: for the index to be useful in a query, the query must use columns from the index starting from the left - it can't use just the second, third or fourth part of an index, unless it is also using the previous columns in the index to match static values. (For a FULLTEXT index to be useful to a query, the query must use all columns of the index.)
Dec 25th, 2019 :
Whoever facing issue regarding Image not showing in Flutter , let me give you simple checkpoints :
First point is very important
If you like doing things the hard way:
my (undef,undef,undef,$mday,$mon,$year) = localtime;
$year = $year+1900;
$mon += 1;
if (length($mon) == 1) {$mon = "0$mon";}
if (length($mday) == 1) {$mday = "0$mday";}
my $today = "$mon/$mday/$year";
I experienced a similar issue.
Here's how I solved it
Run the service command below to start ElasticSearch
sudo service elasticsearch start
OR
sudo systemctl start elasticsearch
If you still get the error
curl: (7) Failed to connect to localhost port 9200: Connection refused
Run the service command below to check the status of ElasticSearch
sudo service elasticsearch status
OR
sudo systemctl status elasticsearch
If you get a response (Active: active (running)) like the one below then you ElasticSearch is active and running
? elasticsearch.service - Elasticsearch Loaded: loaded (/usr/lib/systemd/system/elasticsearch.service; disabled; vendor preset: enabled) Active: active (running) since Sat 2019-09-21 11:22:21 WAT; 3s ago
You can then test that your Elasticsearch node is running by sending an HTTP request to port 9200 on localhost using the command below:
curl http://localhost:9200
Else, if you get a response a different response, you may have to debug further to fix it, but the running the command below, will help you detect what caveats are holding ElasticSearch service from starting.
sudo service elasticsearch status
OR
sudo systemctl status elasticsearch
If you want to stop the ElasticSearch service, simply run the service command below;
sudo service elasticsearch stop
OR
sudo systemctl stop elasticsearch
N/B: You may have to run the command sudo service elasticsearch status
OR sudo systemctl status elasticsearch
each time you encounter the error, in order to tell the state of the ElasticSearch service.
This also applies for Kibana, run the command sudo service kibana status
OR sudo systemctl status kibana
each time you encounter the error, in order to tell the state of the Kibana service.
That's all.
I hope this helps.
As Ben said, you are POSTing your request ( HttpMethod.Post specified in your code )
The querystring (get) parameters included in your url probably will not do anything.
Try this:
string url = "http://myserver/method";
string content = "param1=1¶m2=2";
HttpClientHandler handler = new HttpClientHandler();
HttpClient httpClient = new HttpClient(handler);
HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, url);
HttpResponseMessage response = await httpClient.SendAsync(request,content);
HTH,
bovako
You should add AutoPostBack="true" to DropDownList1
<asp:DropDownList ID="ddmanu" runat="server" AutoPostBack="true"
DataSourceID="Sql_fur_model_manu"
DataTextField="manufacturer" DataValueField="manufacturer"
onselectedindexchanged="ddmanu_SelectedIndexChanged">
</asp:DropDownList>
a.button a:hover
means "a link that's being hovered over that is a child of a link with the class button
".
Go instead for a.button:hover
.
Here's one way to do it, using MySQLdb, which only supports Python 2:
#!/usr/bin/python
import MySQLdb
# Connect
db = MySQLdb.connect(host="localhost",
user="appuser",
passwd="",
db="onco")
cursor = db.cursor()
# Execute SQL select statement
cursor.execute("SELECT * FROM location")
# Commit your changes if writing
# In this case, we are only reading data
# db.commit()
# Get the number of rows in the resultset
numrows = cursor.rowcount
# Get and display one row at a time
for x in range(0, numrows):
row = cursor.fetchone()
print row[0], "-->", row[1]
# Close the connection
db.close()
This is what I'm using:
function cloneObject(obj) {
var clone = {};
for(var i in obj) {
if(typeof(obj[i])=="object" && obj[i] != null)
clone[i] = cloneObject(obj[i]);
else
clone[i] = obj[i];
}
return clone;
}
You're most likely looking at using a flash/silverlight/activeX control. The <input type="file" />
control doesn't handle that.
If you don't mind the user selecting a file as a means to getting its directory, you may be able to bind to that control's change
event then strip the filename portion and save the path somewhere--but that's about as good as it gets.
Keep in mind that webpages are designed to interact with servers. Nothing about providing a local directory to a remote server is "typical" (a server can't access it so why ask for it?); however files are a means to selectively passing information.
This code works for me:
Sub test()
Dim myRange As Range
Dim NumRows As Integer
Set myRange = Range("A:A")
NumRows = Application.WorksheetFunction.CountA(myRange)
MsgBox NumRows
End Sub
To avoid using scriplets in the jsp, follow the advice of "divideByZero", and use
${pageContext.request.requestURI}
This is a better way to go.
Haha, Lovely - let me also include my version of stackPusher's code :). We are using this functionality in C#. Works fine for all Excel ranges.:
public static String ConvertToLiteral(int number)
{
int firstLetter = (((number - 27) / (26 * 26))) % 26;
int middleLetter = ((((number - 1) / 26)) % 26);
int lastLetter = (number % 26);
firstLetter = firstLetter == 0 ? 26 : firstLetter;
middleLetter = middleLetter == 0 ? 26 : middleLetter;
lastLetter = lastLetter == 0 ? 26 : lastLetter;
String returnedString = "";
returnedString = number > 27 * 26 ? (Convert.ToChar(firstLetter + 64).ToString()) : returnedString;
returnedString += number > 26 ? (Convert.ToChar(middleLetter + 64).ToString()) : returnedString;
returnedString += lastLetter >= 0 ? (Convert.ToChar(lastLetter + 64).ToString()) : returnedString;
return returnedString;
}
public void getCityStateFromLocal() {
AssetManager am = getAssets();
InputStream inputStream = null;
try {
inputStream = am.open("city_state.txt");
} catch (IOException e) {
e.printStackTrace();
}
ObjectMapper mapper = new ObjectMapper();
Map<String, String[]> map = new HashMap<String, String[]>();
try {
map = mapper.readValue(getStringFromInputStream(inputStream), new TypeReference<Map<String, String[]>>() {
});
} catch (IOException e) {
e.printStackTrace();
}
ConstantValues.arrayListStateName.clear();
ConstantValues.arrayListCityByState.clear();
if (map.size() > 0)
{
for (Map.Entry<String, String[]> e : map.entrySet()) {
CityByState cityByState = new CityByState();
String key = e.getKey();
String[] value = e.getValue();
ArrayList<String> s = new ArrayList<String>(Arrays.asList(value));
ConstantValues.arrayListStateName.add(key);
s.add(0,"Select City");
cityByState.addValue(s);
ConstantValues.arrayListCityByState.add(cityByState);
}
}
ConstantValues.arrayListStateName.add(0,"Select States");
}
// Convert InputStream to String
public String getStringFromInputStream(InputStream is) {
BufferedReader br = null;
StringBuilder sb = new StringBuilder();
String line;
try {
br = new BufferedReader(new InputStreamReader(is));
while ((line = br.readLine()) != null) {
sb.append(line);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (br != null) {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return sb + "";
}
You will need Javascript to do this:
HTML
<input id="datefield" type='date' min='1899-01-01' max='2000-13-13'></input>
JS
var today = new Date();
var dd = today.getDate();
var mm = today.getMonth()+1; //January is 0!
var yyyy = today.getFullYear();
if(dd<10){
dd='0'+dd
}
if(mm<10){
mm='0'+mm
}
today = yyyy+'-'+mm+'-'+dd;
document.getElementById("datefield").setAttribute("max", today);
If the command contains some special characters such as pipes and quotes, the command needs to be padded with quotes. For example, to repeat ls -l | grep "txt"
, the watch command should be:
watch -n 5 'ls -l | grep "txt"'
I use this simple function for JQuery based project
var pointerEventToXY = function(e){
var out = {x:0, y:0};
if(e.type == 'touchstart' || e.type == 'touchmove' || e.type == 'touchend' || e.type == 'touchcancel'){
var touch = e.originalEvent.touches[0] || e.originalEvent.changedTouches[0];
out.x = touch.pageX;
out.y = touch.pageY;
} else if (e.type == 'mousedown' || e.type == 'mouseup' || e.type == 'mousemove' || e.type == 'mouseover'|| e.type=='mouseout' || e.type=='mouseenter' || e.type=='mouseleave') {
out.x = e.pageX;
out.y = e.pageY;
}
return out;
};
example:
$('a').on('mousedown touchstart', function(e){
console.log(pointerEventToXY(e)); // will return obj ..kind of {x:20,y:40}
})
hope this will be usefull for you ;)
finally solved my problem.
I created a new project in XCode with the sources and changed the C++ Standard Library from the default libc++ to libstdc++ as in this and this.
As you run your spark app on top of HDFS, according to Sandy Ryza
I’ve noticed that the HDFS client has trouble with tons of concurrent threads. A rough guess is that at most five tasks per executor can achieve full write throughput, so it’s good to keep the number of cores per executor below that number.
So I believe that your first configuration is slower than third one is because of bad HDFS I/O throughput
Validating that it is a real email address is much harder.
The regex to confirm the syntax is correct can be very long (see http://www.regular-expressions.info/email.html for example). The best way to confirm an email address is to email the user, and get the user to reply by clicking on a link to validate that they have recieved the email (the way most sign-up systems work).
An optional prefix
!
which negates the pattern; any matching file excluded by a previous pattern will become included again. If a negated pattern matches, this will override lower precedence patterns sources.
http://schacon.github.com/git/gitignore.html
*.json
!spec/*.json
Cmd + Shift + 7 will comment the selected lines.
You were close
/my/bash/script <<< 'This string will be sent to stdin.'
For multiline input, here-docs are suited:
/my/bash/script <<STDIN -o other --options
line 1
line 2
STDIN
Edit To the comments:
To achieve binary input, say
xxd -r -p <<BINARY | iconv -f UCS-4BE -t UTF-8 | /my/bash/script
0000 79c1 0000 306f 0000 3061 0000 3093 0000 3077 0000 3093 0000 304b 0000 3093 0000 3077 0000 3093 0000 306a 0000 8a71 0000 306b 0000 30ca 0000 30f3 0000 30bb
0000 30f3 0000 30b9 0000 3092 0000 7ffb 0000 8a33 0000 3059 0000 308b 0000 3053 0000 3068 0000 304c 0000 3067 0000 304d 0000 000a
BINARY
If you substitute cat
for /my/bash/script
(or indeed drop the last pipe), this prints:
????????????????????????????
Or, if you wanted something a little more geeky:
0000000: 0000 0000 bef9 0e3c 59f8 8e3c 0a71 d63c .......<Y..<.q.<
0000010: c6f2 0e3d 3eaa 323d 3a5e 563d 090e 7a3d ...=>.2=:^V=..z=
0000020: 7bdc 8e3d 2aaf a03d b67e b23d c74a c43d {..=*..=.~.=.J.=
0000030: 0513 d63d 16d7 e73d a296 f93d a8a8 053e ...=...=...=...>
0000040: 6583 0e3e 5a5b 173e 5b30 203e 3d02 293e e..>Z[.>[0 >=.)>
0000050: d4d0 313e f39b 3a3e 6f63 433e 1c27 4c3e ..1>..:>ocC>.'L>
0000060: cde6 543e 59a2 5d3e 9259 663e 4d0c 6f3e ..T>Y.]>.Yf>M.o>
0000070: 60ba 773e cf31 803e ee83 843e 78d3 883e `.w>.1.>...>x..>
0000080: 5720 8d3e 766a 913e beb1 953e 1cf6 993e W .>vj.>...>...>
0000090: 7a37 9e3e c275 a23e dfb0 a63e bce8 aa3e z7.>.u.>...>...>
00000a0: 441d af3e 624e b33e 017c b73e 0ca6 bb3e D..>bN.>.|.>...>
00000b0: 6fcc bf3e 15ef c33e e90d c83e d728 cc3e o..>...>...>.(.>
00000c0: c93f d03e ac52 d43e 6c61 d83e f36b dc3e .?.>.R.>la.>.k.>
00000d0: 2f72 e03e 0a74 e43e 7171 e83e 506a ec3e /r.>.t.>qq.>Pj.>
00000e0: 945e f03e 274e f43e f738 f83e f11e fc3e .^.>'N.>.8.>...>
00000f0: 0000 003f 09ee 013f 89d9 033f 77c2 053f ...?...?...?w..?
0000100: caa8 073f 788c 093f 776d 0b3f be4b 0d3f ...?x..?wm.?.K.?
0000110: 4427 0f3f 0000 113f e8d5 123f f3a8 143f D'.?...?...?...?
0000120: 1879 163f 4e46 183f 8d10 1a3f cad7 1b3f .y.?NF.?...?...?
0000130: fe9b 1d3f 1f5d 1f3f 241b 213f 06d6 223f ...?.].?$.!?.."?
0000140: bb8d 243f 3a42 263f 7cf3 273f 78a1 293f ..$?:B&?|.'?x.)?
0000150: 254c 2b3f 7bf3 2c3f 7297 2e3f 0138 303f %L+?{.,?r..?.80?
0000160: 22d5 313f ca6e 333f ".1?.n3?
Which is the sines of the first 90 degrees in 4byte binary floats
To run test cases in IE Browser make sure you have downloaded IE driver and you need to set the property as well.
Below code will help you
// This will set the driver
System.setProperty("webdriver.ie.driver","driver path\\IEDriverServer.exe");
// Initialise browser
WebDriver driver=new InternetExplorerDriver();
You can check IE Browser challenges with Selenium and complete code for more details
"Failed to show response data" can also happen if you are doing crossdomain requests and the remote host is not properly handling the CORS headers. Check your js console for errors.
To name a few we can use redux-react-session which is having good API for session management like, initSessionService
, refreshFromLocalStorage
, checkAuth
and many other. It also provide some advanced functionality like Immutable JS
.
Alternatively we can leverage react-web-session which provides options like callback
and timeout
.
This will work.
def check(arr):
if np.all(arr == 0):
return True
return False
Another method through re
module. It does the reverse operation of matching all the words instead of spitting the whole sentence by space.
>>> import re
>>> s = "many fancy word \nhello \thi"
>>> re.findall(r'\S+', s)
['many', 'fancy', 'word', 'hello', 'hi']
Above regex would match one or more non-space characters.
If you don't care about loading the file into memory, as of Go 1.16, you can use the os.ReadFile
and bytes.Count
functions.
package main
import (
"log"
"os"
"bytes"
)
func main() {
data, err := os.ReadFile("input.txt")
if err != nil {
log.Fatal(err)
}
n := bytes.Count(data, []byte{'\n'})
fmt.Printf("input.txt has %d lines\n", n)
}
I solved it now. However it only is solved in Netbeans. Not sure why eclipse still won't take the settings.xml that is changed. The solution is however to remove/comment the User/Password param in settings.xml
Before:
<proxies>
<proxy>
<id>optional</id>
<active>true</active>
<protocol>http</protocol>
<username>proxyuser</username>
<password>proxypass</password>
<host>proxyserver.company.com</host>
<port>8080</port>
<nonProxyHosts>local.net|some.host.com</nonProxyHosts>
</proxy>
</proxies>
After:
<proxies>
<proxy>
<id>optional</id>
<active>true</active>
<protocol>http</protocol>
<host>proxyserver.company.com</host>
<port>8080</port>
<nonProxyHosts>local.net|some.host.com</nonProxyHosts>
</proxy>
</proxies>
If the strings are the same length, then I would go for '%x' % ()
of the built-in xor (^
).
Examples -
>>>a = '290b6e3a'
>>>b = 'd6f491c5'
>>>'%x' % (int(a,16)^int(b,16))
'ffffffff'
>>>c = 'abcd'
>>>d = '12ef'
>>>'%x' % (int(a,16)^int(b,16))
'b922'
If the strings are not the same length, truncate the longer string to the length of the shorter using a slice longer = longer[:len(shorter)]
Maybe this is a bit redundant, but no one appeared to have mentioned this as a solution.
As a beginner in SQL I find that when using a BEGIN
and END
SSMS usually adds a squiggly line with incorrect syntax near 'END'
to END, simply because there's no content in between yet. If you're just setting up BEGIN
and END
to get started and add the actual query later, then simply add a bogus PRINT
statement so SSMS stops bothering you.
For example:
IF (1=1)
BEGIN
PRINT 'BOGUS'
END
The following will indeed set you on the wrong track, thinking you made a syntax error which in this case just means you still need to add content in between BEGIN and END:
IF (1=1)
BEGIN
END
This is a variable jQuery uses internally, but had no reason to hide, so it's there to use. Just a heads up, it becomes jquery.ajax.active
next release. There's no documentation because it's exposed but not in the official API, lots of things are like this actually, like jQuery.cache
(where all of jQuery.data()
goes).
I'm guessing here by actual usage in the library, it seems to be there exclusively to support $.ajaxStart()
and $.ajaxStop()
(which I'll explain further), but they only care if it's 0 or not when a request starts or stops. But, since there's no reason to hide it, it's exposed to you can see the actual number of simultaneous AJAX requests currently going on.
When jQuery starts an AJAX request, this happens:
if ( s.global && ! jQuery.active++ ) {
jQuery.event.trigger( "ajaxStart" );
}
This is what causes the $.ajaxStart()
event to fire, the number of connections just went from 0 to 1 (jQuery.active++
isn't 0 after this one, and !0 == true
), this means the first of the current simultaneous requests started. The same thing happens at the other end. When an AJAX request stops (because of a beforeSend
abort via return false
or an ajax call complete
function runs):
if ( s.global && ! --jQuery.active ) {
jQuery.event.trigger( "ajaxStop" );
}
This is what causes the $.ajaxStop()
event to fire, the number of requests went down to 0, meaning the last simultaneous AJAX call finished. The other global AJAX handlers fire in there along the way as well.
Try this code:
<input type="text" name="Phone Number" pattern="[7-9]{1}[0-9]{9}"
title="Phone number with 7-9 and remaing 9 digit with 0-9">
This code will inputs only in the following format:
9238726384 (starting with 9 or 8 or 7 and other 9 digit using any number)
8237373746
7383673874
Incorrect format:
2937389471(starting not with 9 or 8 or 7)
32796432796(more than 10 digit)
921543(less than 10 digit)
A simple solution without need for require which solves the multiple period extension problem:
var filename = 'file.with.long.extension';
var ext = filename.substring(filename.indexOf('.'));
//ext = '.with.long.extension'
Or if you don't want the leading dot:
var filename = 'file.with.long.extension';
var ext = filename.substring(filename.indexOf('.')+1);
//ext = 'with.long.extension'
Make sure to test that the file has an extension too.
You can run the tool from Microsoft in this KB http://support.microsoft.com/default.aspx?scid=kb;en-us;Q195353 to fix the licensing issues for earlier ActiveX controls. This worked for me.
above answers In simple words,
you have to register under @NgModule
's
declarations: [
AppComponent, YourNewComponentHere
]
of app.module.ts
do not forget to import
that component.
O(n^2) is polynomial time. The polynomial is f(n) = n^2. On the other hand, O(2^n) is exponential time, where the exponential function implied is f(n) = 2^n. The difference is whether the function of n places n in the base of an exponentiation, or in the exponent itself.
Any exponential growth function will grow significantly faster (long term) than any polynomial function, so the distinction is relevant to the efficiency of an algorithm, especially for large values of n.
Another way of doing it would be centering an enclosing paragraph:
<p style="text-align:center; border:1px solid black"><img src="https://cdn.sstatic.net/Sites/stackoverflow/company/img/logos/so/so-icon.png?v=c78bd457575a"></p>
_x000D_
Thanks for your great question, this has caught me out a few times. When using dataURI HTML source, I find that I have to define a complete HTML document.
See below a modified example.
var html = '<html><head></head><body>Foo</body></html>';
var iframe = document.createElement('iframe');
iframe.src = 'data:text/html;charset=utf-8,' + encodeURI(html);
take note of the html content wrapped with <html>
tags and the iframe.src
string.
The iframe element needs to be added to the DOM tree to be parsed.
document.body.appendChild(iframe);
You will not be able to inspect the iframe.contentDocument
unless you disable-web-security
on your browser.
You'll get a message
DOMException: Failed to read the 'contentDocument' property from 'HTMLIFrameElement': Blocked a frame with origin "http://localhost:7357" from accessing a cross-origin frame.
A relatively newer (de)compression tool you might want to consider is zstandard. It does an excellent job of utilizing spare cores, and it has made some great trade-offs when it comes to compression ratio vs. (de)compression time. It is also highly tweak-able depending on your compression ratio needs.
This is how I get UILabel Autoshrink
work (especially for height of label font fitting in 4s device from 6s Plus Storyboard) in iOS 9.2, Xcode 7.2 ...
Assuming that both data1()
and data2()
are in the same class, then another alternative is to make data1()
static.
private static void data1()
{
}
private static void data2()
{
data1();
}
This error could also happen because of version mismatch of jmeter and java. As jmeter versions supports different java versions as below.
Download the zip accordingly and you are good to go.
Ok, personal opinion here, but Append and Prepend imply precise positions in a set.
Push and Pop are really concepts that can be applied to either end of a set... Just as long as you're consistent... For some reason, to me, Push() seems like it should apply to the front of a set...
Using the ArrayObject from Std or building your own
(new \ArrayObject($existingStdClass))
you can use the build in method on the new class:
getArrayCopy()
or pass the new object to
iterator_to_array
The %pdb
magic command is good to use as well. Just say %pdb on
and subsequently the pdb
debugger will run on all exceptions, no matter how deep in the call stack. Very handy.
If you have a particular line that you want to debug, just raise an exception there (often you already are!) or use the %debug
magic command that other folks have been suggesting.
I had the same requirement for a project I am doing. But none of the answers came elegant to my requirement. Here is something which finally helped me, and might be useful for this case:
from bokeh.io import export_png, export_svgs
from bokeh.models import ColumnDataSource, DataTable, TableColumn
def save_df_as_image(df, path):
source = ColumnDataSource(df)
df_columns = [df.index.name]
df_columns.extend(df.columns.values)
columns_for_table=[]
for column in df_columns:
columns_for_table.append(TableColumn(field=column, title=column))
data_table = DataTable(source=source, columns=columns_for_table,height_policy="auto",width_policy="auto",index_position=None)
export_png(data_table, filename = path)
Maybe the best way to answer the questions like "which version is faster and which one shall I use?" is to look to the source code:
map.forEach() - from Map.java
default void forEach(BiConsumer<? super K, ? super V> action) {
Objects.requireNonNull(action);
for (Map.Entry<K, V> entry : entrySet()) {
K k;
V v;
try {
k = entry.getKey();
v = entry.getValue();
} catch(IllegalStateException ise) {
// this usually means the entry is no longer in the map.
throw new ConcurrentModificationException(ise);
}
action.accept(k, v);
}
}
map.entrySet().forEach() - from Iterable.java
default void forEach(Consumer<? super T> action) {
Objects.requireNonNull(action);
for (T t : this) {
action.accept(t);
}
}
This immediately reveals that map.forEach() is also using Map.Entry internally. So I would not expect any performance benefit in using map.forEach() over the map.entrySet().forEach(). So in your case the answer really depends on your personal taste :)
For the complete list of differences please refer to the provided javadoc links. Happy coding!
The Easiest way to implement scrollbar using java swing is as below :
In the comments you asked if another view can be focused instead of the EditText. Yes it can. Use .requestFocus()
method for the view you want to be focused at the beginning (in onCreate() method)
Also focusing other view will cut out some amount of code. (code for hiding the keyboard for example)
The token has to be placed in an Authorization header according to the following format:
Authorization: Bearer [Token_Value]
import urllib2
import json
def get_auth_token():
"""
get an auth token
"""
req=urllib2.Request("https://xforce-api.mybluemix.net/auth/anonymousToken")
response=urllib2.urlopen(req)
html=response.read()
json_obj=json.loads(html)
token_string=json_obj["token"].encode("ascii","ignore")
return token_string
def get_response_json_object(url, auth_token):
"""
returns json object with info
"""
auth_token=get_auth_token()
req=urllib2.Request(url, None, {"Authorization": "Bearer %s" %auth_token})
response=urllib2.urlopen(req)
html=response.read()
json_obj=json.loads(html)
return json_obj
Convert the image to a byte[]
and store that in the database.
Add this column to your model:
public byte[] Content { get; set; }
Then convert your image to a byte array and store that like you would any other data:
public byte[] ImageToByteArray(System.Drawing.Image imageIn)
{
using(var ms = new MemoryStream())
{
imageIn.Save(ms, System.Drawing.Imaging.ImageFormat.Gif);
return ms.ToArray();
}
}
public Image ByteArrayToImage(byte[] byteArrayIn)
{
using(var ms = new MemoryStream(byteArrayIn))
{
var returnImage = Image.FromStream(ms);
return returnImage;
}
}
Source: Fastest way to convert Image to Byte array
var image = new ImageEntity()
{
Content = ImageToByteArray(image)
};
_context.Images.Add(image);
_context.SaveChanges();
When you want to get the image back, get the byte array from the database and use the ByteArrayToImage
and do what you wish with the Image
This stops working when the byte[]
gets to big. It will work for files under 100Mb
IEnumerable cannot count without iterating.
Under "normal" circumstances, it would be possible for classes implementing IEnumerable or IEnumerable<T>, such as List<T>, to implement the Count method by returning the List<T>.Count property. However, the Count method is not actually a method defined on the IEnumerable<T> or IEnumerable interface. (The only one that is, in fact, is GetEnumerator.) And this means that a class-specific implementation cannot be provided for it.
Rather, Count it is an extension method, defined on the static class Enumerable. This means it can be called on any instance of an IEnumerable<T> derived class, regardless of that class's implementation. But it also means it is implemented in a single place, external to any of those classes. Which of course means that it must be implemented in a way that is completely independent of these class' internals. The only such way to do counting is via iteration.
I prefer simplicity:
var days = [1, 2, 3, 4, 5];
if ( 2 in days ) {console.log('weekday');}
I've got the same issue as stated by Grigoriy Yuschenko. Same Intellij 2018 3.3
I was able to start my project by setting (like stated by Grigoriy)
File->Project Structure->Modules ->> Language level to 8 ( my maven project was set to 1.8 java)
AND
File -> Settings -> Build, Execution, Deployment -> Compiler -> Java Compiler -> 8 also there
I hope it would be useful
An easier alternative to solve this problem is to return an string, and format that string to json with JavaScriptSerializer.
public string GetEntityInJson()
{
JavaScriptSerializer j = new JavaScriptSerializer();
var entityList = dataContext.Entitites.Select(x => new { ID = x.ID, AnotherAttribute = x.AnotherAttribute });
return j.Serialize(entityList );
}
It is important the "Select" part, which choose the properties you want in your view. Some object have a reference for the parent. If you do not choose the attributes, the circular reference may appear, if you just take the tables as a whole.
Do not do this:
public string GetEntityInJson()
{
JavaScriptSerializer j = new JavaScriptSerializer();
var entityList = dataContext.Entitites.toList();
return j.Serialize(entityList );
}
Do this instead if you don't want the whole table:
public string GetEntityInJson()
{
JavaScriptSerializer j = new JavaScriptSerializer();
var entityList = dataContext.Entitites.Select(x => new { ID = x.ID, AnotherAttribute = x.AnotherAttribute });
return j.Serialize(entityList );
}
This helps render a view with less data, just with the attributes you need, and makes your web run faster.